@agirails/sdk 2.5.2 → 2.5.4

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 (172) hide show
  1. package/dist/ACTPClient.d.ts +18 -0
  2. package/dist/ACTPClient.d.ts.map +1 -1
  3. package/dist/ACTPClient.js +67 -22
  4. package/dist/ACTPClient.js.map +1 -1
  5. package/dist/adapters/BasicAdapter.d.ts +12 -0
  6. package/dist/adapters/BasicAdapter.d.ts.map +1 -1
  7. package/dist/adapters/BasicAdapter.js +30 -4
  8. package/dist/adapters/BasicAdapter.js.map +1 -1
  9. package/dist/adapters/StandardAdapter.d.ts +20 -3
  10. package/dist/adapters/StandardAdapter.d.ts.map +1 -1
  11. package/dist/adapters/StandardAdapter.js +45 -11
  12. package/dist/adapters/StandardAdapter.js.map +1 -1
  13. package/dist/cli/commands/publish.js +16 -4
  14. package/dist/cli/commands/publish.js.map +1 -1
  15. package/dist/cli/commands/register.js +16 -4
  16. package/dist/cli/commands/register.js.map +1 -1
  17. package/dist/cli/commands/tx.js +31 -3
  18. package/dist/cli/commands/tx.js.map +1 -1
  19. package/dist/cli/utils/client.d.ts.map +1 -1
  20. package/dist/cli/utils/client.js +1 -0
  21. package/dist/cli/utils/client.js.map +1 -1
  22. package/dist/config/networks.d.ts +2 -2
  23. package/dist/config/networks.d.ts.map +1 -1
  24. package/dist/config/networks.js +27 -22
  25. package/dist/config/networks.js.map +1 -1
  26. package/dist/level0/request.d.ts.map +1 -1
  27. package/dist/level0/request.js +2 -1
  28. package/dist/level0/request.js.map +1 -1
  29. package/dist/runtime/BlockchainRuntime.d.ts.map +1 -1
  30. package/dist/runtime/BlockchainRuntime.js +11 -5
  31. package/dist/runtime/BlockchainRuntime.js.map +1 -1
  32. package/dist/runtime/MockStateManager.d.ts.map +1 -1
  33. package/dist/runtime/MockStateManager.js +2 -1
  34. package/dist/runtime/MockStateManager.js.map +1 -1
  35. package/dist/utils/IPFSClient.d.ts +3 -1
  36. package/dist/utils/IPFSClient.d.ts.map +1 -1
  37. package/dist/utils/IPFSClient.js +27 -7
  38. package/dist/utils/IPFSClient.js.map +1 -1
  39. package/dist/wallet/AutoWalletProvider.d.ts.map +1 -1
  40. package/dist/wallet/AutoWalletProvider.js +52 -18
  41. package/dist/wallet/AutoWalletProvider.js.map +1 -1
  42. package/dist/wallet/SmartWalletRouter.d.ts +116 -0
  43. package/dist/wallet/SmartWalletRouter.d.ts.map +1 -0
  44. package/dist/wallet/SmartWalletRouter.js +212 -0
  45. package/dist/wallet/SmartWalletRouter.js.map +1 -0
  46. package/dist/wallet/aa/DualNonceManager.d.ts +19 -0
  47. package/dist/wallet/aa/DualNonceManager.d.ts.map +1 -1
  48. package/dist/wallet/aa/DualNonceManager.js +100 -5
  49. package/dist/wallet/aa/DualNonceManager.js.map +1 -1
  50. package/package.json +3 -6
  51. package/src/ACTPClient.ts +0 -1579
  52. package/src/abi/ACTPKernel.json +0 -1356
  53. package/src/abi/AgentRegistry.json +0 -915
  54. package/src/abi/ERC20.json +0 -40
  55. package/src/abi/EscrowVault.json +0 -134
  56. package/src/abi/IdentityRegistry.json +0 -316
  57. package/src/adapters/AdapterRegistry.ts +0 -173
  58. package/src/adapters/AdapterRouter.ts +0 -416
  59. package/src/adapters/BaseAdapter.ts +0 -498
  60. package/src/adapters/BasicAdapter.ts +0 -514
  61. package/src/adapters/IAdapter.ts +0 -292
  62. package/src/adapters/StandardAdapter.ts +0 -555
  63. package/src/adapters/X402Adapter.ts +0 -731
  64. package/src/adapters/index.ts +0 -60
  65. package/src/builders/DeliveryProofBuilder.ts +0 -327
  66. package/src/builders/QuoteBuilder.ts +0 -483
  67. package/src/builders/index.ts +0 -17
  68. package/src/cli/commands/balance.ts +0 -110
  69. package/src/cli/commands/batch.ts +0 -487
  70. package/src/cli/commands/config.ts +0 -231
  71. package/src/cli/commands/deploy-check.ts +0 -364
  72. package/src/cli/commands/deploy-env.ts +0 -120
  73. package/src/cli/commands/diff.ts +0 -141
  74. package/src/cli/commands/init.ts +0 -469
  75. package/src/cli/commands/mint.ts +0 -116
  76. package/src/cli/commands/pay.ts +0 -113
  77. package/src/cli/commands/publish.ts +0 -475
  78. package/src/cli/commands/pull.ts +0 -124
  79. package/src/cli/commands/register.ts +0 -247
  80. package/src/cli/commands/simulate.ts +0 -345
  81. package/src/cli/commands/time.ts +0 -302
  82. package/src/cli/commands/tx.ts +0 -448
  83. package/src/cli/commands/watch.ts +0 -211
  84. package/src/cli/index.ts +0 -134
  85. package/src/cli/utils/client.ts +0 -251
  86. package/src/cli/utils/config.ts +0 -389
  87. package/src/cli/utils/output.ts +0 -465
  88. package/src/cli/utils/wallet.ts +0 -109
  89. package/src/config/agirailsmd.ts +0 -262
  90. package/src/config/networks.ts +0 -275
  91. package/src/config/pendingPublish.ts +0 -237
  92. package/src/config/publishPipeline.ts +0 -359
  93. package/src/config/syncOperations.ts +0 -279
  94. package/src/erc8004/ERC8004Bridge.ts +0 -462
  95. package/src/erc8004/ReputationReporter.ts +0 -468
  96. package/src/erc8004/index.ts +0 -61
  97. package/src/errors/index.ts +0 -427
  98. package/src/index.ts +0 -364
  99. package/src/level0/Provider.ts +0 -117
  100. package/src/level0/ServiceDirectory.ts +0 -131
  101. package/src/level0/index.ts +0 -10
  102. package/src/level0/provide.ts +0 -132
  103. package/src/level0/request.ts +0 -432
  104. package/src/level1/Agent.ts +0 -1426
  105. package/src/level1/index.ts +0 -10
  106. package/src/level1/pricing/PriceCalculator.ts +0 -255
  107. package/src/level1/pricing/PricingStrategy.ts +0 -198
  108. package/src/level1/types/Job.ts +0 -179
  109. package/src/level1/types/Options.ts +0 -291
  110. package/src/level1/types/index.ts +0 -8
  111. package/src/protocol/ACTPKernel.ts +0 -808
  112. package/src/protocol/AgentRegistry.ts +0 -559
  113. package/src/protocol/DIDManager.ts +0 -629
  114. package/src/protocol/DIDResolver.ts +0 -554
  115. package/src/protocol/EASHelper.ts +0 -378
  116. package/src/protocol/EscrowVault.ts +0 -255
  117. package/src/protocol/EventMonitor.ts +0 -204
  118. package/src/protocol/MessageSigner.ts +0 -510
  119. package/src/protocol/ProofGenerator.ts +0 -339
  120. package/src/protocol/QuoteBuilder.ts +0 -15
  121. package/src/registry/AgentRegistryClient.ts +0 -202
  122. package/src/runtime/BlockchainRuntime.ts +0 -1015
  123. package/src/runtime/IACTPRuntime.ts +0 -306
  124. package/src/runtime/MockRuntime.ts +0 -1298
  125. package/src/runtime/MockStateManager.ts +0 -576
  126. package/src/runtime/index.ts +0 -25
  127. package/src/runtime/types/MockState.ts +0 -237
  128. package/src/storage/ArchiveBundleBuilder.ts +0 -561
  129. package/src/storage/ArweaveClient.ts +0 -946
  130. package/src/storage/FilebaseClient.ts +0 -790
  131. package/src/storage/index.ts +0 -96
  132. package/src/storage/types.ts +0 -348
  133. package/src/types/adapter.ts +0 -310
  134. package/src/types/agent.ts +0 -79
  135. package/src/types/did.ts +0 -223
  136. package/src/types/eip712.ts +0 -175
  137. package/src/types/erc8004.ts +0 -293
  138. package/src/types/escrow.ts +0 -27
  139. package/src/types/index.ts +0 -17
  140. package/src/types/message.ts +0 -145
  141. package/src/types/state.ts +0 -87
  142. package/src/types/transaction.ts +0 -69
  143. package/src/types/x402.ts +0 -251
  144. package/src/utils/ErrorRecoveryGuide.ts +0 -676
  145. package/src/utils/Helpers.ts +0 -688
  146. package/src/utils/IPFSClient.ts +0 -368
  147. package/src/utils/Logger.ts +0 -484
  148. package/src/utils/NonceManager.ts +0 -591
  149. package/src/utils/RateLimiter.ts +0 -534
  150. package/src/utils/ReceivedNonceTracker.ts +0 -567
  151. package/src/utils/SDKLifecycle.ts +0 -416
  152. package/src/utils/SecureNonce.ts +0 -78
  153. package/src/utils/Semaphore.ts +0 -276
  154. package/src/utils/UsedAttestationTracker.ts +0 -385
  155. package/src/utils/canonicalJson.ts +0 -38
  156. package/src/utils/circuitBreaker.ts +0 -324
  157. package/src/utils/computeTypeHash.ts +0 -48
  158. package/src/utils/fsSafe.ts +0 -80
  159. package/src/utils/index.ts +0 -80
  160. package/src/utils/retry.ts +0 -364
  161. package/src/utils/security.ts +0 -418
  162. package/src/utils/validation.ts +0 -540
  163. package/src/wallet/AutoWalletProvider.ts +0 -299
  164. package/src/wallet/EOAWalletProvider.ts +0 -69
  165. package/src/wallet/IWalletProvider.ts +0 -135
  166. package/src/wallet/aa/BundlerClient.ts +0 -274
  167. package/src/wallet/aa/DualNonceManager.ts +0 -173
  168. package/src/wallet/aa/PaymasterClient.ts +0 -174
  169. package/src/wallet/aa/TransactionBatcher.ts +0 -353
  170. package/src/wallet/aa/UserOpBuilder.ts +0 -246
  171. package/src/wallet/aa/constants.ts +0 -60
  172. package/src/wallet/keystore.ts +0 -240
@@ -1,353 +0,0 @@
1
- /**
2
- * TransactionBatcher — Encodes ACTP multi-call batches.
3
- *
4
- * An ACTP payment requires 3 contract calls:
5
- * 1. USDC.approve(escrowVault, amount)
6
- * 2. ACTPKernel.createTransaction(provider, requester, amount, deadline, disputeWindow, serviceHash, agentId)
7
- * 3. ACTPKernel.linkEscrow(txId, escrowVault, escrowId)
8
- *
9
- * TransactionBatcher encodes all 3 as SmartWalletCall[] for executeBatch.
10
- * It pre-computes the txId using the same keccak256 formula as the contract.
11
- *
12
- * @module wallet/aa/TransactionBatcher
13
- */
14
-
15
- import { ethers } from 'ethers';
16
- import { SmartWalletCall } from './constants';
17
- import { ServiceDescriptor } from '../../types/agent';
18
-
19
- // ============================================================================
20
- // ABI fragments — minimal for encoding only
21
- // ============================================================================
22
-
23
- const ERC20_APPROVE_ABI = [
24
- 'function approve(address spender, uint256 amount)',
25
- ];
26
-
27
- const ACTP_KERNEL_ABI = [
28
- 'function createTransaction(address provider, address requester, uint256 amount, uint256 deadline, uint256 disputeWindow, bytes32 serviceHash, uint256 agentId)',
29
- 'function linkEscrow(bytes32 txId, address escrowVault, bytes32 escrowId)',
30
- ];
31
-
32
- // ============================================================================
33
- // Types
34
- // ============================================================================
35
-
36
- export interface ACTPBatchParams {
37
- /** Provider address */
38
- provider: string;
39
- /** Requester address (= Smart Wallet address) */
40
- requester: string;
41
- /** Amount in USDC wei (e.g., "1000000" for 1 USDC) */
42
- amount: string;
43
- /** Unix timestamp deadline */
44
- deadline: number;
45
- /** Dispute window in seconds */
46
- disputeWindow: number;
47
- /** Service hash (bytes32) */
48
- serviceHash: string;
49
- /** ERC-8004 agent ID (0 if none) */
50
- agentId: string;
51
- /** Current ACTP nonce for the requester (from ACTPKernel.requesterNonces) */
52
- actpNonce: bigint;
53
- /** Contract addresses */
54
- contracts: {
55
- usdc: string;
56
- actpKernel: string;
57
- escrowVault: string;
58
- };
59
- }
60
-
61
- export interface ACTPBatchResult {
62
- /** Encoded SmartWalletCall[] ready for executeBatch */
63
- calls: SmartWalletCall[];
64
- /** Pre-computed transaction ID */
65
- txId: string;
66
- }
67
-
68
- // ============================================================================
69
- // Public API
70
- // ============================================================================
71
-
72
- /**
73
- * Pre-compute ACTP transaction ID.
74
- *
75
- * Matches ACTPKernel.sol:
76
- * transactionId = keccak256(abi.encodePacked(requester, provider, amount, serviceHash, nonce))
77
- */
78
- export function computeTransactionId(
79
- requester: string,
80
- provider: string,
81
- amount: string,
82
- serviceHash: string,
83
- nonce: bigint
84
- ): string {
85
- return ethers.keccak256(
86
- ethers.solidityPacked(
87
- ['address', 'address', 'uint256', 'bytes32', 'uint256'],
88
- [requester, provider, BigInt(amount), serviceHash, nonce]
89
- )
90
- );
91
- }
92
-
93
- /**
94
- * Build the 3-call ACTP payment batch.
95
- *
96
- * Returns SmartWalletCall[] for executeBatch and the pre-computed txId.
97
- */
98
- export function buildACTPPayBatch(params: ACTPBatchParams): ACTPBatchResult {
99
- const amount = BigInt(params.amount);
100
-
101
- // Pre-compute txId
102
- const txId = computeTransactionId(
103
- params.requester,
104
- params.provider,
105
- params.amount,
106
- params.serviceHash,
107
- params.actpNonce
108
- );
109
-
110
- const erc20Iface = new ethers.Interface(ERC20_APPROVE_ABI);
111
- const kernelIface = new ethers.Interface(ACTP_KERNEL_ABI);
112
-
113
- // Call 1: USDC.approve(escrowVault, amount)
114
- const approveData = erc20Iface.encodeFunctionData('approve', [
115
- params.contracts.escrowVault,
116
- amount,
117
- ]);
118
-
119
- // Call 2: ACTPKernel.createTransaction(...)
120
- const createTxData = kernelIface.encodeFunctionData('createTransaction', [
121
- params.provider,
122
- params.requester,
123
- amount,
124
- params.deadline,
125
- params.disputeWindow,
126
- params.serviceHash,
127
- BigInt(params.agentId || '0'),
128
- ]);
129
-
130
- // Call 3: ACTPKernel.linkEscrow(txId, escrowVault, escrowId)
131
- // escrowId = txId (ACTP standard)
132
- const linkEscrowData = kernelIface.encodeFunctionData('linkEscrow', [
133
- txId,
134
- params.contracts.escrowVault,
135
- txId,
136
- ]);
137
-
138
- const calls: SmartWalletCall[] = [
139
- { target: params.contracts.usdc, value: 0n, data: approveData },
140
- { target: params.contracts.actpKernel, value: 0n, data: createTxData },
141
- { target: params.contracts.actpKernel, value: 0n, data: linkEscrowData },
142
- ];
143
-
144
- return { calls, txId };
145
- }
146
-
147
- /**
148
- * ABI fragment for AgentRegistry.registerAgent.
149
- *
150
- * Matches IAgentRegistry.sol:
151
- * registerAgent(string endpoint, ServiceDescriptor[] serviceDescriptors)
152
- *
153
- * ServiceDescriptor = (bytes32, string, string, uint256, uint256, uint256, string)
154
- */
155
- const AGENT_REGISTRY_ABI = [
156
- 'function registerAgent(string endpoint, (bytes32 serviceTypeHash, string serviceType, string schemaURI, uint256 minPrice, uint256 maxPrice, uint256 avgCompletionTime, string metadataCID)[] serviceDescriptors)',
157
- 'function publishConfig(string cid, bytes32 configHash)',
158
- 'function setListed(bool listed)',
159
- ];
160
-
161
- /**
162
- * Build a register-agent batch for AgentRegistry.
163
- *
164
- * Used for bootstrap registration (gasless even before registration — chicken-and-egg).
165
- *
166
- * @param agentRegistryAddress - AgentRegistry contract address
167
- * @param endpoint - Agent webhook / IPFS gateway URL
168
- * @param serviceDescriptors - At least 1 service descriptor (contract requirement)
169
- */
170
- export function buildRegisterAgentBatch(
171
- agentRegistryAddress: string,
172
- endpoint: string,
173
- serviceDescriptors: ServiceDescriptor[]
174
- ): SmartWalletCall[] {
175
- if (serviceDescriptors.length === 0) {
176
- throw new Error('At least one service descriptor is required for registration');
177
- }
178
-
179
- const iface = new ethers.Interface(AGENT_REGISTRY_ABI);
180
-
181
- // Convert to contract format (bigint fields already correct)
182
- const descriptors = serviceDescriptors.map(sd => ({
183
- serviceTypeHash: sd.serviceTypeHash,
184
- serviceType: sd.serviceType,
185
- schemaURI: sd.schemaURI,
186
- minPrice: sd.minPrice,
187
- maxPrice: sd.maxPrice,
188
- avgCompletionTime: sd.avgCompletionTime,
189
- metadataCID: sd.metadataCID,
190
- }));
191
-
192
- const data = iface.encodeFunctionData('registerAgent', [endpoint, descriptors]);
193
-
194
- return [
195
- { target: agentRegistryAddress, value: 0n, data },
196
- ];
197
- }
198
-
199
- /**
200
- * Build a MockUSDC mint call (testnet only).
201
- */
202
- export function buildTestnetMintBatch(
203
- mockUsdcAddress: string,
204
- recipient: string,
205
- amount: string
206
- ): SmartWalletCall[] {
207
- const iface = new ethers.Interface([
208
- 'function mint(address to, uint256 amount)',
209
- ]);
210
- const data = iface.encodeFunctionData('mint', [recipient, BigInt(amount)]);
211
-
212
- return [
213
- { target: mockUsdcAddress, value: 0n, data },
214
- ];
215
- }
216
-
217
- /**
218
- * Build a combined register + mint batch for testnet init.
219
- *
220
- * Single UserOp: register on AgentRegistry + mint test USDC.
221
- * Both are bootstrap-allowed (gasless without prior registration).
222
- */
223
- export function buildTestnetInitBatch(params: {
224
- agentRegistryAddress: string;
225
- endpoint: string;
226
- serviceDescriptors: ServiceDescriptor[];
227
- mockUsdcAddress: string;
228
- recipient: string;
229
- mintAmount: string;
230
- }): SmartWalletCall[] {
231
- const registerCalls = buildRegisterAgentBatch(
232
- params.agentRegistryAddress,
233
- params.endpoint,
234
- params.serviceDescriptors
235
- );
236
- const mintCalls = buildTestnetMintBatch(
237
- params.mockUsdcAddress,
238
- params.recipient,
239
- params.mintAmount
240
- );
241
- return [...registerCalls, ...mintCalls];
242
- }
243
-
244
- // ============================================================================
245
- // Lazy Publish — Activation Batch Builders
246
- // ============================================================================
247
-
248
- /**
249
- * Lazy publish activation scenario.
250
- *
251
- * - 'A': First activation — registerAgent + publishConfig + setListed (3 calls)
252
- * - 'B1': Re-publish with listing change — publishConfig + setListed (2 calls)
253
- * - 'B2': Re-publish config only — publishConfig (1 call)
254
- * - 'C': Stale pending — delete pending-publish.json, no calls
255
- * - 'none': No pending publish, normal flow
256
- */
257
- export type ActivationScenario = 'A' | 'B1' | 'B2' | 'C' | 'none';
258
-
259
- /**
260
- * Parameters for building an activation batch.
261
- */
262
- export interface ActivationBatchParams {
263
- /** Activation scenario */
264
- scenario: ActivationScenario;
265
- /** AgentRegistry contract address */
266
- agentRegistryAddress: string;
267
- /** IPFS CID of the published AGIRAILS.md */
268
- cid: string;
269
- /** Canonical config hash (bytes32) */
270
- configHash: string;
271
- /** Agent endpoint URL (for scenario A registration) */
272
- endpoint?: string;
273
- /** Service descriptors (for scenario A registration) */
274
- serviceDescriptors?: ServiceDescriptor[];
275
- /** Whether to set listed=true (for scenarios A, B1) */
276
- listed?: boolean;
277
- }
278
-
279
- /**
280
- * Build a publishConfig batch call for AgentRegistry.
281
- *
282
- * @param agentRegistryAddress - AgentRegistry contract address
283
- * @param cid - IPFS CID of the uploaded AGIRAILS.md
284
- * @param configHash - Canonical config hash (bytes32)
285
- */
286
- export function buildPublishConfigBatch(
287
- agentRegistryAddress: string,
288
- cid: string,
289
- configHash: string
290
- ): SmartWalletCall[] {
291
- const iface = new ethers.Interface(AGENT_REGISTRY_ABI);
292
- const data = iface.encodeFunctionData('publishConfig', [cid, configHash]);
293
- return [{ target: agentRegistryAddress, value: 0n, data }];
294
- }
295
-
296
- /**
297
- * Build a setListed batch call for AgentRegistry.
298
- *
299
- * @param agentRegistryAddress - AgentRegistry contract address
300
- * @param listed - Whether to list the agent
301
- */
302
- export function buildSetListedBatch(
303
- agentRegistryAddress: string,
304
- listed: boolean
305
- ): SmartWalletCall[] {
306
- const iface = new ethers.Interface(AGENT_REGISTRY_ABI);
307
- const data = iface.encodeFunctionData('setListed', [listed]);
308
- return [{ target: agentRegistryAddress, value: 0n, data }];
309
- }
310
-
311
- /**
312
- * Build the full activation batch based on scenario.
313
- *
314
- * Scenario call counts:
315
- * - A: registerAgent + publishConfig + setListed = 3 calls
316
- * - B1: publishConfig + setListed = 2 calls
317
- * - B2: publishConfig = 1 call
318
- * - C/none: empty (0 calls)
319
- */
320
- export function buildActivationBatch(params: ActivationBatchParams): SmartWalletCall[] {
321
- const { scenario, agentRegistryAddress, cid, configHash } = params;
322
-
323
- switch (scenario) {
324
- case 'A': {
325
- // First activation: register + publish + list
326
- if (!params.endpoint || !params.serviceDescriptors || params.serviceDescriptors.length === 0) {
327
- throw new Error('Scenario A requires endpoint and serviceDescriptors');
328
- }
329
- const registerCalls = buildRegisterAgentBatch(
330
- agentRegistryAddress,
331
- params.endpoint,
332
- params.serviceDescriptors
333
- );
334
- const publishCalls = buildPublishConfigBatch(agentRegistryAddress, cid, configHash);
335
- const listCalls = buildSetListedBatch(agentRegistryAddress, params.listed ?? true);
336
- return [...registerCalls, ...publishCalls, ...listCalls];
337
- }
338
- case 'B1': {
339
- // Re-publish with listing: publish + list
340
- const publishCalls = buildPublishConfigBatch(agentRegistryAddress, cid, configHash);
341
- const listCalls = buildSetListedBatch(agentRegistryAddress, params.listed ?? true);
342
- return [...publishCalls, ...listCalls];
343
- }
344
- case 'B2': {
345
- // Re-publish config only
346
- return buildPublishConfigBatch(agentRegistryAddress, cid, configHash);
347
- }
348
- case 'C':
349
- case 'none':
350
- // Stale or no pending — no activation calls
351
- return [];
352
- }
353
- }
@@ -1,246 +0,0 @@
1
- /**
2
- * UserOpBuilder — Constructs ERC-4337 v0.6 UserOperations.
3
- *
4
- * Builds UserOps for CoinbaseSmartWallet:
5
- * - Encodes executeBatch(Call[]) as callData
6
- * - Adds initCode for first-time wallet deployment
7
- * - Signs with owner's private key (EIP-191 over UserOp hash)
8
- *
9
- * Uses ethers v6 for ABI encoding (no viem dependency yet — see Phase 2 note).
10
- * viem+permissionless will be added if needed for paymaster integration.
11
- *
12
- * @module wallet/aa/UserOpBuilder
13
- */
14
-
15
- import { ethers } from 'ethers';
16
- import {
17
- UserOperationV06,
18
- SmartWalletCall,
19
- ENTRYPOINT_V06,
20
- SMART_WALLET_FACTORY,
21
- DEFAULT_WALLET_NONCE,
22
- } from './constants';
23
-
24
- const abiCoder = ethers.AbiCoder.defaultAbiCoder();
25
-
26
- // ============================================================================
27
- // ABI fragments
28
- // ============================================================================
29
-
30
- /** CoinbaseSmartWallet.executeBatch(Call[]) */
31
- const EXECUTE_BATCH_ABI = [
32
- 'function executeBatch((address target, uint256 value, bytes data)[] calls)',
33
- ];
34
-
35
- /** CoinbaseSmartWalletFactory.createAccount(bytes[],uint256) */
36
- const FACTORY_CREATE_ABI = [
37
- 'function createAccount(bytes[] owners, uint256 nonce)',
38
- ];
39
-
40
- /** CoinbaseSmartWalletFactory.getAddress(bytes[],uint256) */
41
- const FACTORY_GET_ADDRESS_ABI = [
42
- 'function getAddress(bytes[] owners, uint256 nonce) view returns (address)',
43
- ];
44
-
45
- // Typed factory interface to avoid ethers v6 getAddress() collision
46
- const FACTORY_ABI = [
47
- ...FACTORY_CREATE_ABI,
48
- ...FACTORY_GET_ADDRESS_ABI,
49
- ];
50
-
51
- // ============================================================================
52
- // Public API
53
- // ============================================================================
54
-
55
- /**
56
- * Compute the counterfactual Smart Wallet address for a given signer.
57
- *
58
- * This address is deterministic (CREATE2) and can be computed off-chain
59
- * without deploying the wallet.
60
- */
61
- export async function computeSmartWalletAddress(
62
- signerAddress: string,
63
- provider: ethers.JsonRpcProvider,
64
- nonce: bigint = DEFAULT_WALLET_NONCE
65
- ): Promise<string> {
66
- const factory = new ethers.Contract(
67
- SMART_WALLET_FACTORY,
68
- FACTORY_ABI,
69
- provider
70
- );
71
- // CoinbaseSmartWallet encodes owners as bytes[] — EOA address is abi.encode(address)
72
- const ownerBytes = abiCoder.encode(['address'], [signerAddress]);
73
- // Use getFunction to avoid collision with ethers v6 BaseContract.getAddress()
74
- const fn = factory.getFunction('getAddress');
75
- return await fn([ownerBytes], nonce);
76
- }
77
-
78
- /**
79
- * Build initCode for first-time wallet deployment.
80
- *
81
- * initCode = factory address + createAccount calldata
82
- * When the wallet already exists, pass '0x' as initCode.
83
- */
84
- export function buildInitCode(
85
- signerAddress: string,
86
- nonce: bigint = DEFAULT_WALLET_NONCE
87
- ): string {
88
- const iface = new ethers.Interface(FACTORY_CREATE_ABI);
89
- const ownerBytes = abiCoder.encode(['address'], [signerAddress]);
90
- const calldata = iface.encodeFunctionData('createAccount', [
91
- [ownerBytes],
92
- nonce,
93
- ]);
94
- // initCode = factory address (20 bytes) + calldata
95
- return SMART_WALLET_FACTORY + calldata.slice(2);
96
- }
97
-
98
- /**
99
- * Encode executeBatch calldata from an array of calls.
100
- */
101
- export function encodeExecuteBatch(calls: SmartWalletCall[]): string {
102
- const iface = new ethers.Interface(EXECUTE_BATCH_ABI);
103
- return iface.encodeFunctionData('executeBatch', [
104
- calls.map((c) => ({
105
- target: c.target,
106
- value: c.value,
107
- data: c.data,
108
- })),
109
- ]);
110
- }
111
-
112
- /**
113
- * Build a full UserOperation (unsigned).
114
- *
115
- * Gas limits and paymasterAndData must be filled by the caller
116
- * (via BundlerClient.estimateGas and PaymasterClient.sponsor).
117
- */
118
- export function buildUserOp(params: {
119
- sender: string;
120
- nonce: bigint;
121
- calls: SmartWalletCall[];
122
- isFirstDeploy: boolean;
123
- signerAddress: string;
124
- }): UserOperationV06 {
125
- const callData = encodeExecuteBatch(params.calls);
126
- const initCode = params.isFirstDeploy
127
- ? buildInitCode(params.signerAddress)
128
- : '0x';
129
-
130
- return {
131
- sender: params.sender,
132
- nonce: params.nonce,
133
- initCode,
134
- callData,
135
- // Placeholder values — filled by gas estimation
136
- callGasLimit: 0n,
137
- verificationGasLimit: 0n,
138
- preVerificationGas: 0n,
139
- maxFeePerGas: 0n,
140
- maxPriorityFeePerGas: 0n,
141
- paymasterAndData: '0x',
142
- signature: '0x',
143
- };
144
- }
145
-
146
- /**
147
- * Compute the UserOperation hash for signing (v0.6).
148
- *
149
- * hash = keccak256(abi.encode(
150
- * keccak256(pack(userOp)),
151
- * entryPoint,
152
- * chainId
153
- * ))
154
- */
155
- export function getUserOpHash(
156
- userOp: UserOperationV06,
157
- chainId: number
158
- ): string {
159
- // Pack all fields except signature
160
- const packed = abiCoder.encode(
161
- [
162
- 'address', // sender
163
- 'uint256', // nonce
164
- 'bytes32', // keccak256(initCode)
165
- 'bytes32', // keccak256(callData)
166
- 'uint256', // callGasLimit
167
- 'uint256', // verificationGasLimit
168
- 'uint256', // preVerificationGas
169
- 'uint256', // maxFeePerGas
170
- 'uint256', // maxPriorityFeePerGas
171
- 'bytes32', // keccak256(paymasterAndData)
172
- ],
173
- [
174
- userOp.sender,
175
- userOp.nonce,
176
- ethers.keccak256(userOp.initCode),
177
- ethers.keccak256(userOp.callData),
178
- userOp.callGasLimit,
179
- userOp.verificationGasLimit,
180
- userOp.preVerificationGas,
181
- userOp.maxFeePerGas,
182
- userOp.maxPriorityFeePerGas,
183
- ethers.keccak256(userOp.paymasterAndData),
184
- ]
185
- );
186
-
187
- const packedHash = ethers.keccak256(packed);
188
-
189
- return ethers.keccak256(
190
- abiCoder.encode(
191
- ['bytes32', 'address', 'uint256'],
192
- [packedHash, ENTRYPOINT_V06, chainId]
193
- )
194
- );
195
- }
196
-
197
- /**
198
- * Sign a UserOperation with the owner's private key.
199
- *
200
- * CoinbaseSmartWallet expects the signature to be:
201
- * abi.encode(SignatureWrapper(0, abi.encodePacked(r,s,v)))
202
- *
203
- * where ownerIndex=0 for single-owner wallets.
204
- */
205
- export async function signUserOp(
206
- userOp: UserOperationV06,
207
- signer: ethers.Wallet,
208
- chainId: number
209
- ): Promise<string> {
210
- const hash = getUserOpHash(userOp, chainId);
211
- // ethers signMessage adds EIP-191 prefix. CoinbaseSmartWallet expects raw ECDSA.
212
- // We use signingKey.sign() for raw signature over the hash bytes.
213
- const sig = signer.signingKey.sign(hash);
214
- // Pack r + s + v
215
- const rawSig = ethers.concat([sig.r, sig.s, new Uint8Array([sig.v])]);
216
-
217
- // CoinbaseSmartWallet SignatureWrapper: abi.encode(uint256 ownerIndex, bytes signatureData)
218
- return abiCoder.encode(
219
- ['uint256', 'bytes'],
220
- [0, rawSig]
221
- );
222
- }
223
-
224
- /**
225
- * Serialize UserOp for JSON-RPC (bundler API).
226
- * Converts bigints to hex strings.
227
- */
228
- export function serializeUserOp(userOp: UserOperationV06): Record<string, string> {
229
- return {
230
- sender: userOp.sender,
231
- nonce: toHex(userOp.nonce),
232
- initCode: userOp.initCode,
233
- callData: userOp.callData,
234
- callGasLimit: toHex(userOp.callGasLimit),
235
- verificationGasLimit: toHex(userOp.verificationGasLimit),
236
- preVerificationGas: toHex(userOp.preVerificationGas),
237
- maxFeePerGas: toHex(userOp.maxFeePerGas),
238
- maxPriorityFeePerGas: toHex(userOp.maxPriorityFeePerGas),
239
- paymasterAndData: userOp.paymasterAndData,
240
- signature: userOp.signature,
241
- };
242
- }
243
-
244
- function toHex(n: bigint): string {
245
- return '0x' + n.toString(16);
246
- }
@@ -1,60 +0,0 @@
1
- /**
2
- * Account Abstraction constants for CoinbaseSmartWallet on Base.
3
- *
4
- * EntryPoint v0.6 — CoinbaseSmartWallet hardcodes this version.
5
- * Factory address is canonical across all Base networks.
6
- *
7
- * @module wallet/aa/constants
8
- */
9
-
10
- /** ERC-4337 EntryPoint v0.6 (canonical, all EVM chains) */
11
- export const ENTRYPOINT_V06 = '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789';
12
-
13
- /** CoinbaseSmartWallet factory (canonical, all Base networks) */
14
- export const SMART_WALLET_FACTORY = '0xBA5ED110eFDBa3D005bfC882d75358ACBbB85842';
15
-
16
- /** Default nonce for first Smart Wallet per owner */
17
- export const DEFAULT_WALLET_NONCE = 0n;
18
-
19
- /**
20
- * UserOperation v0.6 struct — 11 unpacked fields.
21
- * CoinbaseSmartWallet does NOT support v0.7 packed format.
22
- */
23
- export interface UserOperationV06 {
24
- sender: string;
25
- nonce: bigint;
26
- initCode: string;
27
- callData: string;
28
- callGasLimit: bigint;
29
- verificationGasLimit: bigint;
30
- preVerificationGas: bigint;
31
- maxFeePerGas: bigint;
32
- maxPriorityFeePerGas: bigint;
33
- paymasterAndData: string;
34
- signature: string;
35
- }
36
-
37
- /**
38
- * CoinbaseSmartWallet Call struct for executeBatch.
39
- */
40
- export interface SmartWalletCall {
41
- target: string;
42
- value: bigint;
43
- data: string;
44
- }
45
-
46
- /**
47
- * Gas estimation result from bundler.
48
- */
49
- export interface GasEstimate {
50
- callGasLimit: bigint;
51
- verificationGasLimit: bigint;
52
- preVerificationGas: bigint;
53
- }
54
-
55
- /**
56
- * Paymaster sponsorship response.
57
- */
58
- export interface PaymasterResponse {
59
- paymasterAndData: string;
60
- }