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