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A,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA;AACrD","file":"index.mjs","sourcesContent":["/**\n * Identity for a Cavos wallet. Login (email / social / OTP) only ever produces a\n * stable `userId`; that's all the wallet needs to derive its address. Auth never\n * touches signing — the device key does that, silently.\n *\n * Privy-style UX: the user \"logs in\" and the wallet is provisioned behind the\n * scenes (device key + auto-deployed smart account). The app never handles keys.\n */\nexport interface Identity {\n  /** Stable, backend-managed user identifier. */\n  userId: string;\n  /** Optional metadata (email, provider) for display only. */\n  email?: string;\n  /**\n   * Display name from the OAuth id_token (standard OIDC `name` claim).\n   * Populated by Google sign-in; absent for email and Apple\n   * (their tokens don't carry it). Optional on purpose —\n   * consumers should fall back to `email` / `userId` when unset.\n   */\n  name?: string;\n  provider?: \"google\" | \"apple\" | \"email\" | \"otp\" | string;\n}\n\n/**\n * Authenticates a user and returns their stable identity. Implementations:\n * - `CavosAuth` (hosted, mirrors `@cavos/react`: Google/Apple/email/OTP via the\n *   Cavos backend) — the default, Privy-like experience.\n * - any custom provider (the app already authenticated the user elsewhere).\n */\nexport interface AuthProvider {\n  authenticate(): Promise<Identity>;\n  /**\n   * The provider id_token from the last login, if this provider has one. The\n   * wallet registry authenticates the end user with it — Cavos decides who owns\n   * an address, so a public app id is not enough. Kept in memory only; a\n   * returning device that no longer has one falls back to its address cache.\n   */\n  getAuthToken?(): string | null;\n}\n\n/** Trivial provider when the app already has the user's stable id. */\nexport class StaticIdentity implements AuthProvider {\n  constructor(private readonly identity: Identity) {}\n  async authenticate(): Promise<Identity> {\n    return this.identity;\n  }\n}\n","import { Address, nativeToScVal, xdr } from \"@stellar/stellar-sdk\";\nimport { Buffer } from \"buffer\";\nimport type { CavosStellar } from \"../chains/stellar/CavosStellar\";\nimport type { StellarAdapter } from \"../chains/stellar/StellarAdapter\";\nimport type { ExecuteOptions } from \"../chains/ChainAdapter\";\nimport { secureRandomBytes } from \"../crypto/encoding\";\n\n/**\n * Turnkey wrapper over `CavosStellar.invokeContract` for Trustless Work's\n * single-release milestone escrow (Soroban). Each method maps 1:1 to a contract\n * entrypoint and passes THIS Cavos account's `G…` as the role argument that the\n * contract `require_auth`s — so the account's control key signs the matching\n * Soroban auth entry. See the escrow contract reference for the lifecycle.\n *\n * Gasless by default (the relayer fee-bumps); pass `{ sponsored: false }` to have\n * the account pay its own fee.\n *\n *   const escrow = new TrustlessWorkEscrow(wallet, contractId);\n *   await escrow.approveMilestone(0);   // wallet acts as `approver`\n *   await escrow.releaseFunds(TW_ADDR); // wallet acts as `release_signer`\n */\nexport class TrustlessWorkEscrow {\n  constructor(\n    private readonly wallet: CavosStellar,\n    private readonly contractId: string,\n  ) {}\n\n  /** This account's `G…` as a Soroban address ScVal — the role argument. */\n  private self(): xdr.ScVal {\n    return new Address(this.wallet.address).toScVal();\n  }\n\n  private addr(g: string): xdr.ScVal {\n    return new Address(g).toScVal();\n  }\n\n  // ── Milestones ────────────────────────────────────────────────────────────\n\n  /** `approve_milestone(milestone_index, approver=self)` — the client approves. */\n  approveMilestone(milestoneIndex: number, opts?: ExecuteOptions): Promise<string> {\n    return this.wallet.invokeContract({\n      contractId: this.contractId,\n      method: \"approve_milestone\",\n      args: [nativeToScVal(milestoneIndex, { type: \"u32\" }), this.self()],\n      opts,\n    });\n  }\n\n  /** `change_milestone_status(index, new_status, new_evidence?, service_provider=self)`. */\n  changeMilestoneStatus(\n    milestoneIndex: number,\n    newStatus: string,\n    newEvidence?: string,\n    opts?: ExecuteOptions,\n  ): Promise<string> {\n    const evidence =\n      newEvidence === undefined\n        ? xdr.ScVal.scvVoid()\n        : nativeToScVal(newEvidence, { type: \"string\" });\n    return this.wallet.invokeContract({\n      contractId: this.contractId,\n      method: \"change_milestone_status\",\n      args: [\n        nativeToScVal(milestoneIndex, { type: \"u32\" }),\n        nativeToScVal(newStatus, { type: \"string\" }),\n        evidence,\n        this.self(),\n      ],\n      opts,\n    });\n  }\n\n  // ── Release / Dispute ───────────────────────────────────────────────────────\n\n  /** `release_funds(release_signer=self, trustless_work_address)`. */\n  releaseFunds(trustlessWorkAddress: string, opts?: ExecuteOptions): Promise<string> {\n    return this.wallet.invokeContract({\n      contractId: this.contractId,\n      method: \"release_funds\",\n      args: [this.self(), this.addr(trustlessWorkAddress)],\n      opts,\n    });\n  }\n\n  /** `dispute_escrow(signer=self)` — any role (except resolver) can dispute. */\n  disputeEscrow(opts?: ExecuteOptions): Promise<string> {\n    return this.wallet.invokeContract({\n      contractId: this.contractId,\n      method: \"dispute_escrow\",\n      args: [this.self()],\n      opts,\n    });\n  }\n\n  // ── Funding & resolution (complex args) ─────────────────────────────────────\n\n  /**\n   * `fund_escrow(signer=self, expected_escrow, amount)`. `expected_escrow` must be\n   * the current on-chain `Escrow` struct as an ScVal — read it via `getEscrow()`\n   * and pass the raw simulated value, or build it with `nativeToScVal`.\n   */\n  fundEscrow(expectedEscrow: xdr.ScVal, amount: bigint, opts?: ExecuteOptions): Promise<string> {\n    return this.wallet.invokeContract({\n      contractId: this.contractId,\n      method: \"fund_escrow\",\n      args: [this.self(), expectedEscrow, nativeToScVal(amount, { type: \"i128\" })],\n      opts,\n    });\n  }\n\n  /**\n   * `resolve_dispute(dispute_resolver=self, trustless_work_address, distributions)`.\n   * `distributions` is a `Map<Address, i128>` — pass as `{ [gAddress]: amount }`.\n   */\n  resolveDispute(\n    trustlessWorkAddress: string,\n    distributions: Record<string, bigint>,\n    opts?: ExecuteOptions,\n  ): Promise<string> {\n    const entries = Object.entries(distributions).map(\n      ([g, amount]) =>\n        new xdr.ScMapEntry({\n          key: new Address(g).toScVal(),\n          val: nativeToScVal(amount, { type: \"i128\" }),\n        }),\n    );\n    return this.wallet.invokeContract({\n      contractId: this.contractId,\n      method: \"resolve_dispute\",\n      args: [this.self(), this.addr(trustlessWorkAddress), xdr.ScVal.scvMap(entries)],\n      opts,\n    });\n  }\n\n  /** Read the current on-chain escrow state (roles, milestones, flags, amount).\n   *  Read-only simulation — needs an adapter but no signing. */\n  async getEscrow(adapter: StellarAdapter): Promise<EscrowState> {\n    return adapter.readContract({\n      from: this.wallet.address,\n      contractId: this.contractId,\n      method: \"get_escrow\",\n    }) as Promise<EscrowState>;\n  }\n}\n\n// ── Escrow struct encoding + factory deploy ───────────────────────────────────\n\nexport interface MilestoneInput {\n  description: string;\n  status?: string;\n  evidence?: string;\n  approved?: boolean;\n}\n\nexport interface EscrowInput {\n  engagementId: string;\n  title: string;\n  description: string;\n  /** Total amount in the trustline token's base units (7-dp for USDC/XLM). */\n  amount: bigint;\n  /** Platform fee in basis points (e.g. 100 = 1%). */\n  platformFeeBps: number;\n  roles: {\n    approver: string;\n    serviceProvider: string;\n    platform: string;\n    releaseSigner: string;\n    disputeResolver: string;\n    receiver: string;\n  };\n  milestones: MilestoneInput[];\n  /** Trustline token contract (SAC) address — e.g. USDC's `C…`. */\n  trustline: string;\n  receiverMemo?: number;\n}\n\n/** Decoded `get_escrow` result (native JS shape from `scValToNative`). */\nexport interface EscrowState {\n  engagement_id: string;\n  title: string;\n  description: string;\n  amount: bigint;\n  platform_fee: number;\n  roles: Record<string, string>;\n  milestones: { description: string; status: string; evidence: string; approved: boolean }[];\n  flags: { disputed: boolean; released: boolean; resolved: boolean };\n  trustline: { address: string };\n  receiver_memo: number;\n}\n\nconst sym = (s: string) => xdr.ScVal.scvSymbol(s);\nconst str = (s: string) => nativeToScVal(s, { type: \"string\" });\nconst u32 = (n: number) => nativeToScVal(n, { type: \"u32\" });\nconst boolVal = (b: boolean) => xdr.ScVal.scvBool(b);\nconst addrVal = (g: string) => new Address(g).toScVal();\n\n/** A contracttype struct → scvMap with symbol keys sorted by name. */\nfunction struct(fields: Record<string, xdr.ScVal>): xdr.ScVal {\n  const entries = Object.keys(fields)\n    .sort()\n    .map((k) => new xdr.ScMapEntry({ key: sym(k), val: fields[k] }));\n  return xdr.ScVal.scvMap(entries);\n}\n\n/** Encode an `EscrowInput` as the Soroban `Escrow` struct ScVal. */\nexport function buildEscrowScVal(input: EscrowInput): xdr.ScVal {\n  return struct({\n    engagement_id: str(input.engagementId),\n    title: str(input.title),\n    roles: struct({\n      approver: addrVal(input.roles.approver),\n      service_provider: addrVal(input.roles.serviceProvider),\n      platform: addrVal(input.roles.platform),\n      release_signer: addrVal(input.roles.releaseSigner),\n      dispute_resolver: addrVal(input.roles.disputeResolver),\n      receiver: addrVal(input.roles.receiver),\n    }),\n    description: str(input.description),\n    amount: nativeToScVal(input.amount, { type: \"i128\" }),\n    platform_fee: u32(input.platformFeeBps),\n    milestones: xdr.ScVal.scvVec(\n      input.milestones.map((m) =>\n        struct({\n          description: str(m.description),\n          status: str(m.status ?? \"pending\"),\n          evidence: str(m.evidence ?? \"\"),\n          approved: boolVal(m.approved ?? false),\n        }),\n      ),\n    ),\n    flags: struct({ disputed: boolVal(false), released: boolVal(false), resolved: boolVal(false) }),\n    trustline: struct({ address: addrVal(input.trustline) }),\n    receiver_memo: u32(input.receiverMemo ?? 0),\n  });\n}\n\n/**\n * Deploy + initialize a fresh escrow instance through a Trustless Work factory\n * contract (`tw_new_single_release_escrow`), signed by a Cavos account. Returns\n * the deployed escrow contract address. This is TW's production pattern: one\n * factory spawns an independent escrow per engagement.\n */\nexport async function deployEscrow(\n  wallet: CavosStellar,\n  params: {\n    factoryId: string;\n    wasmHash: string;\n    adapter: StellarAdapter;\n    escrow: EscrowInput;\n    opts?: ExecuteOptions;\n  },\n): Promise<{ escrowId: string; txHash: string }> {\n  const salt = secureRandomBytes(32);\n  const txHash = await wallet.invokeContract({\n    contractId: params.factoryId,\n    method: \"tw_new_single_release_escrow\",\n    args: [\n      new Address(wallet.address).toScVal(),\n      xdr.ScVal.scvBytes(Buffer.from(params.wasmHash, \"hex\")),\n      xdr.ScVal.scvBytes(Buffer.from(salt)),\n      sym(\"initialize_escrow\"),\n      xdr.ScVal.scvVec([buildEscrowScVal(params.escrow)]),\n      xdr.ScVal.scvVec([]),\n    ],\n    opts: params.opts,\n  });\n  const result = (await params.adapter.transactionResult(txHash)) as unknown[];\n  const escrowId = Array.isArray(result) ? String(result[0]) : \"\";\n  if (!escrowId) throw new Error(\"kit/tw: factory did not return a deployed address\");\n  return { escrowId, txHash };\n}\n","import { Keypair } from \"@stellar/stellar-sdk\";\nimport { Buffer } from \"buffer\";\nimport { randomBytes } from \"@noble/hashes/utils\";\n\n/**\n * Key derivation for the classic Stellar (`G…`) multisig account.\n *\n * A partner integration requires classic ed25519 `G…` addresses, which the\n * Soroban device-account (`C…`) model cannot provide. Instead of a smart\n * contract we use a classic account whose UX matches the rest of Cavos (social\n * login → one address per app, silent signing, gasless, self-custodial):\n *\n *   - The **control key** is a random ed25519 key generated on the first device.\n *     Its public key IS the account's `G…` address, and it is the account's\n *     master key (weight 1) — the address is therefore named by the first\n *     device, exactly as the Starknet constructor and the Solana PDA seeds do.\n *   - Its 32-byte seed is never stored in the clear: it lives envelope-encrypted\n *     in the account's own on-chain data entries (see `envelope.ts`), unlocked\n *     per-device by a P-256 device factor, a passkey, or recovery.\n *\n * The address is not derivable from identity. A returning device looks it up in\n * the Cavos registry and then unlocks the control key from the envelope; it\n * never mints a second `G…`.\n *\n * This module is pure `@noble/*` + stellar-sdk keypair math (no WebCrypto/DOM),\n * so the identical derivation runs in the browser and React Native.\n */\n\n/** A freshly generated control key: the real (weight-1) signer of the account.\n *  Returns both the `Keypair` and its raw 32-byte seed (the secret that the\n *  envelope encrypts). Generated once at account creation, then only ever\n *  recovered by decrypting the on-chain envelope. */\nexport function generateControlKey(): { keypair: Keypair; seed: Uint8Array } {\n  const seed = randomBytes(32);\n  return { keypair: Keypair.fromRawEd25519Seed(Buffer.from(seed)), seed };\n}\n\n/** Rebuild the control `Keypair` from a decrypted 32-byte seed. */\nexport function controlKeypairFromSeed(seed: Uint8Array): Keypair {\n  if (seed.length !== 32) throw new Error(\"kit/stellar: control seed must be 32 bytes\");\n  return Keypair.fromRawEd25519Seed(Buffer.from(seed));\n}\n"]}