[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GPYGXMWK08F3Y21G7SV7TY":3,"skill-same:01M6GPYGXMWK08F3Y21G7SV7TY":89},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":43,"linkOnly":44,"markdownContent":45,"markdownBody":46,"frontMatter":47,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":55,"repositoryHtmlUrl":56,"repositoryHomepageUrl":6,"ownerHtmlUrl":57,"ownerBlogUrl":58,"ownerDescription":59,"updatedAt":60,"install":61,"resources":74},"01M6GPYGXMWK08F3Y21G7SV7TY","wallet-integration",null,"Integrate an external wallet (signer) into an IC dapp with @icp-sdk\u002Fsigner — the relying-party side of the ICRC signer standards. Covers picking a transport (popup via ICRC-29 \u002F top-level redirect via ICRC-167 \u002F browser extension via ICRC-94) then negotiating capabilities, the permission and account lifecycle, and executing canister calls the user approves through SignerAgent (ICRC-49). Uses OISY as the worked example but applies to any ICRC-25 signer. Do NOT use for Internet Identity login (use the user-sign-in skill) or for implementing a wallet yourself. Use when the developer mentions wallet integration or OISY or @icp-sdk\u002Fsigner or approving a transaction in a wallet popup.","jiayaoqijia\u002Fcryptoskill","jiayaoqijia","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1453879?v=4","01M6GMYTX7Q7S504VC6E756ENR","YQ","01M6GMYV1QKJ1CC75MTTGT9PR0",81,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-wallet-integration\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-wallet-integration\u002FSKILL.md",[],[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42],"wallet integration","integration","Wallet","login","when","implementing","standards","developer","context","identity","defi","but","integrate","permission","node","secure","top","browser extension","browser","capabilities","internet","icp","dapp","2026-11-10 10:12:30",false,"---\nname: wallet-integration\ndescription: \"Integrate an external wallet (signer) into an IC dapp with @icp-sdk\u002Fsigner — the relying-party side of the ICRC signer standards. Covers picking a transport (popup via ICRC-29 \u002F top-level redirect via ICRC-167 \u002F browser extension via ICRC-94) then negotiating capabilities, the permission and account lifecycle, and executing canister calls the user approves through SignerAgent (ICRC-49). Uses OISY as the worked example but applies to any ICRC-25 signer. Do NOT use for Internet Identity login (use the user-sign-in skill) or for implementing a wallet yourself. Use when the developer mentions wallet integration or OISY or @icp-sdk\u002Fsigner or approving a transaction in a wallet popup.\"\nlicense: Apache-2.0\ncompatibility: \"Node.js >= 22, a browser (secure context: HTTPS, localhost, or 127.0.0.1)\"\nmetadata:\n  title: Wallet Integration\n  category: DeFi\n---\n\n# Wallet Integration\n\n## What This Is\n\nConnecting an **external wallet** to your dapp so the user approves actions in the wallet rather than handing your app a key. `@icp-sdk\u002Fsigner` is the **relying-party** client: your app is the relying party, the wallet is the signer, and they exchange JSON-RPC 2.0 messages over a transport defined by the ICRC signer standards.\n\nThis skill covers **integrating a signer**. Implementing one is out of scope — consent screens, prompt registration and account custody are the wallet's job.\n\nExamples use [OISY](https:\u002F\u002Foisy.com) (`https:\u002F\u002Foisy.com\u002Fsign`), but nothing here is OISY-specific. For another web signer the transport URL is usually the only change, and [`BrowserExtensionTransport`](#extension-icrc-94) discovers extension signers you never hardcoded. What a given signer actually supports is a separate question from which transport reaches it — negotiate it rather than assuming (see [Negotiate capabilities](#negotiate-capabilities) and pitfall 5).\n\n| Standard | What it gives you | API |\n|----------|-------------------|-----|\n| ICRC-25 | Capability discovery + permission lifecycle | `getSupportedStandards`, `requestPermissions`, `getPermissions` |\n| ICRC-27 | The user's accounts | `getAccounts` |\n| ICRC-29 | Popup transport over `postMessage` | `PostMessageTransport` |\n| ICRC-49 | Execute a canister call | `SignerAgent` (or `callCanister`, the raw primitive) |\n| ICRC-94 | Browser-extension discovery | `BrowserExtensionTransport.discover` |\n| ICRC-167 | Top-level redirect transport | `UrlTransport` (**new in signer 6**) |\n\n## What the model is\n\nEvery write is an individual, user-approved act. Your app asks the wallet to execute one canister call (ICRC-49); the wallet shows the user what it is about to do, the user approves, and the wallet signs and submits it. Your app never holds a key and never acts on the user's behalf unattended.\n\nThat is the whole shape, and it is what makes wallet integration appropriate for deliberate, high-value actions — transfers, approvals, mints — and inappropriate for anything frequent or invisible. If a user should not see a prompt per action, you do not want a wallet; you want authentication.\n\n### When NOT to use this skill\n\n- **A session — sign in once, then act many times.** That is authentication, not wallet integration: a delegation is scoped and issued by an identity provider. Use the **user-sign-in** skill. ICRC-34 exists, but it is an auth mechanism and out of scope here.\n- **Internet Identity sign-in** → the **user-sign-in** skill. II is an identity provider, not an ICRC-25 signer.\n- **Letting an agent or CLI act as the user** → the **agent-web-identity** skill.\n- **Building a wallet** → out of scope, as above.\n\n## Prerequisites\n\n```bash\nnpm i '@icp-sdk\u002Fsigner@^6' '@icp-sdk\u002Fcore@^6'\n```\n\nAdd `@icp-sdk\u002Fcanisters@^4` if you call ICP\u002FICRC ledgers (it brings `@dfinity\u002Futils@^5` as a peer). Pin `@icp-sdk\u002Fcore` to `^6`: signer 6 peers it, and so do `@icp-sdk\u002Fauth@^10` and `@icp-sdk\u002Fcanisters@^4`.\n\nThe transport URL must be a **secure context** — HTTPS, `localhost`, or `127.0.0.1`.\n\n## Pick a transport\n\nThe transport is the only part that knows *how* the wallet is reached; the `Signer` API above it is identical whichever you choose.\n\n| Transport | Mechanism | Use when |\n|-----------|-----------|----------|\n| `PostMessageTransport` | Popup, handshaken with `icrc29_status`, then `postMessage` | Default for web wallets like OISY |\n| `UrlTransport` | Navigates the top-level window; wallet returns to your `callbackUrl` | Mobile, or anywhere popups are blocked |\n| `BrowserExtensionTransport` | Extensions announce themselves on `window` events | Extension wallets; discovering unknown signers |\n\n```typescript\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { PostMessageTransport } from '@icp-sdk\u002Fsigner\u002Fweb';\n\n\u002F\u002F One Signer per wallet connection; safe to create at module scope.\nconst signer = new Signer({\n  transport: new PostMessageTransport({ url: 'https:\u002F\u002Foisy.com\u002Fsign' })\n});\n```\n\n### Extension (ICRC-94)\n\n```typescript\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { BrowserExtensionTransport } from '@icp-sdk\u002Fsigner\u002Fextension';\n\n\u002F\u002F Discovery order is whichever extension announced first, not a user\n\u002F\u002F preference, so return the list rather than choosing. Each provider carries\n\u002F\u002F { uuid, name, icon, rdns } — enough to render a picker.\nfunction discoverExtensionSigners() {\n  return BrowserExtensionTransport.discover();\n}\n\n\u002F\u002F Build the signer only from the uuid the user picked.\nasync function connectExtensionSigner(uuid: string) {\n  const transport = await BrowserExtensionTransport.findTransport({ uuid });\n  return new Signer({ transport });\n}\n```\n\n### Redirect (ICRC-167)\n\n`UrlTransport` unloads your page on every request, so it keeps a call-order journal in `sessionStorage` and replays it when the wallet returns. Two rules make or break it:\n\n1. **Issue the same requests, in the same order, on every load.** Branch only on values recovered from earlier results. A divergence guard rejects a replay that does not match.\n2. **Put anything that must come back *the same value* through `memoize()`** — a nonce above all. Its result is journaled and replayed instead of re-run. Deterministic async work needs no `memoize`: building an `HttpAgent` yields an equivalent agent on every load, so it cannot drift from the journal.\n\n`SignerAgent` works over this transport, so a redirect flow is the same code as a popup flow:\n\n```typescript\nimport { IcrcLedgerCanister, toCandidAccount, type IcrcAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\nimport { HttpAgent } from '@icp-sdk\u002Fcore\u002Fagent';\nimport type { Principal } from '@icp-sdk\u002Fcore\u002Fprincipal';\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { SignerAgent } from '@icp-sdk\u002Fsigner\u002Fagent';\nimport { UrlTransport } from '@icp-sdk\u002Fsigner\u002Fweb';\n\nconst transport = new UrlTransport({\n  \u002F\u002F The path is the wallet's own; ICRC-167 does not dictate one.\n  url: 'https:\u002F\u002Fwallet.example.com\u002Fsign',\n  \u002F\u002F Absolute, fragment-free, on an origin you control, and declared in that\n  \u002F\u002F origin's \u002F.well-known\u002Fii-auth-callbacks (see pitfall 9).\n  callbackUrl: 'https:\u002F\u002Fapp.example.com\u002Fsigner-callback'\n});\n\n\u002F\u002F Run this on the load of the callback route: a fresh arrival starts the flow,\n\u002F\u002F the wallet's return replays it. No separate resume or cleanup call.\nasync function transferOverRedirect(\n  account: IcrcAccount, to: IcrcAccount, amount: bigint, ledgerId: Principal\n) {\n  const signer = new Signer({ transport });\n\n  \u002F\u002F Deterministic, so no memoize needed — the same agent is built on each load.\n  const agent = await HttpAgent.create({ host: 'https:\u002F\u002Ficp-api.io' });\n  const signerAgent = await SignerAgent.create({ signer, account: account.owner, agent });\n\n  const ledger = IcrcLedgerCanister.create({ agent: signerAgent, canisterId: ledgerId });\n  return ledger.transfer({\n    to: toCandidAccount(to),\n    from_subaccount: account.subaccount,\n    amount\n  });\n}\n```\n\nGoing through `SignerAgent` rather than `signer.callCanister` is what gets you the content-map and certificate checks; `callCanister` is the raw ICRC-49 primitive and validates only that the reply carries both fields. Prefer the agent unless you have a specific reason to drive the primitive yourself, in which case verifying the certificate before trusting the reply is your job.\n\n## Negotiate capabilities\n\nSkip this only if you hardcode one wallet and know what it supports. For generic integration it is the step that keeps you honest: a signer may expose accounts without executing calls, or support a transport you have not built for.\n\n```typescript\nimport { Signer } from '@icp-sdk\u002Fsigner';\n\nasync function capabilities(signer: Signer) {\n  const standards = await signer.getSupportedStandards(); \u002F\u002F [{ name: 'ICRC-27', url }, ...]\n  const names = new Set(standards.map(({ name }) => name));\n  return {\n    canListAccounts: names.has('ICRC-27'),\n    canCallCanisters: names.has('ICRC-49')\n  };\n}\n```\n\n`getSupportedStandards` needs no permission, so it is safe as a first call.\n\n## Permissions and accounts\n\nMost signers start every scope at `ask_on_use`, prompting the first time each method is used — but ICRC-25 leaves the initial state to signer policy, so `getPermissions()` is the only authority. `requestPermissions` is **optional**: it trades several later prompts for one up front.\n\n| State | Behaviour |\n|-------|-----------|\n| `granted` | Proceeds without prompting |\n| `denied` | Rejected immediately with error `3000` |\n| `ask_on_use` | Prompts on first use (the usual initial state) |\n\n```typescript\nimport type { PermissionScope, Signer } from '@icp-sdk\u002Fsigner';\n\n\u002F\u002F The two scopes this skill uses:\n\u002F\u002F   [{ method: 'icrc27_accounts' }, { method: 'icrc49_call_canister' }]\nasync function connect(signer: Signer, scopes?: PermissionScope[]) {\n  \u002F\u002F Omitting `scopes` sets nothing: it leaves whatever states the signer\n  \u002F\u002F already holds for your origin, which a previous session may have left\n  \u002F\u002F `granted` or `denied`. Do not count on being prompted — getPermissions()\n  \u002F\u002F is the only way to know. Supply scopes to trade several later prompts for\n  \u002F\u002F one up front, and ask only for what your path uses:\n  \u002F\u002F a scope the signer does not support is dropped before the prompt is drawn,\n  \u002F\u002F so it costs nothing, but a supported one you never exercise is shown to\n  \u002F\u002F the user for no reason.\n  if (scopes !== undefined) {\n    await signer.requestPermissions(scopes);\n  }\n\n  \u002F\u002F ICRC-27 returns the accounts the user chose to share, as a list: it can be\n  \u002F\u002F empty (they declined) and it can hold several. Hand it back whole and let\n  \u002F\u002F the user pick rather than indexing blindly — see pitfall 4.\n  \u002F\u002F\n  \u002F\u002F Each element is { owner: Principal, subaccount?: Uint8Array } — already an\n  \u002F\u002F IcrcAccount. Usually there is no subaccount, since signers commonly offer\n  \u002F\u002F only the default one, but keep both halves anyway: it costs nothing.\n  return signer.getAccounts();\n}\n```\n\n`getPermissions()` reads the current state without prompting. Do not cache it across sessions — a wallet may expire grants, after which they silently revert to `ask_on_use`.\n\n## Executing a call the user approves\n\n`SignerAgent` implements `Agent`, so it drops into anything that takes one: a ledger client from `@icp-sdk\u002Fcanisters`, or an actor from `@icp-sdk\u002Fbindgen` for your own canister. Each call becomes a wallet prompt.\n\n```typescript\nimport { IcrcLedgerCanister, type IcrcAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\nimport { HttpAgent } from '@icp-sdk\u002Fcore\u002Fagent';\nimport { Principal } from '@icp-sdk\u002Fcore\u002Fprincipal';\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { SignerAgent } from '@icp-sdk\u002Fsigner\u002Fagent';\n\nconst ICP_LEDGER = Principal.fromText('ryjl3-tyaaa-aaaaa-aaaba-cai');\n\n\u002F\u002F Two clients against the same ledger: one for reads, one for writes.\nasync function connectLedger(signer: Signer, account: IcrcAccount) {\n  \u002F\u002F One HttpAgent serves both. It answers reads directly, and SignerAgent\n  \u002F\u002F borrows it for the root key and status instead of building its own.\n  const agent = await HttpAgent.create({ host: 'https:\u002F\u002Ficp-api.io' });\n  \u002F\u002F SignerAgent routes calls as a principal; it has no subaccount field.\n  const signerAgent = await SignerAgent.create({ signer, account: account.owner, agent });\n\n  return {\n    \u002F\u002F Anonymous by default — public reads need no wallet and no prompt.\n    read: IcrcLedgerCanister.create({ agent, canisterId: ICP_LEDGER }),\n    write: IcrcLedgerCanister.create({ agent: signerAgent, canisterId: ICP_LEDGER }),\n    signerAgent\n  };\n}\n```\n\n**Read with the plain agent, write with the signer agent.** `SignerAgent.query()` upgrades every query into a full canister call routed through the wallet, so a balance check would put an approval prompt in front of the user. Public data does not need the wallet at all — read it with an ordinary `HttpAgent`, which is anonymous by default:\n\n```typescript\nimport { type IcrcAccount, toCandidAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\nimport { Signer } from '@icp-sdk\u002Fsigner';\n\nasync function showBalanceThenTransfer(\n  signer: Signer, account: IcrcAccount, to: IcrcAccount, amount: bigint\n) {\n  const { read, write } = await connectLedger(signer, account);\n\n  \u002F\u002F balance() takes an IcrcAccount directly.\n  const balance = await read.balance(account);                     \u002F\u002F no prompt\n\n  const block = await write.transfer({                                    \u002F\u002F prompts\n    \u002F\u002F The ledger's `to` is the Candid shape; convert rather than hand-roll it.\n    to: toCandidAccount(to),\n    \u002F\u002F The subaccount the tokens leave from.\n    from_subaccount: account.subaccount,\n    amount\n  });\n\n  return { balance, block };\n}\n```\n\n`signerAgent.replaceAccount(principal)` switches which principal later writes are signed for, without rebuilding the agent.\n\n## Channel lifecycle and page reloads\n\n`autoCloseTransportChannel` defaults to `true`: the channel closes ~200 ms after each response, so the popup does not linger. For a multi-step flow that awaits your own async work between requests, turn it off or the channel closes underneath you.\n\n```typescript\nimport { Signer } from '@icp-sdk\u002Fsigner';\n\nasync function multiStepFlow(signer: Signer) {\n  signer.autoCloseTransportChannel = false;\n  try {\n    const accounts = await signer.getAccounts();\n    await saveSelectionToYourBackend(accounts);  \u002F\u002F your own async work; channel stays open\n    return await signer.requestPermissions([{ method: 'icrc49_call_canister' }]);\n  } finally {\n    signer.autoCloseTransportChannel = true;\n    await signer.closeChannel();\n  }\n}\n```\n\n**A connection does not survive a page reload.** There is no persistent session to restore — the channel is a live `postMessage` link to a popup that is gone. The workable pattern is to persist the account, render read-only state from it with an anonymous agent, and re-establish the signer lazily on the first write:\n\n```typescript\nimport { type IcrcAccount, decodeIcrcAccount, encodeIcrcAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\nimport { HttpAgent } from '@icp-sdk\u002Fcore\u002Fagent';\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { SignerAgent } from '@icp-sdk\u002Fsigner\u002Fagent';\n\nconst SESSION_KEY = 'wallet-account';\n\n\u002F\u002F On connect: remember the account, not the channel. The ICRC-1 textual\n\u002F\u002F encoding round-trips owner and subaccount as one string, so the\n\u002F\u002F subaccount survives the reload too (see pitfall 12).\nfunction rememberAccount(account: IcrcAccount) {\n  sessionStorage.setItem(SESSION_KEY, encodeIcrcAccount(account));\n}\n\n\u002F\u002F On reload: read-only state renders from this immediately, with no popup.\nfunction restoreAccount(): IcrcAccount | null {\n  const stored = sessionStorage.getItem(SESSION_KEY);\n  if (stored === null) return null;\n  try {\n    return decodeIcrcAccount(stored);\n  } catch {\n    sessionStorage.removeItem(SESSION_KEY);  \u002F\u002F stale or malformed\n    return null;\n  }\n}\n\n\u002F\u002F On the first write after a reload. This reopens the popup, so it must run\n\u002F\u002F from the click that starts that write — pitfall 1 applies here too.\nasync function ensureSignerAgent(signer: Signer, account: IcrcAccount, agent: HttpAgent) {\n  const offered = await signer.getAccounts();  \u002F\u002F re-establishes the channel\n  \u002F\u002F The user may have switched accounts while the page was gone, so the stored\n  \u002F\u002F one is a guess until the wallet confirms it. Compare encodings, not owners:\n  \u002F\u002F the same principal with a different subaccount is a different account.\n  const id = encodeIcrcAccount(account);\n  if (!offered.some((offer) => encodeIcrcAccount(offer) === id)) {\n    sessionStorage.removeItem(SESSION_KEY);\n    throw new Error('the wallet no longer offers the stored account; reconnect');\n  }\n  return SignerAgent.create({ signer, account: account.owner, agent });\n}\n```\n\nTreat \"disconnect\" as clearing your own state — there is no wallet-side logout to call.\n\n## Error handling\n\n```typescript\nimport { Signer, SignerError } from '@icp-sdk\u002Fsigner';\nimport { PostMessageTransportError } from '@icp-sdk\u002Fsigner\u002Fweb';\nimport type { IcrcAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\n\nasync function safeTransfer(\n  signer: Signer, account: IcrcAccount, to: IcrcAccount, amount: bigint\n) {\n  try {\n    await showBalanceThenTransfer(signer, account, to, amount);\n  } catch (err) {\n    \u002F\u002F Anything that is not a SignerError — SignerAgentError above all, where the\n    \u002F\u002F wallet responded and the response failed validation — is not handled here.\n    if (!(err instanceof SignerError)) throw err;\n\n    switch (err.code) {\n      case 3001: return;                       \u002F\u002F user cancelled — not a failure\n      case 3000: showPermissionHelp(); return; \u002F\u002F permission denied\n      case 2000: showUnsupported(); return;    \u002F\u002F wallet does not support the method\n      case 4000:                               \u002F\u002F every transport failure lands here\n      case 4001:                               \u002F\u002F only if the signer itself returns it\n        \u002F\u002F The transport error is the `cause`, never the error you caught.\n        if (err.cause instanceof PostMessageTransportError) showPopupBlockedHelp();\n        else promptReconnect();\n        return;\n    }\n\n    \u002F\u002F ICRC-25 numbers errors by range and a signer may return a code this\n    \u002F\u002F switch has never seen, so fall back on the range rather than rethrowing.\n    switch (Math.floor(err.code \u002F 1000)) {\n      case 3:\n        \u002F\u002F 3xxx is \"user action\", so nothing broke — but 3001 is the only code\n        \u002F\u002F where silence is right, because there you know they cancelled on\n        \u002F\u002F purpose. For an unnamed 3xxx say the action did not go through, or\n        \u002F\u002F the UI sits unchanged after the user pressed the button.\n        showActionNotCompleted();\n        return;\n      case 2: showUnsupported(); return;       \u002F\u002F 2xxx not supported\n      case 4: promptReconnect(); return;       \u002F\u002F 4xxx transport channel\n      default: throw err;                      \u002F\u002F 1xxx generic, and anything else\n    }\n  }\n}\n```\n\nICRC-25 groups errors into ranges and names a few codes inside each. Handle the codes you know, then fall back on the range — a signer may return `3002` or `4002`, and a bare `default: throw` would mishandle it:\n\n| Range | Code | Meaning | Handle by |\n|-------|------|---------|-----------|\n| `1xxx` general | `1000` | Generic error | Surfacing `err.data` to developers |\n| `2xxx` not supported | `2000` | Not supported | Negotiating capabilities first |\n| `3xxx` user action | `3000` | Permission not granted | Explaining what to re-grant |\n| | `3001` | **Action aborted — the user cancelled** | Returning quietly; this is normal |\n| `4xxx` transport | `4000` | Network error | Reconnecting — the library also reports every transport failure here |\n| | `4001` | Transport channel closed | Reconnecting (signer-reported only; see below) |\n\nTwo failures do not arrive as the class you would expect, and they call for opposite reactions:\n\n- **Transport failures arrive as `SignerError` with code `4000`.** `Signer.openChannel()` catches whatever the transport threw — `PostMessageTransportError`, `UrlTransportError`, `BrowserExtensionTransportError` — and rethrows it as a `SignerError` with the original as `cause`. So a blocked popup is *not* `instanceof PostMessageTransportError`; test `err.cause` for that. The library also never emits `4001`: \"channel closed before a response\" is `4000` too, and `4001` reaches you only if the signer itself returns it.\n- **`SignerAgentError`** — the wallet *did* respond, and the response failed validation: the returned content map did not match the call you sent (canister, method, argument, sender, nonce), the certificate did not verify against the IC root key, or the reply was absent from the certified tree. `SignerAgent` runs those checks for you, so this is a wallet returning something it should not have. Do not treat it as a connectivity fault and retry — surface it.\n\n## Pitfalls\n\n1. **Opening the popup outside a click handler.** `PostMessageTransport` rejects establishment that is not user-initiated (`detectNonClickEstablishment`, default `true`) because Safari and others block such popups. Connect from an event handler, never on mount or in a `useEffect`.\n\n   ```typescript\n   \u002F\u002F WRONG — blocked, and the transport detects it\n   useEffect(() => { signer.getAccounts(); }, []);\n\n   \u002F\u002F CORRECT\n   button.addEventListener('click', () => signer.getAccounts());\n   ```\n\n2. **Reading through `SignerAgent`.** `query()` is upgraded to an update call routed through the wallet, so every read costs the user an approval interaction. Public data — a ledger balance, token metadata — needs no wallet: read it with a plain `HttpAgent`, anonymous by default. Only writes go through `SignerAgent`.\n\n3. **Expecting a connection to survive a reload.** No channel outlives the page. Persist the account — both halves, per pitfall 12 — for read-only rendering, and reconnect on first write. See above.\n\n4. **Indexing `getAccounts()` blindly.** It returns a *list* of the accounts the user chose to share. ICRC-27 lets the signer prompt for that selection, so the list can be **empty** — the user declined, which is not an error — and it can hold **several**, where `[0]` silently picks for them. `accounts[0]` on an empty list is `undefined`, so the crash lands later at `.owner` rather than at the call. Check the length, and offer a picker when there is more than one.\n\n5. **Assuming a wallet's capabilities.** Call `getSupportedStandards()`. A signer may list accounts (ICRC-27) without executing calls (ICRC-49), or speak a transport you have not built for.\n\n6. **Coding against one wallet's non-standard error codes.** ICRC-25 owns `1xxx`–`4xxx` and names `1000`\u002F`2000`\u002F`3000`\u002F`3001`\u002F`4000`\u002F`4001` inside them. A code outside those ranges is a vendor extension and does not port — earlier revisions of this skill documented a `503 BUSY` that exists only in `@dfinity\u002Foisy-wallet-signer` and in no standard. Branch on the named codes, fall back on the range, and treat anything outside the ranges as generic.\n\n7. **Journaling something non-serializable through `memoize()`.** It persists via JSON, so a `Uint8Array` round-trips as `{\"0\":1,\"1\":2,…}` and a `CryptoKey` as `{}` — silently, with the flow failing on return rather than at the call. Convert to a plain array (or hex) before memoizing and back afterwards.\n\n8. **Diverging on a redirect replay.** With `UrlTransport`, issue the same requests and `memoize` steps in the same order on every load, and route anything a request depends on — a nonce above all — through `memoize`. Re-fetching a single-use value on the return load invalidates the flow.\n\n9. **A `callbackUrl` that is relative, carries a fragment, or is not served correctly.** It must be absolute, fragment-free (the transport appends its own), on an origin you control, and declared in that origin's `\u002F.well-known\u002Fii-auth-callbacks` — matched exactly, so the full URL. Declaring it is not enough: the wallet reads that document **cross-origin**, so serve it as JSON with CORS or a correctly listed callback still fails validation.\n\n    ```json\n    { \"callbacks\": [\"https:\u002F\u002Fapp.example.com\u002Fsigner-callback\"] }\n    ```\n\n    With `@dfinity\u002Fstatic-site` that is a `_headers` block:\n\n    ```\n    \u002F.well-known\u002Fii-auth-callbacks\n      Content-Type: application\u002Fjson\n      Access-Control-Allow-Origin: *\n    ```\n\n    Validation fails closed — undeclared, unreadable, or not matching exactly, and the response never comes back. See the **user-sign-in** skill, which documents the same file for redirect sign-in.\n\n10. **Top-level `await` in wallet code.** Every call here is async, and with `PostMessageTransport` a module-load `await` opens the popup outside a user gesture, which the transport rejects — pitfall 1. Wrap those calls in functions the UI invokes. `UrlTransport` is the exception, and the reverse: it navigates the top level rather than opening a popup, has no gesture check, and its flow *must* re-run on the callback-route load so the journal can replay — requiring a click there would break it. Either way, do not rely on the build to catch a stray top-level `await`: Vite ≤5 defaulted to `es2020` and rejected it outright, while Vite 6+ defaults to `baseline-widely-available` and allows it.\n\n11. **`@icp-sdk\u002Fcanisters@^3` with `@icp-sdk\u002Fsigner@^6`.** They cannot coexist — canisters 3 peers `@icp-sdk\u002Fcore@^5` or older, signer 6 peers `^6`, so `npm install` fails with `ERESOLVE`. Move to `@icp-sdk\u002Fcanisters@^4` and `@dfinity\u002Futils@^5`. Do not reach for `--legacy-peer-deps`: it skips the peer check and installs the mismatched pair anyway, so the incompatibility surfaces at runtime instead of at install time.\n\n12. **Treating an account as just a principal.** `getAccounts()` returns `{ owner, subaccount? }` — an `IcrcAccount`. The subaccount is usually absent, because signers commonly offer only the default one, so code that assumes a bare principal works until it meets a signer that does not. Carry the account whole and let the library helpers do the rest: **compare** with `encodeIcrcAccount()` and never `owner` alone (that encoding normalizes the default subaccount, so the same principal with a *different* one is correctly a different account), **persist** with `encodeIcrcAccount()` \u002F `decodeIcrcAccount()`, and **send** with `from_subaccount` for the sender plus `toCandidAccount()` for the recipient. `SignerAgent` is the exception — its `account` is a `Principal`, which is why the subaccount travels in the ledger call arguments instead.\n\n13. **Firing a call immediately after connecting.** Let the user initiate. An unprompted approval dialog straight after connect reads as an attack, and wallets are within their rights to reject it.\n\n## Testing against a real wallet\n\nThere is no local signer to run: OISY is hosted, and the transport's secure-context requirement applies to the *signer's* URL, not to your origin — `https:\u002F\u002Foisy.com\u002Fsign` satisfies it. Serving your own frontend from `localhost` is fine, and it is a browser secure context, so WebCrypto key generation works there too. Test on testnet tokens rather than mainnet value.\n\n```bash\nicp network start -d\nicp deploy\n```\n\nGet free testnet tokens from the [ICP Faucet](https:\u002F\u002Ffaucet.internetcomputer.org) and switch OISY to the **IC (testnet tokens)** network to see them. Useful ledgers:\n\n| Token | Ledger canister |\n|-------|-----------------|\n| TESTICP | `xafvr-biaaa-aaaai-aql5q-cai` |\n| TICRC1 | `3jkp5-oyaaa-aaaaj-azwqa-cai` |\n\nSet `host: 'https:\u002F\u002Ficp-api.io'` on the agent even when serving from `localhost` — `host` is the API endpoint calls go to, not the origin your app is served from.\n\n## Expected Behavior\n\n- The first `getAccounts()` opens the wallet and resolves with the accounts the user chose to share, as `{ owner: Principal, subaccount?: Uint8Array }` — possibly none of them.\n- A ledger `transfer` through `SignerAgent` shows the user the call to approve and resolves with a `bigint` block index.\n- Cancelling the **canister-call approval** rejects with `SignerError` and `code === 3001`. The other two refusals look different: declining to share accounts resolves `getAccounts()` with `[]`, and denying a permission gives code `3000`.\n- After a reload, read-only state renders with no popup; the first write reopens one.\n\n## Additional References\n\n- **user-sign-in** — II sign-in, and the place to go if you need a session rather than per-action approval\n- **agent-web-identity** — letting an agent or CLI act as the user in an II app\n- **icp-cli** — `@icp-sdk\u002Fbindgen` actors to call your own canister through a `SignerAgent`\n- **canister-security** — verifying `msg.caller` on the backend once calls arrive\n- [OISY signer demo](https:\u002F\u002Fgithub.com\u002Fdfinity\u002Fexamples\u002Ftree\u002Fmaster\u002Fhosting\u002Foisy-signer-demo) — a working relying party (React) built on `@icp-sdk\u002Fsigner`\n- [ICRC signer standards](https:\u002F\u002Fgithub.com\u002Fdfinity\u002Fwg-identity-authentication) — the specifications behind every method above\n","# Wallet Integration\n\n## What This Is\n\nConnecting an **external wallet** to your dapp so the user approves actions in the wallet rather than handing your app a key. `@icp-sdk\u002Fsigner` is the **relying-party** client: your app is the relying party, the wallet is the signer, and they exchange JSON-RPC 2.0 messages over a transport defined by the ICRC signer standards.\n\nThis skill covers **integrating a signer**. Implementing one is out of scope — consent screens, prompt registration and account custody are the wallet's job.\n\nExamples use [OISY](https:\u002F\u002Foisy.com) (`https:\u002F\u002Foisy.com\u002Fsign`), but nothing here is OISY-specific. For another web signer the transport URL is usually the only change, and [`BrowserExtensionTransport`](#extension-icrc-94) discovers extension signers you never hardcoded. What a given signer actually supports is a separate question from which transport reaches it — negotiate it rather than assuming (see [Negotiate capabilities](#negotiate-capabilities) and pitfall 5).\n\n| Standard | What it gives you | API |\n|----------|-------------------|-----|\n| ICRC-25 | Capability discovery + permission lifecycle | `getSupportedStandards`, `requestPermissions`, `getPermissions` |\n| ICRC-27 | The user's accounts | `getAccounts` |\n| ICRC-29 | Popup transport over `postMessage` | `PostMessageTransport` |\n| ICRC-49 | Execute a canister call | `SignerAgent` (or `callCanister`, the raw primitive) |\n| ICRC-94 | Browser-extension discovery | `BrowserExtensionTransport.discover` |\n| ICRC-167 | Top-level redirect transport | `UrlTransport` (**new in signer 6**) |\n\n## What the model is\n\nEvery write is an individual, user-approved act. Your app asks the wallet to execute one canister call (ICRC-49); the wallet shows the user what it is about to do, the user approves, and the wallet signs and submits it. Your app never holds a key and never acts on the user's behalf unattended.\n\nThat is the whole shape, and it is what makes wallet integration appropriate for deliberate, high-value actions — transfers, approvals, mints — and inappropriate for anything frequent or invisible. If a user should not see a prompt per action, you do not want a wallet; you want authentication.\n\n### When NOT to use this skill\n\n- **A session — sign in once, then act many times.** That is authentication, not wallet integration: a delegation is scoped and issued by an identity provider. Use the **user-sign-in** skill. ICRC-34 exists, but it is an auth mechanism and out of scope here.\n- **Internet Identity sign-in** → the **user-sign-in** skill. II is an identity provider, not an ICRC-25 signer.\n- **Letting an agent or CLI act as the user** → the **agent-web-identity** skill.\n- **Building a wallet** → out of scope, as above.\n\n## Prerequisites\n\n```bash\nnpm i '@icp-sdk\u002Fsigner@^6' '@icp-sdk\u002Fcore@^6'\n```\n\nAdd `@icp-sdk\u002Fcanisters@^4` if you call ICP\u002FICRC ledgers (it brings `@dfinity\u002Futils@^5` as a peer). Pin `@icp-sdk\u002Fcore` to `^6`: signer 6 peers it, and so do `@icp-sdk\u002Fauth@^10` and `@icp-sdk\u002Fcanisters@^4`.\n\nThe transport URL must be a **secure context** — HTTPS, `localhost`, or `127.0.0.1`.\n\n## Pick a transport\n\nThe transport is the only part that knows *how* the wallet is reached; the `Signer` API above it is identical whichever you choose.\n\n| Transport | Mechanism | Use when |\n|-----------|-----------|----------|\n| `PostMessageTransport` | Popup, handshaken with `icrc29_status`, then `postMessage` | Default for web wallets like OISY |\n| `UrlTransport` | Navigates the top-level window; wallet returns to your `callbackUrl` | Mobile, or anywhere popups are blocked |\n| `BrowserExtensionTransport` | Extensions announce themselves on `window` events | Extension wallets; discovering unknown signers |\n\n```typescript\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { PostMessageTransport } from '@icp-sdk\u002Fsigner\u002Fweb';\n\n\u002F\u002F One Signer per wallet connection; safe to create at module scope.\nconst signer = new Signer({\n  transport: new PostMessageTransport({ url: 'https:\u002F\u002Foisy.com\u002Fsign' })\n});\n```\n\n### Extension (ICRC-94)\n\n```typescript\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { BrowserExtensionTransport } from '@icp-sdk\u002Fsigner\u002Fextension';\n\n\u002F\u002F Discovery order is whichever extension announced first, not a user\n\u002F\u002F preference, so return the list rather than choosing. Each provider carries\n\u002F\u002F { uuid, name, icon, rdns } — enough to render a picker.\nfunction discoverExtensionSigners() {\n  return BrowserExtensionTransport.discover();\n}\n\n\u002F\u002F Build the signer only from the uuid the user picked.\nasync function connectExtensionSigner(uuid: string) {\n  const transport = await BrowserExtensionTransport.findTransport({ uuid });\n  return new Signer({ transport });\n}\n```\n\n### Redirect (ICRC-167)\n\n`UrlTransport` unloads your page on every request, so it keeps a call-order journal in `sessionStorage` and replays it when the wallet returns. Two rules make or break it:\n\n1. **Issue the same requests, in the same order, on every load.** Branch only on values recovered from earlier results. A divergence guard rejects a replay that does not match.\n2. **Put anything that must come back *the same value* through `memoize()`** — a nonce above all. Its result is journaled and replayed instead of re-run. Deterministic async work needs no `memoize`: building an `HttpAgent` yields an equivalent agent on every load, so it cannot drift from the journal.\n\n`SignerAgent` works over this transport, so a redirect flow is the same code as a popup flow:\n\n```typescript\nimport { IcrcLedgerCanister, toCandidAccount, type IcrcAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\nimport { HttpAgent } from '@icp-sdk\u002Fcore\u002Fagent';\nimport type { Principal } from '@icp-sdk\u002Fcore\u002Fprincipal';\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { SignerAgent } from '@icp-sdk\u002Fsigner\u002Fagent';\nimport { UrlTransport } from '@icp-sdk\u002Fsigner\u002Fweb';\n\nconst transport = new UrlTransport({\n  \u002F\u002F The path is the wallet's own; ICRC-167 does not dictate one.\n  url: 'https:\u002F\u002Fwallet.example.com\u002Fsign',\n  \u002F\u002F Absolute, fragment-free, on an origin you control, and declared in that\n  \u002F\u002F origin's \u002F.well-known\u002Fii-auth-callbacks (see pitfall 9).\n  callbackUrl: 'https:\u002F\u002Fapp.example.com\u002Fsigner-callback'\n});\n\n\u002F\u002F Run this on the load of the callback route: a fresh arrival starts the flow,\n\u002F\u002F the wallet's return replays it. No separate resume or cleanup call.\nasync function transferOverRedirect(\n  account: IcrcAccount, to: IcrcAccount, amount: bigint, ledgerId: Principal\n) {\n  const signer = new Signer({ transport });\n\n  \u002F\u002F Deterministic, so no memoize needed — the same agent is built on each load.\n  const agent = await HttpAgent.create({ host: 'https:\u002F\u002Ficp-api.io' });\n  const signerAgent = await SignerAgent.create({ signer, account: account.owner, agent });\n\n  const ledger = IcrcLedgerCanister.create({ agent: signerAgent, canisterId: ledgerId });\n  return ledger.transfer({\n    to: toCandidAccount(to),\n    from_subaccount: account.subaccount,\n    amount\n  });\n}\n```\n\nGoing through `SignerAgent` rather than `signer.callCanister` is what gets you the content-map and certificate checks; `callCanister` is the raw ICRC-49 primitive and validates only that the reply carries both fields. Prefer the agent unless you have a specific reason to drive the primitive yourself, in which case verifying the certificate before trusting the reply is your job.\n\n## Negotiate capabilities\n\nSkip this only if you hardcode one wallet and know what it supports. For generic integration it is the step that keeps you honest: a signer may expose accounts without executing calls, or support a transport you have not built for.\n\n```typescript\nimport { Signer } from '@icp-sdk\u002Fsigner';\n\nasync function capabilities(signer: Signer) {\n  const standards = await signer.getSupportedStandards(); \u002F\u002F [{ name: 'ICRC-27', url }, ...]\n  const names = new Set(standards.map(({ name }) => name));\n  return {\n    canListAccounts: names.has('ICRC-27'),\n    canCallCanisters: names.has('ICRC-49')\n  };\n}\n```\n\n`getSupportedStandards` needs no permission, so it is safe as a first call.\n\n## Permissions and accounts\n\nMost signers start every scope at `ask_on_use`, prompting the first time each method is used — but ICRC-25 leaves the initial state to signer policy, so `getPermissions()` is the only authority. `requestPermissions` is **optional**: it trades several later prompts for one up front.\n\n| State | Behaviour |\n|-------|-----------|\n| `granted` | Proceeds without prompting |\n| `denied` | Rejected immediately with error `3000` |\n| `ask_on_use` | Prompts on first use (the usual initial state) |\n\n```typescript\nimport type { PermissionScope, Signer } from '@icp-sdk\u002Fsigner';\n\n\u002F\u002F The two scopes this skill uses:\n\u002F\u002F   [{ method: 'icrc27_accounts' }, { method: 'icrc49_call_canister' }]\nasync function connect(signer: Signer, scopes?: PermissionScope[]) {\n  \u002F\u002F Omitting `scopes` sets nothing: it leaves whatever states the signer\n  \u002F\u002F already holds for your origin, which a previous session may have left\n  \u002F\u002F `granted` or `denied`. Do not count on being prompted — getPermissions()\n  \u002F\u002F is the only way to know. Supply scopes to trade several later prompts for\n  \u002F\u002F one up front, and ask only for what your path uses:\n  \u002F\u002F a scope the signer does not support is dropped before the prompt is drawn,\n  \u002F\u002F so it costs nothing, but a supported one you never exercise is shown to\n  \u002F\u002F the user for no reason.\n  if (scopes !== undefined) {\n    await signer.requestPermissions(scopes);\n  }\n\n  \u002F\u002F ICRC-27 returns the accounts the user chose to share, as a list: it can be\n  \u002F\u002F empty (they declined) and it can hold several. Hand it back whole and let\n  \u002F\u002F the user pick rather than indexing blindly — see pitfall 4.\n  \u002F\u002F\n  \u002F\u002F Each element is { owner: Principal, subaccount?: Uint8Array } — already an\n  \u002F\u002F IcrcAccount. Usually there is no subaccount, since signers commonly offer\n  \u002F\u002F only the default one, but keep both halves anyway: it costs nothing.\n  return signer.getAccounts();\n}\n```\n\n`getPermissions()` reads the current state without prompting. Do not cache it across sessions — a wallet may expire grants, after which they silently revert to `ask_on_use`.\n\n## Executing a call the user approves\n\n`SignerAgent` implements `Agent`, so it drops into anything that takes one: a ledger client from `@icp-sdk\u002Fcanisters`, or an actor from `@icp-sdk\u002Fbindgen` for your own canister. Each call becomes a wallet prompt.\n\n```typescript\nimport { IcrcLedgerCanister, type IcrcAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\nimport { HttpAgent } from '@icp-sdk\u002Fcore\u002Fagent';\nimport { Principal } from '@icp-sdk\u002Fcore\u002Fprincipal';\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { SignerAgent } from '@icp-sdk\u002Fsigner\u002Fagent';\n\nconst ICP_LEDGER = Principal.fromText('ryjl3-tyaaa-aaaaa-aaaba-cai');\n\n\u002F\u002F Two clients against the same ledger: one for reads, one for writes.\nasync function connectLedger(signer: Signer, account: IcrcAccount) {\n  \u002F\u002F One HttpAgent serves both. It answers reads directly, and SignerAgent\n  \u002F\u002F borrows it for the root key and status instead of building its own.\n  const agent = await HttpAgent.create({ host: 'https:\u002F\u002Ficp-api.io' });\n  \u002F\u002F SignerAgent routes calls as a principal; it has no subaccount field.\n  const signerAgent = await SignerAgent.create({ signer, account: account.owner, agent });\n\n  return {\n    \u002F\u002F Anonymous by default — public reads need no wallet and no prompt.\n    read: IcrcLedgerCanister.create({ agent, canisterId: ICP_LEDGER }),\n    write: IcrcLedgerCanister.create({ agent: signerAgent, canisterId: ICP_LEDGER }),\n    signerAgent\n  };\n}\n```\n\n**Read with the plain agent, write with the signer agent.** `SignerAgent.query()` upgrades every query into a full canister call routed through the wallet, so a balance check would put an approval prompt in front of the user. Public data does not need the wallet at all — read it with an ordinary `HttpAgent`, which is anonymous by default:\n\n```typescript\nimport { type IcrcAccount, toCandidAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\nimport { Signer } from '@icp-sdk\u002Fsigner';\n\nasync function showBalanceThenTransfer(\n  signer: Signer, account: IcrcAccount, to: IcrcAccount, amount: bigint\n) {\n  const { read, write } = await connectLedger(signer, account);\n\n  \u002F\u002F balance() takes an IcrcAccount directly.\n  const balance = await read.balance(account);                     \u002F\u002F no prompt\n\n  const block = await write.transfer({                                    \u002F\u002F prompts\n    \u002F\u002F The ledger's `to` is the Candid shape; convert rather than hand-roll it.\n    to: toCandidAccount(to),\n    \u002F\u002F The subaccount the tokens leave from.\n    from_subaccount: account.subaccount,\n    amount\n  });\n\n  return { balance, block };\n}\n```\n\n`signerAgent.replaceAccount(principal)` switches which principal later writes are signed for, without rebuilding the agent.\n\n## Channel lifecycle and page reloads\n\n`autoCloseTransportChannel` defaults to `true`: the channel closes ~200 ms after each response, so the popup does not linger. For a multi-step flow that awaits your own async work between requests, turn it off or the channel closes underneath you.\n\n```typescript\nimport { Signer } from '@icp-sdk\u002Fsigner';\n\nasync function multiStepFlow(signer: Signer) {\n  signer.autoCloseTransportChannel = false;\n  try {\n    const accounts = await signer.getAccounts();\n    await saveSelectionToYourBackend(accounts);  \u002F\u002F your own async work; channel stays open\n    return await signer.requestPermissions([{ method: 'icrc49_call_canister' }]);\n  } finally {\n    signer.autoCloseTransportChannel = true;\n    await signer.closeChannel();\n  }\n}\n```\n\n**A connection does not survive a page reload.** There is no persistent session to restore — the channel is a live `postMessage` link to a popup that is gone. The workable pattern is to persist the account, render read-only state from it with an anonymous agent, and re-establish the signer lazily on the first write:\n\n```typescript\nimport { type IcrcAccount, decodeIcrcAccount, encodeIcrcAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\nimport { HttpAgent } from '@icp-sdk\u002Fcore\u002Fagent';\nimport { Signer } from '@icp-sdk\u002Fsigner';\nimport { SignerAgent } from '@icp-sdk\u002Fsigner\u002Fagent';\n\nconst SESSION_KEY = 'wallet-account';\n\n\u002F\u002F On connect: remember the account, not the channel. The ICRC-1 textual\n\u002F\u002F encoding round-trips owner and subaccount as one string, so the\n\u002F\u002F subaccount survives the reload too (see pitfall 12).\nfunction rememberAccount(account: IcrcAccount) {\n  sessionStorage.setItem(SESSION_KEY, encodeIcrcAccount(account));\n}\n\n\u002F\u002F On reload: read-only state renders from this immediately, with no popup.\nfunction restoreAccount(): IcrcAccount | null {\n  const stored = sessionStorage.getItem(SESSION_KEY);\n  if (stored === null) return null;\n  try {\n    return decodeIcrcAccount(stored);\n  } catch {\n    sessionStorage.removeItem(SESSION_KEY);  \u002F\u002F stale or malformed\n    return null;\n  }\n}\n\n\u002F\u002F On the first write after a reload. This reopens the popup, so it must run\n\u002F\u002F from the click that starts that write — pitfall 1 applies here too.\nasync function ensureSignerAgent(signer: Signer, account: IcrcAccount, agent: HttpAgent) {\n  const offered = await signer.getAccounts();  \u002F\u002F re-establishes the channel\n  \u002F\u002F The user may have switched accounts while the page was gone, so the stored\n  \u002F\u002F one is a guess until the wallet confirms it. Compare encodings, not owners:\n  \u002F\u002F the same principal with a different subaccount is a different account.\n  const id = encodeIcrcAccount(account);\n  if (!offered.some((offer) => encodeIcrcAccount(offer) === id)) {\n    sessionStorage.removeItem(SESSION_KEY);\n    throw new Error('the wallet no longer offers the stored account; reconnect');\n  }\n  return SignerAgent.create({ signer, account: account.owner, agent });\n}\n```\n\nTreat \"disconnect\" as clearing your own state — there is no wallet-side logout to call.\n\n## Error handling\n\n```typescript\nimport { Signer, SignerError } from '@icp-sdk\u002Fsigner';\nimport { PostMessageTransportError } from '@icp-sdk\u002Fsigner\u002Fweb';\nimport type { IcrcAccount } from '@icp-sdk\u002Fcanisters\u002Fledger\u002Ficrc';\n\nasync function safeTransfer(\n  signer: Signer, account: IcrcAccount, to: IcrcAccount, amount: bigint\n) {\n  try {\n    await showBalanceThenTransfer(signer, account, to, amount);\n  } catch (err) {\n    \u002F\u002F Anything that is not a SignerError — SignerAgentError above all, where the\n    \u002F\u002F wallet responded and the response failed validation — is not handled here.\n    if (!(err instanceof SignerError)) throw err;\n\n    switch (err.code) {\n      case 3001: return;                       \u002F\u002F user cancelled — not a failure\n      case 3000: showPermissionHelp(); return; \u002F\u002F permission denied\n      case 2000: showUnsupported(); return;    \u002F\u002F wallet does not support the method\n      case 4000:                               \u002F\u002F every transport failure lands here\n      case 4001:                               \u002F\u002F only if the signer itself returns it\n        \u002F\u002F The transport error is the `cause`, never the error you caught.\n        if (err.cause instanceof PostMessageTransportError) showPopupBlockedHelp();\n        else promptReconnect();\n        return;\n    }\n\n    \u002F\u002F ICRC-25 numbers errors by range and a signer may return a code this\n    \u002F\u002F switch has never seen, so fall back on the range rather than rethrowing.\n    switch (Math.floor(err.code \u002F 1000)) {\n      case 3:\n        \u002F\u002F 3xxx is \"user action\", so nothing broke — but 3001 is the only code\n        \u002F\u002F where silence is right, because there you know they cancelled on\n        \u002F\u002F purpose. For an unnamed 3xxx say the action did not go through, or\n        \u002F\u002F the UI sits unchanged after the user pressed the button.\n        showActionNotCompleted();\n        return;\n      case 2: showUnsupported(); return;       \u002F\u002F 2xxx not supported\n      case 4: promptReconnect(); return;       \u002F\u002F 4xxx transport channel\n      default: throw err;                      \u002F\u002F 1xxx generic, and anything else\n    }\n  }\n}\n```\n\nICRC-25 groups errors into ranges and names a few codes inside each. Handle the codes you know, then fall back on the range — a signer may return `3002` or `4002`, and a bare `default: throw` would mishandle it:\n\n| Range | Code | Meaning | Handle by |\n|-------|------|---------|-----------|\n| `1xxx` general | `1000` | Generic error | Surfacing `err.data` to developers |\n| `2xxx` not supported | `2000` | Not supported | Negotiating capabilities first |\n| `3xxx` user action | `3000` | Permission not granted | Explaining what to re-grant |\n| | `3001` | **Action aborted — the user cancelled** | Returning quietly; this is normal |\n| `4xxx` transport | `4000` | Network error | Reconnecting — the library also reports every transport failure here |\n| | `4001` | Transport channel closed | Reconnecting (signer-reported only; see below) |\n\nTwo failures do not arrive as the class you would expect, and they call for opposite reactions:\n\n- **Transport failures arrive as `SignerError` with code `4000`.** `Signer.openChannel()` catches whatever the transport threw — `PostMessageTransportError`, `UrlTransportError`, `BrowserExtensionTransportError` — and rethrows it as a `SignerError` with the original as `cause`. So a blocked popup is *not* `instanceof PostMessageTransportError`; test `err.cause` for that. The library also never emits `4001`: \"channel closed before a response\" is `4000` too, and `4001` reaches you only if the signer itself returns it.\n- **`SignerAgentError`** — the wallet *did* respond, and the response failed validation: the returned content map did not match the call you sent (canister, method, argument, sender, nonce), the certificate did not verify against the IC root key, or the reply was absent from the certified tree. `SignerAgent` runs those checks for you, so this is a wallet returning something it should not have. Do not treat it as a connectivity fault and retry — surface it.\n\n## Pitfalls\n\n1. **Opening the popup outside a click handler.** `PostMessageTransport` rejects establishment that is not user-initiated (`detectNonClickEstablishment`, default `true`) because Safari and others block such popups. Connect from an event handler, never on mount or in a `useEffect`.\n\n   ```typescript\n   \u002F\u002F WRONG — blocked, and the transport detects it\n   useEffect(() => { signer.getAccounts(); }, []);\n\n   \u002F\u002F CORRECT\n   button.addEventListener('click', () => signer.getAccounts());\n   ```\n\n2. **Reading through `SignerAgent`.** `query()` is upgraded to an update call routed through the wallet, so every read costs the user an approval interaction. Public data — a ledger balance, token metadata — needs no wallet: read it with a plain `HttpAgent`, anonymous by default. Only writes go through `SignerAgent`.\n\n3. **Expecting a connection to survive a reload.** No channel outlives the page. Persist the account — both halves, per pitfall 12 — for read-only rendering, and reconnect on first write. See above.\n\n4. **Indexing `getAccounts()` blindly.** It returns a *list* of the accounts the user chose to share. ICRC-27 lets the signer prompt for that selection, so the list can be **empty** — the user declined, which is not an error — and it can hold **several**, where `[0]` silently picks for them. `accounts[0]` on an empty list is `undefined`, so the crash lands later at `.owner` rather than at the call. Check the length, and offer a picker when there is more than one.\n\n5. **Assuming a wallet's capabilities.** Call `getSupportedStandards()`. A signer may list accounts (ICRC-27) without executing calls (ICRC-49), or speak a transport you have not built for.\n\n6. **Coding against one wallet's non-standard error codes.** ICRC-25 owns `1xxx`–`4xxx` and names `1000`\u002F`2000`\u002F`3000`\u002F`3001`\u002F`4000`\u002F`4001` inside them. A code outside those ranges is a vendor extension and does not port — earlier revisions of this skill documented a `503 BUSY` that exists only in `@dfinity\u002Foisy-wallet-signer` and in no standard. Branch on the named codes, fall back on the range, and treat anything outside the ranges as generic.\n\n7. **Journaling something non-serializable through `memoize()`.** It persists via JSON, so a `Uint8Array` round-trips as `{\"0\":1,\"1\":2,…}` and a `CryptoKey` as `{}` — silently, with the flow failing on return rather than at the call. Convert to a plain array (or hex) before memoizing and back afterwards.\n\n8. **Diverging on a redirect replay.** With `UrlTransport`, issue the same requests and `memoize` steps in the same order on every load, and route anything a request depends on — a nonce above all — through `memoize`. Re-fetching a single-use value on the return load invalidates the flow.\n\n9. **A `callbackUrl` that is relative, carries a fragment, or is not served correctly.** It must be absolute, fragment-free (the transport appends its own), on an origin you control, and declared in that origin's `\u002F.well-known\u002Fii-auth-callbacks` — matched exactly, so the full URL. Declaring it is not enough: the wallet reads that document **cross-origin**, so serve it as JSON with CORS or a correctly listed callback still fails validation.\n\n    ```json\n    { \"callbacks\": [\"https:\u002F\u002Fapp.example.com\u002Fsigner-callback\"] }\n    ```\n\n    With `@dfinity\u002Fstatic-site` that is a `_headers` block:\n\n    ```\n    \u002F.well-known\u002Fii-auth-callbacks\n      Content-Type: application\u002Fjson\n      Access-Control-Allow-Origin: *\n    ```\n\n    Validation fails closed — undeclared, unreadable, or not matching exactly, and the response never comes back. See the **user-sign-in** skill, which documents the same file for redirect sign-in.\n\n10. **Top-level `await` in wallet code.** Every call here is async, and with `PostMessageTransport` a module-load `await` opens the popup outside a user gesture, which the transport rejects — pitfall 1. Wrap those calls in functions the UI invokes. `UrlTransport` is the exception, and the reverse: it navigates the top level rather than opening a popup, has no gesture check, and its flow *must* re-run on the callback-route load so the journal can replay — requiring a click there would break it. Either way, do not rely on the build to catch a stray top-level `await`: Vite ≤5 defaulted to `es2020` and rejected it outright, while Vite 6+ defaults to `baseline-widely-available` and allows it.\n\n11. **`@icp-sdk\u002Fcanisters@^3` with `@icp-sdk\u002Fsigner@^6`.** They cannot coexist — canisters 3 peers `@icp-sdk\u002Fcore@^5` or older, signer 6 peers `^6`, so `npm install` fails with `ERESOLVE`. Move to `@icp-sdk\u002Fcanisters@^4` and `@dfinity\u002Futils@^5`. Do not reach for `--legacy-peer-deps`: it skips the peer check and installs the mismatched pair anyway, so the incompatibility surfaces at runtime instead of at install time.\n\n12. **Treating an account as just a principal.** `getAccounts()` returns `{ owner, subaccount? }` — an `IcrcAccount`. The subaccount is usually absent, because signers commonly offer only the default one, so code that assumes a bare principal works until it meets a signer that does not. Carry the account whole and let the library helpers do the rest: **compare** with `encodeIcrcAccount()` and never `owner` alone (that encoding normalizes the default subaccount, so the same principal with a *different* one is correctly a different account), **persist** with `encodeIcrcAccount()` \u002F `decodeIcrcAccount()`, and **send** with `from_subaccount` for the sender plus `toCandidAccount()` for the recipient. `SignerAgent` is the exception — its `account` is a `Principal`, which is why the subaccount travels in the ledger call arguments instead.\n\n13. **Firing a call immediately after connecting.** Let the user initiate. An unprompted approval dialog straight after connect reads as an attack, and wallets are within their rights to reject it.\n\n## Testing against a real wallet\n\nThere is no local signer to run: OISY is hosted, and the transport's secure-context requirement applies to the *signer's* URL, not to your origin — `https:\u002F\u002Foisy.com\u002Fsign` satisfies it. Serving your own frontend from `localhost` is fine, and it is a browser secure context, so WebCrypto key generation works there too. Test on testnet tokens rather than mainnet value.\n\n```bash\nicp network start -d\nicp deploy\n```\n\nGet free testnet tokens from the [ICP Faucet](https:\u002F\u002Ffaucet.internetcomputer.org) and switch OISY to the **IC (testnet tokens)** network to see them. Useful ledgers:\n\n| Token | Ledger canister |\n|-------|-----------------|\n| TESTICP | `xafvr-biaaa-aaaai-aql5q-cai` |\n| TICRC1 | `3jkp5-oyaaa-aaaaj-azwqa-cai` |\n\nSet `host: 'https:\u002F\u002Ficp-api.io'` on the agent even when serving from `localhost` — `host` is the API endpoint calls go to, not the origin your app is served from.\n\n## Expected Behavior\n\n- The first `getAccounts()` opens the wallet and resolves with the accounts the user chose to share, as `{ owner: Principal, subaccount?: Uint8Array }` — possibly none of them.\n- A ledger `transfer` through `SignerAgent` shows the user the call to approve and resolves with a `bigint` block index.\n- Cancelling the **canister-call approval** rejects with `SignerError` and `code === 3001`. The other two refusals look different: declining to share accounts resolves `getAccounts()` with `[]`, and denying a permission gives code `3000`.\n- After a reload, read-only state renders with no popup; the first write reopens one.\n\n## Additional References\n\n- **user-sign-in** — II sign-in, and the place to go if you need a session rather than per-action approval\n- **agent-web-identity** — letting an agent or CLI act as the user in an II app\n- **icp-cli** — `@icp-sdk\u002Fbindgen` actors to call your own canister through a `SignerAgent`\n- **canister-security** — verifying `msg.caller` on the backend once calls arrive\n- [OISY signer demo](https:\u002F\u002Fgithub.com\u002Fdfinity\u002Fexamples\u002Ftree\u002Fmaster\u002Fhosting\u002Foisy-signer-demo) — a working relying party (React) built on `@icp-sdk\u002Fsigner`\n- [ICRC signer standards](https:\u002F\u002Fgithub.com\u002Fdfinity\u002Fwg-identity-authentication) — the specifications behind every method above\n",{"name":5,"license":15,"metadata":48,"description":7,"compatibility":51},{"title":49,"category":50},"Wallet Integration","DeFi","Node.js >= 22, a browser (secure context: HTTPS, localhost, or 127.0.0.1)","main","e981a10d43164675beb283a1ad10bc49ade686f1","skills\u002Fchains\u002Fdfinity-official-wallet-integration",17,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia","https:\u002F\u002Feth2030.com","Hardcore infra. Building @alt-research and applied cryptography.","2026-11-15 02:28:10",{"source":8,"skillName":5,"commands":62,"prompt":72,"zipAvailable":73},[63,66,69],{"tool":64,"command":65},"npx","npx skills add jiayaoqijia\u002Fcryptoskill --skill wallet-integration",{"tool":67,"command":68},"bunx","bunx skills add jiayaoqijia\u002Fcryptoskill --skill wallet-integration",{"tool":70,"command":71},"pnpm","pnpm dlx skills add jiayaoqijia\u002Fcryptoskill --skill wallet-integration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-wallet-integration\u002FSKILL.md",true,[75,79,85],{"path":76,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":78,"sourceHtmlUrl":16},"LICENSE","许可证",10770,{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"SOURCE.md","REFERENCE","参考文档",336,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-wallet-integration\u002FSOURCE.md",{"path":86,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":87,"sourceHtmlUrl":88},"TRUST.auto.yaml",2176,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-wallet-integration\u002FTRUST.auto.yaml",[90,100,108,116,124,132],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":95,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":99},"01M7DTKCERMV0RNX3HZJP4CZ26","troves","Deposit and withdraw from Troves DeFi yield vault strategies on Starknet. View available strategies, check positions, and manage vault deposits. Use this skill when the user mentions Troves, vault, yield vault, DeFi vault, strategy, yield farming, vault deposit, vault withdraw, earning yield through vaults, passive yield strategies, or wants to deposit into or withdraw from a yield strategy — even if they don't say \"Troves\" explicitly.","MIT","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":104,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":99},"01M7DTK6CJSMGC8KCQHGNYFZBD","trade","Swap tokens on Starknet via Fibrous DEX aggregator. Supports per-provider selection (avnu, ekubo, or auto to race all). Use this skill when the user wants to swap, exchange, trade, convert, buy, or sell one token for another on Starknet. Also use when the user asks about token prices, exchange rates, DEX routing, best swap route, or wants to check how much they would receive for a given amount — even if they don't explicitly say \"swap\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":112,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":99},"01M7DTJZ6A0X4PAW3Y8W4J9K64","staking","Stake, unstake, claim, and compound rewards for STRK, WBTC, tBTC, SolvBTC, and LBTC on Starknet. View validators, pools, and staking positions. Use this skill when the user mentions staking, delegating, validators, staking pools, rewards, compounding, unstaking, earning yield, passive income on crypto, or wants to earn on their STRK or BTC tokens — even if they don't say \"stake\" explicitly.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FSKILL.md",[],[],{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":120,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":99},"01M7DTJSDZJKCDMW7GHRF4BRH5","send","Send STRK, ETH, or any ERC-20 token to a Starknet address. Supports simulation (dry-run) before execution. Use this skill when the user wants to send, transfer, pay, tip, or move tokens to another wallet address on Starknet. Also trigger when the user mentions sending funds to someone, making a payment, transferring assets, or moving crypto to a specific address — even if they just say \"pay 10 STRK to 0x...\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FSKILL.md",[],[],{"skillNo":125,"name":126,"nameZh":6,"description":127,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":128,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":99},"01M7DTJG1E480D51ZQ7WKDQ26K","portfolio","View a comprehensive DeFi portfolio dashboard and optimize portfolio allocation via automated rebalancing. Use this skill when the user wants an overview, summary, dashboard, total value, net worth, portfolio rebalancing, target allocation, or wants to see all their DeFi positions across Starknet at once. Also trigger when the user asks \"what do I have\", \"show me everything\", \"how much am I worth\", \"my positions\", \"my investments\", \"rebalance my portfolio\", \"I want 50% ETH\", \"optimize my holdings\", or any request for a holistic view of their Starknet holdings — even if they don't explicitly say \"portfolio\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FSKILL.md",[],[],{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":136,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":99},"01M7DTJ7M8TE9R2N36HFBZDGVD","multi-swap","Execute multiple token swaps in a single Starknet transaction via Fibrous (default). Supports per-provider selection (avnu, ekubo, or auto to race all). Supports 2-3 swap pairs bundled into one multicall. Use this skill when the user wants to swap multiple token pairs at once, do batch swaps, execute several trades simultaneously, perform parallel swaps, or do bulk trading in one transaction. Also trigger when the user mentions \"two swaps\", \"three swaps\", \"swap X and Y at the same time\", or wants to convert multiple tokens in a single call.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FSKILL.md",[],[]]