@veridex/sdk 1.0.0-beta.1

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