@rhinestone/1auth 0.6.8 → 0.6.10

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 (51) hide show
  1. package/README.md +171 -12
  2. package/dist/chunk-GUAI55LL.mjs +179 -0
  3. package/dist/chunk-GUAI55LL.mjs.map +1 -0
  4. package/dist/chunk-IHBVEU33.mjs +20 -0
  5. package/dist/chunk-IHBVEU33.mjs.map +1 -0
  6. package/dist/chunk-IIACVHR3.mjs +28 -0
  7. package/dist/chunk-IIACVHR3.mjs.map +1 -0
  8. package/dist/chunk-N6KE5CII.mjs +72 -0
  9. package/dist/chunk-N6KE5CII.mjs.map +1 -0
  10. package/dist/{chunk-SXISYG2P.mjs → chunk-THKG3FAG.mjs} +137 -255
  11. package/dist/chunk-THKG3FAG.mjs.map +1 -0
  12. package/dist/{client-BrMrhetG.d.mts → client-B_CzDa_I.d.ts} +360 -857
  13. package/dist/{client-BrMrhetG.d.ts → client-F4DnFM8d.d.mts} +360 -857
  14. package/dist/headless.d.mts +109 -0
  15. package/dist/headless.d.ts +109 -0
  16. package/dist/headless.js +467 -0
  17. package/dist/headless.js.map +1 -0
  18. package/dist/headless.mjs +382 -0
  19. package/dist/headless.mjs.map +1 -0
  20. package/dist/index.d.mts +96 -144
  21. package/dist/index.d.ts +96 -144
  22. package/dist/index.js +3212 -756
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +3010 -705
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/{provider-CDl9wYEc.d.mts → provider-Cd7Ip5L-.d.ts} +6 -5
  27. package/dist/{provider-Dgv533YQ.d.ts → provider-IvYXPMpk.d.mts} +6 -5
  28. package/dist/react.d.mts +42 -2
  29. package/dist/react.d.ts +42 -2
  30. package/dist/react.js +92 -2
  31. package/dist/react.js.map +1 -1
  32. package/dist/react.mjs +66 -1
  33. package/dist/react.mjs.map +1 -1
  34. package/dist/server.d.mts +118 -0
  35. package/dist/server.d.ts +118 -0
  36. package/dist/server.js +356 -0
  37. package/dist/server.js.map +1 -0
  38. package/dist/server.mjs +282 -0
  39. package/dist/server.mjs.map +1 -0
  40. package/dist/types-U_dwxbtS.d.mts +1488 -0
  41. package/dist/types-U_dwxbtS.d.ts +1488 -0
  42. package/dist/verify-BLgZzwmJ.d.ts +150 -0
  43. package/dist/verify-C8-a5c3K.d.mts +150 -0
  44. package/dist/wagmi.d.mts +5 -2
  45. package/dist/wagmi.d.ts +5 -2
  46. package/dist/wagmi.js +138 -43
  47. package/dist/wagmi.js.map +1 -1
  48. package/dist/wagmi.mjs +3 -1
  49. package/dist/wagmi.mjs.map +1 -1
  50. package/package.json +15 -2
  51. package/dist/chunk-SXISYG2P.mjs.map +0 -1
@@ -1,202 +1,9 @@
1
- // src/registry.ts
2
- import { isAddress } from "viem";
3
- import * as viemChains from "viem/chains";
4
1
  import {
5
- getAllSupportedChainsAndTokens as getAllSupportedChainsAndTokensRaw,
6
- getSupportedTokens as getSupportedTokensRaw,
7
- getTokenAddress,
8
- getTokenDecimals
9
- } from "@rhinestone/sdk";
10
- var env = typeof process !== "undefined" ? process.env : {};
11
- var VIEM_CHAIN_BY_ID = /* @__PURE__ */ new Map();
12
- for (const value of Object.values(viemChains)) {
13
- if (typeof value !== "object" || value === null || !("id" in value) || !("name" in value)) continue;
14
- const chain = value;
15
- const existing = VIEM_CHAIN_BY_ID.get(chain.id);
16
- if (!existing || existing.testnet && !chain.testnet) {
17
- VIEM_CHAIN_BY_ID.set(chain.id, chain);
18
- }
19
- }
20
- var SUPPORTED_CHAIN_IDS = new Set(
21
- getAllSupportedChainsAndTokensRaw().map((entry) => entry.chainId)
22
- );
23
- function parseBool(value) {
24
- if (value === "true" || value === "1") return true;
25
- if (value === "false" || value === "0") return false;
26
- return void 0;
27
- }
28
- function resolveIncludeTestnets(explicit) {
29
- if (explicit !== void 0) return explicit;
30
- const envValue = parseBool(env.NEXT_PUBLIC_ORCHESTRATOR_USE_TESTNETS) ?? parseBool(env.ORCHESTRATOR_USE_TESTNETS);
31
- return envValue ?? false;
32
- }
33
- function applyChainFilters(chainIds, options) {
34
- const includeTestnets = resolveIncludeTestnets(options?.includeTestnets);
35
- const allowlist = options?.chainIds;
36
- let filtered = chainIds;
37
- if (!includeTestnets) {
38
- filtered = filtered.filter((chainId) => !isTestnet(chainId));
39
- }
40
- if (allowlist) {
41
- const allowed = new Set(allowlist);
42
- filtered = filtered.filter((chainId) => allowed.has(chainId));
43
- }
44
- return filtered;
45
- }
46
- function getSupportedChainIds(options) {
47
- return applyChainFilters(Array.from(SUPPORTED_CHAIN_IDS), options);
48
- }
49
- function getSupportedChains(options) {
50
- return getSupportedChainIds(options).map((chainId) => VIEM_CHAIN_BY_ID.get(chainId)).filter((chain) => Boolean(chain));
51
- }
52
- function getAllSupportedChainsAndTokens(options) {
53
- const allowed = new Set(getSupportedChainIds(options));
54
- return getAllSupportedChainsAndTokensRaw().filter((entry) => allowed.has(entry.chainId)).map((entry) => ({
55
- chainId: entry.chainId,
56
- tokens: entry.tokens
57
- }));
58
- }
59
- function getChainById(chainId) {
60
- if (!SUPPORTED_CHAIN_IDS.has(chainId)) {
61
- throw new Error(`Unsupported chain ID: ${chainId}`);
62
- }
63
- const chain = VIEM_CHAIN_BY_ID.get(chainId);
64
- if (!chain) {
65
- throw new Error(`Unsupported chain ID: ${chainId}`);
66
- }
67
- return chain;
68
- }
69
- function getChainName(chainId) {
70
- try {
71
- return getChainById(chainId).name;
72
- } catch {
73
- return `Chain ${chainId}`;
74
- }
75
- }
76
- function getChainExplorerUrl(chainId) {
77
- try {
78
- return getChainById(chainId).blockExplorers?.default?.url;
79
- } catch {
80
- return void 0;
81
- }
82
- }
83
- function getChainRpcUrl(chainId) {
84
- try {
85
- const chain = getChainById(chainId);
86
- return chain.rpcUrls?.default?.http?.[0] || chain.rpcUrls?.public?.http?.[0];
87
- } catch {
88
- return void 0;
89
- }
90
- }
91
- function getSupportedTokens(chainId) {
92
- return getSupportedTokensRaw(chainId);
93
- }
94
- function getSupportedTokenSymbols(chainId) {
95
- return getSupportedTokens(chainId).map((token) => token.symbol);
96
- }
97
- function resolveTokenAddress(token, chainId) {
98
- if (isAddress(token)) {
99
- return token;
100
- }
101
- const match = getSupportedTokens(chainId).find(
102
- (t) => t.symbol.toUpperCase() === token.toUpperCase()
103
- );
104
- if (!match) {
105
- return getTokenAddress(token, chainId);
106
- }
107
- return match.address;
108
- }
109
- function isTestnet(chainId) {
110
- try {
111
- return getChainById(chainId).testnet ?? false;
112
- } catch {
113
- return false;
114
- }
115
- }
116
- function getTokenSymbol(tokenAddress, chainId) {
117
- const token = getSupportedTokens(chainId).find(
118
- (entry) => entry.address.toLowerCase() === tokenAddress.toLowerCase()
119
- );
120
- if (!token) {
121
- throw new Error(`Unsupported token: ${tokenAddress} on chain ${chainId}`);
122
- }
123
- return token.symbol;
124
- }
125
- function isTokenAddressSupported(tokenAddress, chainId) {
126
- try {
127
- return getSupportedTokens(chainId).some(
128
- (entry) => entry.address.toLowerCase() === tokenAddress.toLowerCase()
129
- );
130
- } catch {
131
- return false;
132
- }
133
- }
134
-
135
- // src/walletClient/utils.ts
136
- import { encodeAbiParameters, keccak256 } from "viem";
137
- var P256_N = BigInt(
138
- "0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"
139
- );
140
- var P256_N_DIV_2 = P256_N / 2n;
141
- var WEBAUTHN_AUTH_TYPE = {
142
- type: "tuple",
143
- components: [
144
- { type: "bytes", name: "authenticatorData" },
145
- { type: "string", name: "clientDataJSON" },
146
- { type: "uint256", name: "challengeIndex" },
147
- { type: "uint256", name: "typeIndex" },
148
- { type: "uint256", name: "r" },
149
- { type: "uint256", name: "s" }
150
- ]
151
- };
152
- function encodeWebAuthnSignature(sig) {
153
- let s = BigInt(sig.s);
154
- if (s > P256_N_DIV_2) {
155
- s = P256_N - s;
156
- }
157
- return encodeAbiParameters([WEBAUTHN_AUTH_TYPE], [
158
- {
159
- authenticatorData: sig.authenticatorData,
160
- clientDataJSON: sig.clientDataJSON,
161
- challengeIndex: BigInt(sig.challengeIndex),
162
- typeIndex: BigInt(sig.typeIndex),
163
- r: BigInt(sig.r),
164
- s
165
- }
166
- ]);
167
- }
168
- function hashCalls(calls) {
169
- const encoded = encodeAbiParameters(
170
- [
171
- {
172
- type: "tuple[]",
173
- components: [
174
- { type: "address", name: "to" },
175
- { type: "bytes", name: "data" },
176
- { type: "uint256", name: "value" }
177
- ]
178
- }
179
- ],
180
- [
181
- calls.map((c) => ({
182
- to: c.to,
183
- data: c.data || "0x",
184
- value: c.value || 0n
185
- }))
186
- ]
187
- );
188
- return keccak256(encoded);
189
- }
190
- function buildTransactionReview(calls) {
191
- return {
192
- actions: calls.map((call, i) => ({
193
- type: "custom",
194
- label: call.label || `Contract Call ${i + 1}`,
195
- sublabel: call.sublabel || `To: ${call.to.slice(0, 10)}...${call.to.slice(-8)}`,
196
- amount: call.value ? `${call.value} wei` : void 0
197
- }))
198
- };
199
- }
2
+ getSupportedChainIds
3
+ } from "./chunk-GUAI55LL.mjs";
4
+ import {
5
+ encodeWebAuthnSignature
6
+ } from "./chunk-N6KE5CII.mjs";
200
7
 
201
8
  // src/provider.ts
202
9
  import {
@@ -255,29 +62,20 @@ function createOneAuthProvider(options) {
255
62
  if (stored) {
256
63
  return [stored.address];
257
64
  }
258
- const connectResult = await client.connectWithModal();
259
- let username;
260
- let address;
261
- if (connectResult.success) {
262
- username = connectResult.user?.username;
263
- address = connectResult.user?.address;
264
- } else if (connectResult.action === "switch") {
265
- const authResult = await client.authWithModal();
266
- if (!authResult.success) {
267
- throw new Error(authResult.error?.message || "Authentication failed");
268
- }
269
- username = authResult.user?.username;
270
- address = authResult.user?.address;
271
- } else {
272
- throw new Error(connectResult.error?.message || "Connection cancelled");
65
+ const authResult = await client.authWithModal();
66
+ if (!authResult.success) {
67
+ throw new Error(authResult.error?.message || "Authentication failed");
273
68
  }
69
+ const username = authResult.user?.username;
70
+ let address = authResult.user?.address;
71
+ const signerType = authResult.signerType;
274
72
  if (!address && username) {
275
73
  address = await resolveAccountAddress(username);
276
74
  }
277
75
  if (!address) {
278
76
  throw new Error("No account address available");
279
77
  }
280
- setStoredUser({ username, address });
78
+ setStoredUser({ username, address, signerType });
281
79
  emit("accountsChanged", [address]);
282
80
  emit("connect", { chainId: numberToHex(chainId) });
283
81
  return [address];
@@ -297,6 +95,22 @@ function createOneAuthProvider(options) {
297
95
  const user = getStoredUser();
298
96
  return user || { address };
299
97
  };
98
+ const getAssetsAccountAddress = (assetsParams) => {
99
+ const raw = Array.isArray(assetsParams) ? assetsParams[0] : assetsParams;
100
+ if (typeof raw === "string" && raw.trim()) return raw.trim();
101
+ if (!raw || typeof raw !== "object") return void 0;
102
+ const request2 = raw;
103
+ const candidates = [
104
+ request2.accountAddress,
105
+ request2.address
106
+ ];
107
+ for (const candidate of candidates) {
108
+ if (typeof candidate === "string" && candidate.trim()) {
109
+ return candidate.trim();
110
+ }
111
+ }
112
+ return void 0;
113
+ };
300
114
  const parseChainId = (value) => {
301
115
  if (typeof value === "number") return value;
302
116
  if (typeof value === "string") {
@@ -326,7 +140,9 @@ function createOneAuthProvider(options) {
326
140
  data: c.data || "0x",
327
141
  value: normalizeValue(c.value) || "0",
328
142
  label: c.label,
329
- sublabel: c.sublabel
143
+ sublabel: c.sublabel,
144
+ icon: c.icon,
145
+ abi: c.abi
330
146
  };
331
147
  });
332
148
  };
@@ -348,13 +164,36 @@ function createOneAuthProvider(options) {
348
164
  return value;
349
165
  }
350
166
  };
167
+ const forwardToWallet = async (method, params, expectedAddress) => {
168
+ const result = await client.requestWithWallet({
169
+ method,
170
+ params,
171
+ expectedAddress
172
+ });
173
+ if (!result.success) {
174
+ const err = new Error(result.error.message);
175
+ err.code = result.error.code;
176
+ throw err;
177
+ }
178
+ return result.result;
179
+ };
180
+ const EOA_FORWARDED_METHODS = /* @__PURE__ */ new Set([
181
+ "personal_sign",
182
+ "eth_sign",
183
+ "eth_signTypedData",
184
+ "eth_signTypedData_v3",
185
+ "eth_signTypedData_v4",
186
+ "eth_sendTransaction",
187
+ "wallet_sendCalls",
188
+ "wallet_getCallsStatus"
189
+ ]);
351
190
  const signMessage = async (message) => {
352
191
  const user = await ensureUser();
353
192
  if (!user.username && !user.address) {
354
193
  throw new Error("Username or address required for signing.");
355
194
  }
356
195
  const result = await client.signMessage({
357
- username: user.username,
196
+ username: user.username || void 0,
358
197
  accountAddress: user.address,
359
198
  message
360
199
  });
@@ -370,7 +209,7 @@ function createOneAuthProvider(options) {
370
209
  }
371
210
  const data = typeof typedData === "string" ? JSON.parse(typedData) : typedData;
372
211
  const result = await client.signTypedData({
373
- username: user.username,
212
+ username: user.username || void 0,
374
213
  accountAddress: user.address,
375
214
  domain: data.domain,
376
215
  types: data.types,
@@ -390,13 +229,12 @@ function createOneAuthProvider(options) {
390
229
  tokenRequests: payload.tokenRequests
391
230
  });
392
231
  const sendIntent = async (payload) => {
393
- const closeOn = options.closeOn ?? (options.waitForHash ?? true ? "completed" : "preconfirmed");
394
232
  const intentPayload = resolveIntentPayload(payload);
395
233
  const result = await client.sendIntent({
396
234
  ...intentPayload,
397
235
  tokenRequests: payload.tokenRequests,
398
236
  sourceChainId: payload.sourceChainId,
399
- closeOn,
237
+ closeOn: options.closeOn,
400
238
  waitForHash: options.waitForHash ?? true,
401
239
  hashTimeoutMs: options.hashTimeoutMs,
402
240
  hashIntervalMs: options.hashIntervalMs
@@ -406,7 +244,70 @@ function createOneAuthProvider(options) {
406
244
  }
407
245
  return result.intentId;
408
246
  };
247
+ const accountMismatchError = () => {
248
+ const err = new Error(
249
+ "Requested signer does not match the active wallet connection."
250
+ );
251
+ err.code = "ACCOUNT_MISMATCH";
252
+ return err;
253
+ };
254
+ const sameAddress = (a, b) => typeof a === "string" && a.toLowerCase() === b.toLowerCase();
255
+ const injectEoaSigner = (method, params, address) => {
256
+ const list = Array.isArray(params) ? params.slice() : params;
257
+ if (!Array.isArray(list)) return params;
258
+ if (method === "eth_sendTransaction") {
259
+ const first = list[0] || {};
260
+ if (first.from !== void 0 && !sameAddress(first.from, address)) {
261
+ throw accountMismatchError();
262
+ }
263
+ list[0] = { ...first, from: address };
264
+ return list;
265
+ }
266
+ if (method === "wallet_sendCalls") {
267
+ const first = list[0] || {};
268
+ if (first.from !== void 0 && !sameAddress(first.from, address)) {
269
+ throw accountMismatchError();
270
+ }
271
+ const calls = first.calls;
272
+ if (Array.isArray(calls)) {
273
+ for (const call of calls) {
274
+ if (!call || typeof call !== "object") continue;
275
+ const callFrom = call.from;
276
+ if (callFrom !== void 0 && !sameAddress(callFrom, address)) {
277
+ throw accountMismatchError();
278
+ }
279
+ }
280
+ }
281
+ list[0] = { ...first, from: address };
282
+ return list;
283
+ }
284
+ if (method === "personal_sign") {
285
+ if (list[1] !== void 0 && !sameAddress(list[1], address)) {
286
+ throw accountMismatchError();
287
+ }
288
+ if (list[0] && list[1] === void 0) list[1] = address;
289
+ return list;
290
+ }
291
+ if (method === "eth_sign" || method === "eth_signTypedData" || method === "eth_signTypedData_v3" || method === "eth_signTypedData_v4") {
292
+ if (list[0] !== void 0 && !sameAddress(list[0], address)) {
293
+ throw accountMismatchError();
294
+ }
295
+ if (list[0] === void 0 && list[1] !== void 0) list[0] = address;
296
+ return list;
297
+ }
298
+ return list;
299
+ };
409
300
  const request = async ({ method, params }) => {
301
+ if (EOA_FORWARDED_METHODS.has(method)) {
302
+ const user = await ensureUser();
303
+ if (user.signerType === "eoa") {
304
+ return forwardToWallet(
305
+ method,
306
+ injectEoaSigner(method, params, user.address),
307
+ user.address
308
+ );
309
+ }
310
+ }
410
311
  switch (method) {
411
312
  case "eth_chainId":
412
313
  return numberToHex(chainId);
@@ -427,6 +328,10 @@ function createOneAuthProvider(options) {
427
328
  if (!next) {
428
329
  throw new Error("Invalid chainId");
429
330
  }
331
+ const stored = getStoredUser();
332
+ if (stored?.signerType === "eoa") {
333
+ await forwardToWallet(method, params, stored.address);
334
+ }
430
335
  chainId = next;
431
336
  emit("chainChanged", numberToHex(chainId));
432
337
  return null;
@@ -460,7 +365,7 @@ function createOneAuthProvider(options) {
460
365
  const tokenRequests = normalizeTokenRequests(tx.tokenRequests);
461
366
  const txSourceChainId = parseChainId(tx.sourceChainId);
462
367
  return sendIntent({
463
- username: user.username,
368
+ username: user.username || void 0,
464
369
  accountAddress: user.address,
465
370
  targetChain,
466
371
  calls,
@@ -478,7 +383,7 @@ function createOneAuthProvider(options) {
478
383
  const sourceChainId = parseChainId(payload.sourceChainId);
479
384
  if (!calls.length) throw new Error("No calls provided");
480
385
  return sendIntent({
481
- username: user.username,
386
+ username: user.username || void 0,
482
387
  accountAddress: user.address,
483
388
  targetChain,
484
389
  calls,
@@ -487,6 +392,10 @@ function createOneAuthProvider(options) {
487
392
  });
488
393
  }
489
394
  case "wallet_getCapabilities": {
395
+ const stored = getStoredUser();
396
+ if (stored?.signerType === "eoa") {
397
+ return {};
398
+ }
490
399
  const paramList = Array.isArray(params) ? params : [];
491
400
  const requestedChains = paramList[1];
492
401
  const chainIds = getSupportedChainIds();
@@ -505,22 +414,13 @@ function createOneAuthProvider(options) {
505
414
  return capabilities;
506
415
  }
507
416
  case "wallet_getAssets": {
508
- const user = await ensureUser();
509
- if (!user.username) {
510
- throw new Error("Username required to fetch assets. Set a username first.");
511
- }
512
- const clientId = client.getClientId();
513
- const response = await fetch(
514
- `${client.getProviderUrl()}/api/users/${encodeURIComponent(user.username)}/portfolio`,
515
- {
516
- headers: clientId ? { "x-client-id": clientId } : {}
517
- }
518
- );
519
- if (!response.ok) {
520
- const data = await response.json().catch(() => ({}));
521
- throw new Error(data.error || "Failed to get assets");
417
+ const explicitAccountAddress = getAssetsAccountAddress(params);
418
+ const user = explicitAccountAddress ? null : await ensureUser();
419
+ const accountAddress = explicitAccountAddress || user?.address;
420
+ if (!accountAddress) {
421
+ throw new Error("wallet_getAssets requires accountAddress or a connected account");
522
422
  }
523
- return response.json();
423
+ return client.getAssets({ accountAddress });
524
424
  }
525
425
  case "wallet_getCallsStatus": {
526
426
  const paramList = Array.isArray(params) ? params : [];
@@ -624,24 +524,6 @@ function createOneAuthProvider(options) {
624
524
  }
625
525
 
626
526
  export {
627
- getTokenAddress,
628
- getTokenDecimals,
629
- getSupportedChainIds,
630
- getSupportedChains,
631
- getAllSupportedChainsAndTokens,
632
- getChainById,
633
- getChainName,
634
- getChainExplorerUrl,
635
- getChainRpcUrl,
636
- getSupportedTokens,
637
- getSupportedTokenSymbols,
638
- resolveTokenAddress,
639
- isTestnet,
640
- getTokenSymbol,
641
- isTokenAddressSupported,
642
- encodeWebAuthnSignature,
643
- hashCalls,
644
- buildTransactionReview,
645
527
  createOneAuthProvider
646
528
  };
647
- //# sourceMappingURL=chunk-SXISYG2P.mjs.map
529
+ //# sourceMappingURL=chunk-THKG3FAG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/provider.ts"],"sourcesContent":["/**\n * EIP-1193 JSON-RPC provider factory for the 1auth passkey authentication system.\n *\n * Creates a browser-side provider object that implements the EIP-1193 standard so any\n * Ethereum library (ethers, viem, wagmi) can use 1auth passkey signing and cross-chain\n * intent execution without modification. All transaction signing is delegated to the\n * passkey service rather than holding private keys in the browser.\n *\n * Supported RPC methods:\n * - eth_chainId, eth_accounts, eth_requestAccounts\n * - personal_sign, eth_sign, eth_signTypedData, eth_signTypedData_v4\n * - eth_sendTransaction\n * - wallet_connect, wallet_disconnect, wallet_switchEthereumChain\n * - wallet_sendCalls, wallet_getCallsStatus, wallet_getCallsHistory (EIP-5792)\n * - wallet_getCapabilities, wallet_getAssets\n *\n * @module\n */\n\nimport {\n hexToString,\n isHex,\n numberToHex,\n type Address,\n type Hex,\n} from \"viem\";\nimport { OneAuthClient } from \"./client\";\nimport { getSupportedChainIds } from \"./registry\";\nimport type { CloseOnStatus, IntentCall, IntentTokenRequest, SignerType } from \"./types\";\nimport { encodeWebAuthnSignature } from \"./walletClient/utils\";\n\ntype ProviderRequest = {\n method: string;\n params?: unknown[] | Record<string, unknown>;\n};\n\ntype Listener = (...args: unknown[]) => void;\n\ntype StoredUser = {\n username?: string;\n address: Address;\n /** Absent = legacy passkey user; populated on new sessions. */\n signerType?: SignerType;\n /** Wagmi connector id for EOA sessions. Iframe-side lookup uses this. */\n connectorId?: string;\n};\n\nexport type OneAuthProvider = {\n request: (args: ProviderRequest) => Promise<unknown>;\n on: (event: string, listener: Listener) => void;\n removeListener: (event: string, listener: Listener) => void;\n disconnect: () => Promise<void>;\n};\n\nexport type OneAuthProviderOptions = {\n client: OneAuthClient;\n chainId: number;\n storageKey?: string;\n /** When to close the dialog and return success. Defaults to \"preconfirmed\" */\n closeOn?: CloseOnStatus;\n waitForHash?: boolean;\n hashTimeoutMs?: number;\n hashIntervalMs?: number;\n};\n\nconst DEFAULT_STORAGE_KEY = \"1auth-user\";\n\n/**\n * Creates an EIP-1193 compatible JSON-RPC provider backed by 1auth passkey authentication.\n *\n * The returned provider object can be used anywhere a standard Ethereum provider is\n * accepted (e.g. passed to `createWalletClient` in viem, used as `window.ethereum`, or\n * supplied to ethers.js `BrowserProvider`). Connection state (address + username) is\n * persisted in `localStorage` under the configured `storageKey`.\n *\n * @param options - Provider configuration\n * @param options.client - Configured `OneAuthClient` instance used to open auth/sign dialogs\n * @param options.chainId - Default chain ID the provider reports via `eth_chainId`\n * @param options.storageKey - localStorage key for persisting the connected user.\n * Defaults to `\"1auth-user\"`. Override to support multiple concurrent connections.\n * @param options.closeOn - Controls when the signing dialog closes and shows the \"Done\" button.\n * `\"preconfirmed\"` (default) closes as soon as the intent is confirmed by the orchestrator.\n * The `waitForHash` option independently controls whether the SDK continues polling for\n * a transaction hash after the dialog closes.\n * @param options.waitForHash - When true, polls the intent status until a transaction hash\n * is available before resolving `eth_sendTransaction` / `wallet_sendCalls`. Defaults to true.\n * @param options.hashTimeoutMs - Maximum milliseconds to wait for a transaction hash.\n * Passed directly to the passkey service intent submission.\n * @param options.hashIntervalMs - Polling interval in milliseconds when waiting for a hash.\n * Passed directly to the passkey service intent submission.\n * @returns An EIP-1193 provider with `request`, `on`, `removeListener`, and `disconnect`.\n *\n * @example\n * ```typescript\n * import { OneAuthClient } from \"@rhinestone/1auth\";\n * import { createOneAuthProvider } from \"@rhinestone/1auth\";\n *\n * const client = new OneAuthClient({ clientId: \"my-app\" });\n * const provider = createOneAuthProvider({ client, chainId: 8453 }); // Base\n *\n * // Use with viem\n * import { createWalletClient, custom } from \"viem\";\n * import { base } from \"viem/chains\";\n * const walletClient = createWalletClient({ chain: base, transport: custom(provider) });\n *\n * // Standard EIP-1193 usage\n * const accounts = await provider.request({ method: \"eth_requestAccounts\" });\n * provider.on(\"accountsChanged\", (accounts) => console.log(accounts));\n * ```\n */\nexport function createOneAuthProvider(\n options: OneAuthProviderOptions\n): OneAuthProvider {\n const { client } = options;\n let chainId = options.chainId;\n const storageKey = options.storageKey || DEFAULT_STORAGE_KEY;\n\n const listeners = new Map<string, Set<Listener>>();\n\n /**\n * Dispatches an event to all registered listeners for the given event name.\n *\n * @param event - EIP-1193 event name (e.g. \"accountsChanged\", \"chainChanged\")\n * @param args - Arguments forwarded to each listener callback\n */\n const emit = (event: string, ...args: unknown[]) => {\n const set = listeners.get(event);\n if (!set) return;\n for (const listener of set) listener(...args);\n };\n\n /**\n * Reads the connected user from localStorage.\n *\n * Returns null in non-browser environments (SSR) and when no user has been\n * persisted yet, or when the stored value is malformed.\n *\n * @returns The stored user object, or null if unavailable\n */\n const getStoredUser = (): StoredUser | null => {\n if (typeof window === \"undefined\") return null;\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as StoredUser;\n if (!parsed?.address) return null;\n return parsed;\n } catch {\n return null;\n }\n };\n\n /**\n * Persists the connected user to localStorage.\n *\n * No-ops in non-browser (SSR) environments.\n *\n * @param user - User object with at minimum an `address` field\n */\n const setStoredUser = (user: StoredUser) => {\n if (typeof window === \"undefined\") return;\n localStorage.setItem(storageKey, JSON.stringify(user));\n };\n\n /**\n * Removes the connected user from localStorage, effectively logging them out\n * from the provider's perspective.\n *\n * No-ops in non-browser (SSR) environments.\n */\n const clearStoredUser = () => {\n if (typeof window === \"undefined\") return;\n localStorage.removeItem(storageKey);\n };\n\n /**\n * Fetches the smart account address for a given username from the passkey service.\n *\n * Called as a fallback when the auth/connect modal returns a username but no address\n * (e.g. during first-time sign-up where the account address is computed server-side).\n *\n * @param username - The 1auth username to look up\n * @returns The EVM address of the user's smart account\n * @throws If the HTTP request fails or the service returns an error\n */\n const resolveAccountAddress = async (username: string): Promise<Address> => {\n const clientId = client.getClientId();\n const response = await fetch(\n `${client.getProviderUrl()}/api/users/${encodeURIComponent(username)}/account`,\n {\n headers: clientId ? { \"x-client-id\": clientId } : {},\n }\n );\n\n if (!response.ok) {\n const data = await response.json().catch(() => ({}));\n throw new Error(data.error || \"Failed to resolve account address\");\n }\n\n const data = await response.json();\n return data.address as Address;\n };\n\n /**\n * Connects the user by returning a cached address or opening the auth flow.\n *\n * Returns the dapp-side cached address immediately when present. Otherwise\n * opens the auth modal (`/dialog/auth`) directly — the iframe-side\n * returning-user UX lives inside that flow now. On success the address is\n * stored in localStorage and `accountsChanged` / `connect` events are emitted.\n *\n * @returns Array containing the single connected account address\n * @throws If the user cancels or authentication fails\n */\n const connect = async (): Promise<Address[]> => {\n const stored = getStoredUser();\n if (stored) {\n return [stored.address];\n }\n\n const authResult = await client.authWithModal();\n if (!authResult.success) {\n throw new Error(authResult.error?.message || \"Authentication failed\");\n }\n const username = authResult.user?.username;\n let address = authResult.user?.address;\n const signerType = authResult.signerType;\n\n // Use address from result directly, or resolve from username\n if (!address && username) {\n address = await resolveAccountAddress(username);\n }\n if (!address) {\n throw new Error(\"No account address available\");\n }\n\n setStoredUser({ username, address, signerType });\n emit(\"accountsChanged\", [address]);\n emit(\"connect\", { chainId: numberToHex(chainId) });\n return [address];\n };\n\n /**\n * Disconnects the current user by clearing persisted state and emitting events.\n *\n * Emits `accountsChanged` with an empty array and `disconnect` so that consumers\n * (e.g. wagmi) can update their state accordingly.\n */\n const disconnect = async () => {\n clearStoredUser();\n emit(\"accountsChanged\", []);\n emit(\"disconnect\");\n };\n\n /**\n * Returns the currently connected user, triggering the connect flow if needed.\n *\n * Used internally by methods that require an authenticated session (e.g. signing,\n * sending transactions) to guarantee a user is available before proceeding.\n *\n * @returns The stored user object with at minimum an `address` field\n * @throws If connecting fails and no address can be resolved\n */\n const ensureUser = async (): Promise<StoredUser> => {\n const stored = getStoredUser();\n if (stored) return stored;\n const [address] = await connect();\n if (!address) {\n throw new Error(\"Failed to resolve user session\");\n }\n const user = getStoredUser();\n return user || { address };\n };\n\n /**\n * Read an optional wallet_getAssets account address override from RPC params.\n */\n const getAssetsAccountAddress = (\n assetsParams?: unknown[] | Record<string, unknown>,\n ): string | undefined => {\n const raw = Array.isArray(assetsParams) ? assetsParams[0] : assetsParams;\n if (typeof raw === \"string\" && raw.trim()) return raw.trim();\n if (!raw || typeof raw !== \"object\") return undefined;\n\n const request = raw as Record<string, unknown>;\n const candidates = [\n request.accountAddress,\n request.address,\n ];\n for (const candidate of candidates) {\n if (typeof candidate === \"string\" && candidate.trim()) {\n return candidate.trim();\n }\n }\n return undefined;\n };\n\n /**\n * Parses a chain ID value that may arrive as a hex string, decimal string, or number.\n *\n * Handles both `\"0x1\"` (hex) and `\"1\"` / `1` (decimal) representations that are\n * commonly mixed across different wallet_switchEthereumChain implementations.\n *\n * @param value - The raw chain ID value from RPC params\n * @returns The numeric chain ID, or undefined if the value cannot be parsed\n */\n const parseChainId = (value: unknown): number | undefined => {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\") {\n if (value.startsWith(\"0x\")) return Number.parseInt(value, 16);\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n };\n\n /**\n * Normalizes a transaction value to a decimal string expected by the intent service.\n *\n * Handles the various formats callers may provide: `bigint`, `number`, hex strings\n * (e.g. `\"0x38d7ea4c68000\"`), or plain decimal strings. Returns undefined for null\n * or unsupported types, allowing callers to fall back to `\"0\"`.\n *\n * @param value - Raw value from an RPC transaction param\n * @returns Decimal string representation, or undefined if the input is not usable\n */\n const normalizeValue = (value: unknown): string | undefined => {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"bigint\") return value.toString();\n if (typeof value === \"number\") return Math.trunc(value).toString();\n if (typeof value === \"string\") {\n if (value.startsWith(\"0x\")) {\n return BigInt(value).toString();\n }\n return value;\n }\n return undefined;\n };\n\n /**\n * Converts raw EIP-1193 call objects into the strongly-typed `IntentCall` format\n * expected by the passkey service.\n *\n * Fills in missing `data` with `\"0x\"` and missing `value` with `\"0\"` so the\n * intent service never receives undefined fields.\n *\n * @param calls - Raw call objects from `wallet_sendCalls` or `eth_sendTransaction` params\n * @returns Array of normalized `IntentCall` objects\n */\n const normalizeCalls = (calls: unknown[]): IntentCall[] => {\n return calls.map((call) => {\n const c = call as Record<string, unknown>;\n return {\n to: c.to as Address,\n data: (c.data as Hex | undefined) || \"0x\",\n value: normalizeValue(c.value) || \"0\",\n label: c.label as string | undefined,\n sublabel: c.sublabel as string | undefined,\n icon: c.icon as string | undefined,\n abi: c.abi as readonly unknown[] | undefined,\n };\n });\n };\n\n /**\n * Converts raw token request objects into the typed `IntentTokenRequest` format.\n *\n * Token requests allow callers to specify which tokens and amounts should be sourced\n * when funding a cross-chain intent (e.g. \"bridge 10 USDC from Optimism to Base\").\n * Accepts bigint or string/numeric amounts and normalizes them to bigint.\n *\n * @param requests - Raw token request array from RPC params, or a non-array value\n * @returns Array of typed token requests, or undefined if input is not an array\n */\n const normalizeTokenRequests = (\n requests: unknown\n ): IntentTokenRequest[] | undefined => {\n if (!Array.isArray(requests)) return undefined;\n return requests.map((r) => {\n const req = r as Record<string, unknown>;\n return {\n token: req.token as string,\n amount:\n typeof req.amount === \"bigint\"\n ? req.amount\n : BigInt(String(req.amount || \"0\")),\n };\n });\n };\n\n /**\n * Decodes a message that may be hex-encoded into a human-readable string.\n *\n * Some signers (e.g. MetaMask) encode plain-text messages as hex before passing them\n * to `personal_sign`. This helper reverses that encoding so users see the original\n * text in the signing dialog rather than a raw hex string.\n *\n * @param value - A plain string or hex-encoded string (`\"0x...\"`)\n * @returns The decoded UTF-8 string, or the original value if decoding fails\n */\n const decodeMessage = (value: string) => {\n if (!isHex(value)) return value;\n try {\n return hexToString(value as Hex);\n } catch {\n return value;\n }\n };\n\n /**\n * Forwards a raw EIP-1193 request to the iframe at `/dialog/sign-eoa`, which\n * delegates to the active wagmi connector. The wallet's own prompt is the\n * review screen — no in-dialog review step for EOA sessions.\n */\n const forwardToWallet = async (\n method: string,\n params?: unknown[] | Record<string, unknown>,\n expectedAddress?: Address,\n ): Promise<unknown> => {\n const result = await client.requestWithWallet({\n method,\n params,\n expectedAddress,\n });\n if (!result.success) {\n const err = new Error(result.error.message);\n (err as Error & { code?: string }).code = result.error.code;\n throw err;\n }\n return result.result;\n };\n\n /**\n * EIP-1193 methods forwarded verbatim to the EOA connector. All other methods\n * (eth_accounts, eth_chainId, wallet_connect, wallet_disconnect,\n * wallet_switchEthereumChain, wallet_getCapabilities/Assets) are handled\n * locally against the stored session even for EOA sessions.\n */\n const EOA_FORWARDED_METHODS = new Set([\n \"personal_sign\",\n \"eth_sign\",\n \"eth_signTypedData\",\n \"eth_signTypedData_v3\",\n \"eth_signTypedData_v4\",\n \"eth_sendTransaction\",\n \"wallet_sendCalls\",\n \"wallet_getCallsStatus\",\n ]);\n\n /**\n * Signs an arbitrary string message via the passkey service.\n *\n * Ensures a user session exists before delegating to `OneAuthClient.signMessage`.\n * The raw WebAuthn signature components are ABI-encoded for ERC-1271 on-chain\n * verification before being returned.\n *\n * @param message - Plain-text message to sign\n * @returns ABI-encoded WebAuthn signature as a hex string\n * @throws If no user session is available or the signing dialog is cancelled\n */\n const signMessage = async (message: string) => {\n const user = await ensureUser();\n if (!user.username && !user.address) {\n throw new Error(\"Username or address required for signing.\");\n }\n const result = await client.signMessage({\n username: user.username || undefined,\n accountAddress: user.address,\n message,\n });\n if (!result.success || !result.signature) {\n throw new Error(result.error?.message || \"Signing failed\");\n }\n return encodeWebAuthnSignature(result.signature);\n };\n\n /**\n * Signs EIP-712 typed data via the passkey service.\n *\n * Accepts either a parsed typed-data object or a JSON string (as some libraries\n * serialize the payload before passing it through the provider). The raw WebAuthn\n * signature is ABI-encoded for ERC-1271 on-chain verification.\n *\n * @param typedData - EIP-712 typed data object or its JSON string representation\n * @returns ABI-encoded WebAuthn signature as a hex string\n * @throws If no user session is available or the signing dialog is cancelled\n */\n const signTypedData = async (typedData: unknown) => {\n const user = await ensureUser();\n if (!user.username && !user.address) {\n throw new Error(\"Username or address required for signing.\");\n }\n const data =\n typeof typedData === \"string\" ? JSON.parse(typedData) : typedData;\n const result = await client.signTypedData({\n username: user.username || undefined,\n accountAddress: user.address,\n domain: (data as any).domain,\n types: (data as any).types,\n primaryType: (data as any).primaryType,\n message: (data as any).message,\n });\n if (!result.success || !result.signature) {\n throw new Error(result.error?.message || \"Signing failed\");\n }\n return encodeWebAuthnSignature(result.signature);\n };\n\n /**\n * Extracts the fields required by `OneAuthClient.sendIntent` from a richer payload.\n *\n * This thin wrapper makes it explicit which fields travel to the intent service and\n * which are local concerns (e.g. `sourceChainId` is handled at the call site).\n *\n * @param payload - Full intent payload including user identity and transaction data\n * @returns Subset of fields forwarded to the intent service\n */\n const resolveIntentPayload = (payload: {\n username?: string;\n accountAddress: Address;\n targetChain: number;\n calls: IntentCall[];\n tokenRequests?: IntentTokenRequest[];\n }) => ({\n username: payload.username,\n accountAddress: payload.accountAddress,\n targetChain: payload.targetChain,\n calls: payload.calls,\n tokenRequests: payload.tokenRequests,\n });\n\n /**\n * Submits a cross-chain intent through the passkey service and returns the intent ID.\n *\n * Opens the signing dialog, waits for user confirmation, then polls the orchestrator\n * until a transaction hash is available (controlled by `waitForHash` and the timeout\n * options). The returned intent ID is used as the `callsId` in EIP-5792 responses.\n *\n * The dialog closes based on `closeOn` (defaults to `\"preconfirmed\"`). The `waitForHash`\n * option independently polls for a transaction hash after the dialog closes.\n *\n * @param payload - Intent details including target chain, calls, token requests, and\n * an optional `sourceChainId` for cross-chain bridging\n * @returns The orchestrator intent ID string\n * @throws If the user rejects the signing dialog or the intent fails\n */\n const sendIntent = async (payload: {\n username?: string;\n accountAddress: Address;\n targetChain: number;\n calls: IntentCall[];\n tokenRequests?: IntentTokenRequest[];\n sourceChainId?: number;\n }) => {\n const intentPayload = resolveIntentPayload(payload);\n const result = await client.sendIntent({\n ...intentPayload,\n tokenRequests: payload.tokenRequests,\n sourceChainId: payload.sourceChainId,\n closeOn: options.closeOn,\n waitForHash: options.waitForHash ?? true,\n hashTimeoutMs: options.hashTimeoutMs,\n hashIntervalMs: options.hashIntervalMs,\n });\n\n if (!result.success) {\n throw new Error(result.error?.message || \"Transaction failed\");\n }\n\n // Return intentId as callsId for EIP-5792 compatibility\n return result.intentId;\n };\n\n const accountMismatchError = (): Error & { code?: string } => {\n const err = new Error(\n \"Requested signer does not match the active wallet connection.\",\n ) as Error & { code?: string };\n err.code = \"ACCOUNT_MISMATCH\";\n return err;\n };\n\n const sameAddress = (a: unknown, b: string): boolean =>\n typeof a === \"string\" && a.toLowerCase() === b.toLowerCase();\n\n /**\n * Some wallets (MetaMask, Rabby) reject `eth_sendTransaction` /\n * `wallet_sendCalls` / `personal_sign` / `eth_signTypedData_v4` when the\n * signer address is missing. The dapp doesn't know the EOA address, so the\n * SDK fills it in from the stored session.\n *\n * If the caller supplies a `from` (or address arg) that differs from the\n * connected EOA, we throw `ACCOUNT_MISMATCH` rather than letting the\n * caller's value win. A dapp asking the wallet to sign on behalf of a\n * different account than the user connected is a trust-boundary violation\n * — the user reviewed and approved exactly one address, not whatever the\n * dapp later substitutes.\n */\n const injectEoaSigner = (\n method: string,\n params: unknown[] | Record<string, unknown> | undefined,\n address: Address,\n ): unknown[] | Record<string, unknown> | undefined => {\n const list = Array.isArray(params) ? params.slice() : params;\n if (!Array.isArray(list)) return params;\n\n if (method === \"eth_sendTransaction\") {\n const first = (list[0] || {}) as Record<string, unknown>;\n if (first.from !== undefined && !sameAddress(first.from, address)) {\n throw accountMismatchError();\n }\n list[0] = { ...first, from: address };\n return list;\n }\n if (method === \"wallet_sendCalls\") {\n const first = (list[0] || {}) as Record<string, unknown>;\n if (first.from !== undefined && !sameAddress(first.from, address)) {\n throw accountMismatchError();\n }\n // EIP-5792 lets each call carry its own `from`. Validate every one —\n // a single mismatched call would otherwise sneak through unchecked.\n const calls = first.calls;\n if (Array.isArray(calls)) {\n for (const call of calls) {\n if (!call || typeof call !== \"object\") continue;\n const callFrom = (call as Record<string, unknown>).from;\n if (callFrom !== undefined && !sameAddress(callFrom, address)) {\n throw accountMismatchError();\n }\n }\n }\n list[0] = { ...first, from: address };\n return list;\n }\n if (method === \"personal_sign\") {\n // personal_sign(message, address) — fill address if absent.\n if (list[1] !== undefined && !sameAddress(list[1], address)) {\n throw accountMismatchError();\n }\n if (list[0] && list[1] === undefined) list[1] = address;\n return list;\n }\n if (\n method === \"eth_sign\" ||\n method === \"eth_signTypedData\" ||\n method === \"eth_signTypedData_v3\" ||\n method === \"eth_signTypedData_v4\"\n ) {\n // signTypedData(address, typedData) — fill address if absent.\n if (list[0] !== undefined && !sameAddress(list[0], address)) {\n throw accountMismatchError();\n }\n if (list[0] === undefined && list[1] !== undefined) list[0] = address;\n return list;\n }\n return list;\n };\n\n const request = async ({ method, params }: ProviderRequest) => {\n // For sign/tx methods, resolve the user first — this opens the auth modal\n // on the very first call so we know the signerType before deciding\n // between the passkey path and forwarding to the wagmi connector. Local-\n // only methods (eth_accounts, eth_chainId, wallet_switchEthereumChain,\n // etc.) fall through to the switch below and read stored state directly.\n if (EOA_FORWARDED_METHODS.has(method)) {\n const user = await ensureUser();\n if (user.signerType === \"eoa\") {\n return forwardToWallet(\n method,\n injectEoaSigner(method, params, user.address),\n user.address,\n );\n }\n }\n\n switch (method) {\n case \"eth_chainId\":\n return numberToHex(chainId);\n case \"eth_accounts\": {\n const stored = getStoredUser();\n return stored ? [stored.address] : [];\n }\n case \"eth_requestAccounts\":\n return connect();\n case \"wallet_connect\":\n return connect();\n case \"wallet_disconnect\":\n await disconnect();\n return true;\n case \"wallet_switchEthereumChain\": {\n const [param] = (params as any[]) || [];\n const next = parseChainId(param?.chainId ?? param);\n if (!next) {\n throw new Error(\"Invalid chainId\");\n }\n const stored = getStoredUser();\n if (stored?.signerType === \"eoa\") {\n await forwardToWallet(method, params, stored.address);\n }\n chainId = next;\n emit(\"chainChanged\", numberToHex(chainId));\n return null;\n }\n case \"personal_sign\": {\n const paramList = Array.isArray(params) ? params : [];\n const first = paramList[0];\n const second = paramList[1];\n // personal_sign param order varies: some callers send [message, address],\n // others send [hexEncodedMessage, address]. When the first param is hex and\n // the second is a non-hex string we treat the second as the plain message\n // (MetaMask-style). Otherwise we always decode the first param.\n const message =\n typeof first === \"string\" && first.startsWith(\"0x\") && second\n ? typeof second === \"string\" && !second.startsWith(\"0x\")\n ? second\n : decodeMessage(first)\n : typeof first === \"string\"\n ? decodeMessage(first)\n : typeof second === \"string\"\n ? decodeMessage(second)\n : \"\";\n if (!message) throw new Error(\"Invalid personal_sign payload\");\n return signMessage(message);\n }\n case \"eth_sign\": {\n const paramList = Array.isArray(params) ? params : [];\n const message = typeof paramList[1] === \"string\" ? paramList[1] : \"\";\n if (!message) throw new Error(\"Invalid eth_sign payload\");\n return signMessage(decodeMessage(message));\n }\n case \"eth_signTypedData\":\n case \"eth_signTypedData_v4\": {\n const paramList = Array.isArray(params) ? params : [];\n const typedData = paramList[1] ?? paramList[0];\n return signTypedData(typedData);\n }\n case \"eth_sendTransaction\": {\n const paramList = Array.isArray(params) ? params : [];\n const tx = (paramList[0] || {}) as Record<string, unknown>;\n const user = await ensureUser();\n const targetChain = parseChainId(tx.chainId) ?? chainId;\n const calls = normalizeCalls([tx]);\n const tokenRequests = normalizeTokenRequests(tx.tokenRequests);\n const txSourceChainId = parseChainId(tx.sourceChainId);\n return sendIntent({\n username: user.username || undefined,\n accountAddress: user.address,\n targetChain,\n calls,\n tokenRequests,\n sourceChainId: txSourceChainId,\n });\n }\n case \"wallet_sendCalls\": {\n const paramList = Array.isArray(params) ? params : [];\n const payload = (paramList[0] || {}) as Record<string, unknown>;\n const user = await ensureUser();\n const targetChain = parseChainId(payload.chainId) ?? chainId;\n const calls = normalizeCalls((payload.calls as unknown[]) || []);\n const tokenRequests = normalizeTokenRequests(payload.tokenRequests);\n const sourceChainId = parseChainId(payload.sourceChainId);\n if (!calls.length) throw new Error(\"No calls provided\");\n return sendIntent({\n username: user.username || undefined,\n accountAddress: user.address,\n targetChain,\n calls,\n tokenRequests,\n sourceChainId,\n });\n }\n case \"wallet_getCapabilities\": {\n const stored = getStoredUser();\n if (stored?.signerType === \"eoa\") {\n return {};\n }\n\n const paramList = Array.isArray(params) ? params : [];\n // walletAddress is params[0] - we ignore since all accounts have same capabilities\n const requestedChains = paramList[1] as `0x${string}`[] | undefined;\n\n const chainIds = getSupportedChainIds();\n const capabilities: Record<`0x${string}`, Record<string, unknown>> = {};\n\n for (const chainId of chainIds) {\n const hexChainId = `0x${chainId.toString(16)}` as `0x${string}`;\n\n // Filter if specific chains requested\n if (requestedChains && !requestedChains.includes(hexChainId)) {\n continue;\n }\n\n // All supported chains advertise atomic batching, gasless transactions via\n // paymasters, and cross-chain auxiliary funds (EIP-5792 capability keys).\n capabilities[hexChainId] = {\n atomic: { status: \"supported\" },\n paymasterService: { supported: true },\n auxiliaryFunds: { supported: true },\n };\n }\n\n return capabilities;\n }\n case \"wallet_getAssets\": {\n const explicitAccountAddress = getAssetsAccountAddress(params);\n const user = explicitAccountAddress ? null : await ensureUser();\n // The portfolio endpoint resolves identifiers via resolveUserWhere,\n // and the current SDK account model is address-first. Explicit params\n // let app-level verified sessions query balances without relying on\n // the provider's localStorage cache, while connected EIP-1193 consumers\n // still work with no params.\n const accountAddress = explicitAccountAddress || user?.address;\n if (!accountAddress) {\n throw new Error(\"wallet_getAssets requires accountAddress or a connected account\");\n }\n return client.getAssets({ accountAddress: accountAddress as Address });\n }\n case \"wallet_getCallsStatus\": {\n const paramList = Array.isArray(params) ? params : [];\n const callsId = paramList[0] as string;\n if (!callsId) {\n throw new Error(\"callsId is required\");\n }\n const statusClientId = client.getClientId();\n const response = await fetch(\n `${client.getProviderUrl()}/api/intent/status/${encodeURIComponent(callsId)}`,\n {\n headers: statusClientId ? { \"x-client-id\": statusClientId } : {},\n }\n );\n if (!response.ok) {\n const data = await response.json().catch(() => ({}));\n throw new Error(data.error || \"Failed to get calls status\");\n }\n const data = await response.json();\n // Map intent status to EIP-5792 status strings.\n // Both \"failed\" and \"expired\" map to \"CONFIRMED\" because EIP-5792 uses receipts\n // (and a 0x0 status code) to communicate failure — there is no \"FAILED\" state.\n const statusMap: Record<string, string> = {\n pending: \"PENDING\",\n preconfirmed: \"PENDING\",\n completed: \"CONFIRMED\",\n failed: \"CONFIRMED\",\n expired: \"CONFIRMED\",\n };\n return {\n status: statusMap[data.status] || \"PENDING\",\n receipts: data.transactionHash\n ? [\n {\n logs: [],\n // 0x1 = success, 0x0 = reverted/failed — mirrors EVM receipt status\n status: data.status === \"completed\" ? \"0x1\" : \"0x0\",\n blockHash: data.blockHash,\n blockNumber: data.blockNumber,\n transactionHash: data.transactionHash,\n },\n ]\n : [],\n };\n }\n case \"wallet_getCallsHistory\": {\n const paramList = Array.isArray(params) ? params : [];\n const options = (paramList[0] || {}) as {\n limit?: number;\n offset?: number;\n status?: string;\n from?: string;\n to?: string;\n };\n\n const queryParams = new URLSearchParams();\n if (options.limit) queryParams.set(\"limit\", String(options.limit));\n if (options.offset) queryParams.set(\"offset\", String(options.offset));\n if (options.status) queryParams.set(\"status\", options.status);\n if (options.from) queryParams.set(\"from\", options.from);\n if (options.to) queryParams.set(\"to\", options.to);\n\n const url = `${client.getProviderUrl()}/api/intent/history${\n queryParams.toString() ? `?${queryParams}` : \"\"\n }`;\n\n const historyClientId = client.getClientId();\n const response = await fetch(url, {\n headers: historyClientId ? { \"x-client-id\": historyClientId } : {},\n credentials: \"include\",\n });\n\n if (!response.ok) {\n const data = await response.json().catch(() => ({}));\n throw new Error(data.error || \"Failed to get calls history\");\n }\n\n const data = await response.json();\n\n // Map intent status to EIP-5792 format\n const statusMap: Record<string, string> = {\n pending: \"PENDING\",\n preconfirmed: \"PENDING\",\n completed: \"CONFIRMED\",\n failed: \"CONFIRMED\",\n expired: \"CONFIRMED\",\n };\n\n // intentId IS the orchestrator's ID (used as callsId in EIP-5792)\n return {\n calls: data.intents.map(\n (intent: {\n intentId: string;\n status: string;\n transactionHash?: string;\n targetChain: number;\n }) => ({\n callsId: intent.intentId, // intentId is the orchestrator's ID\n status: statusMap[intent.status] || \"PENDING\",\n receipts: intent.transactionHash\n ? [{ transactionHash: intent.transactionHash }]\n : [],\n chainId: `0x${intent.targetChain.toString(16)}`,\n })\n ),\n total: data.total,\n hasMore: data.hasMore,\n };\n }\n default:\n throw new Error(`Unsupported method: ${method}`);\n }\n };\n\n return {\n request,\n on(event, listener) {\n const set = listeners.get(event) ?? new Set();\n set.add(listener);\n listeners.set(event, set);\n },\n removeListener(event, listener) {\n const set = listeners.get(event);\n if (!set) return;\n set.delete(listener);\n if (set.size === 0) listeners.delete(event);\n },\n disconnect,\n };\n}\n"],"mappings":";;;;;;;;AAmBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAwCP,IAAM,sBAAsB;AA6CrB,SAAS,sBACd,SACiB;AACjB,QAAM,EAAE,OAAO,IAAI;AACnB,MAAI,UAAU,QAAQ;AACtB,QAAM,aAAa,QAAQ,cAAc;AAEzC,QAAM,YAAY,oBAAI,IAA2B;AAQjD,QAAM,OAAO,CAAC,UAAkB,SAAoB;AAClD,UAAM,MAAM,UAAU,IAAI,KAAK;AAC/B,QAAI,CAAC,IAAK;AACV,eAAW,YAAY,IAAK,UAAS,GAAG,IAAI;AAAA,EAC9C;AAUA,QAAM,gBAAgB,MAAyB;AAC7C,QAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAI;AACF,YAA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