[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72SWVRWQK4026Q0YSQQARV7":3,"skill-same:01M72SWVRWQK4026Q0YSQQARV7":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":32,"ownerDescription":33,"updatedAt":34,"install":35,"resources":47},"01M72SWVRWQK4026Q0YSQQARV7","dapp",null,"Stellar dApp \u002F frontend development. Covers the JavaScript stellar-sdk (browser + Node.js), Freighter wallet, Stellar Wallets Kit (multi-wallet), Wallet Standard, smart accounts with passkeys, transaction building \u002F signing \u002F submission, smart contract invocation from the client, simulation, and error handling. Use when building a React\u002FNext.js\u002FNode.js app that talks to Stellar - classic operations or smart contracts.","LumenWipe\u002Flumenwipe","LumenWipe","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F289893933?v=4","01M72SD8X7756DM2C1FCDS4AQA","01M72SD8YZQ3TP9Z7G95QT4YC4",4,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FLumenWipe\u002Flumenwipe\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdapp\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: dapp\ndescription: Stellar dApp \u002F frontend development. Covers the JavaScript stellar-sdk (browser + Node.js), Freighter wallet, Stellar Wallets Kit (multi-wallet), Wallet Standard, smart accounts with passkeys, transaction building \u002F signing \u002F submission, smart contract invocation from the client, simulation, and error handling. Use when building a React\u002FNext.js\u002FNode.js app that talks to Stellar - classic operations or smart contracts.\nuser-invocable: true\nargument-hint: \"[dapp task]\"\n---\n\n# Stellar dApp \u002F Frontend\n\nClient-side development with `@stellar\u002Fstellar-sdk`, wallet connection, signing, and submitting transactions. Covers both classic Stellar operations and smart contract invocation from the browser or Node.js.\n\n## When to use this skill\n- Connecting Freighter or other wallets via Stellar Wallets Kit\n- Building, simulating, signing, and submitting transactions\n- Invoking Stellar smart contracts from a frontend\n- Implementing smart accounts with passkeys\n- Handling network passphrases (Mainnet \u002F Testnet \u002F local)\n\n## Related skills\n- Writing the contract being invoked → `..\u002Fsmart-contracts\u002FSKILL.md`\n- Issuing assets and managing trustlines → `..\u002Fassets\u002FSKILL.md`\n- Querying chain state via RPC \u002F Horizon → `..\u002Fdata\u002FSKILL.md`\n- Building paid APIs or agent payment clients → `..\u002Fagentic-payments\u002FSKILL.md`\n- SEPs the wallet\u002Fanchor flows depend on → `..\u002Fstandards\u002FSKILL.md`\n\n---\n\n\n## Goals\n- Single SDK instance for the app (RPC\u002FHorizon + transaction building)\n- Freighter wallet integration (or multi-wallet via Stellar Wallets Kit)\n- Clean separation of client\u002Fserver in Next.js\n- Transaction sending with proper confirmation handling\n\n## Quick Navigation\n- SDK setup and env config: [SDK Initialization](#sdk-initialization)\n- Wallet integrations: [Wallet Integration](#wallet-integration)\n- Tx build\u002Fsend patterns: [Transaction Building](#transaction-building), [Transaction Submission](#transaction-submission)\n- React + Next.js patterns: [React Components](#react-components), [Next.js App Router Setup](#nextjs-app-router-setup)\n- Smart wallets\u002Fpasskeys: [Smart Accounts (Passkey Wallets)](#smart-accounts-passkey-wallets)\n- Production UX checklist: [Transaction UX Checklist](#transaction-ux-checklist)\n\n## Recommended Dependencies\n\n> **Requires Node.js 22+.** As of SDK v16, Node 22 is the minimum (older Node produces an `EBADENGINE` warning). v16 also folded `@stellar\u002Fstellar-base` into `@stellar\u002Fstellar-sdk`, is ESM-first, and uses native `fetch` instead of axios. If you still import `@stellar\u002Fstellar-base` directly, switch the import to `@stellar\u002Fstellar-sdk` and uninstall the base package (keeping both breaks `instanceof` checks). See the [migration guide](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fguides\u002F00-migration).\n\n```bash\nnpm install @stellar\u002Fstellar-sdk @stellar\u002Ffreighter-api\n# Or for multi-wallet support - Wallets Kit v2 is distributed on JSR, not npm:\nnpx jsr add @creit-tech\u002Fstellar-wallets-kit\n```\n\n> **Sourcing:** SDK mechanics below (init, transaction building, contract invocation, submission, data fetching, error handling) track the official [JS SDK docs](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002F) (which also publish [`llms.txt`](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fllms.txt) \u002F [`llms-full.txt`](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fllms-full.txt) bundles for agents). Wallet integrations (Freighter, Stellar Wallets Kit), passkey smart accounts, and the OpenZeppelin relayer are separate packages, not part of the JS SDK - verify those against their own upstream docs.\n\n## SDK Initialization\n\n> For the full API reference (RPC methods, Horizon endpoints, migration guide), see the [data skill](..\u002Fdata\u002FSKILL.md).\n\n### Basic Setup\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\n\u002F\u002F For Testnet\nconst testnetServer = new StellarSdk.Horizon.Server(\"https:\u002F\u002Fhorizon-testnet.stellar.org\");\nconst testnetRpc = new StellarSdk.rpc.Server(\"https:\u002F\u002Fsoroban-testnet.stellar.org\");\nconst testnetNetworkPassphrase = StellarSdk.Networks.TESTNET;\n\n\u002F\u002F For Mainnet\nconst mainnetServer = new StellarSdk.Horizon.Server(\"https:\u002F\u002Fhorizon.stellar.org\");\nconst mainnetRpcUrl = process.env.NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL;\nif (!mainnetRpcUrl) throw new Error(\"Missing NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL\");\nconst mainnetRpc = new StellarSdk.rpc.Server(mainnetRpcUrl); \u002F\u002F set from your chosen RPC provider\nconst mainnetNetworkPassphrase = StellarSdk.Networks.PUBLIC;\n```\n\n### Environment Configuration\n> Use a provider-specific mainnet RPC URL (see: https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fdata\u002Fapis\u002Frpc\u002Fproviders).\n\n```typescript\n\u002F\u002F lib\u002Fstellar.ts\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\nconst NETWORK = process.env.NEXT_PUBLIC_STELLAR_NETWORK || \"testnet\";\n\nconst requireEnv = (name: string): string => {\n  const value = process.env[name];\n  if (!value) throw new Error(`Missing required env var: ${name}`);\n  return value;\n};\n\nfunction getConfig(network: string) {\n  switch (network) {\n    case \"testnet\":\n      return {\n        horizonUrl: \"https:\u002F\u002Fhorizon-testnet.stellar.org\",\n        rpcUrl: \"https:\u002F\u002Fsoroban-testnet.stellar.org\",\n        networkPassphrase: StellarSdk.Networks.TESTNET,\n        friendbotUrl: \"https:\u002F\u002Ffriendbot.stellar.org\" as string | null,\n      };\n    case \"mainnet\":\n      return {\n        horizonUrl: \"https:\u002F\u002Fhorizon.stellar.org\",\n        \u002F\u002F Resolved lazily so testnet runs don't require the mainnet env var\n        rpcUrl: requireEnv(\"NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL\"),\n        networkPassphrase: StellarSdk.Networks.PUBLIC,\n        friendbotUrl: null,\n      };\n    default:\n      throw new Error(`Unknown network: ${network}`);\n  }\n}\n\nexport const config = getConfig(NETWORK);\n\nexport const horizon = new StellarSdk.Horizon.Server(config.horizonUrl);\nexport const rpc = new StellarSdk.rpc.Server(config.rpcUrl);\n```\n\n## Wallet Integration\n\n### Freighter (Primary Browser Wallet)\n```typescript\n\u002F\u002F hooks\u002FuseFreighter.ts\nimport { useState, useEffect, useCallback } from \"react\";\nimport {\n  isConnected,\n  getAddress,\n  requestAccess,\n  signTransaction,\n  getNetwork,\n} from \"@stellar\u002Ffreighter-api\";\n\nexport function useFreighter() {\n  const [connected, setConnected] = useState(false);\n  const [address, setAddress] = useState\u003Cstring | null>(null);\n  const [network, setNetwork] = useState\u003Cstring | null>(null);\n\n  useEffect(() => {\n    checkConnection();\n  }, []);\n\n  const checkConnection = async () => {\n    const { isConnected: installed, error } = await isConnected();\n    if (error || !installed) return;\n\n    \u002F\u002F getAddress returns address: \"\" until the app has been granted access,\n    \u002F\u002F so a non-empty address means we're already authorized.\n    const { address: addr, error: addressError } = await getAddress();\n    if (addressError || !addr) return;\n\n    const { network: net, error: networkError } = await getNetwork();\n    if (networkError) return;\n    setConnected(true);\n    setAddress(addr);\n    setNetwork(net);\n  };\n\n  const connect = useCallback(async () => {\n    const { isConnected: installed, error } = await isConnected();\n    if (error || !installed) {\n      throw new Error(\"Freighter extension not installed\");\n    }\n\n    \u002F\u002F requestAccess prompts the user and returns the granted address.\n    const { address: addr, error: accessError } = await requestAccess();\n    if (accessError) throw new Error(accessError.message);\n\n    const { network: net, error: networkError } = await getNetwork();\n    if (networkError) throw new Error(networkError.message);\n    setConnected(true);\n    setAddress(addr);\n    setNetwork(net);\n\n    return addr;\n  }, []);\n\n  const disconnect = useCallback(() => {\n    setConnected(false);\n    setAddress(null);\n    setNetwork(null);\n  }, []);\n\n  const sign = useCallback(\n    async (xdr: string, networkPassphrase: string) => {\n      if (!connected) throw new Error(\"Wallet not connected\");\n      const { signedTxXdr, error } = await signTransaction(xdr, {\n        networkPassphrase,\n      });\n      if (error) throw new Error(error.message);\n      return signedTxXdr;\n    },\n    [connected]\n  );\n\n  return { connected, address, network, connect, disconnect, sign };\n}\n```\n\n### Stellar Wallets Kit (Multi-Wallet)\n\n```typescript\n\u002F\u002F hooks\u002FuseStellarWallet.ts\nimport { useState, useCallback } from \"react\";\nimport { StellarWalletsKit, Networks } from \"@creit-tech\u002Fstellar-wallets-kit\";\nimport { defaultModules } from \"@creit-tech\u002Fstellar-wallets-kit\u002Fmodules\u002Futils\";\n\n\u002F\u002F v2 is a static singleton: init once at module load, then call static methods -\n\u002F\u002F there is no instance to construct or pass around.\n\u002F\u002F defaultModules() loads every wallet that needs no extra setup; modules with\n\u002F\u002F prerequisites (WalletConnect, Ledger, Trezor) must be imported and added explicitly.\nStellarWalletsKit.init({\n  modules: defaultModules(),\n  network: Networks.TESTNET,\n});\n\nexport function useStellarWallet() {\n  const [address, setAddress] = useState\u003Cstring | null>(null);\n\n  const connect = useCallback(async () => {\n    \u002F\u002F authModal() opens the wallet picker, sets the chosen module active,\n    \u002F\u002F and returns the address - one call replaces v1's openModal callback dance.\n    const { address } = await StellarWalletsKit.authModal();\n    setAddress(address);\n  }, []);\n\n  const disconnect = useCallback(async () => {\n    await StellarWalletsKit.disconnect();\n    setAddress(null);\n  }, []);\n\n  const sign = useCallback(async (xdr: string) => {\n    const { signedTxXdr } = await StellarWalletsKit.signTransaction(xdr);\n    return signedTxXdr;\n  }, []);\n\n  return { address, connect, disconnect, sign };\n}\n```\n\n> **Migrating from v1?** (noted July 2026) v1 lived on npm under the dotted scope `@creit.tech\u002Fstellar-wallets-kit`, with `new StellarWalletsKit({...})`, `allowAllModules()`, and `openModal({ onWalletSelected })`. v2 moved to JSR under `@creit-tech\u002Fstellar-wallets-kit`, made the kit fully static, replaced `allowAllModules()` with `defaultModules()`, and folded wallet selection + address fetch into `authModal()`. npm parity is maintained for now, but the maintainers say npm updates will eventually stop - install from JSR. Pre-selecting a wallet (`setWallet(FREIGHTER_ID)`) still works; the ID constants now live in per-wallet module subpaths like `@creit-tech\u002Fstellar-wallets-kit\u002Fmodules\u002Ffreighter`.\n\n## Transaction Building\n\n### Basic Payment\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\nimport { horizon, config } from \"@\u002Flib\u002Fstellar\";\n\nexport async function buildPaymentTx(\n  sourceAddress: string,\n  destinationAddress: string,\n  amount: string,\n  asset: StellarSdk.Asset = StellarSdk.Asset.native()\n) {\n  const account = await horizon.loadAccount(sourceAddress);\n\n  const transaction = new StellarSdk.TransactionBuilder(account, {\n    fee: StellarSdk.BASE_FEE,\n    networkPassphrase: config.networkPassphrase,\n  })\n    .addOperation(\n      StellarSdk.Operation.payment({\n        destination: destinationAddress,\n        asset: asset,\n        amount: amount,\n      })\n    )\n    .setTimeout(180)\n    .build();\n\n  return transaction.toXDR();\n}\n```\n\n### Smart Contract Invocation (`contract.Client`)\n\nThe canonical way to call a Soroban contract from JS is the `contract.Client`, not hand-built `Contract.call` + `assembleTransaction`. The client reads the contract's interface from the network, so each method is callable by name and returns an `AssembledTransaction`. You get a native JS result and don't build ScVals by hand.\n\n```typescript\nimport { contract } from \"@stellar\u002Fstellar-sdk\";\nimport { config } from \"@\u002Flib\u002Fstellar\";\n\n\u002F\u002F Describe just the methods you call. `Client.from\u003CT>()` uses this to type\n\u002F\u002F the returned client, so calls are checked and autocompleted - no codegen.\n\u002F\u002F For a contract with many methods, generate this interface from its spec\n\u002F\u002F with the SDK's binding CLI instead of writing it by hand.\ninterface CounterContract {\n  increment: (\n    options?: contract.MethodOptions,\n  ) => Promise\u003Ccontract.AssembledTransaction\u003Cnumber>>;\n}\n\n\u002F\u002F `signTransaction` comes from the wallet (e.g. Freighter\u002FWallets Kit in the\n\u002F\u002F browser). `contract.basicNodeSigner(keypair, networkPassphrase)` is the\n\u002F\u002F Node equivalent for scripts and tests.\nexport async function getCounterClient(\n  contractId: string,\n  publicKey: string,\n  signTransaction: contract.ClientOptions[\"signTransaction\"],\n) {\n  return contract.Client.from\u003CCounterContract>({\n    contractId,\n    rpcUrl: config.rpcUrl,\n    networkPassphrase: config.networkPassphrase,\n    publicKey,\n    signTransaction,\n  });\n}\n\n\u002F\u002F Preview (free simulation) then sign + send to apply on-chain.\nexport async function increment(client: contract.Client & CounterContract) {\n  const tx = await client.increment();\n  console.log(\"preview:\", tx.result); \u002F\u002F predicted return value, no signature\n  const sent = await tx.signAndSend(); \u002F\u002F submits and polls to completion\n  return sent.result;\n}\n```\n\n`AssembledTransaction` also supports fine-grained control (`{ fee, simulate, timeoutInSeconds }` as a second arg) and multi-party auth via `tx.needsNonInvokerSigningBy()` \u002F `tx.signAuthEntries()`. See [Invoke a Contract](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fguides\u002F06-invoke-a-contract) and [Authorize a Contract Call](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fguides\u002F07-contract-auth).\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>Advanced: low-level invocation without a client\u003C\u002Fb>\u003C\u002Fsummary>\n\nUse this only when you need direct control over the transaction (e.g. batching a contract call with classic operations). Otherwise prefer `contract.Client` above.\n\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\nimport { rpc, config } from \"@\u002Flib\u002Fstellar\";\n\nexport async function invokeContract(\n  sourceAddress: string,\n  contractId: string,\n  method: string,\n  args: StellarSdk.xdr.ScVal[]\n) {\n  const account = await rpc.getAccount(sourceAddress);\n  const contract = new StellarSdk.Contract(contractId);\n\n  const transaction = new StellarSdk.TransactionBuilder(account, {\n    fee: StellarSdk.BASE_FEE,\n    networkPassphrase: config.networkPassphrase,\n  })\n    .addOperation(contract.call(method, ...args))\n    .setTimeout(180)\n    .build();\n\n  \u002F\u002F `prepareTransaction` simulates and applies footprint\u002Fauth\u002Ffees in one step.\n  \u002F\u002F (Equivalent to simulateTransaction + rpc.assembleTransaction.)\n  const prepared = await rpc.prepareTransaction(transaction);\n  return prepared.toXDR();\n}\n```\n\n**Building ScVal arguments by hand** (only needed for the low-level path - `contract.Client` converts native JS args for you):\n\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\nconst addressVal = StellarSdk.Address.fromString(address).toScVal();\nconst i128Val = StellarSdk.nativeToScVal(BigInt(amount), { type: \"i128\" });\nconst u32Val = StellarSdk.nativeToScVal(42, { type: \"u32\" });\nconst stringVal = StellarSdk.nativeToScVal(\"hello\", { type: \"string\" });\nconst symbolVal = StellarSdk.nativeToScVal(\"transfer\", { type: \"symbol\" });\n\n\u002F\u002F Struct\nconst structVal = StellarSdk.nativeToScVal(\n  { name: \"Token\", decimals: 7 },\n  {\n    type: {\n      name: [\"symbol\", null],\n      decimals: [\"u32\", null],\n    },\n  }\n);\n\n\u002F\u002F Vec of i128 - the element type is applied to each item\nconst vecVal = StellarSdk.nativeToScVal(\n  [1, 2, 3].map((n) => BigInt(n)),\n  { type: \"i128\" }\n);\n```\n\n\u003C\u002Fdetails>\n\n## Transaction Submission\n\n### Submit and Wait for Confirmation\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\nimport { rpc, horizon, config } from \"@\u002Flib\u002Fstellar\";\n\nexport async function submitTransaction(signedXdr: string) {\n  const transaction = StellarSdk.TransactionBuilder.fromXDR(\n    signedXdr,\n    config.networkPassphrase\n  );\n\n  \u002F\u002F For smart contract transactions, use RPC\n  if (transaction.operations.some(op => op.type === \"invokeHostFunction\")) {\n    return submitSorobanTransaction(signedXdr);\n  }\n\n  \u002F\u002F For classic transactions, use Horizon\n  return submitClassicTransaction(signedXdr);\n}\n\nasync function submitSorobanTransaction(signedXdr: string) {\n  const transaction = StellarSdk.TransactionBuilder.fromXDR(\n    signedXdr,\n    config.networkPassphrase\n  ) as StellarSdk.Transaction;\n\n  const response = await rpc.sendTransaction(transaction);\n\n  if (response.status === \"ERROR\") {\n    throw new Error(`Send failed: ${response.errorResult}`);\n  }\n\n  \u002F\u002F Poll for completion. pollTransaction handles the retry loop (default 5\n  \u002F\u002F attempts, 1s apart - tune with { attempts, sleepStrategy }) instead of a\n  \u002F\u002F hand-rolled while loop that can spin forever.\n  const getResponse = await rpc.pollTransaction(response.hash);\n\n  if (getResponse.status === \"SUCCESS\") {\n    return {\n      hash: response.hash,\n      result: getResponse.returnValue,\n    };\n  }\n\n  throw new Error(`Transaction failed: ${getResponse.status}`);\n}\n\nasync function submitClassicTransaction(signedXdr: string) {\n  const transaction = StellarSdk.TransactionBuilder.fromXDR(\n    signedXdr,\n    config.networkPassphrase\n  ) as StellarSdk.Transaction;\n\n  const response = await horizon.submitTransaction(transaction);\n  return {\n    hash: response.hash,\n    ledger: response.ledger,\n  };\n}\n```\n\n## React Components\n\n### Connect Wallet Button\n```tsx\n\u002F\u002F components\u002FConnectButton.tsx\n\"use client\";\n\nimport { useFreighter } from \"@\u002Fhooks\u002FuseFreighter\";\n\nexport function ConnectButton() {\n  const { connected, address, connect, disconnect } = useFreighter();\n\n  if (connected && address) {\n    return (\n      \u003Cdiv className=\"flex items-center gap-2\">\n        \u003Cspan className=\"text-sm\">\n          {address.slice(0, 4)}...{address.slice(-4)}\n        \u003C\u002Fspan>\n        \u003Cbutton\n          onClick={disconnect}\n          className=\"px-4 py-2 bg-red-500 text-white rounded\"\n        >\n          Disconnect\n        \u003C\u002Fbutton>\n      \u003C\u002Fdiv>\n    );\n  }\n\n  return (\n    \u003Cbutton\n      onClick={connect}\n      className=\"px-4 py-2 bg-blue-500 text-white rounded\"\n    >\n      Connect Wallet\n    \u003C\u002Fbutton>\n  );\n}\n```\n\n### Send Payment Form\n```tsx\n\u002F\u002F components\u002FSendPayment.tsx\n\"use client\";\n\nimport { useState } from \"react\";\nimport { useFreighter } from \"@\u002Fhooks\u002FuseFreighter\";\nimport { buildPaymentTx, submitTransaction } from \"@\u002Flib\u002Ftransactions\";\nimport { config } from \"@\u002Flib\u002Fstellar\";\n\nexport function SendPayment() {\n  const { address, sign } = useFreighter();\n  const [destination, setDestination] = useState(\"\");\n  const [amount, setAmount] = useState(\"\");\n  const [status, setStatus] = useState\u003Cstring | null>(null);\n  const [loading, setLoading] = useState(false);\n\n  const handleSubmit = async (e: React.FormEvent) => {\n    e.preventDefault();\n    if (!address) return;\n\n    setLoading(true);\n    setStatus(\"Building transaction...\");\n\n    try {\n      const xdr = await buildPaymentTx(address, destination, amount);\n\n      setStatus(\"Please sign in your wallet...\");\n      const signedXdr = await sign(xdr, config.networkPassphrase);\n\n      setStatus(\"Submitting transaction...\");\n      const result = await submitTransaction(signedXdr);\n\n      setStatus(`Success! Hash: ${result.hash}`);\n    } catch (error) {\n      setStatus(`Error: ${error.message}`);\n    } finally {\n      setLoading(false);\n    }\n  };\n\n  return (\n    \u003Cform onSubmit={handleSubmit} className=\"space-y-4\">\n      \u003Cinput\n        type=\"text\"\n        placeholder=\"Destination Address\"\n        value={destination}\n        onChange={(e) => setDestination(e.target.value)}\n        className=\"w-full p-2 border rounded\"\n      \u002F>\n      \u003Cinput\n        type=\"text\"\n        placeholder=\"Amount (XLM)\"\n        value={amount}\n        onChange={(e) => setAmount(e.target.value)}\n        className=\"w-full p-2 border rounded\"\n      \u002F>\n      \u003Cbutton\n        type=\"submit\"\n        disabled={loading || !address}\n        className=\"w-full p-2 bg-blue-500 text-white rounded disabled:opacity-50\"\n      >\n        {loading ? \"Processing...\" : \"Send\"}\n      \u003C\u002Fbutton>\n      {status && \u003Cp className=\"text-sm\">{status}\u003C\u002Fp>}\n    \u003C\u002Fform>\n  );\n}\n```\n\n## Next.js App Router Setup\n\n### Provider Component\n```tsx\n\u002F\u002F app\u002Fproviders.tsx\n\"use client\";\n\nimport { ReactNode } from \"react\";\n\n\u002F\u002F Add any context providers here\nexport function Providers({ children }: { children: ReactNode }) {\n  return \u003C>{children}\u003C\u002F>;\n}\n```\n\n### Layout\n```tsx\n\u002F\u002F app\u002Flayout.tsx\nimport { Providers } from \".\u002Fproviders\";\n\nexport default function RootLayout({\n  children,\n}: {\n  children: React.ReactNode;\n}) {\n  return (\n    \u003Chtml lang=\"en\">\n      \u003Cbody>\n        \u003CProviders>{children}\u003C\u002FProviders>\n      \u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  );\n}\n```\n\n## Data Fetching\n\n### Account Balance\n```typescript\nimport { NotFoundError } from \"@stellar\u002Fstellar-sdk\";\nimport { horizon } from \"@\u002Flib\u002Fstellar\";\n\nexport async function getBalance(address: string) {\n  try {\n    const account = await horizon.loadAccount(address);\n    const nativeBalance = account.balances.find(\n      (b) => b.asset_type === \"native\"\n    );\n    return nativeBalance?.balance || \"0\";\n  } catch (error) {\n    \u002F\u002F loadAccount rejects with the typed NotFoundError for an unfunded account.\n    if (error instanceof NotFoundError) {\n      return \"0\"; \u002F\u002F Account not funded yet\n    }\n    throw error;\n  }\n}\n```\n\n> For submission failures, Horizon returns result codes under `error.response?.data?.extras?.result_codes` (`transaction` + per-`operation`). See [Handle Errors](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fguides\u002F05-handle-errors).\n\n### Contract State\n\nFor a read-only contract call, `rpc.Server` has one-line shortcuts that build the contract interface for you (including the built-in spec for Stellar Asset Contracts), so no client setup or manual ScVal work is needed:\n\n```typescript\nimport { rpc } from \"@\u002Flib\u002Fstellar\";\n\n\u002F\u002F Run a read-only method and get the decoded result directly.\nconst { result: balance, isReadCall } = await rpc.queryContract\u003Cbigint>(\n  tokenId,\n  \"balance\",\n  { id: \"G...\" } \u002F\u002F named args, keyed by parameter name; omit for no-arg methods\n);\n\n\u002F\u002F Discover a contract's callable methods from just its ID.\nconst methods = await rpc.getContractMethods(tokenId);\n\u002F\u002F [{ name: \"balance\", inputs: [{ name: \"id\", type: \"Address\" }], outputs: [\"I128\"] }, ...]\n```\n\n`isReadCall` is per-call: `false` means the `result` is only a simulation preview of a call that would change state (apply it by signing a transaction via `contract.Client`).\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>Advanced: read a raw ledger entry\u003C\u002Fb>\u003C\u002Fsummary>\n\nReach for `getLedgerEntries` only when you need a specific storage key that isn't exposed as a contract method.\n\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\nimport { rpc } from \"@\u002Flib\u002Fstellar\";\n\nexport async function getContractData(\n  contractId: string,\n  key: StellarSdk.xdr.ScVal\n) {\n  const ledgerKey = StellarSdk.xdr.LedgerKey.contractData(\n    new StellarSdk.xdr.LedgerKeyContractData({\n      contract: new StellarSdk.Address(contractId).toScAddress(),\n      key: key,\n      durability: StellarSdk.xdr.ContractDataDurability.persistent(),\n    })\n  );\n\n  const entries = await rpc.getLedgerEntries(ledgerKey);\n\n  if (entries.entries.length === 0) {\n    return null;\n  }\n\n  return StellarSdk.scValToNative(\n    entries.entries[0].val.contractData().val()\n  );\n}\n```\n\n\u003C\u002Fdetails>\n\n## Smart Accounts (Passkey Wallets)\n\nFor passwordless authentication using WebAuthn passkeys, use Smart Account Kit.\n\n### Installation\n```bash\nnpm install smart-account-kit\n```\n\n### Quick Start\n```typescript\nimport { SmartAccountKit, IndexedDBStorage } from 'smart-account-kit';\n\nconst kit = new SmartAccountKit({\n  rpcUrl: 'https:\u002F\u002Fsoroban-testnet.stellar.org',\n  networkPassphrase: 'Test SDF Network ; September 2015',\n  accountWasmHash: 'YOUR_ACCOUNT_WASM_HASH',\n  webauthnVerifierAddress: 'CWEBAUTHN_VERIFIER_ADDRESS',\n  storage: new IndexedDBStorage(),\n});\n\n\u002F\u002F On page load - silent restore from stored session\nconst result = await kit.connectWallet();\nif (!result) {\n  showConnectButton(); \u002F\u002F No stored session\n}\n\n\u002F\u002F Create new wallet with passkey\nconst { contractId, credentialId } = await kit.createWallet(\n  'My App',\n  'user@example.com',\n  { autoSubmit: true }\n);\n\n\u002F\u002F Connect to existing wallet (prompts for passkey)\nawait kit.connectWallet({ prompt: true });\n\n\u002F\u002F Sign and submit transactions\nconst result = await kit.signAndSubmit(transaction);\n\n\u002F\u002F Transfer tokens\nawait kit.transfer(tokenContract, recipient, amount);\n```\n\n### Key Features\n- **Session Management**: Automatic credential persistence and silent reconnection\n- **Multiple Signer Types**: Passkeys (secp256r1), Ed25519 keys, policies\n- **Context Rules**: Fine-grained authorization for different operations\n- **Policy Support**: Threshold multisig, spending limits, custom policies\n- **External Wallet Support**: Connect Freighter, LOBSTR via adapters\n- **Gasless Transactions**: Optional relayer integration for fee sponsoring\n\n### Fee Sponsorship with OpenZeppelin Relayer\n\nThe [OpenZeppelin Relayer](https:\u002F\u002Fdocs.openzeppelin.com\u002Frelayer\u002Fstellar) (also called Stellar Channels Service) handles gasless transaction submission. It replaces the deprecated Launchtube service and uses Stellar's native fee bump mechanism so users don't need XLM for fees.\n\n```typescript\nimport * as RPChannels from \"@openzeppelin\u002Frelayer-plugin-channels\";\n\nconst client = new RPChannels.ChannelsClient({\n  baseUrl: \"https:\u002F\u002Fchannels.openzeppelin.com\u002Ftestnet\",\n  apiKey: \"your-api-key\",\n});\n\n\u002F\u002F Submit a smart contract call with fee sponsorship\nconst response = await client.submitSorobanTransaction({\n  func: contractFunc,\n  auth: contractAuth,\n});\n```\n\n- **Testnet hosted instance**: `https:\u002F\u002Fchannels.openzeppelin.com\u002Ftestnet` (API keys at `\u002Fgen`)\n- **Production**: Self-host via Docker ([GitHub](https:\u002F\u002Fgithub.com\u002FOpenZeppelin\u002Fopenzeppelin-relayer))\n- **Stellar docs**: https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Ftools\u002Fopenzeppelin-relayer\n\n### Resources\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fkalepail\u002Fsmart-account-kit\n- **OpenZeppelin Contracts**: https:\u002F\u002Fgithub.com\u002FOpenZeppelin\u002Fstellar-contracts\n- **Legacy SDK**: https:\u002F\u002Fgithub.com\u002Fkalepail\u002Fpasskey-kit (for simpler use cases)\n\n## Transaction UX Checklist\n\n- [ ] Show loading state during wallet signing\n- [ ] Display transaction hash immediately after submission\n- [ ] Track confirmation status (pending → success\u002Ffailed)\n- [ ] Handle common errors with clear messages:\n  - Wallet not connected\n  - User rejected signing\n  - Insufficient XLM for fees\n  - Account not funded\n  - Network mismatch (wallet on wrong network)\n  - Transaction timeout\u002Fexpired\n- [ ] Prevent double-submission while processing\n- [ ] Show destination and amount before signing\n","# Stellar dApp \u002F Frontend\n\nClient-side development with `@stellar\u002Fstellar-sdk`, wallet connection, signing, and submitting transactions. Covers both classic Stellar operations and smart contract invocation from the browser or Node.js.\n\n## When to use this skill\n- Connecting Freighter or other wallets via Stellar Wallets Kit\n- Building, simulating, signing, and submitting transactions\n- Invoking Stellar smart contracts from a frontend\n- Implementing smart accounts with passkeys\n- Handling network passphrases (Mainnet \u002F Testnet \u002F local)\n\n## Related skills\n- Writing the contract being invoked → `..\u002Fsmart-contracts\u002FSKILL.md`\n- Issuing assets and managing trustlines → `..\u002Fassets\u002FSKILL.md`\n- Querying chain state via RPC \u002F Horizon → `..\u002Fdata\u002FSKILL.md`\n- Building paid APIs or agent payment clients → `..\u002Fagentic-payments\u002FSKILL.md`\n- SEPs the wallet\u002Fanchor flows depend on → `..\u002Fstandards\u002FSKILL.md`\n\n---\n\n\n## Goals\n- Single SDK instance for the app (RPC\u002FHorizon + transaction building)\n- Freighter wallet integration (or multi-wallet via Stellar Wallets Kit)\n- Clean separation of client\u002Fserver in Next.js\n- Transaction sending with proper confirmation handling\n\n## Quick Navigation\n- SDK setup and env config: [SDK Initialization](#sdk-initialization)\n- Wallet integrations: [Wallet Integration](#wallet-integration)\n- Tx build\u002Fsend patterns: [Transaction Building](#transaction-building), [Transaction Submission](#transaction-submission)\n- React + Next.js patterns: [React Components](#react-components), [Next.js App Router Setup](#nextjs-app-router-setup)\n- Smart wallets\u002Fpasskeys: [Smart Accounts (Passkey Wallets)](#smart-accounts-passkey-wallets)\n- Production UX checklist: [Transaction UX Checklist](#transaction-ux-checklist)\n\n## Recommended Dependencies\n\n> **Requires Node.js 22+.** As of SDK v16, Node 22 is the minimum (older Node produces an `EBADENGINE` warning). v16 also folded `@stellar\u002Fstellar-base` into `@stellar\u002Fstellar-sdk`, is ESM-first, and uses native `fetch` instead of axios. If you still import `@stellar\u002Fstellar-base` directly, switch the import to `@stellar\u002Fstellar-sdk` and uninstall the base package (keeping both breaks `instanceof` checks). See the [migration guide](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fguides\u002F00-migration).\n\n```bash\nnpm install @stellar\u002Fstellar-sdk @stellar\u002Ffreighter-api\n# Or for multi-wallet support - Wallets Kit v2 is distributed on JSR, not npm:\nnpx jsr add @creit-tech\u002Fstellar-wallets-kit\n```\n\n> **Sourcing:** SDK mechanics below (init, transaction building, contract invocation, submission, data fetching, error handling) track the official [JS SDK docs](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002F) (which also publish [`llms.txt`](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fllms.txt) \u002F [`llms-full.txt`](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fllms-full.txt) bundles for agents). Wallet integrations (Freighter, Stellar Wallets Kit), passkey smart accounts, and the OpenZeppelin relayer are separate packages, not part of the JS SDK - verify those against their own upstream docs.\n\n## SDK Initialization\n\n> For the full API reference (RPC methods, Horizon endpoints, migration guide), see the [data skill](..\u002Fdata\u002FSKILL.md).\n\n### Basic Setup\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\n\u002F\u002F For Testnet\nconst testnetServer = new StellarSdk.Horizon.Server(\"https:\u002F\u002Fhorizon-testnet.stellar.org\");\nconst testnetRpc = new StellarSdk.rpc.Server(\"https:\u002F\u002Fsoroban-testnet.stellar.org\");\nconst testnetNetworkPassphrase = StellarSdk.Networks.TESTNET;\n\n\u002F\u002F For Mainnet\nconst mainnetServer = new StellarSdk.Horizon.Server(\"https:\u002F\u002Fhorizon.stellar.org\");\nconst mainnetRpcUrl = process.env.NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL;\nif (!mainnetRpcUrl) throw new Error(\"Missing NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL\");\nconst mainnetRpc = new StellarSdk.rpc.Server(mainnetRpcUrl); \u002F\u002F set from your chosen RPC provider\nconst mainnetNetworkPassphrase = StellarSdk.Networks.PUBLIC;\n```\n\n### Environment Configuration\n> Use a provider-specific mainnet RPC URL (see: https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fdata\u002Fapis\u002Frpc\u002Fproviders).\n\n```typescript\n\u002F\u002F lib\u002Fstellar.ts\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\nconst NETWORK = process.env.NEXT_PUBLIC_STELLAR_NETWORK || \"testnet\";\n\nconst requireEnv = (name: string): string => {\n  const value = process.env[name];\n  if (!value) throw new Error(`Missing required env var: ${name}`);\n  return value;\n};\n\nfunction getConfig(network: string) {\n  switch (network) {\n    case \"testnet\":\n      return {\n        horizonUrl: \"https:\u002F\u002Fhorizon-testnet.stellar.org\",\n        rpcUrl: \"https:\u002F\u002Fsoroban-testnet.stellar.org\",\n        networkPassphrase: StellarSdk.Networks.TESTNET,\n        friendbotUrl: \"https:\u002F\u002Ffriendbot.stellar.org\" as string | null,\n      };\n    case \"mainnet\":\n      return {\n        horizonUrl: \"https:\u002F\u002Fhorizon.stellar.org\",\n        \u002F\u002F Resolved lazily so testnet runs don't require the mainnet env var\n        rpcUrl: requireEnv(\"NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL\"),\n        networkPassphrase: StellarSdk.Networks.PUBLIC,\n        friendbotUrl: null,\n      };\n    default:\n      throw new Error(`Unknown network: ${network}`);\n  }\n}\n\nexport const config = getConfig(NETWORK);\n\nexport const horizon = new StellarSdk.Horizon.Server(config.horizonUrl);\nexport const rpc = new StellarSdk.rpc.Server(config.rpcUrl);\n```\n\n## Wallet Integration\n\n### Freighter (Primary Browser Wallet)\n```typescript\n\u002F\u002F hooks\u002FuseFreighter.ts\nimport { useState, useEffect, useCallback } from \"react\";\nimport {\n  isConnected,\n  getAddress,\n  requestAccess,\n  signTransaction,\n  getNetwork,\n} from \"@stellar\u002Ffreighter-api\";\n\nexport function useFreighter() {\n  const [connected, setConnected] = useState(false);\n  const [address, setAddress] = useState\u003Cstring | null>(null);\n  const [network, setNetwork] = useState\u003Cstring | null>(null);\n\n  useEffect(() => {\n    checkConnection();\n  }, []);\n\n  const checkConnection = async () => {\n    const { isConnected: installed, error } = await isConnected();\n    if (error || !installed) return;\n\n    \u002F\u002F getAddress returns address: \"\" until the app has been granted access,\n    \u002F\u002F so a non-empty address means we're already authorized.\n    const { address: addr, error: addressError } = await getAddress();\n    if (addressError || !addr) return;\n\n    const { network: net, error: networkError } = await getNetwork();\n    if (networkError) return;\n    setConnected(true);\n    setAddress(addr);\n    setNetwork(net);\n  };\n\n  const connect = useCallback(async () => {\n    const { isConnected: installed, error } = await isConnected();\n    if (error || !installed) {\n      throw new Error(\"Freighter extension not installed\");\n    }\n\n    \u002F\u002F requestAccess prompts the user and returns the granted address.\n    const { address: addr, error: accessError } = await requestAccess();\n    if (accessError) throw new Error(accessError.message);\n\n    const { network: net, error: networkError } = await getNetwork();\n    if (networkError) throw new Error(networkError.message);\n    setConnected(true);\n    setAddress(addr);\n    setNetwork(net);\n\n    return addr;\n  }, []);\n\n  const disconnect = useCallback(() => {\n    setConnected(false);\n    setAddress(null);\n    setNetwork(null);\n  }, []);\n\n  const sign = useCallback(\n    async (xdr: string, networkPassphrase: string) => {\n      if (!connected) throw new Error(\"Wallet not connected\");\n      const { signedTxXdr, error } = await signTransaction(xdr, {\n        networkPassphrase,\n      });\n      if (error) throw new Error(error.message);\n      return signedTxXdr;\n    },\n    [connected]\n  );\n\n  return { connected, address, network, connect, disconnect, sign };\n}\n```\n\n### Stellar Wallets Kit (Multi-Wallet)\n\n```typescript\n\u002F\u002F hooks\u002FuseStellarWallet.ts\nimport { useState, useCallback } from \"react\";\nimport { StellarWalletsKit, Networks } from \"@creit-tech\u002Fstellar-wallets-kit\";\nimport { defaultModules } from \"@creit-tech\u002Fstellar-wallets-kit\u002Fmodules\u002Futils\";\n\n\u002F\u002F v2 is a static singleton: init once at module load, then call static methods -\n\u002F\u002F there is no instance to construct or pass around.\n\u002F\u002F defaultModules() loads every wallet that needs no extra setup; modules with\n\u002F\u002F prerequisites (WalletConnect, Ledger, Trezor) must be imported and added explicitly.\nStellarWalletsKit.init({\n  modules: defaultModules(),\n  network: Networks.TESTNET,\n});\n\nexport function useStellarWallet() {\n  const [address, setAddress] = useState\u003Cstring | null>(null);\n\n  const connect = useCallback(async () => {\n    \u002F\u002F authModal() opens the wallet picker, sets the chosen module active,\n    \u002F\u002F and returns the address - one call replaces v1's openModal callback dance.\n    const { address } = await StellarWalletsKit.authModal();\n    setAddress(address);\n  }, []);\n\n  const disconnect = useCallback(async () => {\n    await StellarWalletsKit.disconnect();\n    setAddress(null);\n  }, []);\n\n  const sign = useCallback(async (xdr: string) => {\n    const { signedTxXdr } = await StellarWalletsKit.signTransaction(xdr);\n    return signedTxXdr;\n  }, []);\n\n  return { address, connect, disconnect, sign };\n}\n```\n\n> **Migrating from v1?** (noted July 2026) v1 lived on npm under the dotted scope `@creit.tech\u002Fstellar-wallets-kit`, with `new StellarWalletsKit({...})`, `allowAllModules()`, and `openModal({ onWalletSelected })`. v2 moved to JSR under `@creit-tech\u002Fstellar-wallets-kit`, made the kit fully static, replaced `allowAllModules()` with `defaultModules()`, and folded wallet selection + address fetch into `authModal()`. npm parity is maintained for now, but the maintainers say npm updates will eventually stop - install from JSR. Pre-selecting a wallet (`setWallet(FREIGHTER_ID)`) still works; the ID constants now live in per-wallet module subpaths like `@creit-tech\u002Fstellar-wallets-kit\u002Fmodules\u002Ffreighter`.\n\n## Transaction Building\n\n### Basic Payment\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\nimport { horizon, config } from \"@\u002Flib\u002Fstellar\";\n\nexport async function buildPaymentTx(\n  sourceAddress: string,\n  destinationAddress: string,\n  amount: string,\n  asset: StellarSdk.Asset = StellarSdk.Asset.native()\n) {\n  const account = await horizon.loadAccount(sourceAddress);\n\n  const transaction = new StellarSdk.TransactionBuilder(account, {\n    fee: StellarSdk.BASE_FEE,\n    networkPassphrase: config.networkPassphrase,\n  })\n    .addOperation(\n      StellarSdk.Operation.payment({\n        destination: destinationAddress,\n        asset: asset,\n        amount: amount,\n      })\n    )\n    .setTimeout(180)\n    .build();\n\n  return transaction.toXDR();\n}\n```\n\n### Smart Contract Invocation (`contract.Client`)\n\nThe canonical way to call a Soroban contract from JS is the `contract.Client`, not hand-built `Contract.call` + `assembleTransaction`. The client reads the contract's interface from the network, so each method is callable by name and returns an `AssembledTransaction`. You get a native JS result and don't build ScVals by hand.\n\n```typescript\nimport { contract } from \"@stellar\u002Fstellar-sdk\";\nimport { config } from \"@\u002Flib\u002Fstellar\";\n\n\u002F\u002F Describe just the methods you call. `Client.from\u003CT>()` uses this to type\n\u002F\u002F the returned client, so calls are checked and autocompleted - no codegen.\n\u002F\u002F For a contract with many methods, generate this interface from its spec\n\u002F\u002F with the SDK's binding CLI instead of writing it by hand.\ninterface CounterContract {\n  increment: (\n    options?: contract.MethodOptions,\n  ) => Promise\u003Ccontract.AssembledTransaction\u003Cnumber>>;\n}\n\n\u002F\u002F `signTransaction` comes from the wallet (e.g. Freighter\u002FWallets Kit in the\n\u002F\u002F browser). `contract.basicNodeSigner(keypair, networkPassphrase)` is the\n\u002F\u002F Node equivalent for scripts and tests.\nexport async function getCounterClient(\n  contractId: string,\n  publicKey: string,\n  signTransaction: contract.ClientOptions[\"signTransaction\"],\n) {\n  return contract.Client.from\u003CCounterContract>({\n    contractId,\n    rpcUrl: config.rpcUrl,\n    networkPassphrase: config.networkPassphrase,\n    publicKey,\n    signTransaction,\n  });\n}\n\n\u002F\u002F Preview (free simulation) then sign + send to apply on-chain.\nexport async function increment(client: contract.Client & CounterContract) {\n  const tx = await client.increment();\n  console.log(\"preview:\", tx.result); \u002F\u002F predicted return value, no signature\n  const sent = await tx.signAndSend(); \u002F\u002F submits and polls to completion\n  return sent.result;\n}\n```\n\n`AssembledTransaction` also supports fine-grained control (`{ fee, simulate, timeoutInSeconds }` as a second arg) and multi-party auth via `tx.needsNonInvokerSigningBy()` \u002F `tx.signAuthEntries()`. See [Invoke a Contract](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fguides\u002F06-invoke-a-contract) and [Authorize a Contract Call](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fguides\u002F07-contract-auth).\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>Advanced: low-level invocation without a client\u003C\u002Fb>\u003C\u002Fsummary>\n\nUse this only when you need direct control over the transaction (e.g. batching a contract call with classic operations). Otherwise prefer `contract.Client` above.\n\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\nimport { rpc, config } from \"@\u002Flib\u002Fstellar\";\n\nexport async function invokeContract(\n  sourceAddress: string,\n  contractId: string,\n  method: string,\n  args: StellarSdk.xdr.ScVal[]\n) {\n  const account = await rpc.getAccount(sourceAddress);\n  const contract = new StellarSdk.Contract(contractId);\n\n  const transaction = new StellarSdk.TransactionBuilder(account, {\n    fee: StellarSdk.BASE_FEE,\n    networkPassphrase: config.networkPassphrase,\n  })\n    .addOperation(contract.call(method, ...args))\n    .setTimeout(180)\n    .build();\n\n  \u002F\u002F `prepareTransaction` simulates and applies footprint\u002Fauth\u002Ffees in one step.\n  \u002F\u002F (Equivalent to simulateTransaction + rpc.assembleTransaction.)\n  const prepared = await rpc.prepareTransaction(transaction);\n  return prepared.toXDR();\n}\n```\n\n**Building ScVal arguments by hand** (only needed for the low-level path - `contract.Client` converts native JS args for you):\n\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\nconst addressVal = StellarSdk.Address.fromString(address).toScVal();\nconst i128Val = StellarSdk.nativeToScVal(BigInt(amount), { type: \"i128\" });\nconst u32Val = StellarSdk.nativeToScVal(42, { type: \"u32\" });\nconst stringVal = StellarSdk.nativeToScVal(\"hello\", { type: \"string\" });\nconst symbolVal = StellarSdk.nativeToScVal(\"transfer\", { type: \"symbol\" });\n\n\u002F\u002F Struct\nconst structVal = StellarSdk.nativeToScVal(\n  { name: \"Token\", decimals: 7 },\n  {\n    type: {\n      name: [\"symbol\", null],\n      decimals: [\"u32\", null],\n    },\n  }\n);\n\n\u002F\u002F Vec of i128 - the element type is applied to each item\nconst vecVal = StellarSdk.nativeToScVal(\n  [1, 2, 3].map((n) => BigInt(n)),\n  { type: \"i128\" }\n);\n```\n\n\u003C\u002Fdetails>\n\n## Transaction Submission\n\n### Submit and Wait for Confirmation\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\nimport { rpc, horizon, config } from \"@\u002Flib\u002Fstellar\";\n\nexport async function submitTransaction(signedXdr: string) {\n  const transaction = StellarSdk.TransactionBuilder.fromXDR(\n    signedXdr,\n    config.networkPassphrase\n  );\n\n  \u002F\u002F For smart contract transactions, use RPC\n  if (transaction.operations.some(op => op.type === \"invokeHostFunction\")) {\n    return submitSorobanTransaction(signedXdr);\n  }\n\n  \u002F\u002F For classic transactions, use Horizon\n  return submitClassicTransaction(signedXdr);\n}\n\nasync function submitSorobanTransaction(signedXdr: string) {\n  const transaction = StellarSdk.TransactionBuilder.fromXDR(\n    signedXdr,\n    config.networkPassphrase\n  ) as StellarSdk.Transaction;\n\n  const response = await rpc.sendTransaction(transaction);\n\n  if (response.status === \"ERROR\") {\n    throw new Error(`Send failed: ${response.errorResult}`);\n  }\n\n  \u002F\u002F Poll for completion. pollTransaction handles the retry loop (default 5\n  \u002F\u002F attempts, 1s apart - tune with { attempts, sleepStrategy }) instead of a\n  \u002F\u002F hand-rolled while loop that can spin forever.\n  const getResponse = await rpc.pollTransaction(response.hash);\n\n  if (getResponse.status === \"SUCCESS\") {\n    return {\n      hash: response.hash,\n      result: getResponse.returnValue,\n    };\n  }\n\n  throw new Error(`Transaction failed: ${getResponse.status}`);\n}\n\nasync function submitClassicTransaction(signedXdr: string) {\n  const transaction = StellarSdk.TransactionBuilder.fromXDR(\n    signedXdr,\n    config.networkPassphrase\n  ) as StellarSdk.Transaction;\n\n  const response = await horizon.submitTransaction(transaction);\n  return {\n    hash: response.hash,\n    ledger: response.ledger,\n  };\n}\n```\n\n## React Components\n\n### Connect Wallet Button\n```tsx\n\u002F\u002F components\u002FConnectButton.tsx\n\"use client\";\n\nimport { useFreighter } from \"@\u002Fhooks\u002FuseFreighter\";\n\nexport function ConnectButton() {\n  const { connected, address, connect, disconnect } = useFreighter();\n\n  if (connected && address) {\n    return (\n      \u003Cdiv className=\"flex items-center gap-2\">\n        \u003Cspan className=\"text-sm\">\n          {address.slice(0, 4)}...{address.slice(-4)}\n        \u003C\u002Fspan>\n        \u003Cbutton\n          onClick={disconnect}\n          className=\"px-4 py-2 bg-red-500 text-white rounded\"\n        >\n          Disconnect\n        \u003C\u002Fbutton>\n      \u003C\u002Fdiv>\n    );\n  }\n\n  return (\n    \u003Cbutton\n      onClick={connect}\n      className=\"px-4 py-2 bg-blue-500 text-white rounded\"\n    >\n      Connect Wallet\n    \u003C\u002Fbutton>\n  );\n}\n```\n\n### Send Payment Form\n```tsx\n\u002F\u002F components\u002FSendPayment.tsx\n\"use client\";\n\nimport { useState } from \"react\";\nimport { useFreighter } from \"@\u002Fhooks\u002FuseFreighter\";\nimport { buildPaymentTx, submitTransaction } from \"@\u002Flib\u002Ftransactions\";\nimport { config } from \"@\u002Flib\u002Fstellar\";\n\nexport function SendPayment() {\n  const { address, sign } = useFreighter();\n  const [destination, setDestination] = useState(\"\");\n  const [amount, setAmount] = useState(\"\");\n  const [status, setStatus] = useState\u003Cstring | null>(null);\n  const [loading, setLoading] = useState(false);\n\n  const handleSubmit = async (e: React.FormEvent) => {\n    e.preventDefault();\n    if (!address) return;\n\n    setLoading(true);\n    setStatus(\"Building transaction...\");\n\n    try {\n      const xdr = await buildPaymentTx(address, destination, amount);\n\n      setStatus(\"Please sign in your wallet...\");\n      const signedXdr = await sign(xdr, config.networkPassphrase);\n\n      setStatus(\"Submitting transaction...\");\n      const result = await submitTransaction(signedXdr);\n\n      setStatus(`Success! Hash: ${result.hash}`);\n    } catch (error) {\n      setStatus(`Error: ${error.message}`);\n    } finally {\n      setLoading(false);\n    }\n  };\n\n  return (\n    \u003Cform onSubmit={handleSubmit} className=\"space-y-4\">\n      \u003Cinput\n        type=\"text\"\n        placeholder=\"Destination Address\"\n        value={destination}\n        onChange={(e) => setDestination(e.target.value)}\n        className=\"w-full p-2 border rounded\"\n      \u002F>\n      \u003Cinput\n        type=\"text\"\n        placeholder=\"Amount (XLM)\"\n        value={amount}\n        onChange={(e) => setAmount(e.target.value)}\n        className=\"w-full p-2 border rounded\"\n      \u002F>\n      \u003Cbutton\n        type=\"submit\"\n        disabled={loading || !address}\n        className=\"w-full p-2 bg-blue-500 text-white rounded disabled:opacity-50\"\n      >\n        {loading ? \"Processing...\" : \"Send\"}\n      \u003C\u002Fbutton>\n      {status && \u003Cp className=\"text-sm\">{status}\u003C\u002Fp>}\n    \u003C\u002Fform>\n  );\n}\n```\n\n## Next.js App Router Setup\n\n### Provider Component\n```tsx\n\u002F\u002F app\u002Fproviders.tsx\n\"use client\";\n\nimport { ReactNode } from \"react\";\n\n\u002F\u002F Add any context providers here\nexport function Providers({ children }: { children: ReactNode }) {\n  return \u003C>{children}\u003C\u002F>;\n}\n```\n\n### Layout\n```tsx\n\u002F\u002F app\u002Flayout.tsx\nimport { Providers } from \".\u002Fproviders\";\n\nexport default function RootLayout({\n  children,\n}: {\n  children: React.ReactNode;\n}) {\n  return (\n    \u003Chtml lang=\"en\">\n      \u003Cbody>\n        \u003CProviders>{children}\u003C\u002FProviders>\n      \u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  );\n}\n```\n\n## Data Fetching\n\n### Account Balance\n```typescript\nimport { NotFoundError } from \"@stellar\u002Fstellar-sdk\";\nimport { horizon } from \"@\u002Flib\u002Fstellar\";\n\nexport async function getBalance(address: string) {\n  try {\n    const account = await horizon.loadAccount(address);\n    const nativeBalance = account.balances.find(\n      (b) => b.asset_type === \"native\"\n    );\n    return nativeBalance?.balance || \"0\";\n  } catch (error) {\n    \u002F\u002F loadAccount rejects with the typed NotFoundError for an unfunded account.\n    if (error instanceof NotFoundError) {\n      return \"0\"; \u002F\u002F Account not funded yet\n    }\n    throw error;\n  }\n}\n```\n\n> For submission failures, Horizon returns result codes under `error.response?.data?.extras?.result_codes` (`transaction` + per-`operation`). See [Handle Errors](https:\u002F\u002Fstellar.github.io\u002Fjs-stellar-sdk\u002Fguides\u002F05-handle-errors).\n\n### Contract State\n\nFor a read-only contract call, `rpc.Server` has one-line shortcuts that build the contract interface for you (including the built-in spec for Stellar Asset Contracts), so no client setup or manual ScVal work is needed:\n\n```typescript\nimport { rpc } from \"@\u002Flib\u002Fstellar\";\n\n\u002F\u002F Run a read-only method and get the decoded result directly.\nconst { result: balance, isReadCall } = await rpc.queryContract\u003Cbigint>(\n  tokenId,\n  \"balance\",\n  { id: \"G...\" } \u002F\u002F named args, keyed by parameter name; omit for no-arg methods\n);\n\n\u002F\u002F Discover a contract's callable methods from just its ID.\nconst methods = await rpc.getContractMethods(tokenId);\n\u002F\u002F [{ name: \"balance\", inputs: [{ name: \"id\", type: \"Address\" }], outputs: [\"I128\"] }, ...]\n```\n\n`isReadCall` is per-call: `false` means the `result` is only a simulation preview of a call that would change state (apply it by signing a transaction via `contract.Client`).\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>Advanced: read a raw ledger entry\u003C\u002Fb>\u003C\u002Fsummary>\n\nReach for `getLedgerEntries` only when you need a specific storage key that isn't exposed as a contract method.\n\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\nimport { rpc } from \"@\u002Flib\u002Fstellar\";\n\nexport async function getContractData(\n  contractId: string,\n  key: StellarSdk.xdr.ScVal\n) {\n  const ledgerKey = StellarSdk.xdr.LedgerKey.contractData(\n    new StellarSdk.xdr.LedgerKeyContractData({\n      contract: new StellarSdk.Address(contractId).toScAddress(),\n      key: key,\n      durability: StellarSdk.xdr.ContractDataDurability.persistent(),\n    })\n  );\n\n  const entries = await rpc.getLedgerEntries(ledgerKey);\n\n  if (entries.entries.length === 0) {\n    return null;\n  }\n\n  return StellarSdk.scValToNative(\n    entries.entries[0].val.contractData().val()\n  );\n}\n```\n\n\u003C\u002Fdetails>\n\n## Smart Accounts (Passkey Wallets)\n\nFor passwordless authentication using WebAuthn passkeys, use Smart Account Kit.\n\n### Installation\n```bash\nnpm install smart-account-kit\n```\n\n### Quick Start\n```typescript\nimport { SmartAccountKit, IndexedDBStorage } from 'smart-account-kit';\n\nconst kit = new SmartAccountKit({\n  rpcUrl: 'https:\u002F\u002Fsoroban-testnet.stellar.org',\n  networkPassphrase: 'Test SDF Network ; September 2015',\n  accountWasmHash: 'YOUR_ACCOUNT_WASM_HASH',\n  webauthnVerifierAddress: 'CWEBAUTHN_VERIFIER_ADDRESS',\n  storage: new IndexedDBStorage(),\n});\n\n\u002F\u002F On page load - silent restore from stored session\nconst result = await kit.connectWallet();\nif (!result) {\n  showConnectButton(); \u002F\u002F No stored session\n}\n\n\u002F\u002F Create new wallet with passkey\nconst { contractId, credentialId } = await kit.createWallet(\n  'My App',\n  'user@example.com',\n  { autoSubmit: true }\n);\n\n\u002F\u002F Connect to existing wallet (prompts for passkey)\nawait kit.connectWallet({ prompt: true });\n\n\u002F\u002F Sign and submit transactions\nconst result = await kit.signAndSubmit(transaction);\n\n\u002F\u002F Transfer tokens\nawait kit.transfer(tokenContract, recipient, amount);\n```\n\n### Key Features\n- **Session Management**: Automatic credential persistence and silent reconnection\n- **Multiple Signer Types**: Passkeys (secp256r1), Ed25519 keys, policies\n- **Context Rules**: Fine-grained authorization for different operations\n- **Policy Support**: Threshold multisig, spending limits, custom policies\n- **External Wallet Support**: Connect Freighter, LOBSTR via adapters\n- **Gasless Transactions**: Optional relayer integration for fee sponsoring\n\n### Fee Sponsorship with OpenZeppelin Relayer\n\nThe [OpenZeppelin Relayer](https:\u002F\u002Fdocs.openzeppelin.com\u002Frelayer\u002Fstellar) (also called Stellar Channels Service) handles gasless transaction submission. It replaces the deprecated Launchtube service and uses Stellar's native fee bump mechanism so users don't need XLM for fees.\n\n```typescript\nimport * as RPChannels from \"@openzeppelin\u002Frelayer-plugin-channels\";\n\nconst client = new RPChannels.ChannelsClient({\n  baseUrl: \"https:\u002F\u002Fchannels.openzeppelin.com\u002Ftestnet\",\n  apiKey: \"your-api-key\",\n});\n\n\u002F\u002F Submit a smart contract call with fee sponsorship\nconst response = await client.submitSorobanTransaction({\n  func: contractFunc,\n  auth: contractAuth,\n});\n```\n\n- **Testnet hosted instance**: `https:\u002F\u002Fchannels.openzeppelin.com\u002Ftestnet` (API keys at `\u002Fgen`)\n- **Production**: Self-host via Docker ([GitHub](https:\u002F\u002Fgithub.com\u002FOpenZeppelin\u002Fopenzeppelin-relayer))\n- **Stellar docs**: https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Ftools\u002Fopenzeppelin-relayer\n\n### Resources\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fkalepail\u002Fsmart-account-kit\n- **OpenZeppelin Contracts**: https:\u002F\u002Fgithub.com\u002FOpenZeppelin\u002Fstellar-contracts\n- **Legacy SDK**: https:\u002F\u002Fgithub.com\u002Fkalepail\u002Fpasskey-kit (for simpler use cases)\n\n## Transaction UX Checklist\n\n- [ ] Show loading state during wallet signing\n- [ ] Display transaction hash immediately after submission\n- [ ] Track confirmation status (pending → success\u002Ffailed)\n- [ ] Handle common errors with clear messages:\n  - Wallet not connected\n  - User rejected signing\n  - Insufficient XLM for fees\n  - Account not funded\n  - Network mismatch (wallet on wrong network)\n  - Transaction timeout\u002Fexpired\n- [ ] Prevent double-submission while processing\n- [ ] Show destination and amount before signing\n",{"name":5,"description":7,"argument-hint":23,"user-invocable":24},"[dapp task]",true,"main","e65f7386cd18b47d7a784711244666ba0bd61615",".codex\u002Fskills\u002Fdapp",2,"https:\u002F\u002Fgithub.com\u002FLumenWipe\u002Flumenwipe","https:\u002F\u002Fwww.lumenwipe.com","https:\u002F\u002Fgithub.com\u002FLumenWipe","https:\u002F\u002Flumenwipe.com","Infrastructure for closing Stellar accounts and recovering the XLM locked in their reserves","2026-11-15 03:49:47",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":24},[37,40,43],{"tool":38,"command":39},"npx","npx skills add LumenWipe\u002Flumenwipe --skill dapp",{"tool":41,"command":42},"bunx","bunx skills add LumenWipe\u002Flumenwipe --skill dapp",{"tool":44,"command":45},"pnpm","pnpm dlx skills add LumenWipe\u002Flumenwipe --skill dapp","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLumenWipe\u002Flumenwipe\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdapp\u002FSKILL.md",[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M72T06QQJYT961FXT1SAVQ8E","zk-proofs","Zero-knowledge proofs and privacy patterns on Stellar. Covers Groth16 verification in smart contracts via BLS12-381 host functions (CAP-0059, available), the BN254 + Poseidon proposals (CAP-0074\u002F0075, status-sensitive), and concrete toolchain walkthroughs for Circom (on-chain verifiable today), Noir, and RISC Zero (attestation pattern until BN254 lands). Use when building privacy-preserving applications, ZK-verifier contracts, or wiring a proving toolchain to Stellar.","https:\u002F\u002Fgithub.com\u002FLumenWipe\u002Flumenwipe\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fzk-proofs\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":18},"01M72T02TZBBW0STY8VJMX8FP0","tyler-architect","System architect and technical design leader. Use when the user asks to talk to Tyler or requests the architect.","https:\u002F\u002Fgithub.com\u002FLumenWipe\u002Flumenwipe\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Ftyler-architect\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":18},"01M72T00FVQP0RKW7QGB89QK1N","stellar-help","Analyzes current state and user query to answer BMad questions or recommend the next skill(s) to use. Use when user asks for help, bmad help, what to do next, or what to start with in BMad.","https:\u002F\u002Fgithub.com\u002FLumenWipe\u002Flumenwipe\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fstellar-help\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":18},"01M72SZSK5VQTTAW4DZT89R3B1","stellar-competitive-landscape","Map the competitive landscape for a Stellar project idea. Use when a user says \"who are my competitors on Stellar\", \"competitive analysis Stellar\", \"what already exists in this space on Stellar\", \"show me similar Stellar projects\", \"is anyone else building this on Stellar\", or \"map the Stellar landscape for X\". Queries the 728-project LumenLoop ecosystem database and Electric Capital developer activity to rank competitors by SCF funding history and repo activity.","https:\u002F\u002Fgithub.com\u002FLumenWipe\u002Flumenwipe\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fstellar-competitive-landscape\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":18},"01M72SZKTXT2Q3K1HX80S58SY4","standards","Stellar standards, ecosystem, and reference. Covers SEPs (Stellar Ecosystem Proposals), CAPs (Core Advancement Proposals), and a quick map for picking the right standard for wallets, anchors, payments, deposits\u002Fwithdrawals, federation, deep links, and KYC. Also bundles ecosystem references (DeFi protocols, dev tools, wallets, infra, community projects), curated documentation links, and MCP servers (live tools such as Raven). Use when you need to know which SEP applies, or want a starting point for ecosystem integrations, official docs, or live MCP tooling.","https:\u002F\u002Fgithub.com\u002FLumenWipe\u002Flumenwipe\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fstandards\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":18},"01M72SZDKFNPQXE9EX2Z7S8KRF","smart-contracts","Stellar smart contract development (Rust, soroban-sdk). Entry point with project setup, contract anatomy, and build\u002Fdeploy workflow, routing to three companion files in this directory - development.md (storage\u002FTTL, authorization, cross-contract calls, tokens, events, errors, upgrades, fees, troubleshooting), testing.md (unit, fuzz, property, fork, mutation, integration), and security.md (vulnerability classes, checklists, tooling, audits). Use when writing, testing, reviewing, securing, debugging, or shipping Stellar smart contracts, including anything the user calls \"Soroban\" - Soroban contracts, soroban-sdk, Soroban auth\u002Fstorage\u002FTTL errors, SEP-41 tokens, or SAC integration from contract code.","https:\u002F\u002Fgithub.com\u002FLumenWipe\u002Flumenwipe\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fsmart-contracts\u002FSKILL.md",[],[]]