@pepu-chain/sdk 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +26 -2
  2. package/dist/aa/kernel.cjs +11 -9
  3. package/dist/aa/kernel.guard.js +15 -0
  4. package/dist/aa/kernel.js +5 -4
  5. package/dist/aa/react-direct.cjs +14 -12
  6. package/dist/aa/react-direct.cjs.map +1 -1
  7. package/dist/aa/react-direct.guard.js +15 -0
  8. package/dist/aa/react-direct.js +7 -6
  9. package/dist/aa/react-direct.js.map +1 -1
  10. package/dist/aa/react.cjs +7 -5
  11. package/dist/aa/react.cjs.map +1 -1
  12. package/dist/aa/react.d.cts +1 -1
  13. package/dist/aa/react.d.ts +1 -1
  14. package/dist/aa/react.guard.js +15 -0
  15. package/dist/aa/react.js +4 -3
  16. package/dist/aa/react.js.map +1 -1
  17. package/dist/aa.cjs +19 -18
  18. package/dist/aa.d.cts +1 -1
  19. package/dist/aa.d.ts +1 -1
  20. package/dist/aa.js +6 -5
  21. package/dist/chunk-4GEC7GUU.cjs +283 -0
  22. package/dist/chunk-4GEC7GUU.cjs.map +1 -0
  23. package/dist/{chunk-PHM3ZORG.cjs → chunk-4L4CHIXE.cjs} +9 -9
  24. package/dist/{chunk-PHM3ZORG.cjs.map → chunk-4L4CHIXE.cjs.map} +1 -1
  25. package/dist/{chunk-A5LP2UCS.cjs → chunk-65Y5UCQ7.cjs} +2 -276
  26. package/dist/chunk-65Y5UCQ7.cjs.map +1 -0
  27. package/dist/{chunk-MBA4CLA5.js → chunk-7PVR7QSE.js} +3 -3
  28. package/dist/{chunk-MBA4CLA5.js.map → chunk-7PVR7QSE.js.map} +1 -1
  29. package/dist/{chunk-7MNJF2OB.cjs → chunk-DNWWZWUW.cjs} +4 -4
  30. package/dist/{chunk-7MNJF2OB.cjs.map → chunk-DNWWZWUW.cjs.map} +1 -1
  31. package/dist/{chunk-D52PADVY.js → chunk-GFKIM7HT.js} +25 -2
  32. package/dist/chunk-GFKIM7HT.js.map +1 -0
  33. package/dist/{chunk-IY3ALPUJ.js → chunk-GIZNH65Q.js} +5 -273
  34. package/dist/chunk-GIZNH65Q.js.map +1 -0
  35. package/dist/{chunk-WANILJZQ.cjs → chunk-HTCX46RJ.cjs} +25 -2
  36. package/dist/chunk-HTCX46RJ.cjs.map +1 -0
  37. package/dist/{chunk-TIEAZYHF.cjs → chunk-K7JSQPZO.cjs} +8 -2
  38. package/dist/chunk-K7JSQPZO.cjs.map +1 -0
  39. package/dist/{chunk-FCXSP2YF.js → chunk-KJYNF5KH.js} +8 -3
  40. package/dist/chunk-KJYNF5KH.js.map +1 -0
  41. package/dist/{chunk-KVG3AYYR.js → chunk-NHPWXIA2.js} +4 -4
  42. package/dist/{chunk-KVG3AYYR.js.map → chunk-NHPWXIA2.js.map} +1 -1
  43. package/dist/{chunk-ZB6SVBK4.js → chunk-QIDMFFAQ.js} +4 -4
  44. package/dist/{chunk-ZB6SVBK4.js.map → chunk-QIDMFFAQ.js.map} +1 -1
  45. package/dist/{chunk-IB2FSPMJ.js → chunk-QZKUPCUD.js} +3 -3
  46. package/dist/{chunk-IB2FSPMJ.js.map → chunk-QZKUPCUD.js.map} +1 -1
  47. package/dist/{chunk-ET3P6TX6.cjs → chunk-RCMKPJZO.cjs} +4 -4
  48. package/dist/{chunk-ET3P6TX6.cjs.map → chunk-RCMKPJZO.cjs.map} +1 -1
  49. package/dist/chunk-RSPAN44L.js +276 -0
  50. package/dist/chunk-RSPAN44L.js.map +1 -0
  51. package/dist/{chunk-NVOPDXTA.cjs → chunk-UQH4ZAXD.cjs} +10 -10
  52. package/dist/{chunk-NVOPDXTA.cjs.map → chunk-UQH4ZAXD.cjs.map} +1 -1
  53. package/dist/{chunk-SLW7FRTL.cjs → chunk-VYMAZVIK.cjs} +52 -22
  54. package/dist/chunk-VYMAZVIK.cjs.map +1 -0
  55. package/dist/{chunk-KIIFL4VM.js → chunk-XR5ONV2Y.js} +42 -12
  56. package/dist/chunk-XR5ONV2Y.js.map +1 -0
  57. package/dist/combo/react.cjs +62 -13
  58. package/dist/combo/react.cjs.map +1 -1
  59. package/dist/combo/react.d.cts +14 -2
  60. package/dist/combo/react.d.ts +14 -2
  61. package/dist/combo/react.guard.js +15 -0
  62. package/dist/combo/react.js +58 -11
  63. package/dist/combo/react.js.map +1 -1
  64. package/dist/combo.cjs +45 -29
  65. package/dist/combo.cjs.map +1 -1
  66. package/dist/combo.d.cts +11 -0
  67. package/dist/combo.d.ts +11 -0
  68. package/dist/combo.guard.js +15 -0
  69. package/dist/combo.js +33 -18
  70. package/dist/combo.js.map +1 -1
  71. package/dist/index.cjs +28 -23
  72. package/dist/index.cjs.map +1 -1
  73. package/dist/index.d.cts +2 -2
  74. package/dist/index.d.ts +2 -2
  75. package/dist/index.js +6 -5
  76. package/dist/index.js.map +1 -1
  77. package/dist/paymaster.cjs +39 -38
  78. package/dist/paymaster.cjs.map +1 -1
  79. package/dist/paymaster.js +4 -3
  80. package/dist/paymaster.js.map +1 -1
  81. package/dist/privy/react.cjs +1 -0
  82. package/dist/privy/react.guard.js +15 -0
  83. package/dist/privy/server.cjs +1 -0
  84. package/dist/privy/server.guard.js +15 -0
  85. package/dist/privy/wagmi.guard.js +15 -0
  86. package/dist/react.cjs +6 -4
  87. package/dist/react.cjs.map +1 -1
  88. package/dist/react.d.cts +1 -1
  89. package/dist/react.d.ts +1 -1
  90. package/dist/react.guard.js +15 -0
  91. package/dist/react.js +4 -3
  92. package/dist/react.js.map +1 -1
  93. package/dist/session/kernel.cjs +19 -17
  94. package/dist/session/kernel.guard.js +15 -0
  95. package/dist/session/kernel.js +6 -5
  96. package/dist/session/react.cjs +1 -0
  97. package/dist/session/react.guard.js +15 -0
  98. package/dist/session/server.cjs +1 -0
  99. package/dist/session/server.guard.js +15 -0
  100. package/dist/{status-DwkkOrGQ.d.ts → status-Dx9zAFo9.d.ts} +42 -10
  101. package/dist/{status-CmOsyPmO.d.cts → status-wgTM26V7.d.cts} +42 -10
  102. package/package.json +38 -2
  103. package/dist/chunk-A5LP2UCS.cjs.map +0 -1
  104. package/dist/chunk-D52PADVY.js.map +0 -1
  105. package/dist/chunk-FCXSP2YF.js.map +0 -1
  106. package/dist/chunk-IY3ALPUJ.js.map +0 -1
  107. package/dist/chunk-KIIFL4VM.js.map +0 -1
  108. package/dist/chunk-SLW7FRTL.cjs.map +0 -1
  109. package/dist/chunk-TIEAZYHF.cjs.map +0 -1
  110. package/dist/chunk-WANILJZQ.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/abi/kernelFactory.ts","../src/abi/entryPointV07.ts","../src/aa/probes.ts","../src/aa/status.ts"],"names":["parseAbi"],"mappings":";;;;;;;AA6BO,IAAM,mBAAmB,QAAA,CAAS;AAAA,EACvC,kDAAA;AAAA,EACA,+EAAA;AAAA,EACA;AACF,CAAC;AAOM,IAAM,kCAAA,GACX;ACdK,IAAM,mBAAmBA,QAAAA,CAAS;AAAA,EACvC,6EAAA;AAAA,EACA,4DAAA;AAAA,EACA,6CAAA;AAAA,EACA,8EAAA;AAAA,EACA,wJAAA;AAAA,EACA,gEAAA;AAAA,EACA;AACF,CAAC;;;ACuBD,IAAM,eAAA,GAAkB;AAAA,EACtB,uBAAA;AAAA,EACA,8BAAA;AAAA,EACA,6BAAA;AAAA,EACA,4BAAA;AAAA,EACA,kCAAA;AAAA,EACA;AACF,CAAA;AAGO,IAAM,wBAAA,GAA2B;AAAA,EACtC,uBAAA;AAAA,EACA,8BAAA;AAAA,EACA;AACF,CAAA;AAEA,IAAM,gBAAA,GAAmB,MAAA;AASzB,SAAS,iBAAiB,KAAA,EAAiE;AACzF,EAAA,IAAI,CAAC,KAAA,IAAS,KAAA,CAAM,IAAA,KAAS,kBAAkB,OAAO,KAAA;AACtD,EAAA,MAAM,OAAA,GAAU,MAAM,OAAA,IAAW,EAAA;AACjC,EAAA,IAAI,8BAAA,CAA+B,IAAA,CAAK,OAAO,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D,EAAA,MAAM,MAAA,GAAS,SAAA,GACX,4EAAA,GACA,CAAC,aACC,qHAAA,GACA,wEAAA;AACN,EAAA,OAAO;AAAA,IACL,SAAA;AAAA,IACA,SAAA,EAAW,aAAa,QAAA,GAAW,MAAA;AAAA,IACnC,OAAA,EAAS,EAAE,UAAA,EAAY,UAAA,KAAe,IAAA,EAAM,GAAI,MAAA,GAAS,EAAE,KAAA,EAAO,MAAA,EAAO,GAAI,EAAC,EAAG;AAAA,IACjF,SAAA,EAAW;AAAA,MACT,YAAY,YAAA,KAAiB,IAAA;AAAA,MAC7B,GAAI,MAAA,GAAS,EAAE,KAAA,EAAO,MAAA,KAAW,EAAC;AAAA,MAClC,GAAI,UAAA,KAAe,MAAA,GAAY,EAAE,UAAA,KAAe;AAAC,KACnD;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-XR5ONV2Y.js","sourcesContent":["import { parseAbi } from \"viem\";\n\n/**\n * ZeroDev Kernel v3 account factory ABI, at\n * `0xaac5D4240AF87249B3f71BC8E4A2cae074A3E419` (deployed on PEPU mainnet\n * only; see `pepuContracts.kernelFactory` in `../contracts.js`).\n *\n * Verified live against mainnet 2026-09-24 via `eth_call`:\n * - `implementation()` returns `0xbAC849bB641841b44E965fb01A4Bf5F074F84B4d` —\n * ZeroDev's Kernel v3.1 singleton implementation address, deployed at the\n * same address on every chain that has it via CREATE2.\n * - `getAddress(bytes,bytes32)`, called with empty `data` and a zero salt,\n * returns a computed address without reverting.\n * - `createAccount(bytes,bytes32)`, simulated (not sent) with the same\n * empty `data` and zero salt via `eth_call`, returns the **same** address\n * `getAddress` computed for those inputs — exactly the counterfactual-\n * address behavior a CREATE2 account factory is supposed to have.\n *\n * What this package does NOT ship: a helper that encodes the `data`\n * argument (Kernel v3.1's `initialize(...)` calldata — root validator,\n * hook, validator data, hook data, init config). No account has ever been\n * created through this factory on PEPU yet (its transaction history is\n * empty as of the verification date above), so there was nothing on-chain\n * to check a hand-rolled encoding against, and guessing one here would be\n * exactly the kind of invented byte layout this package's rules forbid.\n * Use ZeroDev's own `@zerodev/sdk` (or the public Kernel contracts source)\n * to build that payload, then pass the resulting bytes into\n * `getAddress`/`createAccount` from this ABI.\n */\nexport const kernelFactoryAbi = parseAbi([\n \"function implementation() view returns (address)\",\n \"function getAddress(bytes calldata data, bytes32 salt) view returns (address)\",\n \"function createAccount(bytes calldata data, bytes32 salt) payable returns (address)\",\n]);\n\n/**\n * The verified Kernel v3.1 singleton implementation address that\n * `kernelFactoryAbi`'s `implementation()` resolves to on PEPU mainnet. Same\n * address ZeroDev uses across every chain that has this Kernel version.\n */\nexport const KERNEL_V3_1_IMPLEMENTATION_ADDRESS =\n \"0xbAC849bB641841b44E965fb01A4Bf5F074F84B4d\" as const;\n","import { parseAbi } from \"viem\";\n\n/**\n * ERC-4337 EntryPoint v0.7 ABI — the subset a dapp actually needs to manage\n * a smart account's gas deposit and read its nonce, at the canonical address\n * `0x0000000071727De22E5E9d8BAf0edAc6f37da032` (deployed on PEPU mainnet\n * only; see `pepuContracts.entryPoint07` in `../contracts.js`).\n *\n * This is NOT the full `IEntryPoint` interface (no `handleOps`,\n * `simulateValidation`, etc.) — those are normally called by a bundler, and\n * PEPU has no publicly hosted bundler yet (see `getSponsorshipStatus` in\n * `../aa/status.js`). This ABI only covers deposit/nonce management, which works\n * today with a plain viem wallet client and no bundler at all.\n *\n * Verified live against mainnet 2026-09-24 via `eth_call`:\n * - `getNonce(address,uint192)` for the zero address/key returns `0`.\n * - `balanceOf(address)` for the zero address returns `0`.\n * - `getDepositInfo(address)` for the zero address returns a 5-word\n * (all-zero) tuple, matching the v0.7 `DepositInfo` struct shape\n * `(uint256 deposit, bool staked, uint96 stake, uint32 unstakeDelaySec,\n * uint48 withdrawTime)` field-for-field.\n * `depositTo`/`withdrawTo` share the same `IStakeManager` interface as the\n * verified `getDepositInfo`/`balanceOf` pair and are standard across every\n * EntryPoint version; they were not separately simulated (both mutate\n * state, and simulating a withdrawal from an empty deposit would only prove\n * it reverts, not that it works).\n */\nexport const entryPointV07Abi = parseAbi([\n \"function getNonce(address sender, uint192 key) view returns (uint256 nonce)\",\n \"function balanceOf(address account) view returns (uint256)\",\n \"function depositTo(address account) payable\",\n \"function withdrawTo(address payable withdrawAddress, uint256 withdrawAmount)\",\n \"function getDepositInfo(address account) view returns ((uint256 deposit, bool staked, uint96 stake, uint32 unstakeDelaySec, uint48 withdrawTime) info)\",\n \"event Deposited(address indexed account, uint256 totalDeposit)\",\n \"event Withdrawn(address indexed account, address withdrawAddress, uint256 amount)\",\n]);\n","import type { Address, PublicClient } from \"viem\";\n\nimport { entryPointV07Abi } from \"../abi/entryPointV07.js\";\nimport { pepuMainnet } from \"../chains.js\";\nimport { getContract } from \"../contracts.js\";\nimport { PepuBundlerError, PepuConfigError } from \"../errors.js\";\nimport { redactSecrets } from \"./describe.js\";\n\n/** Minimal fetch signature, so tests and non-browser hosts can inject one. */\nexport type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\nexport interface ProbeOptions {\n fetch?: FetchLike;\n /** Per-request timeout. Default 8000. */\n timeoutMs?: number;\n}\n\nexport interface BundlerProbeResult {\n ok: boolean;\n chainId?: number;\n entryPoints?: Address[];\n /**\n * `true` when the method exists. Each method is called with deliberately empty\n * (invalid) params, so nothing is ever sent on-chain: an \"invalid params\" or\n * validation answer means the method exists, a \"method not found\" answer\n * (including Alto's \"Invalid discriminator value\") means it does not.\n */\n supportedMethods?: Record<string, boolean>;\n /** Required methods (see `REQUIRED_BUNDLER_METHODS`) the bundler lacks. Empty when all are present. */\n missingRequiredMethods?: string[];\n latencyMs: number;\n error?: PepuBundlerError;\n}\n\nexport interface PaymasterProbeResult {\n ok: boolean;\n /** `GET <origin>/health` answered `{ status: \"ok\" }`. */\n health?: boolean;\n /** Body of `GET <origin>/v2/free-tier` when the service exposes it. */\n freeTier?: unknown;\n /**\n * `true` when the URL answered `pm_getPaymasterStubData` with a stub result,\n * `false` when it did not answer JSON-RPC at all. A JSON-RPC denial (no\n * credential, unknown sender) leaves it `undefined`: the endpoint speaks\n * ERC-7677 but the probe has no credential, so a stub cannot be judged. Read\n * `erc7677` for the three-way answer.\n */\n erc7677StubOk?: boolean;\n /**\n * `\"stub-ok\"`: a stub came back. `\"needs-credential\"`: the endpoint speaks ERC-7677\n * JSON-RPC and answered with an error (no credential, unknown sender), so the stub\n * check is not applicable without a client token. `\"not-responding\"`: no JSON-RPC answer.\n */\n erc7677?: \"stub-ok\" | \"needs-credential\" | \"not-responding\";\n latencyMs: number;\n error?: PepuBundlerError;\n}\n\nconst BUNDLER_METHODS = [\n \"eth_sendUserOperation\",\n \"eth_estimateUserOperationGas\",\n \"eth_getUserOperationReceipt\",\n \"eth_getUserOperationByHash\",\n \"pimlico_getUserOperationGasPrice\",\n \"zd_getUserOperationGasPrice\",\n] as const;\n\n/** Methods a bundler must support to be usable for PEPU sponsored UserOperations. */\nexport const REQUIRED_BUNDLER_METHODS = [\n \"eth_sendUserOperation\",\n \"eth_estimateUserOperationGas\",\n \"eth_getUserOperationReceipt\",\n] as const;\n\nconst METHOD_NOT_FOUND = -32601;\n\n/**\n * A bundler answers a method that does not exist with \"method not found\". Alto\n * (Pimlico) also reports bad params of a KNOWN method with code -32601 and a\n * \"Validation error: ...\" message, and an unknown method as \"Validation error:\n * Invalid discriminator value\". So -32601 means unsupported unless the message is\n * a params validation error that is not the discriminator one.\n */\nfunction isMethodNotFound(error: { code?: number; message?: string } | undefined): boolean {\n if (!error || error.code !== METHOD_NOT_FOUND) return false;\n const message = error.message ?? \"\";\n if (/invalid discriminator value/i.test(message)) return true;\n return !/validation error|invalid params|must contain|required at/i.test(message);\n}\n\nfunction hostOf(url: string): string {\n try {\n return new URL(url).host;\n } catch {\n return \"the configured host\";\n }\n}\n\nfunction checkUrl(url: string, label: string): void {\n let u: URL;\n try {\n u = new URL(url);\n } catch {\n throw new PepuConfigError(\"CONFIG_BAD_URL\", `${label} is not a valid URL.`);\n }\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") {\n throw new PepuConfigError(\"CONFIG_BAD_URL\", `${label} must be an http(s) URL.`);\n }\n}\n\nasync function timedFetch(f: FetchLike, url: string, init: RequestInit, timeoutMs: number): Promise<Response> {\n const ctl = new AbortController();\n const t = setTimeout(() => ctl.abort(), timeoutMs);\n try {\n return await f(url, { ...init, signal: ctl.signal });\n } finally {\n clearTimeout(t);\n }\n}\n\ninterface RpcReply {\n result?: unknown;\n error?: { code?: number; message?: string; data?: unknown };\n}\n\nasync function rpc(f: FetchLike, url: string, method: string, params: unknown[], timeoutMs: number): Promise<RpcReply> {\n const res = await timedFetch(\n f,\n url,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }),\n },\n timeoutMs,\n );\n let body: unknown;\n try {\n body = await res.json();\n } catch {\n throw new Error(`HTTP ${res.status} with a non-JSON body`);\n }\n if (!body || typeof body !== \"object\") throw new Error(`HTTP ${res.status} with an unexpected body`);\n return body as RpcReply;\n}\n\nfunction unreachable(url: string, e: unknown): PepuBundlerError {\n const reason = e instanceof Error && e.name === \"AbortError\" ? \"timed out\" : redactSecrets(e instanceof Error ? e.message : String(e)).replace(/https?:\\/\\/\\S+/g, \"[url]\");\n return new PepuBundlerError(\"BUNDLER_UNREACHABLE\", `Could not reach ${hostOf(url)}: ${reason}`, { cause: e });\n}\n\n/**\n * Probe a bundler URL: `eth_chainId`, `eth_supportedEntryPoints` and a\n * capability check of the methods PEPU apps use (a method answered with\n * anything but \"method not found\" counts as supported; nothing is sent\n * on-chain). Never throws for network trouble; returns `ok: false` with a\n * `BUNDLER_UNREACHABLE` error. Throws `CONFIG_BAD_URL` for a malformed URL.\n *\n * @example\n * const r = await probeBundler(\"https://bundler.example.com\");\n * if (!r.ok) console.log(r.error?.hint);\n */\nexport async function probeBundler(url: string, o: ProbeOptions = {}): Promise<BundlerProbeResult> {\n checkUrl(url, \"Bundler URL\");\n const f: FetchLike = o.fetch ?? ((i, init) => fetch(i, init));\n const timeoutMs = o.timeoutMs ?? 8000;\n const started = Date.now();\n try {\n const chain = await rpc(f, url, \"eth_chainId\", [], timeoutMs);\n const eps = await rpc(f, url, \"eth_supportedEntryPoints\", [], timeoutMs);\n const chainId = typeof chain.result === \"string\" ? Number(BigInt(chain.result)) : undefined;\n const entryPoints = Array.isArray(eps.result) ? (eps.result as Address[]) : undefined;\n const supportedMethods: Record<string, boolean> = {};\n for (const m of BUNDLER_METHODS) {\n try {\n const r = await rpc(f, url, m, [], timeoutMs);\n supportedMethods[m] = !isMethodNotFound(r.error);\n } catch {\n supportedMethods[m] = false;\n }\n }\n const ep07 = getContract(pepuMainnet.id, \"entryPoint07\");\n const want = ep07?.status === \"deployed\" ? ep07.address.toLowerCase() : undefined;\n const missing = REQUIRED_BUNDLER_METHODS.filter((m) => supportedMethods[m] !== true);\n const chainAndEntryPointOk =\n chainId === pepuMainnet.id &&\n (want === undefined || (entryPoints?.some((a) => a.toLowerCase() === want) ?? false));\n const ok = chainAndEntryPointOk && missing.length === 0;\n const out: BundlerProbeResult = {\n ok,\n latencyMs: Date.now() - started,\n supportedMethods,\n missingRequiredMethods: [...missing],\n };\n if (chainId !== undefined) out.chainId = chainId;\n if (entryPoints) out.entryPoints = entryPoints;\n if (!ok) {\n out.error = new PepuBundlerError(\n \"BUNDLER_UNREACHABLE\",\n chainId !== undefined && chainId !== pepuMainnet.id\n ? `The bundler serves chain ${chainId}, not ${pepuMainnet.id}.`\n : !chainAndEntryPointOk\n ? \"The bundler does not list EntryPoint v0.7.\"\n : `The bundler does not support ${missing.join(\", \")}.`,\n {\n hint: \"Point PEPU_BUNDLER_URL at a bundler for chain 97741 that supports EntryPoint v0.7 and the ERC-4337 UserOperation methods.\",\n },\n );\n }\n return out;\n } catch (e) {\n return { ok: false, latencyMs: Date.now() - started, error: unreachable(url, e) };\n }\n}\n\nconst STUB_PROBE_OP = {\n sender: \"0x0000000000000000000000000000000000000001\",\n nonce: \"0x0\",\n callData: \"0x\",\n callGasLimit: \"0x0\",\n verificationGasLimit: \"0x0\",\n preVerificationGas: \"0x0\",\n maxFeePerGas: \"0x0\",\n maxPriorityFeePerGas: \"0x0\",\n signature: \"0x\",\n} as const;\n\n/**\n * Probe a paymaster URL: the service base (`https://paymaster.pepeunchained.com`) or the ERC-7677 endpoint\n * (`https://host/v2/paymaster/<token>`).\n * Checks `GET <origin>/health`, `GET <origin>/v2/free-tier`, and whether the URL\n * answers JSON-RPC `pm_getPaymasterStubData` (`erc7677`: without a client token a\n * JSON-RPC denial is reported as `\"needs-credential\"`, not as a failure). `ok` means\n * every capability that could be checked is fine: `/health` did not fail and the URL\n * spoke ERC-7677 JSON-RPC. The URL (which can embed a\n * token) never appears in the returned error.\n *\n * @example\n * const r = await probePaymaster(process.env.PEPU_PAYMASTER_URL!);\n * console.log(r.ok, r.freeTier);\n */\nexport async function probePaymaster(url: string, o: ProbeOptions = {}): Promise<PaymasterProbeResult> {\n checkUrl(url, \"Paymaster URL\");\n const f: FetchLike = o.fetch ?? ((i, init) => fetch(i, init));\n const timeoutMs = o.timeoutMs ?? 8000;\n const started = Date.now();\n const origin = new URL(url).origin;\n const out: PaymasterProbeResult = { ok: false, latencyMs: 0 };\n let reached = false;\n let lastError: unknown;\n\n try {\n const res = await timedFetch(f, `${origin}/health`, { method: \"GET\" }, timeoutMs);\n reached = true;\n const body = (await res.json().catch(() => null)) as { status?: unknown } | null;\n out.health = res.ok && body?.status === \"ok\";\n } catch (e) {\n lastError = e;\n out.health = false;\n }\n\n try {\n const res = await timedFetch(f, `${origin}/v2/free-tier`, { method: \"GET\" }, timeoutMs);\n reached = true;\n if (res.ok) out.freeTier = await res.json().catch(() => undefined);\n } catch (e) {\n lastError = e;\n }\n\n let speaksRpc = false;\n try {\n const ep07 = getContract(pepuMainnet.id, \"entryPoint07\");\n const ep = ep07?.status === \"deployed\" ? ep07.address : \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\";\n const reply = await rpc(\n f,\n url,\n \"pm_getPaymasterStubData\",\n [STUB_PROBE_OP, ep, `0x${pepuMainnet.id.toString(16)}`, {}],\n timeoutMs,\n );\n reached = true;\n // A JSON-RPC answer has a result, or an error OBJECT (a REST 404 body like {\"error\":\"not_found\"} is not one).\n const rpcError = reply.error !== null && typeof reply.error === \"object\";\n speaksRpc = reply.result !== undefined || rpcError;\n if (reply.result !== undefined) {\n out.erc7677StubOk = true;\n out.erc7677 = \"stub-ok\";\n } else if (rpcError) {\n // Alive and speaking JSON-RPC, but the probe has no credential: not applicable, not a failure.\n out.erc7677 = \"needs-credential\";\n } else {\n out.erc7677StubOk = false;\n out.erc7677 = \"not-responding\";\n }\n } catch (e) {\n lastError = e;\n out.erc7677StubOk = false;\n out.erc7677 = \"not-responding\";\n }\n\n out.latencyMs = Date.now() - started;\n out.ok = speaksRpc && out.health !== false;\n if (!reached) out.error = unreachable(url, lastError);\n else if (!out.ok) {\n out.error = new PepuBundlerError(\"BUNDLER_UNREACHABLE\", `${hostOf(url)} answered but is not a PEPU paymaster service.`, {\n hint: \"Check PEPU_PAYMASTER_URL points at the policy service (https://paymaster.pepeunchained.com), or its /v2/paymaster/<client token> endpoint.\",\n });\n }\n return out;\n}\n\n/**\n * The paymaster's EntryPoint v0.7 deposit in wei. A drop across a UserOperation\n * is the proof that it was sponsored. Defaults to PEPU's deployed paymaster.\n *\n * @example\n * const before = await getPaymasterDeposit(publicClient);\n */\nexport async function getPaymasterDeposit(client: PublicClient, paymaster?: Address): Promise<bigint> {\n const pm = getContract(pepuMainnet.id, \"paymaster\");\n const ep = getContract(pepuMainnet.id, \"entryPoint07\");\n const account = paymaster ?? (pm?.status === \"deployed\" ? pm.address : undefined);\n if (!account || ep?.status !== \"deployed\") {\n throw new PepuConfigError(\"CONFIG_MISSING_ENV\", \"No paymaster address is known; pass one explicitly.\", {\n hint: \"Pass the paymaster address as the second argument.\",\n });\n }\n return client.readContract({\n address: ep.address,\n abi: entryPointV07Abi,\n functionName: \"balanceOf\",\n args: [account],\n });\n}\n","import type { Address, Hex, PublicClient, Transport } from \"viem\";\n\nimport { kernelFactoryAbi } from \"../abi/kernelFactory.js\";\nimport type { PepuChain } from \"../chains.js\";\nimport type { DeployedContract } from \"../contracts.js\";\nimport { getContract } from \"../contracts.js\";\nimport { PEPU_ENV, resolvePepuEndpoints } from \"../endpoints.js\";\nimport { getPaymasterDeposit, probeBundler, probePaymaster } from \"./probes.js\";\nimport type { BundlerProbeResult, FetchLike, PaymasterProbeResult } from \"./probes.js\";\n\n/**\n * The account-abstraction contracts a Kernel v3 smart account needs,\n * narrowed to their {@link DeployedContract} form for a given chain.\n * Returns `undefined` if any one of them isn't deployed on that chain\n * (today: everything except mainnet, `97741`) — this package never fabricates\n * a partial/best-effort bundle.\n */\nexport interface PepuKernelStack {\n readonly entryPoint06: DeployedContract;\n readonly entryPoint07: DeployedContract;\n readonly kernelFactory: DeployedContract;\n readonly kernelMetaFactory: DeployedContract;\n readonly ecdsaValidator: DeployedContract;\n}\n\n/**\n * Look up every AA contract this package knows about for `chainId`, already\n * narrowed to {@link DeployedContract}. Returns `undefined` unless *all* five\n * are deployed on that chain (today, only PEPU mainnet qualifies) — a caller\n * building a Kernel account needs every one of them, so a partial result\n * would just move the \"is this actually usable\" check into every caller.\n *\n * This is a convenience grouping over `getContract` from `./contracts.js`;\n * it doesn't add any address or fact that registry doesn't already have.\n */\nexport function getPepuKernelStack(chainId: number): PepuKernelStack | undefined {\n const entryPoint06 = getContract(chainId, \"entryPoint06\");\n const entryPoint07 = getContract(chainId, \"entryPoint07\");\n const kernelFactory = getContract(chainId, \"kernelFactory\");\n const kernelMetaFactory = getContract(chainId, \"kernelMetaFactory\");\n const ecdsaValidator = getContract(chainId, \"ecdsaValidator\");\n\n if (\n entryPoint06?.status !== \"deployed\" ||\n entryPoint07?.status !== \"deployed\" ||\n kernelFactory?.status !== \"deployed\" ||\n kernelMetaFactory?.status !== \"deployed\" ||\n ecdsaValidator?.status !== \"deployed\"\n ) {\n return undefined;\n }\n\n return { entryPoint06, entryPoint07, kernelFactory, kernelMetaFactory, ecdsaValidator };\n}\n\n/**\n * Legacy static gas-sponsorship status for PEPU. **Always reports\n * unavailable** (it never probes). Sponsorship is PROVEN end to end on PEPU\n * mainnet through the hosted bundler and paymaster service (a zero-balance\n * Kernel smart account transacted, paid for by the paymaster); use\n * `checkSponsorship()` for the live answer. This function\n * exists so nothing downstream (this package, `@pepu-chain/mcp`, an app)\n * has to independently invent an \"is sponsorship on?\" check, and so that\n * check can't silently start lying once this file changes.\n *\n * Do not treat the presence of `kernelFactory`/`ecdsaValidator`/`paymaster`\n * addresses in {@link getPepuKernelStack} / the contract registry as\n * sponsorship support — those let you build and deploy a Kernel account and\n * send its UserOperations through a normal `eth_sendTransaction`-style flow\n * (self-paying its own gas via the EntryPoint deposit), which is a real,\n * working feature; sponsoring that gas needs a funded project or free-tier token.\n */\nexport interface SponsorshipStatus {\n readonly available: false;\n readonly reason: string;\n /**\n * Extension point for a future bundler/paymaster integration. Passing a\n * URL here does **not** make sponsorship available — `available` stays\n * `false` regardless — this field only exists so a caller can start\n * wiring a URL through their own config today and have this function\n * start using it later without an API change.\n */\n readonly bundlerUrl?: string;\n}\n\n/** Options for {@link getSponsorshipStatus}. */\nexport interface GetSponsorshipStatusOptions {\n /** See {@link SponsorshipStatus.bundlerUrl}. Not yet used for anything. */\n readonly bundlerUrl?: string;\n}\n\n/**\n * @deprecated Always reports `available: false`. Use `checkSponsorship()` (live\n * bundler and paymaster probe) from `@pepu-chain/sdk`. Kept for 0.1 callers.\n */\nexport function getSponsorshipStatus(\n options?: GetSponsorshipStatusOptions,\n): SponsorshipStatus {\n const reason =\n \"This deprecated function never probes anything and always reports \" +\n \"unavailable. The hosted bundler (bundler.pepeunchained.com) and \" +\n \"paymaster service (paymaster.pepeunchained.com) are live, and \" +\n \"sponsorship is proven end to end on mainnet through them. Call \" +\n \"checkSponsorship() for the live status. A Kernel v3 smart account \" +\n \"without a funded project or free-tier token must still fund its own \" +\n \"EntryPoint deposit and pay its own gas, like a normal EOA-sent transaction.\";\n return options?.bundlerUrl === undefined\n ? { available: false, reason }\n : { available: false, reason, bundlerUrl: options.bundlerUrl };\n}\n\n/**\n * Compute (or confirm) the counterfactual address of a Kernel v3 smart\n * account via the verified factory's `getAddress(data, salt)` — a thin,\n * typed pass-through, not a re-implementation.\n *\n * Deliberately does **not** build `data` (Kernel v3.1's `initialize(...)`\n * calldata: root validator, hook, validator data, hook data, init config)\n * for you. A hand-rolled encoding here would be a second, unverified copy of\n * the byte layout that ZeroDev's SDK already produces (and that has been\n * exercised against PEPU's factory through the sponsored-transaction run),\n * which is exactly the kind of invented encoding this package's rules\n * forbid for addresses. Build `data` with ZeroDev's\n * `@zerodev/sdk` (or by hand from the public Kernel v3 contracts source),\n * then pass the result here.\n */\nexport async function getKernelAccountAddress(\n client: PublicClient<Transport, PepuChain>,\n factory: Pick<DeployedContract, \"address\">,\n args: { readonly data: Hex; readonly salt: Hex },\n): Promise<Address> {\n return client.readContract({\n address: factory.address,\n abi: kernelFactoryAbi,\n functionName: \"getAddress\",\n args: [args.data, args.salt],\n });\n}\n\n/** Live sponsorship report from {@link checkSponsorship}. */\nexport interface SponsorshipReport {\n /** True only when a bundler and a paymaster are configured and both answer. */\n available: boolean;\n /** `direct` when you bring your own bundler and paymaster URLs; `none` when nothing is configured. */\n transport: \"direct\" | \"none\";\n bundler: { configured: boolean; probe?: BundlerProbeResult };\n paymaster: { configured: boolean; probe?: PaymasterProbeResult; depositWei?: bigint };\n /** One sentence for a human or an agent. */\n reason: string;\n /** Concrete next steps, empty when `available`. */\n fixes: string[];\n}\n\n/** Options for {@link checkSponsorship}. */\nexport interface CheckSponsorshipOptions {\n bundlerUrl?: string;\n paymasterUrl?: string;\n env?: Record<string, string | undefined>;\n fetch?: FetchLike;\n /** When given, also read the paymaster's EntryPoint deposit. */\n publicClient?: PublicClient;\n /** Paymaster contract to read the deposit of. Defaults to PEPU's deployed paymaster. */\n paymasterAddress?: Address;\n timeoutMs?: number;\n}\n\n/**\n * Live gas-sponsorship status. Resolves the bundler and paymaster URLs from\n * options, env, then the hosted defaults (bundler.pepeunchained.com and the paymaster\n * service base; with no token URL the service is probed at its base), probes both,\n * and optionally reads the paymaster deposit. Never throws for an\n * unreachable service; it reports `available: false` with `fixes`.\n * Replaces the hard-coded {@link getSponsorshipStatus}.\n *\n * @example\n * const s = await checkSponsorship({ publicClient });\n * if (!s.available) console.log(s.reason, s.fixes);\n */\nexport async function checkSponsorship(options: CheckSponsorshipOptions = {}): Promise<SponsorshipReport> {\n const { bundlerUrl, paymasterUrl: erc7677Url, paymasterBaseUrl } = resolvePepuEndpoints({\n ...(options.bundlerUrl !== undefined ? { bundlerUrl: options.bundlerUrl } : {}),\n ...(options.paymasterUrl !== undefined ? { paymasterUrl: options.paymasterUrl } : {}),\n ...(options.env ? { env: options.env } : {}),\n });\n // No token means no complete ERC-7677 URL: probe the service base (health + free-tier state) instead.\n const paymasterUrl = erc7677Url ?? paymasterBaseUrl;\n const probeOpts = {\n ...(options.fetch ? { fetch: options.fetch } : {}),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n };\n const fixes: string[] = [];\n if (bundlerUrl === null) fixes.push(`Set ${PEPU_ENV.bundlerUrl} to a bundler for chain 97741 (EntryPoint v0.7).`);\n if (paymasterUrl === null) fixes.push(`Set ${PEPU_ENV.paymasterUrl} to your ERC-7677 paymaster endpoint (https://paymaster.pepeunchained.com/v2/paymaster/<client token>).`);\n\n const [bProbe, pProbe] = await Promise.all([\n bundlerUrl === null ? undefined : probeBundler(bundlerUrl, probeOpts),\n paymasterUrl === null ? undefined : probePaymaster(paymasterUrl, probeOpts),\n ]);\n if (bProbe && !bProbe.ok) fixes.push(bProbe.error?.hint ?? \"The bundler did not answer correctly.\");\n if (pProbe && !pProbe.ok) fixes.push(pProbe.error?.hint ?? \"The paymaster did not answer correctly.\");\n\n let depositWei: bigint | undefined;\n if (options.publicClient) {\n try {\n depositWei = await getPaymasterDeposit(options.publicClient, options.paymasterAddress);\n if (depositWei === 0n) fixes.push(\"The paymaster's EntryPoint deposit is empty. Deposit PEPU to it.\");\n } catch {\n // A failed read must not flip availability; the probes are the source of truth.\n }\n }\n\n const available = !!bProbe?.ok && !!pProbe?.ok && depositWei !== 0n;\n const configured = bundlerUrl !== null || paymasterUrl !== null;\n const reason = available\n ? \"Bundler and paymaster are reachable; sponsored UserOperations can be sent.\"\n : !configured\n ? \"No bundler or paymaster URL is configured. Set PEPU_BUNDLER_URL and PEPU_PAYMASTER_URL, or use the hosted defaults.\"\n : \"A bundler or paymaster is configured but not fully working. See fixes.\";\n return {\n available,\n transport: configured ? \"direct\" : \"none\",\n bundler: { configured: bundlerUrl !== null, ...(bProbe ? { probe: bProbe } : {}) },\n paymaster: {\n configured: paymasterUrl !== null,\n ...(pProbe ? { probe: pProbe } : {}),\n ...(depositWei !== undefined ? { depositWei } : {}),\n },\n reason,\n fixes,\n };\n}\n"]}
@@ -1,12 +1,14 @@
1
1
  'use strict';
2
+ /* @pepu-chain/peer-guard */(function(){var p=["react","@privy-io/react-auth","@zerodev/sdk","@zerodev/permissions","@zerodev/ecdsa-validator"];for(var i=0;i<p.length;i++){try{require.resolve(p[i])}catch(e){if(e&&e.code==="MODULE_NOT_FOUND"){var m="@pepu-chain/sdk/combo/react needs peer packages that are not installed: react @privy-io/react-auth @zerodev/sdk @zerodev/permissions @zerodev/ecdsa-validator. Install with: npm i react @privy-io/react-auth @zerodev/sdk @zerodev/permissions @zerodev/ecdsa-validator (or let create-pepu-app scaffold everything).";var x=new Error(m);x.code="PEPU_MISSING_PEER";throw x}}}})();
2
3
 
3
4
  var chunkR5PXQNO3_cjs = require('../chunk-R5PXQNO3.cjs');
4
- var chunkPHM3ZORG_cjs = require('../chunk-PHM3ZORG.cjs');
5
- var chunkNVOPDXTA_cjs = require('../chunk-NVOPDXTA.cjs');
6
- require('../chunk-7MNJF2OB.cjs');
5
+ var chunk4L4CHIXE_cjs = require('../chunk-4L4CHIXE.cjs');
6
+ var chunkUQH4ZAXD_cjs = require('../chunk-UQH4ZAXD.cjs');
7
+ require('../chunk-DNWWZWUW.cjs');
7
8
  require('../chunk-AJS4UFQX.cjs');
8
- require('../chunk-A5LP2UCS.cjs');
9
- require('../chunk-WANILJZQ.cjs');
9
+ require('../chunk-4GEC7GUU.cjs');
10
+ require('../chunk-HTCX46RJ.cjs');
11
+ require('../chunk-65Y5UCQ7.cjs');
10
12
  var chunkDH6BFNVJ_cjs = require('../chunk-DH6BFNVJ.cjs');
11
13
  require('../chunk-NE3QKDOB.cjs');
12
14
  var chunkJ3O2ZGG3_cjs = require('../chunk-J3O2ZGG3.cjs');
@@ -34,6 +36,22 @@ function deriveSessionPhase(p) {
34
36
  if (p.validUntil !== void 0) return p.nowSeconds < p.validUntil ? "active" : "expired";
35
37
  return p.hasError ? "error" : "ready";
36
38
  }
39
+ var PROVISIONING_RETRY_DELAYS_MS = [500, 1e3, 2e3, 3e3];
40
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
41
+ function isProvisioning(e) {
42
+ return e?.code === "WALLET_NOT_PROVISIONED";
43
+ }
44
+ async function whileProvisioning(fn, delays) {
45
+ for (let i = 0; ; i++) {
46
+ try {
47
+ return await fn();
48
+ } catch (e) {
49
+ const delay = delays[i];
50
+ if (!isProvisioning(e) || delay === void 0) throw e;
51
+ await sleep(delay);
52
+ }
53
+ }
54
+ }
37
55
  async function postJson(authFetch, url, body) {
38
56
  const res = await authFetch(url, {
39
57
  method: "POST",
@@ -44,16 +62,20 @@ async function postJson(authFetch, url, body) {
44
62
  }
45
63
  async function grantKernelSession(p) {
46
64
  const ep = { ...DEFAULT_SESSION_ENDPOINTS, ...p.endpoints };
47
- const prepared = await postJson(p.authFetch, ep.prepare);
48
- const { approval } = await chunkPHM3ZORG_cjs.approveKernelSession({
65
+ const prepared = await whileProvisioning(
66
+ () => postJson(p.authFetch, ep.prepare),
67
+ p.provisioningRetryDelaysMs ?? PROVISIONING_RETRY_DELAYS_MS
68
+ );
69
+ const { approval } = await chunk4L4CHIXE_cjs.approveKernelSession({
49
70
  publicClient: p.publicClient,
50
71
  owner: p.owner,
51
72
  sessionKeyAddress: prepared.sessionKeyAddress,
52
- policies: chunkPHM3ZORG_cjs.buildKernelSessionPolicies({ calls: p.scope.calls, validUntil: prepared.validUntil })
73
+ policies: chunk4L4CHIXE_cjs.buildKernelSessionPolicies({ calls: p.scope.calls, validUntil: prepared.validUntil })
53
74
  });
54
75
  await postJson(p.authFetch, ep.activate, { approval });
55
76
  return prepared;
56
77
  }
78
+ var STATUS_PROVISIONING_DELAYS_MS = [...PROVISIONING_RETRY_DELAYS_MS, 5e3, 5e3, 5e3, 5e3, 5e3];
57
79
  var sharedClient;
58
80
  function defaultPublicClient() {
59
81
  sharedClient ??= chunkC7IC36XS_cjs.getPublicClient(chunkDPCZJLB3_cjs.pepuMainnet);
@@ -84,13 +106,17 @@ function useSponsoredSession(o) {
84
106
  const refetch = react.useCallback(() => setTick((t) => t + 1), []);
85
107
  const [lastValidUntil, setLastValidUntil] = react.useState();
86
108
  const grantInFlight = react.useRef(false);
109
+ const provisioningDelays = o.provisioningRetryDelaysMs ?? STATUS_PROVISIONING_DELAYS_MS;
110
+ const delaysRef = react.useRef(provisioningDelays);
111
+ delaysRef.current = provisioningDelays;
112
+ const provisioningAttempts = react.useRef(0);
87
113
  react.useEffect(() => {
88
114
  if (!owner) {
89
115
  setSmartAccount(void 0);
90
116
  return;
91
117
  }
92
118
  let cancelled = false;
93
- chunkNVOPDXTA_cjs.getKernelAddress(publicClient, owner).then((a) => {
119
+ chunkUQH4ZAXD_cjs.getKernelAddress(publicClient, owner).then((a) => {
94
120
  if (!cancelled) setSmartAccount(a);
95
121
  }).catch((e) => {
96
122
  if (!cancelled) setError(chunkYQL7NISX_cjs.toPepuError(e, { op: "derive smart account" }));
@@ -102,24 +128,45 @@ function useSponsoredSession(o) {
102
128
  react.useEffect(() => {
103
129
  if (!authenticated || !owner) return;
104
130
  let cancelled = false;
131
+ let timer;
132
+ const retryLater = () => {
133
+ const delay = delaysRef.current[provisioningAttempts.current];
134
+ if (delay === void 0) return false;
135
+ provisioningAttempts.current += 1;
136
+ timer = setTimeout(() => {
137
+ if (!cancelled) refetch();
138
+ }, delay);
139
+ return true;
140
+ };
105
141
  void (async () => {
142
+ let waiting = false;
106
143
  try {
107
144
  const res = await authFetch(endpointsRef.current.status);
108
145
  if (!res.ok) throw await chunkR5PXQNO3_cjs.errorFromResponse(res);
109
146
  const body = await res.json();
110
147
  if (cancelled) return;
148
+ if (!body.active && body.provisioning) {
149
+ waiting = retryLater();
150
+ if (!waiting) setStatus({ active: false });
151
+ return;
152
+ }
153
+ provisioningAttempts.current = 0;
111
154
  setStatus(body);
155
+ setError(void 0);
112
156
  if (body.active) setLastValidUntil(body.validUntil);
113
157
  } catch (e) {
114
- if (!cancelled) setError(chunkYQL7NISX_cjs.toPepuError(e, { op: "session status" }));
158
+ if (cancelled) return;
159
+ if (isProvisioning(e) && (waiting = retryLater())) return;
160
+ setError(chunkYQL7NISX_cjs.toPepuError(e, { op: "session status" }));
115
161
  } finally {
116
- if (!cancelled) setStatusChecked(true);
162
+ if (!cancelled && !waiting) setStatusChecked(true);
117
163
  }
118
164
  })();
119
165
  return () => {
120
166
  cancelled = true;
167
+ if (timer) clearTimeout(timer);
121
168
  };
122
- }, [authenticated, owner, authFetch, tick]);
169
+ }, [authenticated, owner, authFetch, tick, refetch]);
123
170
  react.useEffect(() => {
124
171
  const id = setInterval(() => setNow(Math.floor(Date.now() / 1e3)), 1e3);
125
172
  return () => clearInterval(id);
@@ -149,7 +196,8 @@ function useSponsoredSession(o) {
149
196
  publicClient,
150
197
  owner: walletClient,
151
198
  scope: scopeRef.current,
152
- endpoints: endpointsRef.current
199
+ endpoints: endpointsRef.current,
200
+ provisioningRetryDelaysMs: delaysRef.current
153
201
  });
154
202
  setPrepared(result);
155
203
  setLastValidUntil(result.validUntil);
@@ -228,6 +276,7 @@ function useSponsoredSession(o) {
228
276
  }
229
277
 
230
278
  exports.DEFAULT_SESSION_ENDPOINTS = DEFAULT_SESSION_ENDPOINTS;
279
+ exports.PROVISIONING_RETRY_DELAYS_MS = PROVISIONING_RETRY_DELAYS_MS;
231
280
  exports.deriveSessionPhase = deriveSessionPhase;
232
281
  exports.grantKernelSession = grantKernelSession;
233
282
  exports.useSponsoredSession = useSponsoredSession;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/combo/react.ts"],"names":["errorFromResponse","approveKernelSession","buildKernelSessionPolicies","getPublicClient","pepuMainnet","usePrivy","useEmbeddedWallet","usePepuAuthFetch","useCallback","useRef","useState","useEffect","getKernelAddress","toPepuError","PepuAuthError","createWalletClient","custom","describeKernelSessionScope"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyCO,IAAM,yBAAA,GAAuD;AAAA,EAClE,OAAA,EAAS,sBAAA;AAAA,EACT,QAAA,EAAU,uBAAA;AAAA,EACV,MAAA,EAAQ,qBAAA;AAAA,EACR,GAAA,EAAK,kBAAA;AAAA,EACL,MAAA,EAAQ;AACV;AAuBO,SAAS,mBAAmB,CAAA,EAQT;AACxB,EAAA,IAAI,CAAC,CAAA,CAAE,aAAA,EAAe,OAAO,YAAA;AAC7B,EAAA,IAAI,CAAC,CAAA,CAAE,SAAA,EAAW,OAAO,cAAA;AACzB,EAAA,IAAI,CAAA,CAAE,UAAU,OAAO,UAAA;AACvB,EAAA,IAAI,CAAA,CAAE,eAAe,MAAA,EAAW,OAAO,EAAE,UAAA,GAAa,CAAA,CAAE,aAAa,QAAA,GAAW,SAAA;AAChF,EAAA,OAAO,CAAA,CAAE,WAAW,OAAA,GAAU,OAAA;AAChC;AAwBA,eAAe,QAAA,CAAY,SAAA,EAAsB,GAAA,EAAa,IAAA,EAA4B;AACxF,EAAA,MAAM,GAAA,GAAM,MAAM,SAAA,CAAU,GAAA,EAAK;AAAA,IAC/B,MAAA,EAAQ,MAAA;AAAA,IACR,GAAI,IAAA,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A;AAAA,IACA,GAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,GAAI,KAAA,GAAQ,EAAE,KAAA,KAAU;AAAC,GAC3B;AACF","file":"react.cjs","sourcesContent":["import { usePrivy } from \"@privy-io/react-auth\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createWalletClient, custom } from \"viem\";\nimport type { Address, PublicClient } from \"viem\";\nimport { pepuMainnet } from \"../chains.js\";\nimport { getPublicClient } from \"../client.js\";\nimport { PepuAuthError, toPepuError } from \"../errors.js\";\nimport type { PepuError } from \"../errors.js\";\nimport { usePepuAuthFetch, useEmbeddedWallet } from \"../privy/react.js\";\nimport { errorFromResponse } from \"../session/react.js\";\nimport type { AuthFetch } from \"../session/react.js\";\nimport { approveKernelSession, buildKernelSessionPolicies, getKernelAddress } from \"../session/kernel.js\";\nimport type { KernelOwner } from \"../session/kernel.js\";\nimport { describeKernelSessionScope } from \"../session/scope.js\";\nimport type { KernelSessionCall, KernelSessionScope } from \"../session/scope.js\";\n\nexport type { SponsoredActResult } from \"./types.js\";\n\n/**\n * `@pepu-chain/sdk/combo/react` (browser): hooks for the combined flow. Google\n * sign-in (Privy), ONE owner signature for an on-chain session, then actions\n * with no popup and no gas. Pairs with `createSponsoredSessionRoutes` from\n * `@pepu-chain/sdk/combo`.\n *\n * Extracted from templates/sponsored-session-app/components/session-flow.tsx.\n * The browser's only signing job is the grant; everything after it is a request\n * to your own server, authenticated by the Privy access token.\n *\n * Needs `react`, `@privy-io/react-auth` and the `@zerodev/*` peers.\n */\n\n/** The routes {@link useSponsoredSession} calls. */\nexport interface SponsoredSessionEndpoints {\n prepare: string;\n activate: string;\n status: string;\n act: string;\n revoke: string;\n}\n\n/** Defaults match the `app/api/session/<name>/route.ts` convention. */\nexport const DEFAULT_SESSION_ENDPOINTS: SponsoredSessionEndpoints = {\n prepare: \"/api/session/prepare\",\n activate: \"/api/session/activate\",\n status: \"/api/session/status\",\n act: \"/api/session/act\",\n revoke: \"/api/session/revoke\",\n};\n\n/** Where the session flow is, for rendering. */\nexport type SponsoredSessionPhase =\n | \"signed-out\"\n | \"provisioning\"\n | \"ready\"\n | \"granting\"\n | \"active\"\n | \"expired\"\n | \"error\";\n\n/**\n * Derive the phase from plain inputs. Pure.\n *\n * - not signed in: `signed-out`; signed in without an embedded wallet: `provisioning`\n * - a grant in flight: `granting`\n * - an expiry that has passed: `expired`; one still ahead: `active`\n * - an error with nothing active: `error`; otherwise `ready`\n *\n * @example\n * deriveSessionPhase({ authenticated: true, hasWallet: true, validUntil: 100, nowSeconds: 200 }); // \"expired\"\n */\nexport function deriveSessionPhase(p: {\n authenticated: boolean;\n hasWallet: boolean;\n /** The last expiry the server reported for an active session, if any. */\n validUntil?: number | undefined;\n nowSeconds: number;\n granting?: boolean;\n hasError?: boolean;\n}): SponsoredSessionPhase {\n if (!p.authenticated) return \"signed-out\";\n if (!p.hasWallet) return \"provisioning\";\n if (p.granting) return \"granting\";\n if (p.validUntil !== undefined) return p.nowSeconds < p.validUntil ? \"active\" : \"expired\";\n return p.hasError ? \"error\" : \"ready\";\n}\n\n/** What the server's `prepare` route returns. */\nexport interface PreparedSession {\n ownerAddress: Address;\n kernelAddress: Address;\n sessionKeyAddress: Address;\n validUntil: number;\n minutes: number;\n scope: KernelSessionScope;\n}\n\n/** What the server's `status` route returns. */\nexport type SponsoredSessionStatus =\n | { active: false }\n | {\n active: true;\n validUntil: number;\n kernelAddress: Address;\n ownerAddress: Address;\n sessionKeyAddress: Address;\n actions: number;\n };\n\nasync function postJson<T>(authFetch: AuthFetch, url: string, body?: unknown): Promise<T> {\n const res = await authFetch(url, {\n method: \"POST\",\n ...(body === undefined\n ? {}\n : { headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(body) }),\n });\n if (!res.ok) throw await errorFromResponse(res);\n return (await res.json()) as T;\n}\n\n/**\n * The grant, outside React: ask the server to `prepare` a session key, have\n * `owner` sign the ONE EIP-712 approval (no gas), then `activate`. Rebuilds\n * the policies from `scope` and the server's expiry; the server checks the\n * resulting permission id matches what it issued, so a different scope is\n * rejected with `SESSION_APPROVAL_MISMATCH`.\n *\n * @example\n * const prepared = await grantKernelSession({ authFetch, publicClient, owner: walletClient, scope });\n */\nexport async function grantKernelSession(p: {\n authFetch: AuthFetch;\n publicClient: PublicClient;\n owner: KernelOwner;\n scope: { calls: readonly KernelSessionCall[] };\n endpoints?: Partial<SponsoredSessionEndpoints>;\n}): Promise<PreparedSession> {\n const ep = { ...DEFAULT_SESSION_ENDPOINTS, ...p.endpoints };\n const prepared = await postJson<PreparedSession>(p.authFetch, ep.prepare);\n const { approval } = await approveKernelSession({\n publicClient: p.publicClient,\n owner: p.owner,\n sessionKeyAddress: prepared.sessionKeyAddress,\n policies: buildKernelSessionPolicies({ calls: p.scope.calls, validUntil: prepared.validUntil }),\n });\n await postJson<{ active: true; validUntil: number }>(p.authFetch, ep.activate, { approval });\n return prepared;\n}\n\n/** Options for {@link useSponsoredSession}. */\nexport interface UseSponsoredSessionOptions {\n /** The same scope the server uses. The browser rebuilds the policies from it. */\n scope: { calls: readonly KernelSessionCall[] };\n endpoints?: Partial<SponsoredSessionEndpoints>;\n /** Default `usePepuAuthFetch()` (Privy bearer token). */\n authFetch?: AuthFetch;\n /** Default: a viem client on the PEPU RPC. */\n publicClient?: PublicClient;\n /** Re-poll the status route this often. Default 0 (only on mount and after actions). */\n pollMs?: number;\n}\n\nlet sharedClient: PublicClient | undefined;\nfunction defaultPublicClient(): PublicClient {\n sharedClient ??= getPublicClient(pepuMainnet) as unknown as PublicClient;\n return sharedClient;\n}\n\n/**\n * The whole session flow for a component.\n *\n * - `grant()`: prepare, ONE owner signature through the Privy embedded wallet\n * (no gas), activate.\n * - `act(input)`: POST the act route. No popup, no gas.\n * - `revoke()`: deletes the server-side key right away. The on-chain grant\n * lapses at its expiry; only the deleted key could ever use it.\n * - `smartAccount` is the Kernel address that sends and holds assets (a read,\n * known before any session exists); `owner` is the embedded wallet that signs.\n *\n * @example\n * const { phase, grant, act, revoke, smartAccount, expiresAt, error } = useSponsoredSession<{}, { transactionHash: string }>({\n * scope: { calls: [{ target: tapScore, abi: tapScoreAbi, functionName: \"tap\" }] },\n * });\n * if (phase === \"ready\") return <button onClick={grant}>Start session</button>;\n */\nexport function useSponsoredSession<I = undefined, O = unknown>(\n o: UseSponsoredSessionOptions,\n): {\n phase: SponsoredSessionPhase;\n /**\n * True while a signed-in user with a wallet has not yet had the first status\n * response (or failure). While true, `phase` is `ready` only because nothing\n * is known yet: render a spinner instead of the \"start a session\" card.\n */\n statusLoading: boolean;\n owner?: Address;\n smartAccount?: Address;\n scope?: KernelSessionScope;\n expiresAt?: number;\n /** Successful actions in this session, as counted by the server. */\n actions?: number;\n grant(): Promise<void>;\n act(input?: I): Promise<O>;\n revoke(): Promise<void>;\n refetch(): void;\n error?: PepuError;\n} {\n const { authenticated, ready: privyReady } = usePrivy();\n const { wallet, address: owner } = useEmbeddedWallet();\n const pepuAuthFetch = usePepuAuthFetch();\n const customFetch = o.authFetch;\n const authFetch = useCallback<AuthFetch>(\n (url, init) => (customFetch ? customFetch(url, init) : pepuAuthFetch(url, init)),\n [customFetch, pepuAuthFetch],\n );\n const endpointsRef = useRef({ ...DEFAULT_SESSION_ENDPOINTS, ...o.endpoints });\n endpointsRef.current = { ...DEFAULT_SESSION_ENDPOINTS, ...o.endpoints };\n const scopeRef = useRef(o.scope);\n scopeRef.current = o.scope;\n const publicClient = o.publicClient ?? defaultPublicClient();\n\n const [smartAccount, setSmartAccount] = useState<Address | undefined>();\n const [status, setStatus] = useState<SponsoredSessionStatus | undefined>();\n const [statusChecked, setStatusChecked] = useState(false);\n const [prepared, setPrepared] = useState<PreparedSession | undefined>();\n const [granting, setGranting] = useState(false);\n const [error, setError] = useState<PepuError | undefined>();\n const [now, setNow] = useState(() => Math.floor(Date.now() / 1000));\n const [tick, setTick] = useState(0);\n const refetch = useCallback(() => setTick((t) => t + 1), []);\n // The last expiry seen for an active session. The server reports\n // `{ active: false }` once it passes, so this is what makes `expired`.\n const [lastValidUntil, setLastValidUntil] = useState<number | undefined>();\n const grantInFlight = useRef(false);\n\n // The Kernel address depends only on the owner: known before any session.\n useEffect(() => {\n if (!owner) {\n setSmartAccount(undefined);\n return;\n }\n let cancelled = false;\n getKernelAddress(publicClient, owner)\n .then((a) => {\n if (!cancelled) setSmartAccount(a);\n })\n .catch((e: unknown) => {\n if (!cancelled) setError(toPepuError(e, { op: \"derive smart account\" }));\n });\n return () => {\n cancelled = true;\n };\n }, [owner, publicClient]);\n\n useEffect(() => {\n if (!authenticated || !owner) return;\n let cancelled = false;\n void (async () => {\n try {\n const res = await authFetch(endpointsRef.current.status);\n if (!res.ok) throw await errorFromResponse(res);\n const body = (await res.json()) as SponsoredSessionStatus;\n if (cancelled) return;\n setStatus(body);\n if (body.active) setLastValidUntil(body.validUntil);\n } catch (e) {\n if (!cancelled) setError(toPepuError(e, { op: \"session status\" }));\n } finally {\n if (!cancelled) setStatusChecked(true);\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [authenticated, owner, authFetch, tick]);\n\n useEffect(() => {\n const id = setInterval(() => setNow(Math.floor(Date.now() / 1000)), 1000);\n return () => clearInterval(id);\n }, []);\n\n useEffect(() => {\n if (!o.pollMs || o.pollMs <= 0) return;\n const id = setInterval(refetch, o.pollMs);\n return () => clearInterval(id);\n }, [o.pollMs, refetch]);\n\n const grant = useCallback(async (): Promise<void> => {\n if (grantInFlight.current) return;\n grantInFlight.current = true;\n setGranting(true);\n setError(undefined);\n try {\n if (!wallet || !owner) {\n throw new PepuAuthError(\"WALLET_NOT_PROVISIONED\", \"No embedded wallet to sign the session grant.\");\n }\n const provider = await wallet.getEthereumProvider();\n const walletClient = createWalletClient({\n account: owner,\n chain: pepuMainnet,\n transport: custom(provider),\n });\n const result = await grantKernelSession({\n authFetch,\n publicClient,\n owner: walletClient,\n scope: scopeRef.current,\n endpoints: endpointsRef.current,\n });\n setPrepared(result);\n setLastValidUntil(result.validUntil);\n setStatus({\n active: true,\n validUntil: result.validUntil,\n kernelAddress: result.kernelAddress,\n ownerAddress: result.ownerAddress,\n sessionKeyAddress: result.sessionKeyAddress,\n actions: 0,\n });\n } catch (e) {\n setError(toPepuError(e, { op: \"session grant\" }));\n } finally {\n grantInFlight.current = false;\n setGranting(false);\n }\n }, [wallet, owner, authFetch, publicClient]);\n\n const act = useCallback(\n async (input?: I): Promise<O> => {\n try {\n const out = await postJson<O>(authFetch, endpointsRef.current.act, input === undefined ? {} : input);\n setError(undefined);\n refetch();\n return out;\n } catch (e) {\n const err = toPepuError(e, { op: \"session act\" });\n setError(err);\n // Only a 409 (SESSION_NONE) means the session is gone; any other failure is a failed action.\n if (err.code === \"SESSION_NONE\") {\n setStatus({ active: false });\n setLastValidUntil(undefined);\n }\n throw err;\n }\n },\n [authFetch, refetch],\n );\n\n const revoke = useCallback(async (): Promise<void> => {\n try {\n await postJson<{ active: false }>(authFetch, endpointsRef.current.revoke);\n setStatus({ active: false });\n setLastValidUntil(undefined);\n setPrepared(undefined);\n setError(undefined);\n } catch (e) {\n const err = toPepuError(e, { op: \"session revoke\" });\n setError(err);\n throw err;\n }\n }, [authFetch]);\n\n // `ready` must not flip to `signed-out` while Privy hydrates.\n const phase = deriveSessionPhase({\n authenticated: privyReady ? authenticated : false,\n hasWallet: owner !== undefined,\n validUntil: status?.active ? status.validUntil : lastValidUntil,\n nowSeconds: now,\n granting,\n hasError: error !== undefined,\n });\n const expiresAt = status?.active ? status.validUntil : lastValidUntil;\n const scope =\n prepared?.scope ??\n (expiresAt !== undefined\n ? describeKernelSessionScope({ calls: o.scope.calls, validUntil: expiresAt })\n : undefined);\n\n const statusLoading = privyReady && authenticated && owner !== undefined && !statusChecked && status === undefined;\n\n return {\n phase,\n statusLoading,\n ...(owner ? { owner } : {}),\n ...(smartAccount ? { smartAccount } : {}),\n ...(scope ? { scope } : {}),\n ...(expiresAt !== undefined ? { expiresAt } : {}),\n ...(status?.active ? { actions: status.actions } : {}),\n grant,\n act,\n revoke,\n refetch,\n ...(error ? { error } : {}),\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/combo/react.ts"],"names":["errorFromResponse","approveKernelSession","buildKernelSessionPolicies","getPublicClient","pepuMainnet","usePrivy","useEmbeddedWallet","usePepuAuthFetch","useCallback","useRef","useState","useEffect","getKernelAddress","toPepuError","PepuAuthError","createWalletClient","custom","describeKernelSessionScope"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyCO,IAAM,yBAAA,GAAuD;AAAA,EAClE,OAAA,EAAS,sBAAA;AAAA,EACT,QAAA,EAAU,uBAAA;AAAA,EACV,MAAA,EAAQ,qBAAA;AAAA,EACR,GAAA,EAAK,kBAAA;AAAA,EACL,MAAA,EAAQ;AACV;AAuBO,SAAS,mBAAmB,CAAA,EAQT;AACxB,EAAA,IAAI,CAAC,CAAA,CAAE,aAAA,EAAe,OAAO,YAAA;AAC7B,EAAA,IAAI,CAAC,CAAA,CAAE,SAAA,EAAW,OAAO,cAAA;AACzB,EAAA,IAAI,CAAA,CAAE,UAAU,OAAO,UAAA;AACvB,EAAA,IAAI,CAAA,CAAE,eAAe,MAAA,EAAW,OAAO,EAAE,UAAA,GAAa,CAAA,CAAE,aAAa,QAAA,GAAW,SAAA;AAChF,EAAA,OAAO,CAAA,CAAE,WAAW,OAAA,GAAU,OAAA;AAChC;AA0BO,IAAM,4BAAA,GAAkD,CAAC,GAAA,EAAK,GAAA,EAAM,KAAM,GAAI;AAErF,IAAM,KAAA,GAAQ,CAAC,EAAA,KAA8B,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AAE7F,SAAS,eAAe,CAAA,EAAqB;AAC3C,EAAA,OAAQ,GAAiC,IAAA,KAAS,wBAAA;AACpD;AAMA,eAAe,iBAAA,CAAqB,IAAsB,MAAA,EAAuC;AAC/F,EAAA,KAAA,IAAS,CAAA,GAAI,KAAK,CAAA,EAAA,EAAK;AACrB,IAAA,IAAI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,CAAA;AAEN,EAAA,MAAM,gBAAgB,UAAA,IAAc,aAAA,IAAiB,UAAU,MAAA,IAAa,CAAC,iBAAiB,MAAA,KAAW,MAAA;AAEzG,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,aAAA;AAAA,IACA,GAAI,KAAA,GAAQ,EAAE,KAAA,KAAU,EAAC;AAAA,IACzB,GAAI,YAAA,GAAe,EAAE,YAAA,KAAiB,EAAC;AAAA,IACvC,GAAI,KAAA,GAAQ,EAAE,KAAA,KAAU,EAAC;AAAA,IACzB,GAAI,SAAA,KAAc,MAAA,GAAY,EAAE,SAAA,KAAc,EAAC;AAAA,IAC/C,GAAI,QAAQ,MAAA,GAAS,EAAE,SAAS,MAAA,CAAO,OAAA,KAAY,EAAC;AAAA,IACpD,KAAA;AAAA,IACA,GAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,GAAI,KAAA,GAAQ,EAAE,KAAA,KAAU;AAAC,GAC3B;AACF","file":"react.cjs","sourcesContent":["import { usePrivy } from \"@privy-io/react-auth\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createWalletClient, custom } from \"viem\";\nimport type { Address, PublicClient } from \"viem\";\nimport { pepuMainnet } from \"../chains.js\";\nimport { getPublicClient } from \"../client.js\";\nimport { PepuAuthError, toPepuError } from \"../errors.js\";\nimport type { PepuError } from \"../errors.js\";\nimport { usePepuAuthFetch, useEmbeddedWallet } from \"../privy/react.js\";\nimport { errorFromResponse } from \"../session/react.js\";\nimport type { AuthFetch } from \"../session/react.js\";\nimport { approveKernelSession, buildKernelSessionPolicies, getKernelAddress } from \"../session/kernel.js\";\nimport type { KernelOwner } from \"../session/kernel.js\";\nimport { describeKernelSessionScope } from \"../session/scope.js\";\nimport type { KernelSessionCall, KernelSessionScope } from \"../session/scope.js\";\n\nexport type { SponsoredActResult } from \"./types.js\";\n\n/**\n * `@pepu-chain/sdk/combo/react` (browser): hooks for the combined flow. Google\n * sign-in (Privy), ONE owner signature for an on-chain session, then actions\n * with no popup and no gas. Pairs with `createSponsoredSessionRoutes` from\n * `@pepu-chain/sdk/combo`.\n *\n * Extracted from templates/sponsored-session-app/components/session-flow.tsx.\n * The browser's only signing job is the grant; everything after it is a request\n * to your own server, authenticated by the Privy access token.\n *\n * Needs `react`, `@privy-io/react-auth` and the `@zerodev/*` peers.\n */\n\n/** The routes {@link useSponsoredSession} calls. */\nexport interface SponsoredSessionEndpoints {\n prepare: string;\n activate: string;\n status: string;\n act: string;\n revoke: string;\n}\n\n/** Defaults match the `app/api/session/<name>/route.ts` convention. */\nexport const DEFAULT_SESSION_ENDPOINTS: SponsoredSessionEndpoints = {\n prepare: \"/api/session/prepare\",\n activate: \"/api/session/activate\",\n status: \"/api/session/status\",\n act: \"/api/session/act\",\n revoke: \"/api/session/revoke\",\n};\n\n/** Where the session flow is, for rendering. */\nexport type SponsoredSessionPhase =\n | \"signed-out\"\n | \"provisioning\"\n | \"ready\"\n | \"granting\"\n | \"active\"\n | \"expired\"\n | \"error\";\n\n/**\n * Derive the phase from plain inputs. Pure.\n *\n * - not signed in: `signed-out`; signed in without an embedded wallet: `provisioning`\n * - a grant in flight: `granting`\n * - an expiry that has passed: `expired`; one still ahead: `active`\n * - an error with nothing active: `error`; otherwise `ready`\n *\n * @example\n * deriveSessionPhase({ authenticated: true, hasWallet: true, validUntil: 100, nowSeconds: 200 }); // \"expired\"\n */\nexport function deriveSessionPhase(p: {\n authenticated: boolean;\n hasWallet: boolean;\n /** The last expiry the server reported for an active session, if any. */\n validUntil?: number | undefined;\n nowSeconds: number;\n granting?: boolean;\n hasError?: boolean;\n}): SponsoredSessionPhase {\n if (!p.authenticated) return \"signed-out\";\n if (!p.hasWallet) return \"provisioning\";\n if (p.granting) return \"granting\";\n if (p.validUntil !== undefined) return p.nowSeconds < p.validUntil ? \"active\" : \"expired\";\n return p.hasError ? \"error\" : \"ready\";\n}\n\n/** What the server's `prepare` route returns. */\nexport interface PreparedSession {\n ownerAddress: Address;\n kernelAddress: Address;\n sessionKeyAddress: Address;\n validUntil: number;\n minutes: number;\n scope: KernelSessionScope;\n}\n\n/** What the server's `status` route returns. */\nexport type SponsoredSessionStatus =\n /** `provisioning`: signed in, but the server cannot see the new embedded wallet yet. Transient: retry. */\n | { active: false; provisioning?: true }\n | {\n active: true;\n validUntil: number;\n kernelAddress: Address;\n ownerAddress: Address;\n sessionKeyAddress: Address;\n actions: number;\n };\n\n/** Waits between retries while the server cannot see a just-created embedded wallet (total about 6.5 s). */\nexport const PROVISIONING_RETRY_DELAYS_MS: readonly number[] = [500, 1000, 2000, 3000];\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction isProvisioning(e: unknown): boolean {\n return (e as { code?: unknown } | null)?.code === \"WALLET_NOT_PROVISIONED\";\n}\n\n/**\n * Run `fn`, retrying with backoff while it fails with `WALLET_NOT_PROVISIONED`. A new user's embedded wallet exists in\n * the browser a moment before Privy's server lists it; that gap is not an error the user should ever see.\n */\nasync function whileProvisioning<T>(fn: () => Promise<T>, delays: readonly number[]): Promise<T> {\n for (let i = 0; ; i++) {\n try {\n return await fn();\n } catch (e) {\n const delay = delays[i];\n if (!isProvisioning(e) || delay === undefined) throw e;\n await sleep(delay);\n }\n }\n}\n\nasync function postJson<T>(authFetch: AuthFetch, url: string, body?: unknown): Promise<T> {\n const res = await authFetch(url, {\n method: \"POST\",\n ...(body === undefined\n ? {}\n : { headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(body) }),\n });\n if (!res.ok) throw await errorFromResponse(res);\n return (await res.json()) as T;\n}\n\n/**\n * The grant, outside React: ask the server to `prepare` a session key, have\n * `owner` sign the ONE EIP-712 approval (no gas), then `activate`. Rebuilds\n * the policies from `scope` and the server's expiry; the server checks the\n * resulting permission id matches what it issued, so a different scope is\n * rejected with `SESSION_APPROVAL_MISMATCH`.\n *\n * @example\n * const prepared = await grantKernelSession({ authFetch, publicClient, owner: walletClient, scope });\n */\nexport async function grantKernelSession(p: {\n authFetch: AuthFetch;\n publicClient: PublicClient;\n owner: KernelOwner;\n scope: { calls: readonly KernelSessionCall[] };\n endpoints?: Partial<SponsoredSessionEndpoints>;\n /** Waits between retries of `prepare` while the server cannot see a new wallet yet. Default {@link PROVISIONING_RETRY_DELAYS_MS}. */\n provisioningRetryDelaysMs?: readonly number[];\n}): Promise<PreparedSession> {\n const ep = { ...DEFAULT_SESSION_ENDPOINTS, ...p.endpoints };\n const prepared = await whileProvisioning(\n () => postJson<PreparedSession>(p.authFetch, ep.prepare),\n p.provisioningRetryDelaysMs ?? PROVISIONING_RETRY_DELAYS_MS,\n );\n const { approval } = await approveKernelSession({\n publicClient: p.publicClient,\n owner: p.owner,\n sessionKeyAddress: prepared.sessionKeyAddress,\n policies: buildKernelSessionPolicies({ calls: p.scope.calls, validUntil: prepared.validUntil }),\n });\n await postJson<{ active: true; validUntil: number }>(p.authFetch, ep.activate, { approval });\n return prepared;\n}\n\n/** Options for {@link useSponsoredSession}. */\nexport interface UseSponsoredSessionOptions {\n /** The same scope the server uses. The browser rebuilds the policies from it. */\n scope: { calls: readonly KernelSessionCall[] };\n endpoints?: Partial<SponsoredSessionEndpoints>;\n /** Default `usePepuAuthFetch()` (Privy bearer token). */\n authFetch?: AuthFetch;\n /** Default: a viem client on the PEPU RPC. */\n publicClient?: PublicClient;\n /** Re-poll the status route this often. Default 0 (only on mount and after actions). */\n pollMs?: number;\n /**\n * Waits between status re-checks while the server cannot see a just-created wallet. During them `statusLoading`\n * stays true and no error is shown. Default {@link PROVISIONING_RETRY_DELAYS_MS} extended to a 5 s tail (about 30 s).\n */\n provisioningRetryDelaysMs?: readonly number[];\n}\n\n/** Status re-checks while a new wallet is not visible to the server yet: 0.5, 1, 2, 3 s, then 5 s x 5 (about 30 s). */\nconst STATUS_PROVISIONING_DELAYS_MS: readonly number[] = [...PROVISIONING_RETRY_DELAYS_MS, 5000, 5000, 5000, 5000, 5000];\n\nlet sharedClient: PublicClient | undefined;\nfunction defaultPublicClient(): PublicClient {\n sharedClient ??= getPublicClient(pepuMainnet) as unknown as PublicClient;\n return sharedClient;\n}\n\n/**\n * The whole session flow for a component.\n *\n * - `grant()`: prepare, ONE owner signature through the Privy embedded wallet\n * (no gas), activate.\n * - `act(input)`: POST the act route. No popup, no gas.\n * - `revoke()`: deletes the server-side key right away. The on-chain grant\n * lapses at its expiry; only the deleted key could ever use it.\n * - `smartAccount` is the Kernel address that sends and holds assets (a read,\n * known before any session exists); `owner` is the embedded wallet that signs.\n *\n * @example\n * const { phase, grant, act, revoke, smartAccount, expiresAt, error } = useSponsoredSession<{}, { transactionHash: string }>({\n * scope: { calls: [{ target: tapScore, abi: tapScoreAbi, functionName: \"tap\" }] },\n * });\n * if (phase === \"ready\") return <button onClick={grant}>Start session</button>;\n */\nexport function useSponsoredSession<I = undefined, O = unknown>(\n o: UseSponsoredSessionOptions,\n): {\n phase: SponsoredSessionPhase;\n /**\n * True while a signed-in user with a wallet has not yet had the first status\n * response (or failure). While true, `phase` is `ready` only because nothing\n * is known yet: render a spinner instead of the \"start a session\" card.\n */\n statusLoading: boolean;\n owner?: Address;\n smartAccount?: Address;\n scope?: KernelSessionScope;\n expiresAt?: number;\n /** Successful actions in this session, as counted by the server. */\n actions?: number;\n grant(): Promise<void>;\n act(input?: I): Promise<O>;\n revoke(): Promise<void>;\n refetch(): void;\n error?: PepuError;\n} {\n const { authenticated, ready: privyReady } = usePrivy();\n const { wallet, address: owner } = useEmbeddedWallet();\n const pepuAuthFetch = usePepuAuthFetch();\n const customFetch = o.authFetch;\n const authFetch = useCallback<AuthFetch>(\n (url, init) => (customFetch ? customFetch(url, init) : pepuAuthFetch(url, init)),\n [customFetch, pepuAuthFetch],\n );\n const endpointsRef = useRef({ ...DEFAULT_SESSION_ENDPOINTS, ...o.endpoints });\n endpointsRef.current = { ...DEFAULT_SESSION_ENDPOINTS, ...o.endpoints };\n const scopeRef = useRef(o.scope);\n scopeRef.current = o.scope;\n const publicClient = o.publicClient ?? defaultPublicClient();\n\n const [smartAccount, setSmartAccount] = useState<Address | undefined>();\n const [status, setStatus] = useState<SponsoredSessionStatus | undefined>();\n const [statusChecked, setStatusChecked] = useState(false);\n const [prepared, setPrepared] = useState<PreparedSession | undefined>();\n const [granting, setGranting] = useState(false);\n const [error, setError] = useState<PepuError | undefined>();\n const [now, setNow] = useState(() => Math.floor(Date.now() / 1000));\n const [tick, setTick] = useState(0);\n const refetch = useCallback(() => setTick((t) => t + 1), []);\n // The last expiry seen for an active session. The server reports\n // `{ active: false }` once it passes, so this is what makes `expired`.\n const [lastValidUntil, setLastValidUntil] = useState<number | undefined>();\n const grantInFlight = useRef(false);\n const provisioningDelays = o.provisioningRetryDelaysMs ?? STATUS_PROVISIONING_DELAYS_MS;\n const delaysRef = useRef(provisioningDelays);\n delaysRef.current = provisioningDelays;\n const provisioningAttempts = useRef(0);\n\n // The Kernel address depends only on the owner: known before any session.\n useEffect(() => {\n if (!owner) {\n setSmartAccount(undefined);\n return;\n }\n let cancelled = false;\n getKernelAddress(publicClient, owner)\n .then((a) => {\n if (!cancelled) setSmartAccount(a);\n })\n .catch((e: unknown) => {\n if (!cancelled) setError(toPepuError(e, { op: \"derive smart account\" }));\n });\n return () => {\n cancelled = true;\n };\n }, [owner, publicClient]);\n\n useEffect(() => {\n if (!authenticated || !owner) return;\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n // The server cannot see the new embedded wallet yet: stay in the loading state and ask again, quietly.\n const retryLater = (): boolean => {\n const delay = delaysRef.current[provisioningAttempts.current];\n if (delay === undefined) return false;\n provisioningAttempts.current += 1;\n timer = setTimeout(() => {\n if (!cancelled) refetch();\n }, delay);\n return true;\n };\n void (async () => {\n let waiting = false;\n try {\n const res = await authFetch(endpointsRef.current.status);\n if (!res.ok) throw await errorFromResponse(res);\n const body = (await res.json()) as SponsoredSessionStatus;\n if (cancelled) return;\n if (!body.active && body.provisioning) {\n waiting = retryLater();\n if (!waiting) setStatus({ active: false });\n return;\n }\n provisioningAttempts.current = 0;\n setStatus(body);\n setError(undefined);\n if (body.active) setLastValidUntil(body.validUntil);\n } catch (e) {\n if (cancelled) return;\n if (isProvisioning(e) && (waiting = retryLater())) return;\n setError(toPepuError(e, { op: \"session status\" }));\n } finally {\n if (!cancelled && !waiting) setStatusChecked(true);\n }\n })();\n return () => {\n cancelled = true;\n if (timer) clearTimeout(timer);\n };\n }, [authenticated, owner, authFetch, tick, refetch]);\n\n useEffect(() => {\n const id = setInterval(() => setNow(Math.floor(Date.now() / 1000)), 1000);\n return () => clearInterval(id);\n }, []);\n\n useEffect(() => {\n if (!o.pollMs || o.pollMs <= 0) return;\n const id = setInterval(refetch, o.pollMs);\n return () => clearInterval(id);\n }, [o.pollMs, refetch]);\n\n const grant = useCallback(async (): Promise<void> => {\n if (grantInFlight.current) return;\n grantInFlight.current = true;\n setGranting(true);\n setError(undefined);\n try {\n if (!wallet || !owner) {\n throw new PepuAuthError(\"WALLET_NOT_PROVISIONED\", \"No embedded wallet to sign the session grant.\");\n }\n const provider = await wallet.getEthereumProvider();\n const walletClient = createWalletClient({\n account: owner,\n chain: pepuMainnet,\n transport: custom(provider),\n });\n const result = await grantKernelSession({\n authFetch,\n publicClient,\n owner: walletClient,\n scope: scopeRef.current,\n endpoints: endpointsRef.current,\n provisioningRetryDelaysMs: delaysRef.current,\n });\n setPrepared(result);\n setLastValidUntil(result.validUntil);\n setStatus({\n active: true,\n validUntil: result.validUntil,\n kernelAddress: result.kernelAddress,\n ownerAddress: result.ownerAddress,\n sessionKeyAddress: result.sessionKeyAddress,\n actions: 0,\n });\n } catch (e) {\n setError(toPepuError(e, { op: \"session grant\" }));\n } finally {\n grantInFlight.current = false;\n setGranting(false);\n }\n }, [wallet, owner, authFetch, publicClient]);\n\n const act = useCallback(\n async (input?: I): Promise<O> => {\n try {\n const out = await postJson<O>(authFetch, endpointsRef.current.act, input === undefined ? {} : input);\n setError(undefined);\n refetch();\n return out;\n } catch (e) {\n const err = toPepuError(e, { op: \"session act\" });\n setError(err);\n // Only a 409 (SESSION_NONE) means the session is gone; any other failure is a failed action.\n if (err.code === \"SESSION_NONE\") {\n setStatus({ active: false });\n setLastValidUntil(undefined);\n }\n throw err;\n }\n },\n [authFetch, refetch],\n );\n\n const revoke = useCallback(async (): Promise<void> => {\n try {\n await postJson<{ active: false }>(authFetch, endpointsRef.current.revoke);\n setStatus({ active: false });\n setLastValidUntil(undefined);\n setPrepared(undefined);\n setError(undefined);\n } catch (e) {\n const err = toPepuError(e, { op: \"session revoke\" });\n setError(err);\n throw err;\n }\n }, [authFetch]);\n\n // `ready` must not flip to `signed-out` while Privy hydrates.\n const phase = deriveSessionPhase({\n authenticated: privyReady ? authenticated : false,\n hasWallet: owner !== undefined,\n validUntil: status?.active ? status.validUntil : lastValidUntil,\n nowSeconds: now,\n granting,\n hasError: error !== undefined,\n });\n const expiresAt = status?.active ? status.validUntil : lastValidUntil;\n const scope =\n prepared?.scope ??\n (expiresAt !== undefined\n ? describeKernelSessionScope({ calls: o.scope.calls, validUntil: expiresAt })\n : undefined);\n\n const statusLoading = privyReady && authenticated && owner !== undefined && !statusChecked && status === undefined;\n\n return {\n phase,\n statusLoading,\n ...(owner ? { owner } : {}),\n ...(smartAccount ? { smartAccount } : {}),\n ...(scope ? { scope } : {}),\n ...(expiresAt !== undefined ? { expiresAt } : {}),\n ...(status?.active ? { actions: status.actions } : {}),\n grant,\n act,\n revoke,\n refetch,\n ...(error ? { error } : {}),\n };\n}\n"]}
@@ -64,8 +64,11 @@ interface PreparedSession {
64
64
  scope: KernelSessionScope;
65
65
  }
66
66
  /** What the server's `status` route returns. */
67
- type SponsoredSessionStatus = {
67
+ type SponsoredSessionStatus =
68
+ /** `provisioning`: signed in, but the server cannot see the new embedded wallet yet. Transient: retry. */
69
+ {
68
70
  active: false;
71
+ provisioning?: true;
69
72
  } | {
70
73
  active: true;
71
74
  validUntil: number;
@@ -74,6 +77,8 @@ type SponsoredSessionStatus = {
74
77
  sessionKeyAddress: Address;
75
78
  actions: number;
76
79
  };
80
+ /** Waits between retries while the server cannot see a just-created embedded wallet (total about 6.5 s). */
81
+ declare const PROVISIONING_RETRY_DELAYS_MS: readonly number[];
77
82
  /**
78
83
  * The grant, outside React: ask the server to `prepare` a session key, have
79
84
  * `owner` sign the ONE EIP-712 approval (no gas), then `activate`. Rebuilds
@@ -92,6 +97,8 @@ declare function grantKernelSession(p: {
92
97
  calls: readonly KernelSessionCall[];
93
98
  };
94
99
  endpoints?: Partial<SponsoredSessionEndpoints>;
100
+ /** Waits between retries of `prepare` while the server cannot see a new wallet yet. Default {@link PROVISIONING_RETRY_DELAYS_MS}. */
101
+ provisioningRetryDelaysMs?: readonly number[];
95
102
  }): Promise<PreparedSession>;
96
103
  /** Options for {@link useSponsoredSession}. */
97
104
  interface UseSponsoredSessionOptions {
@@ -106,6 +113,11 @@ interface UseSponsoredSessionOptions {
106
113
  publicClient?: PublicClient;
107
114
  /** Re-poll the status route this often. Default 0 (only on mount and after actions). */
108
115
  pollMs?: number;
116
+ /**
117
+ * Waits between status re-checks while the server cannot see a just-created wallet. During them `statusLoading`
118
+ * stays true and no error is shown. Default {@link PROVISIONING_RETRY_DELAYS_MS} extended to a 5 s tail (about 30 s).
119
+ */
120
+ provisioningRetryDelaysMs?: readonly number[];
109
121
  }
110
122
  /**
111
123
  * The whole session flow for a component.
@@ -145,4 +157,4 @@ declare function useSponsoredSession<I = undefined, O = unknown>(o: UseSponsored
145
157
  error?: PepuError;
146
158
  };
147
159
 
148
- export { DEFAULT_SESSION_ENDPOINTS, type PreparedSession, type SponsoredSessionEndpoints, type SponsoredSessionPhase, type SponsoredSessionStatus, type UseSponsoredSessionOptions, deriveSessionPhase, grantKernelSession, useSponsoredSession };
160
+ export { DEFAULT_SESSION_ENDPOINTS, PROVISIONING_RETRY_DELAYS_MS, type PreparedSession, type SponsoredSessionEndpoints, type SponsoredSessionPhase, type SponsoredSessionStatus, type UseSponsoredSessionOptions, deriveSessionPhase, grantKernelSession, useSponsoredSession };
@@ -64,8 +64,11 @@ interface PreparedSession {
64
64
  scope: KernelSessionScope;
65
65
  }
66
66
  /** What the server's `status` route returns. */
67
- type SponsoredSessionStatus = {
67
+ type SponsoredSessionStatus =
68
+ /** `provisioning`: signed in, but the server cannot see the new embedded wallet yet. Transient: retry. */
69
+ {
68
70
  active: false;
71
+ provisioning?: true;
69
72
  } | {
70
73
  active: true;
71
74
  validUntil: number;
@@ -74,6 +77,8 @@ type SponsoredSessionStatus = {
74
77
  sessionKeyAddress: Address;
75
78
  actions: number;
76
79
  };
80
+ /** Waits between retries while the server cannot see a just-created embedded wallet (total about 6.5 s). */
81
+ declare const PROVISIONING_RETRY_DELAYS_MS: readonly number[];
77
82
  /**
78
83
  * The grant, outside React: ask the server to `prepare` a session key, have
79
84
  * `owner` sign the ONE EIP-712 approval (no gas), then `activate`. Rebuilds
@@ -92,6 +97,8 @@ declare function grantKernelSession(p: {
92
97
  calls: readonly KernelSessionCall[];
93
98
  };
94
99
  endpoints?: Partial<SponsoredSessionEndpoints>;
100
+ /** Waits between retries of `prepare` while the server cannot see a new wallet yet. Default {@link PROVISIONING_RETRY_DELAYS_MS}. */
101
+ provisioningRetryDelaysMs?: readonly number[];
95
102
  }): Promise<PreparedSession>;
96
103
  /** Options for {@link useSponsoredSession}. */
97
104
  interface UseSponsoredSessionOptions {
@@ -106,6 +113,11 @@ interface UseSponsoredSessionOptions {
106
113
  publicClient?: PublicClient;
107
114
  /** Re-poll the status route this often. Default 0 (only on mount and after actions). */
108
115
  pollMs?: number;
116
+ /**
117
+ * Waits between status re-checks while the server cannot see a just-created wallet. During them `statusLoading`
118
+ * stays true and no error is shown. Default {@link PROVISIONING_RETRY_DELAYS_MS} extended to a 5 s tail (about 30 s).
119
+ */
120
+ provisioningRetryDelaysMs?: readonly number[];
109
121
  }
110
122
  /**
111
123
  * The whole session flow for a component.
@@ -145,4 +157,4 @@ declare function useSponsoredSession<I = undefined, O = unknown>(o: UseSponsored
145
157
  error?: PepuError;
146
158
  };
147
159
 
148
- export { DEFAULT_SESSION_ENDPOINTS, type PreparedSession, type SponsoredSessionEndpoints, type SponsoredSessionPhase, type SponsoredSessionStatus, type UseSponsoredSessionOptions, deriveSessionPhase, grantKernelSession, useSponsoredSession };
160
+ export { DEFAULT_SESSION_ENDPOINTS, PROVISIONING_RETRY_DELAYS_MS, type PreparedSession, type SponsoredSessionEndpoints, type SponsoredSessionPhase, type SponsoredSessionStatus, type UseSponsoredSessionOptions, deriveSessionPhase, grantKernelSession, useSponsoredSession };
@@ -0,0 +1,15 @@
1
+ // Generated by scripts/guard-peers.mjs. Used only under the "node" export condition.
2
+ const peers = ["react","@privy-io/react-auth","@zerodev/sdk","@zerodev/permissions","@zerodev/ecdsa-validator"];
3
+ for (const peer of peers) {
4
+ try {
5
+ import.meta.resolve?.(peer);
6
+ } catch (e) {
7
+ if (e && e.code === "ERR_MODULE_NOT_FOUND") {
8
+ const err = new Error("@pepu-chain/sdk/combo/react needs peer packages that are not installed: react @privy-io/react-auth @zerodev/sdk @zerodev/permissions @zerodev/ecdsa-validator. Install with: npm i react @privy-io/react-auth @zerodev/sdk @zerodev/permissions @zerodev/ecdsa-validator (or let create-pepu-app scaffold everything).");
9
+ err.code = "PEPU_MISSING_PEER";
10
+ throw err;
11
+ }
12
+ }
13
+ }
14
+ const mod = await import("./react.js");
15
+ export const { DEFAULT_SESSION_ENDPOINTS, PROVISIONING_RETRY_DELAYS_MS, deriveSessionPhase, grantKernelSession, useSponsoredSession } = mod;
@@ -1,10 +1,11 @@
1
1
  import { errorFromResponse } from '../chunk-T43PQXJD.js';
2
- import { approveKernelSession, buildKernelSessionPolicies } from '../chunk-KVG3AYYR.js';
3
- import { getKernelAddress } from '../chunk-ZB6SVBK4.js';
4
- import '../chunk-IB2FSPMJ.js';
2
+ import { approveKernelSession, buildKernelSessionPolicies } from '../chunk-NHPWXIA2.js';
3
+ import { getKernelAddress } from '../chunk-QIDMFFAQ.js';
4
+ import '../chunk-QZKUPCUD.js';
5
5
  import '../chunk-VBH3JLQ5.js';
6
- import '../chunk-IY3ALPUJ.js';
7
- import '../chunk-D52PADVY.js';
6
+ import '../chunk-RSPAN44L.js';
7
+ import '../chunk-GFKIM7HT.js';
8
+ import '../chunk-GIZNH65Q.js';
8
9
  import { useEmbeddedWallet, usePepuAuthFetch } from '../chunk-EHBPIYY4.js';
9
10
  import '../chunk-JLZ4LZ4Z.js';
10
11
  import { describeKernelSessionScope } from '../chunk-ESMNAXUI.js';
@@ -32,6 +33,22 @@ function deriveSessionPhase(p) {
32
33
  if (p.validUntil !== void 0) return p.nowSeconds < p.validUntil ? "active" : "expired";
33
34
  return p.hasError ? "error" : "ready";
34
35
  }
36
+ var PROVISIONING_RETRY_DELAYS_MS = [500, 1e3, 2e3, 3e3];
37
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
38
+ function isProvisioning(e) {
39
+ return e?.code === "WALLET_NOT_PROVISIONED";
40
+ }
41
+ async function whileProvisioning(fn, delays) {
42
+ for (let i = 0; ; i++) {
43
+ try {
44
+ return await fn();
45
+ } catch (e) {
46
+ const delay = delays[i];
47
+ if (!isProvisioning(e) || delay === void 0) throw e;
48
+ await sleep(delay);
49
+ }
50
+ }
51
+ }
35
52
  async function postJson(authFetch, url, body) {
36
53
  const res = await authFetch(url, {
37
54
  method: "POST",
@@ -42,7 +59,10 @@ async function postJson(authFetch, url, body) {
42
59
  }
43
60
  async function grantKernelSession(p) {
44
61
  const ep = { ...DEFAULT_SESSION_ENDPOINTS, ...p.endpoints };
45
- const prepared = await postJson(p.authFetch, ep.prepare);
62
+ const prepared = await whileProvisioning(
63
+ () => postJson(p.authFetch, ep.prepare),
64
+ p.provisioningRetryDelaysMs ?? PROVISIONING_RETRY_DELAYS_MS
65
+ );
46
66
  const { approval } = await approveKernelSession({
47
67
  publicClient: p.publicClient,
48
68
  owner: p.owner,
@@ -52,6 +72,7 @@ async function grantKernelSession(p) {
52
72
  await postJson(p.authFetch, ep.activate, { approval });
53
73
  return prepared;
54
74
  }
75
+ var STATUS_PROVISIONING_DELAYS_MS = [...PROVISIONING_RETRY_DELAYS_MS, 5e3, 5e3, 5e3, 5e3, 5e3];
55
76
  var sharedClient;
56
77
  function defaultPublicClient() {
57
78
  sharedClient ??= getPublicClient(pepuMainnet);
@@ -82,6 +103,10 @@ function useSponsoredSession(o) {
82
103
  const refetch = useCallback(() => setTick((t) => t + 1), []);
83
104
  const [lastValidUntil, setLastValidUntil] = useState();
84
105
  const grantInFlight = useRef(false);
106
+ const provisioningDelays = o.provisioningRetryDelaysMs ?? STATUS_PROVISIONING_DELAYS_MS;
107
+ const delaysRef = useRef(provisioningDelays);
108
+ delaysRef.current = provisioningDelays;
109
+ const provisioningAttempts = useRef(0);
85
110
  useEffect(() => {
86
111
  if (!owner) {
87
112
  setSmartAccount(void 0);
@@ -100,24 +125,45 @@ function useSponsoredSession(o) {
100
125
  useEffect(() => {
101
126
  if (!authenticated || !owner) return;
102
127
  let cancelled = false;
128
+ let timer;
129
+ const retryLater = () => {
130
+ const delay = delaysRef.current[provisioningAttempts.current];
131
+ if (delay === void 0) return false;
132
+ provisioningAttempts.current += 1;
133
+ timer = setTimeout(() => {
134
+ if (!cancelled) refetch();
135
+ }, delay);
136
+ return true;
137
+ };
103
138
  void (async () => {
139
+ let waiting = false;
104
140
  try {
105
141
  const res = await authFetch(endpointsRef.current.status);
106
142
  if (!res.ok) throw await errorFromResponse(res);
107
143
  const body = await res.json();
108
144
  if (cancelled) return;
145
+ if (!body.active && body.provisioning) {
146
+ waiting = retryLater();
147
+ if (!waiting) setStatus({ active: false });
148
+ return;
149
+ }
150
+ provisioningAttempts.current = 0;
109
151
  setStatus(body);
152
+ setError(void 0);
110
153
  if (body.active) setLastValidUntil(body.validUntil);
111
154
  } catch (e) {
112
- if (!cancelled) setError(toPepuError(e, { op: "session status" }));
155
+ if (cancelled) return;
156
+ if (isProvisioning(e) && (waiting = retryLater())) return;
157
+ setError(toPepuError(e, { op: "session status" }));
113
158
  } finally {
114
- if (!cancelled) setStatusChecked(true);
159
+ if (!cancelled && !waiting) setStatusChecked(true);
115
160
  }
116
161
  })();
117
162
  return () => {
118
163
  cancelled = true;
164
+ if (timer) clearTimeout(timer);
119
165
  };
120
- }, [authenticated, owner, authFetch, tick]);
166
+ }, [authenticated, owner, authFetch, tick, refetch]);
121
167
  useEffect(() => {
122
168
  const id = setInterval(() => setNow(Math.floor(Date.now() / 1e3)), 1e3);
123
169
  return () => clearInterval(id);
@@ -147,7 +193,8 @@ function useSponsoredSession(o) {
147
193
  publicClient,
148
194
  owner: walletClient,
149
195
  scope: scopeRef.current,
150
- endpoints: endpointsRef.current
196
+ endpoints: endpointsRef.current,
197
+ provisioningRetryDelaysMs: delaysRef.current
151
198
  });
152
199
  setPrepared(result);
153
200
  setLastValidUntil(result.validUntil);
@@ -225,6 +272,6 @@ function useSponsoredSession(o) {
225
272
  };
226
273
  }
227
274
 
228
- export { DEFAULT_SESSION_ENDPOINTS, deriveSessionPhase, grantKernelSession, useSponsoredSession };
275
+ export { DEFAULT_SESSION_ENDPOINTS, PROVISIONING_RETRY_DELAYS_MS, deriveSessionPhase, grantKernelSession, useSponsoredSession };
229
276
  //# sourceMappingURL=react.js.map
230
277
  //# sourceMappingURL=react.js.map