@veridex/sdk 1.0.0-beta.22 → 1.0.0-beta.24

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 (112) hide show
  1. package/dist/EVMClient-CoOR_ywD.d.mts +332 -0
  2. package/dist/auth/prepareAuth.d.mts +1 -1
  3. package/dist/auth/prepareAuth.js +749 -3
  4. package/dist/auth/prepareAuth.js.map +1 -1
  5. package/dist/auth/prepareAuth.mjs +25 -1404
  6. package/dist/auth/prepareAuth.mjs.map +1 -1
  7. package/dist/chains/aptos/index.d.mts +1 -1
  8. package/dist/chains/aptos/index.mjs +5 -574
  9. package/dist/chains/aptos/index.mjs.map +1 -1
  10. package/dist/chains/avalanche/index.d.mts +137 -0
  11. package/dist/chains/avalanche/index.js +1407 -0
  12. package/dist/chains/avalanche/index.js.map +1 -0
  13. package/dist/chains/avalanche/index.mjs +10 -0
  14. package/dist/chains/avalanche/index.mjs.map +1 -0
  15. package/dist/chains/evm/index.d.mts +4 -2
  16. package/dist/chains/evm/index.mjs +8 -1200
  17. package/dist/chains/evm/index.mjs.map +1 -1
  18. package/dist/chains/solana/index.d.mts +1 -1
  19. package/dist/chains/solana/index.mjs +4 -486
  20. package/dist/chains/solana/index.mjs.map +1 -1
  21. package/dist/chains/stacks/index.d.mts +1 -1
  22. package/dist/chains/stacks/index.mjs +36 -1114
  23. package/dist/chains/stacks/index.mjs.map +1 -1
  24. package/dist/chains/starknet/index.d.mts +1 -1
  25. package/dist/chains/starknet/index.mjs +5 -503
  26. package/dist/chains/starknet/index.mjs.map +1 -1
  27. package/dist/chains/sui/index.d.mts +1 -1
  28. package/dist/chains/sui/index.mjs +5 -529
  29. package/dist/chains/sui/index.mjs.map +1 -1
  30. package/dist/chunk-3Q34PMHU.mjs +840 -0
  31. package/dist/chunk-3Q34PMHU.mjs.map +1 -0
  32. package/dist/chunk-72ZA3OYQ.mjs +20 -0
  33. package/dist/chunk-72ZA3OYQ.mjs.map +1 -0
  34. package/dist/chunk-7IEUU6LD.mjs +549 -0
  35. package/dist/chunk-7IEUU6LD.mjs.map +1 -0
  36. package/dist/chunk-ABLEEC5N.mjs +38 -0
  37. package/dist/chunk-ABLEEC5N.mjs.map +1 -0
  38. package/dist/chunk-AORSW75A.mjs +1101 -0
  39. package/dist/chunk-AORSW75A.mjs.map +1 -0
  40. package/dist/chunk-BKTCPT7P.mjs +269 -0
  41. package/dist/chunk-BKTCPT7P.mjs.map +1 -0
  42. package/dist/chunk-CCHASDAI.mjs +330 -0
  43. package/dist/chunk-CCHASDAI.mjs.map +1 -0
  44. package/dist/chunk-FQ2WU7PX.mjs +509 -0
  45. package/dist/chunk-FQ2WU7PX.mjs.map +1 -0
  46. package/dist/chunk-JO74ENTF.mjs +417 -0
  47. package/dist/chunk-JO74ENTF.mjs.map +1 -0
  48. package/dist/chunk-K73Y36KS.mjs +407 -0
  49. package/dist/chunk-K73Y36KS.mjs.map +1 -0
  50. package/dist/chunk-KHV3EP3I.mjs +179 -0
  51. package/dist/chunk-KHV3EP3I.mjs.map +1 -0
  52. package/dist/chunk-MMSTOW4F.mjs +722 -0
  53. package/dist/chunk-MMSTOW4F.mjs.map +1 -0
  54. package/dist/chunk-MWZ5UHCF.mjs +1082 -0
  55. package/dist/chunk-MWZ5UHCF.mjs.map +1 -0
  56. package/dist/chunk-NU6JGI7L.mjs +565 -0
  57. package/dist/chunk-NU6JGI7L.mjs.map +1 -0
  58. package/dist/chunk-PIC2Y5DF.mjs +422 -0
  59. package/dist/chunk-PIC2Y5DF.mjs.map +1 -0
  60. package/dist/chunk-PPN7BG3A.mjs +464 -0
  61. package/dist/chunk-PPN7BG3A.mjs.map +1 -0
  62. package/dist/chunk-RSV7J43V.mjs +438 -0
  63. package/dist/chunk-RSV7J43V.mjs.map +1 -0
  64. package/dist/chunk-UTT6KI7N.mjs +216 -0
  65. package/dist/chunk-UTT6KI7N.mjs.map +1 -0
  66. package/dist/constants.mjs +16 -389
  67. package/dist/constants.mjs.map +1 -1
  68. package/dist/index-Du1PoZqu.d.mts +216 -0
  69. package/dist/index.d.mts +131 -9
  70. package/dist/index.js +12064 -11594
  71. package/dist/index.js.map +1 -1
  72. package/dist/index.mjs +4407 -12273
  73. package/dist/index.mjs.map +1 -1
  74. package/dist/passkey.d.mts +142 -0
  75. package/dist/passkey.js +807 -0
  76. package/dist/passkey.js.map +1 -0
  77. package/dist/passkey.mjs +15 -0
  78. package/dist/passkey.mjs.map +1 -0
  79. package/dist/payload.mjs +25 -244
  80. package/dist/payload.mjs.map +1 -1
  81. package/dist/portfolio-UV3LLWKI.mjs +13 -0
  82. package/dist/portfolio-UV3LLWKI.mjs.map +1 -0
  83. package/dist/queries/index.js +39 -1
  84. package/dist/queries/index.js.map +1 -1
  85. package/dist/queries/index.mjs +14 -1591
  86. package/dist/queries/index.mjs.map +1 -1
  87. package/dist/{types-DakHNZIP.d.ts → types-Bmk689Lw.d.mts} +1 -1
  88. package/dist/types.d.mts +10 -0
  89. package/dist/types.js.map +1 -1
  90. package/dist/utils.mjs +19 -385
  91. package/dist/utils.mjs.map +1 -1
  92. package/dist/wormhole.mjs +25 -397
  93. package/dist/wormhole.mjs.map +1 -1
  94. package/package.json +11 -1
  95. package/dist/auth/prepareAuth.d.ts +0 -25
  96. package/dist/chains/aptos/index.d.ts +0 -146
  97. package/dist/chains/evm/index.d.ts +0 -5
  98. package/dist/chains/solana/index.d.ts +0 -116
  99. package/dist/chains/stacks/index.d.ts +0 -559
  100. package/dist/chains/starknet/index.d.ts +0 -172
  101. package/dist/chains/sui/index.d.ts +0 -182
  102. package/dist/constants.d.ts +0 -150
  103. package/dist/index-Dy29mvBf.d.mts +0 -683
  104. package/dist/index-eXXqodd0.d.ts +0 -683
  105. package/dist/index.d.ts +0 -3442
  106. package/dist/payload.d.ts +0 -125
  107. package/dist/queries/index.d.ts +0 -148
  108. package/dist/types-DakHNZIP.d.mts +0 -571
  109. package/dist/types-DvFRnIBd.d.ts +0 -172
  110. package/dist/types.d.ts +0 -413
  111. package/dist/utils.d.ts +0 -81
  112. package/dist/wormhole.d.ts +0 -167
@@ -0,0 +1,1407 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/chains/avalanche/index.ts
21
+ var avalanche_exports = {};
22
+ __export(avalanche_exports, {
23
+ AvalancheClient: () => AvalancheClient
24
+ });
25
+ module.exports = __toCommonJS(avalanche_exports);
26
+
27
+ // src/chains/avalanche/AvalancheClient.ts
28
+ var import_ethers3 = require("ethers");
29
+
30
+ // src/chains/evm/EVMClient.ts
31
+ var import_ethers2 = require("ethers");
32
+
33
+ // src/payload.ts
34
+ var import_ethers = require("ethers");
35
+
36
+ // src/constants.ts
37
+ var ACTION_TRANSFER = 1;
38
+ var ACTION_EXECUTE = 2;
39
+ var ACTION_BRIDGE = 4;
40
+
41
+ // src/payload.ts
42
+ function encodeTransferAction(token, recipient, amount) {
43
+ const tokenPadded = padTo32Bytes(token);
44
+ const recipientPadded = padTo32Bytes(recipient);
45
+ const amountBytes = import_ethers.ethers.zeroPadValue(import_ethers.ethers.toBeHex(amount), 32);
46
+ return import_ethers.ethers.concat([
47
+ import_ethers.ethers.toBeHex(ACTION_TRANSFER, 1),
48
+ tokenPadded,
49
+ recipientPadded,
50
+ amountBytes
51
+ ]);
52
+ }
53
+ function encodeBridgeAction(token, amount, targetChain, recipient) {
54
+ const tokenPadded = padTo32Bytes(token);
55
+ const amountBytes = import_ethers.ethers.zeroPadValue(import_ethers.ethers.toBeHex(amount), 32);
56
+ const targetChainBytes = import_ethers.ethers.toBeHex(targetChain, 2);
57
+ const recipientPadded = padTo32Bytes(recipient);
58
+ return import_ethers.ethers.concat([
59
+ import_ethers.ethers.toBeHex(ACTION_BRIDGE, 1),
60
+ tokenPadded,
61
+ amountBytes,
62
+ targetChainBytes,
63
+ recipientPadded
64
+ ]);
65
+ }
66
+ function encodeExecuteAction(target, value, data) {
67
+ const targetPadded = padTo32Bytes(target);
68
+ const valueBytes = import_ethers.ethers.zeroPadValue(import_ethers.ethers.toBeHex(value), 32);
69
+ const dataBytes = import_ethers.ethers.getBytes(data);
70
+ const dataLengthBytes = import_ethers.ethers.toBeHex(dataBytes.length, 2);
71
+ return import_ethers.ethers.concat([
72
+ import_ethers.ethers.toBeHex(ACTION_EXECUTE, 1),
73
+ targetPadded,
74
+ valueBytes,
75
+ dataLengthBytes,
76
+ data
77
+ ]);
78
+ }
79
+ function padTo32Bytes(address) {
80
+ if (address.toLowerCase() === "native") {
81
+ return "0x" + "0".repeat(64);
82
+ }
83
+ if (address.startsWith("0x")) {
84
+ const hex2 = address.replace("0x", "");
85
+ if (!/^[0-9a-fA-F]*$/.test(hex2)) {
86
+ throw new Error(`Invalid address: ${address}. Expected hex string or 'native'.`);
87
+ }
88
+ return "0x" + hex2.padStart(64, "0");
89
+ }
90
+ const base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
91
+ for (const char of address) {
92
+ if (!base58Chars.includes(char)) {
93
+ throw new Error(`Invalid address: ${address}. Contains invalid base58 character '${char}'.`);
94
+ }
95
+ }
96
+ let value = BigInt(0);
97
+ for (const char of address) {
98
+ value = value * 58n + BigInt(base58Chars.indexOf(char));
99
+ }
100
+ let hex = value.toString(16);
101
+ if (hex.length > 64) {
102
+ throw new Error(`Invalid address: ${address}. Decoded value too large for 32 bytes.`);
103
+ }
104
+ return "0x" + hex.padStart(64, "0");
105
+ }
106
+
107
+ // src/chains/evm/EVMClient.ts
108
+ var PROXY_BYTECODE_PREFIX = "0x3d602d80600a3d3981f3363d3d373d3d3d363d73";
109
+ var PROXY_BYTECODE_SUFFIX = "5af43d82803e903d91602b57fd5bf3";
110
+ var ERC20_ABI = [
111
+ "function balanceOf(address owner) view returns (uint256)",
112
+ "function decimals() view returns (uint8)",
113
+ "function symbol() view returns (string)",
114
+ "function name() view returns (string)",
115
+ "function allowance(address owner, address spender) view returns (uint256)",
116
+ "function transfer(address to, uint256 amount) returns (bool)",
117
+ "function approve(address spender, uint256 amount) returns (bool)"
118
+ ];
119
+ var HUB_ABI = [
120
+ "function dispatch(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) signature, uint256 publicKeyX, uint256 publicKeyY, uint16 targetChain, bytes actionPayload, uint256 nonce) payable returns (uint64 sequence)",
121
+ "function userNonces(bytes32 userKeyHash) view returns (uint256)",
122
+ "function getMessageFee() view returns (uint256)",
123
+ "function getVaultAddress(bytes32 userKeyHash) view returns (address)",
124
+ "function vaultExists(bytes32 userKeyHash) view returns (bool)",
125
+ "function createVault(bytes32 userKeyHash) returns (address)",
126
+ // Issue #9/#10: New Hub methods for Query-based execution
127
+ "function getUserState(bytes32 userKeyHash) view returns (bytes32 keyHash, uint256 nonce, bytes32 lastActionHash)",
128
+ "function getUserLastActionHash(bytes32 userKeyHash) view returns (bytes32)",
129
+ // Issue #13: Session key management
130
+ "function registerSession(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY, bytes32 sessionKeyHash, uint256 duration, uint256 maxValue, bool requireUV) external",
131
+ "function isSessionActive(bytes32 userKeyHash, bytes32 sessionKeyHash) view returns (bool active, uint256 expiry, uint256 maxValue, uint256 sessionIndex)",
132
+ "function revokeSession(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY, bytes32 sessionKeyHash, bool requireUV) external",
133
+ "function getUserSessions(bytes32 userKeyHash) view returns (tuple(bytes32 sessionKeyHash, uint256 expiry, uint256 maxValue, bool revoked)[])",
134
+ "function getUserSessionCount(bytes32 userKeyHash) view returns (uint256)",
135
+ // Issue #22: Backup Passkey / Multi-Key Identity management
136
+ "function registerIdentity(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY) external",
137
+ "function addBackupKey(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY, uint256 newPublicKeyX, uint256 newPublicKeyY, uint256 nonce) external payable returns (uint64 sequence)",
138
+ "function removeKey(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY, bytes32 keyToRemove, uint256 nonce) external payable returns (uint64 sequence)",
139
+ "function getIdentityForKey(bytes32 keyHash) view returns (bytes32)",
140
+ "function getAuthorizedKeys(bytes32 identity) view returns (bytes32[])",
141
+ "function getAuthorizedKeyCount(bytes32 identity) view returns (uint256)",
142
+ "function isAuthorizedForIdentity(bytes32 identity, bytes32 keyHash) view returns (bool)",
143
+ "function isIdentityRoot(bytes32 keyHash) view returns (bool)",
144
+ "function getIdentityState(bytes32 keyHash) view returns (bytes32 identity, uint256 keyCount, uint256 maxKeys, bool isRoot)",
145
+ // Issue #23: Social Recovery / Guardian Management
146
+ "function setupGuardians(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY, bytes32[] guardians, uint256 threshold) external payable returns (uint64 sequence)",
147
+ "function addGuardian(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY, bytes32 guardianKeyHash) external payable returns (uint64 sequence)",
148
+ "function removeGuardian(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY, bytes32 guardianKeyHash) external payable returns (uint64 sequence)",
149
+ "function initiateRecovery(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY, bytes32 identityToRecover, bytes32 newOwnerKeyHash) external payable returns (uint64 sequence)",
150
+ "function approveRecovery(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY, bytes32 identityToRecover) external payable returns (uint64 sequence)",
151
+ "function executeRecovery(bytes32 identityToRecover, uint256 newPublicKeyX, uint256 newPublicKeyY) external payable returns (uint64 sequence)",
152
+ "function cancelRecovery(tuple(bytes authenticatorData, string clientDataJSON, uint256 challengeIndex, uint256 typeIndex, uint256 r, uint256 s) auth, uint256 publicKeyX, uint256 publicKeyY) external payable returns (uint64 sequence)",
153
+ "function getGuardians(bytes32 identityKeyHash) view returns (bytes32[] guardians, uint256 threshold, bool isConfigured)",
154
+ "function getRecoveryStatus(bytes32 identityKeyHash) view returns (bool isActive, bytes32 newOwnerKeyHash, uint256 initiatedAt, uint256 approvalCount, uint256 threshold, uint256 canExecuteAt, uint256 expiresAt)",
155
+ "function hasGuardianApproved(bytes32 identityKeyHash, bytes32 guardianKeyHash) view returns (bool hasApproved)"
156
+ ];
157
+ var FACTORY_ABI = [
158
+ "function createVault(bytes32 ownerKeyHash) returns (address vault)",
159
+ "function getVault(bytes32 ownerKeyHash) view returns (address)",
160
+ "function computeVaultAddress(bytes32 ownerKeyHash) view returns (address vault)",
161
+ "function vaultExists(bytes32 ownerKeyHash) view returns (bool)",
162
+ "function implementation() view returns (address)"
163
+ ];
164
+ var EVMClient = class {
165
+ config;
166
+ provider;
167
+ hubContract;
168
+ factoryContract = null;
169
+ cachedImplementation = null;
170
+ constructor(config) {
171
+ this.config = {
172
+ name: config.name ?? `EVM Chain ${config.chainId}`,
173
+ chainId: config.chainId,
174
+ wormholeChainId: config.wormholeChainId,
175
+ rpcUrl: config.rpcUrl,
176
+ explorerUrl: config.explorerUrl ?? "",
177
+ isEvm: true,
178
+ contracts: {
179
+ hub: config.hubContractAddress,
180
+ vaultFactory: config.vaultFactory,
181
+ vaultImplementation: config.vaultImplementation,
182
+ wormholeCoreBridge: config.wormholeCoreBridge,
183
+ tokenBridge: config.tokenBridge
184
+ }
185
+ };
186
+ this.provider = new import_ethers2.ethers.JsonRpcProvider(config.rpcUrl);
187
+ this.hubContract = new import_ethers2.ethers.Contract(
188
+ config.hubContractAddress,
189
+ HUB_ABI,
190
+ this.provider
191
+ );
192
+ if (config.vaultFactory) {
193
+ this.factoryContract = new import_ethers2.ethers.Contract(
194
+ config.vaultFactory,
195
+ FACTORY_ABI,
196
+ this.provider
197
+ );
198
+ }
199
+ if (config.vaultImplementation) {
200
+ this.cachedImplementation = config.vaultImplementation;
201
+ }
202
+ }
203
+ getConfig() {
204
+ return this.config;
205
+ }
206
+ async getNonce(userKeyHash) {
207
+ const nonce = await this.hubContract.userNonces(userKeyHash);
208
+ return BigInt(nonce.toString());
209
+ }
210
+ /**
211
+ * Get user state from Hub (Issue #9/#10)
212
+ * Returns comprehensive state including last action hash
213
+ */
214
+ async getUserState(userKeyHash) {
215
+ try {
216
+ const result = await this.hubContract.getUserState(userKeyHash);
217
+ return {
218
+ keyHash: result[0],
219
+ nonce: BigInt(result[1].toString()),
220
+ lastActionHash: result[2]
221
+ };
222
+ } catch (error) {
223
+ const nonce = await this.getNonce(userKeyHash);
224
+ return {
225
+ keyHash: userKeyHash,
226
+ nonce,
227
+ lastActionHash: import_ethers2.ethers.ZeroHash
228
+ };
229
+ }
230
+ }
231
+ /**
232
+ * Get user's last action hash from Hub (Issue #9/#10)
233
+ * Returns zero hash if user has no actions yet
234
+ */
235
+ async getUserLastActionHash(userKeyHash) {
236
+ try {
237
+ return await this.hubContract.getUserLastActionHash(userKeyHash);
238
+ } catch (error) {
239
+ return import_ethers2.ethers.ZeroHash;
240
+ }
241
+ }
242
+ // ==========================================================================
243
+ // Session Management Methods (Issue #13)
244
+ // ==========================================================================
245
+ /**
246
+ * Register a new session key for temporary authentication
247
+ * Enables native L1 speed for repeat transactions without biometric auth
248
+ *
249
+ * @param params Session registration parameters
250
+ * @param signer Ethereum signer to pay gas
251
+ * @returns Transaction receipt
252
+ */
253
+ async registerSession(params, signer) {
254
+ const hubWithSigner = this.hubContract.connect(signer);
255
+ const authTuple = {
256
+ authenticatorData: params.signature.authenticatorData,
257
+ clientDataJSON: params.signature.clientDataJSON,
258
+ challengeIndex: params.signature.challengeIndex,
259
+ typeIndex: params.signature.typeIndex,
260
+ r: params.signature.r,
261
+ s: params.signature.s
262
+ };
263
+ const tx = await hubWithSigner.registerSession(
264
+ authTuple,
265
+ params.publicKeyX,
266
+ params.publicKeyY,
267
+ params.sessionKeyHash,
268
+ params.duration,
269
+ params.maxValue,
270
+ params.requireUV
271
+ );
272
+ return await tx.wait();
273
+ }
274
+ /**
275
+ * Check if a session is currently active (queryable via Wormhole CCQ)
276
+ *
277
+ * @param userKeyHash Hash of the user's Passkey public key
278
+ * @param sessionKeyHash Hash of the session key to check
279
+ * @returns Session validation result
280
+ */
281
+ async isSessionActive(userKeyHash, sessionKeyHash) {
282
+ const result = await this.hubContract.isSessionActive(userKeyHash, sessionKeyHash);
283
+ return {
284
+ active: result[0],
285
+ expiry: Number(result[1]),
286
+ maxValue: BigInt(result[2].toString()),
287
+ sessionIndex: Number(result[3])
288
+ };
289
+ }
290
+ /**
291
+ * Revoke a session key immediately
292
+ *
293
+ * @param params Session revocation parameters
294
+ * @param signer Ethereum signer to pay gas
295
+ * @returns Transaction receipt
296
+ */
297
+ async revokeSession(params, signer) {
298
+ const hubWithSigner = this.hubContract.connect(signer);
299
+ const authTuple = {
300
+ authenticatorData: params.signature.authenticatorData,
301
+ clientDataJSON: params.signature.clientDataJSON,
302
+ challengeIndex: params.signature.challengeIndex,
303
+ typeIndex: params.signature.typeIndex,
304
+ r: params.signature.r,
305
+ s: params.signature.s
306
+ };
307
+ const tx = await hubWithSigner.revokeSession(
308
+ authTuple,
309
+ params.publicKeyX,
310
+ params.publicKeyY,
311
+ params.sessionKeyHash,
312
+ params.requireUV
313
+ );
314
+ return await tx.wait();
315
+ }
316
+ /**
317
+ * Get all sessions for a user
318
+ *
319
+ * @param userKeyHash Hash of the user's Passkey public key
320
+ * @returns Array of all sessions (active and expired/revoked)
321
+ */
322
+ async getUserSessions(userKeyHash) {
323
+ const sessions = await this.hubContract.getUserSessions(userKeyHash);
324
+ return sessions.map((s) => ({
325
+ sessionKeyHash: s.sessionKeyHash,
326
+ expiry: Number(s.expiry),
327
+ maxValue: BigInt(s.maxValue.toString()),
328
+ revoked: s.revoked
329
+ }));
330
+ }
331
+ /**
332
+ * Get the number of sessions for a user
333
+ *
334
+ * @param userKeyHash Hash of the user's Passkey public key
335
+ * @returns Number of sessions
336
+ */
337
+ async getUserSessionCount(userKeyHash) {
338
+ const count = await this.hubContract.getUserSessionCount(userKeyHash);
339
+ return Number(count);
340
+ }
341
+ async getMessageFee() {
342
+ const fee = await this.hubContract.getMessageFee();
343
+ return BigInt(fee.toString());
344
+ }
345
+ async buildTransferPayload(params) {
346
+ return encodeTransferAction(
347
+ params.token,
348
+ params.recipient,
349
+ params.amount
350
+ );
351
+ }
352
+ async buildExecutePayload(params) {
353
+ return encodeExecuteAction(
354
+ params.target,
355
+ params.value,
356
+ params.data
357
+ );
358
+ }
359
+ async buildBridgePayload(params) {
360
+ return encodeBridgeAction(
361
+ params.token,
362
+ params.amount,
363
+ params.destinationChain,
364
+ params.recipient
365
+ );
366
+ }
367
+ async dispatch(signature, publicKeyX, publicKeyY, targetChain, actionPayload, nonce, signer) {
368
+ const hubWithSigner = this.hubContract.connect(signer);
369
+ const signatureTuple = {
370
+ authenticatorData: signature.authenticatorData,
371
+ clientDataJSON: signature.clientDataJSON,
372
+ challengeIndex: signature.challengeIndex,
373
+ typeIndex: signature.typeIndex,
374
+ r: signature.r,
375
+ s: signature.s
376
+ };
377
+ const messageFee = await this.getMessageFee();
378
+ const tx = await hubWithSigner.dispatch(
379
+ signatureTuple,
380
+ publicKeyX,
381
+ publicKeyY,
382
+ targetChain,
383
+ actionPayload,
384
+ nonce,
385
+ { value: messageFee }
386
+ );
387
+ const receipt = await tx.wait();
388
+ const dispatchEvent = receipt.logs.find((log) => {
389
+ try {
390
+ const parsed = hubWithSigner.interface.parseLog(log);
391
+ return parsed?.name === "ActionDispatched";
392
+ } catch {
393
+ return false;
394
+ }
395
+ });
396
+ let sequence = 0n;
397
+ if (dispatchEvent) {
398
+ const parsed = hubWithSigner.interface.parseLog(dispatchEvent);
399
+ sequence = BigInt(parsed?.args?.sequence?.toString() ?? "0");
400
+ }
401
+ const keyHash = import_ethers2.ethers.keccak256(
402
+ import_ethers2.ethers.AbiCoder.defaultAbiCoder().encode(
403
+ ["uint256", "uint256"],
404
+ [publicKeyX, publicKeyY]
405
+ )
406
+ );
407
+ return {
408
+ transactionHash: receipt.hash,
409
+ sequence,
410
+ userKeyHash: keyHash,
411
+ targetChain,
412
+ blockNumber: receipt.blockNumber
413
+ };
414
+ }
415
+ /**
416
+ * Dispatch an action to the Hub via relayer (gasless)
417
+ * The relayer pays for gas and submits the transaction on behalf of the user
418
+ */
419
+ async dispatchGasless(signature, publicKeyX, publicKeyY, targetChain, actionPayload, nonce, relayerUrl) {
420
+ const keyHash = import_ethers2.ethers.keccak256(
421
+ import_ethers2.ethers.AbiCoder.defaultAbiCoder().encode(
422
+ ["uint256", "uint256"],
423
+ [publicKeyX, publicKeyY]
424
+ )
425
+ );
426
+ const message = import_ethers2.ethers.keccak256(
427
+ import_ethers2.ethers.AbiCoder.defaultAbiCoder().encode(
428
+ ["bytes32", "uint16", "bytes", "uint256"],
429
+ [keyHash, targetChain, actionPayload, nonce]
430
+ )
431
+ );
432
+ const request = {
433
+ messageHash: message,
434
+ r: "0x" + signature.r.toString(16).padStart(64, "0"),
435
+ s: "0x" + signature.s.toString(16).padStart(64, "0"),
436
+ publicKeyX: "0x" + publicKeyX.toString(16).padStart(64, "0"),
437
+ publicKeyY: "0x" + publicKeyY.toString(16).padStart(64, "0"),
438
+ targetChain,
439
+ actionPayload,
440
+ nonce: Number(nonce)
441
+ };
442
+ const response = await fetch(`${relayerUrl}/api/v1/submit`, {
443
+ method: "POST",
444
+ headers: {
445
+ "Content-Type": "application/json"
446
+ },
447
+ body: JSON.stringify(request)
448
+ });
449
+ if (!response.ok) {
450
+ const error = await response.json().catch(() => ({ error: response.statusText }));
451
+ throw new Error(`Relayer submission failed: ${error.error || response.statusText}`);
452
+ }
453
+ const result = await response.json();
454
+ if (!result.success) {
455
+ throw new Error(`Relayer submission failed: ${result.error}`);
456
+ }
457
+ return {
458
+ transactionHash: result.txHash,
459
+ sequence: BigInt(result.sequence || "0"),
460
+ userKeyHash: keyHash,
461
+ targetChain
462
+ };
463
+ }
464
+ async getVaultAddress(userKeyHash) {
465
+ try {
466
+ if (this.factoryContract) {
467
+ const address2 = await this.factoryContract.getVault(userKeyHash);
468
+ if (address2 !== import_ethers2.ethers.ZeroAddress) {
469
+ return address2;
470
+ }
471
+ }
472
+ const address = await this.hubContract.getVaultAddress(userKeyHash);
473
+ if (address === import_ethers2.ethers.ZeroAddress) {
474
+ return null;
475
+ }
476
+ return address;
477
+ } catch (error) {
478
+ console.error("Error getting vault address:", error);
479
+ return null;
480
+ }
481
+ }
482
+ /**
483
+ * Compute vault address deterministically without querying the chain
484
+ * Uses CREATE2 with EIP-1167 minimal proxy pattern
485
+ */
486
+ computeVaultAddress(userKeyHash) {
487
+ const factoryAddress = this.getFactoryAddress();
488
+ const implementationAddress = this.getImplementationAddress();
489
+ if (!factoryAddress || !implementationAddress) {
490
+ throw new Error("Factory and implementation addresses required for address computation");
491
+ }
492
+ const salt = import_ethers2.ethers.keccak256(
493
+ import_ethers2.ethers.solidityPacked(
494
+ ["address", "bytes32"],
495
+ [factoryAddress, userKeyHash]
496
+ )
497
+ );
498
+ const initCode = this.buildProxyInitCode(implementationAddress);
499
+ const initCodeHash = import_ethers2.ethers.keccak256(initCode);
500
+ const create2Data = import_ethers2.ethers.solidityPacked(
501
+ ["bytes1", "address", "bytes32", "bytes32"],
502
+ ["0xff", factoryAddress, salt, initCodeHash]
503
+ );
504
+ const hash = import_ethers2.ethers.keccak256(create2Data);
505
+ return import_ethers2.ethers.getAddress("0x" + hash.slice(26));
506
+ }
507
+ /**
508
+ * Build EIP-1167 minimal proxy initcode
509
+ */
510
+ buildProxyInitCode(implementationAddress) {
511
+ const impl = implementationAddress.toLowerCase().replace("0x", "");
512
+ return PROXY_BYTECODE_PREFIX + impl + PROXY_BYTECODE_SUFFIX;
513
+ }
514
+ async vaultExists(userKeyHash) {
515
+ try {
516
+ if (this.factoryContract) {
517
+ return await this.factoryContract.vaultExists(userKeyHash);
518
+ }
519
+ if (this.hubContract.vaultExists) {
520
+ try {
521
+ return await this.hubContract.vaultExists(userKeyHash);
522
+ } catch {
523
+ return false;
524
+ }
525
+ }
526
+ return false;
527
+ } catch {
528
+ return false;
529
+ }
530
+ }
531
+ async createVault(userKeyHash, signer) {
532
+ const exists = await this.vaultExists(userKeyHash);
533
+ if (exists) {
534
+ const address = await this.getVaultAddress(userKeyHash);
535
+ if (address) {
536
+ return {
537
+ address,
538
+ transactionHash: "",
539
+ blockNumber: 0,
540
+ gasUsed: 0n,
541
+ alreadyExisted: true
542
+ };
543
+ }
544
+ }
545
+ let tx;
546
+ if (this.factoryContract) {
547
+ const factoryWithSigner = this.factoryContract.connect(signer);
548
+ tx = await factoryWithSigner.createVault(userKeyHash);
549
+ } else {
550
+ const hubWithSigner = this.hubContract.connect(signer);
551
+ tx = await hubWithSigner.createVault(userKeyHash);
552
+ }
553
+ const receipt = await tx.wait();
554
+ if (!receipt) {
555
+ throw new Error("Transaction failed - no receipt");
556
+ }
557
+ const vaultAddress = await this.getVaultAddress(userKeyHash);
558
+ if (!vaultAddress) {
559
+ throw new Error("Failed to create vault - address not found after creation");
560
+ }
561
+ return {
562
+ address: vaultAddress,
563
+ transactionHash: receipt.hash,
564
+ blockNumber: receipt.blockNumber,
565
+ gasUsed: receipt.gasUsed,
566
+ alreadyExisted: false
567
+ };
568
+ }
569
+ /**
570
+ * Create a vault with a sponsor wallet paying for gas
571
+ *
572
+ * @param userKeyHash - The user's passkey hash
573
+ * @param sponsorPrivateKey - Private key of the wallet that will pay gas
574
+ * @param rpcUrl - Optional RPC URL to use (defaults to client's RPC)
575
+ * @returns VaultCreationResult with address and transaction details
576
+ */
577
+ async createVaultSponsored(userKeyHash, sponsorPrivateKey, rpcUrl) {
578
+ const exists = await this.vaultExists(userKeyHash);
579
+ if (exists) {
580
+ const address = await this.getVaultAddress(userKeyHash);
581
+ if (address) {
582
+ return {
583
+ address,
584
+ transactionHash: "",
585
+ blockNumber: 0,
586
+ gasUsed: 0n,
587
+ alreadyExisted: true
588
+ };
589
+ }
590
+ }
591
+ const provider = rpcUrl ? new import_ethers2.ethers.JsonRpcProvider(rpcUrl) : this.provider;
592
+ const sponsorWallet = new import_ethers2.ethers.Wallet(sponsorPrivateKey, provider);
593
+ const sponsorBalance = await provider.getBalance(sponsorWallet.address);
594
+ const estimatedGas = await this.estimateVaultCreationGas(userKeyHash);
595
+ const feeData = await provider.getFeeData();
596
+ const estimatedCost = estimatedGas * (feeData.gasPrice ?? 1000000000n);
597
+ if (sponsorBalance < estimatedCost) {
598
+ throw new Error(
599
+ `Sponsor wallet has insufficient funds. Balance: ${import_ethers2.ethers.formatEther(sponsorBalance)} ETH, Estimated cost: ${import_ethers2.ethers.formatEther(estimatedCost)} ETH`
600
+ );
601
+ }
602
+ let tx;
603
+ if (this.factoryContract) {
604
+ const factoryWithSponsor = this.factoryContract.connect(sponsorWallet);
605
+ tx = await factoryWithSponsor.createVault(userKeyHash);
606
+ } else {
607
+ const hubWithSponsor = this.hubContract.connect(sponsorWallet);
608
+ tx = await hubWithSponsor.createVault(userKeyHash);
609
+ }
610
+ const receipt = await tx.wait();
611
+ if (!receipt) {
612
+ throw new Error("Transaction failed - no receipt");
613
+ }
614
+ const vaultAddress = await this.getVaultAddress(userKeyHash);
615
+ if (!vaultAddress) {
616
+ throw new Error("Failed to create vault - address not found after creation");
617
+ }
618
+ return {
619
+ address: vaultAddress,
620
+ transactionHash: receipt.hash,
621
+ blockNumber: receipt.blockNumber,
622
+ gasUsed: receipt.gasUsed,
623
+ alreadyExisted: false,
624
+ sponsoredBy: sponsorWallet.address
625
+ };
626
+ }
627
+ async estimateVaultCreationGas(userKeyHash) {
628
+ try {
629
+ if (this.factoryContract) {
630
+ return await this.factoryContract.createVault.estimateGas(userKeyHash);
631
+ }
632
+ return await this.hubContract.createVault.estimateGas(userKeyHash);
633
+ } catch (error) {
634
+ console.warn("Gas estimation failed, returning default:", error);
635
+ return 150000n;
636
+ }
637
+ }
638
+ getFactoryAddress() {
639
+ return this.config.contracts.vaultFactory;
640
+ }
641
+ getImplementationAddress() {
642
+ return this.config.contracts.vaultImplementation ?? this.cachedImplementation ?? void 0;
643
+ }
644
+ /**
645
+ * Fetch implementation address from factory contract
646
+ */
647
+ async fetchImplementationAddress() {
648
+ if (this.cachedImplementation) {
649
+ return this.cachedImplementation;
650
+ }
651
+ if (!this.factoryContract) {
652
+ return null;
653
+ }
654
+ try {
655
+ this.cachedImplementation = await this.factoryContract.implementation();
656
+ return this.cachedImplementation;
657
+ } catch (error) {
658
+ console.error("Error fetching implementation address:", error);
659
+ return null;
660
+ }
661
+ }
662
+ /**
663
+ * Get the provider instance
664
+ */
665
+ getProvider() {
666
+ return this.provider;
667
+ }
668
+ // ========================================================================
669
+ // Balance Methods (Phase 2)
670
+ // ========================================================================
671
+ /**
672
+ * Get native token balance for an address
673
+ */
674
+ async getNativeBalance(address) {
675
+ return await this.provider.getBalance(address);
676
+ }
677
+ /**
678
+ * Get ERC20 token balance for an address
679
+ */
680
+ async getTokenBalance(tokenAddress, ownerAddress) {
681
+ const contract = new import_ethers2.ethers.Contract(tokenAddress, ERC20_ABI, this.provider);
682
+ return await contract.balanceOf(ownerAddress);
683
+ }
684
+ /**
685
+ * Get token allowance
686
+ */
687
+ async getTokenAllowance(tokenAddress, ownerAddress, spenderAddress) {
688
+ const contract = new import_ethers2.ethers.Contract(tokenAddress, ERC20_ABI, this.provider);
689
+ return await contract.allowance(ownerAddress, spenderAddress);
690
+ }
691
+ /**
692
+ * Estimate gas for a dispatch transaction
693
+ */
694
+ async estimateDispatchGas(signature, publicKeyX, publicKeyY, targetChain, actionPayload, nonce) {
695
+ const signatureTuple = {
696
+ authenticatorData: signature.authenticatorData,
697
+ clientDataJSON: signature.clientDataJSON,
698
+ challengeIndex: signature.challengeIndex,
699
+ typeIndex: signature.typeIndex,
700
+ r: signature.r,
701
+ s: signature.s
702
+ };
703
+ const messageFee = await this.getMessageFee();
704
+ try {
705
+ const gasEstimate = await this.hubContract.dispatch.estimateGas(
706
+ signatureTuple,
707
+ publicKeyX,
708
+ publicKeyY,
709
+ targetChain,
710
+ actionPayload,
711
+ nonce,
712
+ { value: messageFee }
713
+ );
714
+ return gasEstimate;
715
+ } catch (error) {
716
+ console.warn("Gas estimation failed, using default:", error);
717
+ return 500000n;
718
+ }
719
+ }
720
+ /**
721
+ * Get current gas price
722
+ */
723
+ async getGasPrice() {
724
+ const feeData = await this.provider.getFeeData();
725
+ return feeData.gasPrice ?? feeData.maxFeePerGas ?? 0n;
726
+ }
727
+ /**
728
+ * Get current block number
729
+ */
730
+ async getBlockNumber() {
731
+ return await this.provider.getBlockNumber();
732
+ }
733
+ /**
734
+ * Get transaction receipt
735
+ */
736
+ async getTransactionReceipt(hash) {
737
+ return await this.provider.getTransactionReceipt(hash);
738
+ }
739
+ /**
740
+ * Wait for transaction confirmation
741
+ */
742
+ async waitForTransaction(hash, confirmations = 1) {
743
+ return await this.provider.waitForTransaction(hash, confirmations);
744
+ }
745
+ // ==========================================================================
746
+ // Backup Passkey / Multi-Key Identity Methods (Issue #22)
747
+ // ==========================================================================
748
+ /**
749
+ * Get the identity for a given key hash
750
+ * Returns zero hash if key is not registered to any identity
751
+ *
752
+ * @param keyHash Hash of the passkey to look up
753
+ * @returns Identity (first passkey's keyHash) or zero hash
754
+ */
755
+ async getIdentityForKey(keyHash) {
756
+ try {
757
+ return await this.hubContract.getIdentityForKey(keyHash);
758
+ } catch (error) {
759
+ return import_ethers2.ethers.ZeroHash;
760
+ }
761
+ }
762
+ /**
763
+ * Get all authorized keys for an identity
764
+ *
765
+ * @param identity The identity key hash (first passkey's keyHash)
766
+ * @returns Array of authorized key hashes
767
+ */
768
+ async getAuthorizedKeys(identity) {
769
+ try {
770
+ return await this.hubContract.getAuthorizedKeys(identity);
771
+ } catch (error) {
772
+ return [];
773
+ }
774
+ }
775
+ /**
776
+ * Get count of authorized keys for an identity
777
+ *
778
+ * @param identity The identity key hash
779
+ * @returns Number of authorized keys
780
+ */
781
+ async getAuthorizedKeyCount(identity) {
782
+ try {
783
+ const count = await this.hubContract.getAuthorizedKeyCount(identity);
784
+ return Number(count);
785
+ } catch (error) {
786
+ return 0;
787
+ }
788
+ }
789
+ /**
790
+ * Check if a key is authorized for an identity
791
+ *
792
+ * @param identity The identity key hash
793
+ * @param keyHash The key hash to check
794
+ * @returns Whether the key is authorized
795
+ */
796
+ async isAuthorizedForIdentity(identity, keyHash) {
797
+ try {
798
+ return await this.hubContract.isAuthorizedForIdentity(identity, keyHash);
799
+ } catch (error) {
800
+ return false;
801
+ }
802
+ }
803
+ /**
804
+ * Check if a key is the root identity key
805
+ *
806
+ * @param keyHash The key hash to check
807
+ * @returns Whether the key is a root identity
808
+ */
809
+ async isIdentityRootKey(keyHash) {
810
+ try {
811
+ return await this.hubContract.isIdentityRoot(keyHash);
812
+ } catch (error) {
813
+ return false;
814
+ }
815
+ }
816
+ /**
817
+ * Get comprehensive identity state for a key
818
+ *
819
+ * @param keyHash Hash of any key in the identity
820
+ * @returns Identity state including count, max, and root status
821
+ */
822
+ async getIdentityState(keyHash) {
823
+ try {
824
+ const result = await this.hubContract.getIdentityState(keyHash);
825
+ return {
826
+ identity: result[0],
827
+ keyCount: Number(result[1]),
828
+ maxKeys: Number(result[2]),
829
+ isRoot: result[3]
830
+ };
831
+ } catch (error) {
832
+ return {
833
+ identity: import_ethers2.ethers.ZeroHash,
834
+ keyCount: 0,
835
+ maxKeys: 5,
836
+ isRoot: false
837
+ };
838
+ }
839
+ }
840
+ /**
841
+ * Register a new identity with the first passkey
842
+ * This makes the passkey the root identity key
843
+ *
844
+ * @param signature WebAuthn signature
845
+ * @param publicKeyX Passkey public key X coordinate
846
+ * @param publicKeyY Passkey public key Y coordinate
847
+ * @param signer Ethereum signer to pay gas
848
+ * @returns Transaction receipt and identity hash
849
+ */
850
+ async registerIdentity(signature, publicKeyX, publicKeyY, signer) {
851
+ const hubWithSigner = this.hubContract.connect(signer);
852
+ const authTuple = {
853
+ authenticatorData: signature.authenticatorData,
854
+ clientDataJSON: signature.clientDataJSON,
855
+ challengeIndex: signature.challengeIndex,
856
+ typeIndex: signature.typeIndex,
857
+ r: signature.r,
858
+ s: signature.s
859
+ };
860
+ const tx = await hubWithSigner.registerIdentity(
861
+ authTuple,
862
+ publicKeyX,
863
+ publicKeyY
864
+ );
865
+ const receipt = await tx.wait();
866
+ const keyHash = import_ethers2.ethers.keccak256(
867
+ import_ethers2.ethers.solidityPacked(["uint256", "uint256"], [publicKeyX, publicKeyY])
868
+ );
869
+ return { receipt, identity: keyHash };
870
+ }
871
+ /**
872
+ * Add a backup passkey to an existing identity
873
+ * Requires WebAuthn signature from an authorized key
874
+ *
875
+ * @param signature WebAuthn signature from existing authorized key
876
+ * @param publicKeyX Existing key's X coordinate
877
+ * @param publicKeyY Existing key's Y coordinate
878
+ * @param newPublicKeyX New backup key's X coordinate
879
+ * @param newPublicKeyY New backup key's Y coordinate
880
+ * @param nonce Current nonce for the signing key
881
+ * @param signer Ethereum signer to pay gas
882
+ * @returns Transaction receipt and sequence number
883
+ */
884
+ async addBackupKey(signature, publicKeyX, publicKeyY, newPublicKeyX, newPublicKeyY, nonce, signer) {
885
+ const hubWithSigner = this.hubContract.connect(signer);
886
+ const authTuple = {
887
+ authenticatorData: signature.authenticatorData,
888
+ clientDataJSON: signature.clientDataJSON,
889
+ challengeIndex: signature.challengeIndex,
890
+ typeIndex: signature.typeIndex,
891
+ r: signature.r,
892
+ s: signature.s
893
+ };
894
+ const messageFee = await this.getMessageFee();
895
+ const tx = await hubWithSigner.addBackupKey(
896
+ authTuple,
897
+ publicKeyX,
898
+ publicKeyY,
899
+ newPublicKeyX,
900
+ newPublicKeyY,
901
+ nonce,
902
+ { value: messageFee }
903
+ );
904
+ const receipt = await tx.wait();
905
+ let sequence = 0n;
906
+ for (const log of receipt.logs) {
907
+ try {
908
+ const parsed = this.hubContract.interface.parseLog({
909
+ topics: log.topics,
910
+ data: log.data
911
+ });
912
+ if (parsed?.name === "Dispatched") {
913
+ sequence = BigInt(parsed.args[3]);
914
+ break;
915
+ }
916
+ } catch {
917
+ }
918
+ }
919
+ return { receipt, sequence };
920
+ }
921
+ /**
922
+ * Remove a passkey from an identity
923
+ * Cannot remove the last remaining key
924
+ *
925
+ * @param signature WebAuthn signature from an authorized key
926
+ * @param publicKeyX Signing key's X coordinate
927
+ * @param publicKeyY Signing key's Y coordinate
928
+ * @param keyToRemove Hash of the key to remove
929
+ * @param nonce Current nonce for the signing key
930
+ * @param signer Ethereum signer to pay gas
931
+ * @returns Transaction receipt and sequence number
932
+ */
933
+ async removeKey(signature, publicKeyX, publicKeyY, keyToRemove, nonce, signer) {
934
+ const hubWithSigner = this.hubContract.connect(signer);
935
+ const authTuple = {
936
+ authenticatorData: signature.authenticatorData,
937
+ clientDataJSON: signature.clientDataJSON,
938
+ challengeIndex: signature.challengeIndex,
939
+ typeIndex: signature.typeIndex,
940
+ r: signature.r,
941
+ s: signature.s
942
+ };
943
+ const messageFee = await this.getMessageFee();
944
+ const tx = await hubWithSigner.removeKey(
945
+ authTuple,
946
+ publicKeyX,
947
+ publicKeyY,
948
+ keyToRemove,
949
+ nonce,
950
+ { value: messageFee }
951
+ );
952
+ const receipt = await tx.wait();
953
+ let sequence = 0n;
954
+ for (const log of receipt.logs) {
955
+ try {
956
+ const parsed = this.hubContract.interface.parseLog({
957
+ topics: log.topics,
958
+ data: log.data
959
+ });
960
+ if (parsed?.name === "Dispatched") {
961
+ sequence = BigInt(parsed.args[3]);
962
+ break;
963
+ }
964
+ } catch {
965
+ }
966
+ }
967
+ return { receipt, sequence };
968
+ }
969
+ // =========================================================================
970
+ // SOCIAL RECOVERY METHODS (Issue #23)
971
+ // =========================================================================
972
+ /**
973
+ * Setup guardians for an identity
974
+ * @param signature WebAuthn signature from owner
975
+ * @param publicKeyX Owner's public key X coordinate
976
+ * @param publicKeyY Owner's public key Y coordinate
977
+ * @param guardians Array of guardian key hashes
978
+ * @param threshold Required approvals for recovery
979
+ * @param signer Ethers signer for transaction
980
+ */
981
+ async setupGuardians(signature, publicKeyX, publicKeyY, guardians, threshold, signer) {
982
+ const hubWithSigner = this.hubContract.connect(signer);
983
+ const authTuple = {
984
+ authenticatorData: signature.authenticatorData,
985
+ clientDataJSON: signature.clientDataJSON,
986
+ challengeIndex: signature.challengeIndex,
987
+ typeIndex: signature.typeIndex,
988
+ r: signature.r,
989
+ s: signature.s
990
+ };
991
+ const messageFee = await this.getMessageFee();
992
+ const tx = await hubWithSigner.setupGuardians(
993
+ authTuple,
994
+ publicKeyX,
995
+ publicKeyY,
996
+ guardians,
997
+ threshold,
998
+ { value: messageFee }
999
+ );
1000
+ const receipt = await tx.wait();
1001
+ const sequence = this._extractSequenceFromReceipt(receipt);
1002
+ return { receipt, sequence };
1003
+ }
1004
+ /**
1005
+ * Add a guardian to an identity
1006
+ */
1007
+ async addGuardian(signature, publicKeyX, publicKeyY, guardianKeyHash, signer) {
1008
+ const hubWithSigner = this.hubContract.connect(signer);
1009
+ const authTuple = {
1010
+ authenticatorData: signature.authenticatorData,
1011
+ clientDataJSON: signature.clientDataJSON,
1012
+ challengeIndex: signature.challengeIndex,
1013
+ typeIndex: signature.typeIndex,
1014
+ r: signature.r,
1015
+ s: signature.s
1016
+ };
1017
+ const messageFee = await this.getMessageFee();
1018
+ const tx = await hubWithSigner.addGuardian(
1019
+ authTuple,
1020
+ publicKeyX,
1021
+ publicKeyY,
1022
+ guardianKeyHash,
1023
+ { value: messageFee }
1024
+ );
1025
+ const receipt = await tx.wait();
1026
+ const sequence = this._extractSequenceFromReceipt(receipt);
1027
+ return { receipt, sequence };
1028
+ }
1029
+ /**
1030
+ * Remove a guardian from an identity
1031
+ */
1032
+ async removeGuardian(signature, publicKeyX, publicKeyY, guardianKeyHash, signer) {
1033
+ const hubWithSigner = this.hubContract.connect(signer);
1034
+ const authTuple = {
1035
+ authenticatorData: signature.authenticatorData,
1036
+ clientDataJSON: signature.clientDataJSON,
1037
+ challengeIndex: signature.challengeIndex,
1038
+ typeIndex: signature.typeIndex,
1039
+ r: signature.r,
1040
+ s: signature.s
1041
+ };
1042
+ const messageFee = await this.getMessageFee();
1043
+ const tx = await hubWithSigner.removeGuardian(
1044
+ authTuple,
1045
+ publicKeyX,
1046
+ publicKeyY,
1047
+ guardianKeyHash,
1048
+ { value: messageFee }
1049
+ );
1050
+ const receipt = await tx.wait();
1051
+ const sequence = this._extractSequenceFromReceipt(receipt);
1052
+ return { receipt, sequence };
1053
+ }
1054
+ /**
1055
+ * Initiate recovery as a guardian
1056
+ */
1057
+ async initiateRecovery(signature, publicKeyX, publicKeyY, identityToRecover, newOwnerKeyHash, signer) {
1058
+ const hubWithSigner = this.hubContract.connect(signer);
1059
+ const authTuple = {
1060
+ authenticatorData: signature.authenticatorData,
1061
+ clientDataJSON: signature.clientDataJSON,
1062
+ challengeIndex: signature.challengeIndex,
1063
+ typeIndex: signature.typeIndex,
1064
+ r: signature.r,
1065
+ s: signature.s
1066
+ };
1067
+ const messageFee = await this.getMessageFee();
1068
+ const tx = await hubWithSigner.initiateRecovery(
1069
+ authTuple,
1070
+ publicKeyX,
1071
+ publicKeyY,
1072
+ identityToRecover,
1073
+ newOwnerKeyHash,
1074
+ { value: messageFee }
1075
+ );
1076
+ const receipt = await tx.wait();
1077
+ const sequence = this._extractSequenceFromReceipt(receipt);
1078
+ return { receipt, sequence };
1079
+ }
1080
+ /**
1081
+ * Approve recovery as a guardian
1082
+ */
1083
+ async approveRecovery(signature, publicKeyX, publicKeyY, identityToRecover, signer) {
1084
+ const hubWithSigner = this.hubContract.connect(signer);
1085
+ const authTuple = {
1086
+ authenticatorData: signature.authenticatorData,
1087
+ clientDataJSON: signature.clientDataJSON,
1088
+ challengeIndex: signature.challengeIndex,
1089
+ typeIndex: signature.typeIndex,
1090
+ r: signature.r,
1091
+ s: signature.s
1092
+ };
1093
+ const messageFee = await this.getMessageFee();
1094
+ const tx = await hubWithSigner.approveRecovery(
1095
+ authTuple,
1096
+ publicKeyX,
1097
+ publicKeyY,
1098
+ identityToRecover,
1099
+ { value: messageFee }
1100
+ );
1101
+ const receipt = await tx.wait();
1102
+ const sequence = this._extractSequenceFromReceipt(receipt);
1103
+ return { receipt, sequence };
1104
+ }
1105
+ /**
1106
+ * Execute recovery after timelock (anyone can call)
1107
+ */
1108
+ async executeRecovery(identityToRecover, newPublicKeyX, newPublicKeyY, signer) {
1109
+ const hubWithSigner = this.hubContract.connect(signer);
1110
+ const messageFee = await this.getMessageFee();
1111
+ const tx = await hubWithSigner.executeRecovery(
1112
+ identityToRecover,
1113
+ newPublicKeyX,
1114
+ newPublicKeyY,
1115
+ { value: messageFee }
1116
+ );
1117
+ const receipt = await tx.wait();
1118
+ const sequence = this._extractSequenceFromReceipt(receipt);
1119
+ return { receipt, sequence };
1120
+ }
1121
+ /**
1122
+ * Cancel recovery as owner
1123
+ */
1124
+ async cancelRecovery(signature, publicKeyX, publicKeyY, signer) {
1125
+ const hubWithSigner = this.hubContract.connect(signer);
1126
+ const authTuple = {
1127
+ authenticatorData: signature.authenticatorData,
1128
+ clientDataJSON: signature.clientDataJSON,
1129
+ challengeIndex: signature.challengeIndex,
1130
+ typeIndex: signature.typeIndex,
1131
+ r: signature.r,
1132
+ s: signature.s
1133
+ };
1134
+ const messageFee = await this.getMessageFee();
1135
+ const tx = await hubWithSigner.cancelRecovery(
1136
+ authTuple,
1137
+ publicKeyX,
1138
+ publicKeyY,
1139
+ { value: messageFee }
1140
+ );
1141
+ const receipt = await tx.wait();
1142
+ const sequence = this._extractSequenceFromReceipt(receipt);
1143
+ return { receipt, sequence };
1144
+ }
1145
+ /**
1146
+ * Get guardians for an identity
1147
+ */
1148
+ async getGuardians(identityKeyHash) {
1149
+ const result = await this.hubContract.getGuardians(identityKeyHash);
1150
+ return {
1151
+ guardians: result.guardians,
1152
+ threshold: result.threshold,
1153
+ isConfigured: result.isConfigured
1154
+ };
1155
+ }
1156
+ /**
1157
+ * Get recovery status for an identity
1158
+ */
1159
+ async getRecoveryStatus(identityKeyHash) {
1160
+ const result = await this.hubContract.getRecoveryStatus(identityKeyHash);
1161
+ return {
1162
+ isActive: result.isActive,
1163
+ newOwnerKeyHash: result.newOwnerKeyHash,
1164
+ initiatedAt: result.initiatedAt,
1165
+ approvalCount: result.approvalCount,
1166
+ threshold: result.threshold,
1167
+ canExecuteAt: result.canExecuteAt,
1168
+ expiresAt: result.expiresAt
1169
+ };
1170
+ }
1171
+ /**
1172
+ * Check if a guardian has approved recovery
1173
+ */
1174
+ async hasGuardianApproved(identityKeyHash, guardianKeyHash) {
1175
+ return this.hubContract.hasGuardianApproved(identityKeyHash, guardianKeyHash);
1176
+ }
1177
+ /**
1178
+ * Helper to extract sequence from transaction receipt
1179
+ */
1180
+ _extractSequenceFromReceipt(receipt) {
1181
+ for (const log of receipt.logs) {
1182
+ try {
1183
+ const parsed = this.hubContract.interface.parseLog({
1184
+ topics: log.topics,
1185
+ data: log.data
1186
+ });
1187
+ if (parsed?.name === "Dispatch") {
1188
+ return BigInt(parsed.args.sequence);
1189
+ }
1190
+ } catch {
1191
+ }
1192
+ }
1193
+ return 0n;
1194
+ }
1195
+ };
1196
+
1197
+ // src/chains/avalanche/AvalancheClient.ts
1198
+ var ACP204_PRECOMPILE = "0x0000000000000000000000000000000000000100";
1199
+ var CHAINLINK_AGGREGATOR_ABI = [
1200
+ "function latestRoundData() view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)",
1201
+ "function decimals() view returns (uint8)"
1202
+ ];
1203
+ var ICM_SPOKE_ABI = [
1204
+ "function verifySession(bytes32 sessionKeyHash, uint256 amount) view returns (bool valid, uint256 remainingBudget)",
1205
+ "function getSession(bytes32 sessionKeyHash) view returns (bytes32 userKeyHash, uint256 expiry, uint256 maxValue, uint256 totalBudget, uint256 spent, bool active)",
1206
+ "function getStatus() view returns (bool paused, uint256 totalMessages, uint256 totalSessions, uint256 totalPayments)",
1207
+ "function isKeyAuthorized(bytes32 identityKeyHash, bytes32 keyHash) view returns (bool)"
1208
+ ];
1209
+ var P256_VERIFIER_ABI = [
1210
+ "function isPrecompileAvailable() view returns (bool available)",
1211
+ "function computeKeyHash(uint256 x, uint256 y) view returns (bytes32)"
1212
+ ];
1213
+ var AvalancheClient = class extends EVMClient {
1214
+ avaxProvider;
1215
+ p256VerifierAddress;
1216
+ icmSpokeAddress;
1217
+ chainlinkAvaxUsdFeed;
1218
+ chainlinkUsdcUsdFeed;
1219
+ chainlinkUsdtUsdFeed;
1220
+ // Price cache (avoid excessive RPC calls)
1221
+ priceCache = /* @__PURE__ */ new Map();
1222
+ CACHE_TTL_MS = 3e4;
1223
+ // 30 seconds
1224
+ constructor(config) {
1225
+ super(config);
1226
+ this.avaxProvider = new import_ethers3.ethers.JsonRpcProvider(config.rpcUrl);
1227
+ this.p256VerifierAddress = config.p256VerifierAddress || "";
1228
+ this.icmSpokeAddress = config.icmSpokeAddress || "";
1229
+ this.chainlinkAvaxUsdFeed = config.chainlinkAvaxUsdFeed || "";
1230
+ this.chainlinkUsdcUsdFeed = config.chainlinkUsdcUsdFeed || "";
1231
+ this.chainlinkUsdtUsdFeed = config.chainlinkUsdtUsdFeed || "";
1232
+ }
1233
+ // ========================================================================
1234
+ // ACP-204 Precompile Utilities
1235
+ // ========================================================================
1236
+ /**
1237
+ * Check if the ACP-204 secp256r1 precompile is live on this chain.
1238
+ * Returns true on Avalanche C-Chain (mainnet + Fuji), false elsewhere.
1239
+ */
1240
+ async isACP204Available() {
1241
+ if (this.p256VerifierAddress) {
1242
+ try {
1243
+ const verifier = new import_ethers3.ethers.Contract(
1244
+ this.p256VerifierAddress,
1245
+ P256_VERIFIER_ABI,
1246
+ this.avaxProvider
1247
+ );
1248
+ return await verifier.isPrecompileAvailable();
1249
+ } catch {
1250
+ }
1251
+ }
1252
+ try {
1253
+ const zeroInput = new Uint8Array(160);
1254
+ const result = await this.avaxProvider.call({
1255
+ to: ACP204_PRECOMPILE,
1256
+ data: import_ethers3.ethers.hexlify(zeroInput)
1257
+ });
1258
+ return result.length === 66;
1259
+ } catch {
1260
+ return false;
1261
+ }
1262
+ }
1263
+ /**
1264
+ * Get the estimated gas cost (in wei) for a single P-256 verification.
1265
+ * Deterministic on Avalanche: 6,900 gas for precompile + ~300 staticcall overhead.
1266
+ */
1267
+ async estimatePasskeyVerificationGas() {
1268
+ const feeData = await this.avaxProvider.getFeeData();
1269
+ const gasPrice = feeData.gasPrice || import_ethers3.ethers.parseUnits("25", "gwei");
1270
+ return 7200n * gasPrice;
1271
+ }
1272
+ /**
1273
+ * Get estimated USD cost for a passkey verification.
1274
+ */
1275
+ async estimatePasskeyVerificationCostUSD() {
1276
+ const gasCostWei = await this.estimatePasskeyVerificationGas();
1277
+ return this.convertAvaxToUsd(gasCostWei);
1278
+ }
1279
+ // ========================================================================
1280
+ // Chainlink Price Feeds
1281
+ // ========================================================================
1282
+ /**
1283
+ * Get current AVAX/USD price from Chainlink.
1284
+ * Cached for 30 seconds to avoid excessive RPC calls.
1285
+ */
1286
+ async getAvaxPriceUSD() {
1287
+ return this._getChainlinkPrice(this.chainlinkAvaxUsdFeed, "avax-usd");
1288
+ }
1289
+ /**
1290
+ * Get USDC/USD price (for stablecoin verification).
1291
+ */
1292
+ async getUsdcPriceUSD() {
1293
+ if (!this.chainlinkUsdcUsdFeed) return 1;
1294
+ return this._getChainlinkPrice(this.chainlinkUsdcUsdFeed, "usdc-usd");
1295
+ }
1296
+ /**
1297
+ * Get USDT/USD price.
1298
+ */
1299
+ async getUsdtPriceUSD() {
1300
+ if (!this.chainlinkUsdtUsdFeed) return 1;
1301
+ return this._getChainlinkPrice(this.chainlinkUsdtUsdFeed, "usdt-usd");
1302
+ }
1303
+ /**
1304
+ * Convert a USD amount to AVAX wei using live Chainlink prices.
1305
+ */
1306
+ async convertUsdToAvax(usdAmount) {
1307
+ const avaxPrice = await this.getAvaxPriceUSD();
1308
+ if (avaxPrice <= 0) throw new Error("Invalid AVAX price from Chainlink");
1309
+ const avaxAmount = usdAmount / avaxPrice;
1310
+ return import_ethers3.ethers.parseEther(avaxAmount.toFixed(18));
1311
+ }
1312
+ /**
1313
+ * Convert AVAX wei to USD using live Chainlink prices.
1314
+ */
1315
+ async convertAvaxToUsd(avaxWei) {
1316
+ const avaxPrice = await this.getAvaxPriceUSD();
1317
+ return Number(import_ethers3.ethers.formatEther(avaxWei)) * avaxPrice;
1318
+ }
1319
+ // ========================================================================
1320
+ // ICM Spoke Queries
1321
+ // ========================================================================
1322
+ /**
1323
+ * Verify a session is valid on the ICM Spoke (cross-L1 verification).
1324
+ */
1325
+ async verifyICMSession(sessionKeyHash, amount) {
1326
+ if (!this.icmSpokeAddress) {
1327
+ throw new Error("ICM Spoke address not configured");
1328
+ }
1329
+ const spoke = new import_ethers3.ethers.Contract(this.icmSpokeAddress, ICM_SPOKE_ABI, this.avaxProvider);
1330
+ const [valid, remainingBudget] = await spoke.verifySession(sessionKeyHash, amount);
1331
+ return { valid, remainingBudget: BigInt(remainingBudget) };
1332
+ }
1333
+ /**
1334
+ * Get status of the ICM Spoke (paused, message count, session count).
1335
+ */
1336
+ async getICMSpokeStatus() {
1337
+ if (!this.icmSpokeAddress) {
1338
+ throw new Error("ICM Spoke address not configured");
1339
+ }
1340
+ const spoke = new import_ethers3.ethers.Contract(this.icmSpokeAddress, ICM_SPOKE_ABI, this.avaxProvider);
1341
+ const [paused, totalMessages, totalSessions, totalPayments] = await spoke.getStatus();
1342
+ return {
1343
+ paused,
1344
+ totalMessages: BigInt(totalMessages),
1345
+ totalSessions: BigInt(totalSessions),
1346
+ totalPayments: BigInt(totalPayments)
1347
+ };
1348
+ }
1349
+ /**
1350
+ * Check if a key is authorized for an identity on the ICM Spoke.
1351
+ */
1352
+ async isKeyAuthorizedOnSpoke(identityKeyHash, keyHash) {
1353
+ if (!this.icmSpokeAddress) return false;
1354
+ const spoke = new import_ethers3.ethers.Contract(this.icmSpokeAddress, ICM_SPOKE_ABI, this.avaxProvider);
1355
+ return spoke.isKeyAuthorized(identityKeyHash, keyHash);
1356
+ }
1357
+ // ========================================================================
1358
+ // ICM-Aware Routing
1359
+ // ========================================================================
1360
+ /**
1361
+ * Determine whether a cross-chain message should use Teleporter (ICM) or Wormhole.
1362
+ *
1363
+ * Rule: If the target chain is within the Avalanche ecosystem (C-Chain ID or
1364
+ * an Avalanche L1), use ICM/Teleporter for lower latency and no guardian overhead.
1365
+ * Otherwise, fall back to Wormhole VAAs for cross-ecosystem messaging.
1366
+ *
1367
+ * @param targetWormholeChainId Wormhole chain ID of the destination
1368
+ * @returns 'icm' | 'wormhole'
1369
+ */
1370
+ getRoutingStrategy(targetWormholeChainId) {
1371
+ const avalancheEcosystemChainIds = /* @__PURE__ */ new Set([6]);
1372
+ return avalancheEcosystemChainIds.has(targetWormholeChainId) ? "icm" : "wormhole";
1373
+ }
1374
+ // ========================================================================
1375
+ // Accessors
1376
+ // ========================================================================
1377
+ getP256VerifierAddress() {
1378
+ return this.p256VerifierAddress;
1379
+ }
1380
+ getICMSpokeAddress() {
1381
+ return this.icmSpokeAddress;
1382
+ }
1383
+ getChainlinkAvaxUsdFeed() {
1384
+ return this.chainlinkAvaxUsdFeed;
1385
+ }
1386
+ // ========================================================================
1387
+ // Private Helpers
1388
+ // ========================================================================
1389
+ async _getChainlinkPrice(feedAddress, cacheKey) {
1390
+ if (!feedAddress) throw new Error(`Chainlink feed not configured for ${cacheKey}`);
1391
+ const cached = this.priceCache.get(cacheKey);
1392
+ if (cached && Date.now() - cached.timestamp < this.CACHE_TTL_MS) {
1393
+ return cached.price;
1394
+ }
1395
+ const aggregator = new import_ethers3.ethers.Contract(feedAddress, CHAINLINK_AGGREGATOR_ABI, this.avaxProvider);
1396
+ const [, answer] = await aggregator.latestRoundData();
1397
+ const decimals = await aggregator.decimals();
1398
+ const price = Number(answer) / 10 ** Number(decimals);
1399
+ this.priceCache.set(cacheKey, { price, timestamp: Date.now() });
1400
+ return price;
1401
+ }
1402
+ };
1403
+ // Annotate the CommonJS export names for ESM import in node:
1404
+ 0 && (module.exports = {
1405
+ AvalancheClient
1406
+ });
1407
+ //# sourceMappingURL=index.js.map