@agirails/sdk 2.3.0 → 2.3.3

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 (153) hide show
  1. package/README.md +45 -8
  2. package/dist/ACTPClient.d.ts +35 -1
  3. package/dist/ACTPClient.d.ts.map +1 -1
  4. package/dist/ACTPClient.js +156 -26
  5. package/dist/ACTPClient.js.map +1 -1
  6. package/dist/adapters/AdapterRouter.d.ts.map +1 -1
  7. package/dist/adapters/AdapterRouter.js.map +1 -1
  8. package/dist/adapters/BasicAdapter.d.ts +10 -1
  9. package/dist/adapters/BasicAdapter.d.ts.map +1 -1
  10. package/dist/adapters/BasicAdapter.js +36 -1
  11. package/dist/adapters/BasicAdapter.js.map +1 -1
  12. package/dist/cli/commands/init.d.ts +2 -1
  13. package/dist/cli/commands/init.d.ts.map +1 -1
  14. package/dist/cli/commands/init.js +345 -25
  15. package/dist/cli/commands/init.js.map +1 -1
  16. package/dist/cli/commands/publish.d.ts.map +1 -1
  17. package/dist/cli/commands/publish.js.map +1 -1
  18. package/dist/cli/commands/register.d.ts +16 -0
  19. package/dist/cli/commands/register.d.ts.map +1 -0
  20. package/dist/cli/commands/register.js +211 -0
  21. package/dist/cli/commands/register.js.map +1 -0
  22. package/dist/cli/index.js +3 -0
  23. package/dist/cli/index.js.map +1 -1
  24. package/dist/cli/utils/config.d.ts +20 -0
  25. package/dist/cli/utils/config.d.ts.map +1 -1
  26. package/dist/cli/utils/config.js.map +1 -1
  27. package/dist/config/networks.d.ts +20 -4
  28. package/dist/config/networks.d.ts.map +1 -1
  29. package/dist/config/networks.js +59 -27
  30. package/dist/config/networks.js.map +1 -1
  31. package/dist/config/publishPipeline.d.ts +14 -0
  32. package/dist/config/publishPipeline.d.ts.map +1 -1
  33. package/dist/config/publishPipeline.js +2 -1
  34. package/dist/config/publishPipeline.js.map +1 -1
  35. package/dist/erc8004/ERC8004Bridge.d.ts.map +1 -1
  36. package/dist/erc8004/ERC8004Bridge.js +6 -5
  37. package/dist/erc8004/ERC8004Bridge.js.map +1 -1
  38. package/dist/erc8004/ReputationReporter.d.ts.map +1 -1
  39. package/dist/erc8004/ReputationReporter.js +9 -12
  40. package/dist/erc8004/ReputationReporter.js.map +1 -1
  41. package/dist/index.d.ts +4 -0
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +7 -3
  44. package/dist/index.js.map +1 -1
  45. package/dist/level1/Agent.js +4 -4
  46. package/dist/level1/Agent.js.map +1 -1
  47. package/dist/protocol/ACTPKernel.d.ts +7 -1
  48. package/dist/protocol/ACTPKernel.d.ts.map +1 -1
  49. package/dist/protocol/ACTPKernel.js +13 -10
  50. package/dist/protocol/ACTPKernel.js.map +1 -1
  51. package/dist/protocol/EventMonitor.d.ts +14 -0
  52. package/dist/protocol/EventMonitor.d.ts.map +1 -1
  53. package/dist/protocol/EventMonitor.js +14 -0
  54. package/dist/protocol/EventMonitor.js.map +1 -1
  55. package/dist/runtime/BlockchainRuntime.d.ts +5 -0
  56. package/dist/runtime/BlockchainRuntime.d.ts.map +1 -1
  57. package/dist/runtime/BlockchainRuntime.js +1 -1
  58. package/dist/runtime/BlockchainRuntime.js.map +1 -1
  59. package/dist/storage/ArchiveBundleBuilder.d.ts.map +1 -1
  60. package/dist/storage/ArchiveBundleBuilder.js.map +1 -1
  61. package/dist/storage/ArweaveClient.d.ts.map +1 -1
  62. package/dist/storage/ArweaveClient.js +2 -0
  63. package/dist/storage/ArweaveClient.js.map +1 -1
  64. package/dist/storage/FilebaseClient.d.ts.map +1 -1
  65. package/dist/storage/FilebaseClient.js +2 -0
  66. package/dist/storage/FilebaseClient.js.map +1 -1
  67. package/dist/utils/ErrorRecoveryGuide.d.ts.map +1 -1
  68. package/dist/utils/ErrorRecoveryGuide.js +3 -2
  69. package/dist/utils/ErrorRecoveryGuide.js.map +1 -1
  70. package/dist/utils/IPFSClient.d.ts +3 -2
  71. package/dist/utils/IPFSClient.d.ts.map +1 -1
  72. package/dist/utils/IPFSClient.js +7 -5
  73. package/dist/utils/IPFSClient.js.map +1 -1
  74. package/dist/utils/computeTypeHash.js +1 -3
  75. package/dist/utils/computeTypeHash.js.map +1 -1
  76. package/dist/utils/retry.d.ts.map +1 -1
  77. package/dist/utils/retry.js +0 -1
  78. package/dist/utils/retry.js.map +1 -1
  79. package/dist/utils/validation.d.ts +2 -2
  80. package/dist/utils/validation.d.ts.map +1 -1
  81. package/dist/utils/validation.js +2 -2
  82. package/dist/utils/validation.js.map +1 -1
  83. package/dist/wallet/AutoWalletProvider.d.ts +77 -0
  84. package/dist/wallet/AutoWalletProvider.d.ts.map +1 -0
  85. package/dist/wallet/AutoWalletProvider.js +197 -0
  86. package/dist/wallet/AutoWalletProvider.js.map +1 -0
  87. package/dist/wallet/EOAWalletProvider.d.ts +21 -0
  88. package/dist/wallet/EOAWalletProvider.d.ts.map +1 -0
  89. package/dist/wallet/EOAWalletProvider.js +57 -0
  90. package/dist/wallet/EOAWalletProvider.js.map +1 -0
  91. package/dist/wallet/IWalletProvider.d.ts +115 -0
  92. package/dist/wallet/IWalletProvider.d.ts.map +1 -0
  93. package/dist/wallet/IWalletProvider.js +12 -0
  94. package/dist/wallet/IWalletProvider.js.map +1 -0
  95. package/dist/wallet/aa/BundlerClient.d.ts +70 -0
  96. package/dist/wallet/aa/BundlerClient.d.ts.map +1 -0
  97. package/dist/wallet/aa/BundlerClient.js +184 -0
  98. package/dist/wallet/aa/BundlerClient.js.map +1 -0
  99. package/dist/wallet/aa/DualNonceManager.d.ts +56 -0
  100. package/dist/wallet/aa/DualNonceManager.d.ts.map +1 -0
  101. package/dist/wallet/aa/DualNonceManager.js +142 -0
  102. package/dist/wallet/aa/DualNonceManager.js.map +1 -0
  103. package/dist/wallet/aa/PaymasterClient.d.ts +52 -0
  104. package/dist/wallet/aa/PaymasterClient.d.ts.map +1 -0
  105. package/dist/wallet/aa/PaymasterClient.js +116 -0
  106. package/dist/wallet/aa/PaymasterClient.js.map +1 -0
  107. package/dist/wallet/aa/TransactionBatcher.d.ts +87 -0
  108. package/dist/wallet/aa/TransactionBatcher.d.ts.map +1 -0
  109. package/dist/wallet/aa/TransactionBatcher.js +148 -0
  110. package/dist/wallet/aa/TransactionBatcher.js.map +1 -0
  111. package/dist/wallet/aa/UserOpBuilder.d.ts +71 -0
  112. package/dist/wallet/aa/UserOpBuilder.d.ts.map +1 -0
  113. package/dist/wallet/aa/UserOpBuilder.js +196 -0
  114. package/dist/wallet/aa/UserOpBuilder.js.map +1 -0
  115. package/dist/wallet/aa/constants.d.ts +54 -0
  116. package/dist/wallet/aa/constants.d.ts.map +1 -0
  117. package/dist/wallet/aa/constants.js +18 -0
  118. package/dist/wallet/aa/constants.js.map +1 -0
  119. package/package.json +4 -2
  120. package/src/ACTPClient.ts +217 -31
  121. package/src/adapters/AdapterRouter.ts +0 -1
  122. package/src/adapters/BasicAdapter.ts +41 -1
  123. package/src/cli/commands/init.ts +394 -25
  124. package/src/cli/commands/publish.ts +1 -2
  125. package/src/cli/commands/register.ts +233 -0
  126. package/src/cli/index.ts +4 -0
  127. package/src/cli/utils/config.ts +30 -0
  128. package/src/config/networks.ts +82 -27
  129. package/src/config/publishPipeline.ts +2 -2
  130. package/src/erc8004/ERC8004Bridge.ts +6 -5
  131. package/src/erc8004/ReputationReporter.ts +14 -18
  132. package/src/index.ts +12 -0
  133. package/src/level1/Agent.ts +5 -5
  134. package/src/protocol/ACTPKernel.ts +20 -10
  135. package/src/protocol/EventMonitor.ts +14 -0
  136. package/src/runtime/BlockchainRuntime.ts +7 -1
  137. package/src/storage/ArchiveBundleBuilder.ts +0 -2
  138. package/src/storage/ArweaveClient.ts +2 -1
  139. package/src/storage/FilebaseClient.ts +3 -3
  140. package/src/utils/ErrorRecoveryGuide.ts +4 -2
  141. package/src/utils/IPFSClient.ts +9 -7
  142. package/src/utils/computeTypeHash.ts +1 -3
  143. package/src/utils/retry.ts +0 -1
  144. package/src/utils/validation.ts +2 -2
  145. package/src/wallet/AutoWalletProvider.ts +294 -0
  146. package/src/wallet/EOAWalletProvider.ts +69 -0
  147. package/src/wallet/IWalletProvider.ts +133 -0
  148. package/src/wallet/aa/BundlerClient.ts +274 -0
  149. package/src/wallet/aa/DualNonceManager.ts +173 -0
  150. package/src/wallet/aa/PaymasterClient.ts +174 -0
  151. package/src/wallet/aa/TransactionBatcher.ts +240 -0
  152. package/src/wallet/aa/UserOpBuilder.ts +246 -0
  153. package/src/wallet/aa/constants.ts +60 -0
@@ -0,0 +1,133 @@
1
+ /**
2
+ * IWalletProvider — Wallet abstraction for ACTP SDK.
3
+ *
4
+ * Enables pluggable wallet implementations:
5
+ * - EOAWalletProvider (Tier 2): Direct ethers.Wallet signing
6
+ * - AutoWalletProvider (Tier 1): CoinbaseSmartWallet + Paymaster (gasless)
7
+ *
8
+ * @module wallet/IWalletProvider
9
+ */
10
+
11
+ // ============================================================================
12
+ // Types
13
+ // ============================================================================
14
+
15
+ /**
16
+ * Low-level transaction request.
17
+ * Plain strings only — no ethers or viem types at the interface boundary.
18
+ */
19
+ export interface TransactionRequest {
20
+ /** Target contract address (0x-prefixed) */
21
+ to: string;
22
+ /** Calldata (0x-prefixed hex) */
23
+ data: string;
24
+ /** ETH value in wei (decimal string). Defaults to "0". */
25
+ value?: string;
26
+ }
27
+
28
+ /**
29
+ * Transaction receipt returned after submission.
30
+ */
31
+ export interface TransactionReceipt {
32
+ /** Transaction hash (EOA) or UserOp hash (AA) */
33
+ hash: string;
34
+ /** Whether the transaction succeeded */
35
+ success: boolean;
36
+ }
37
+
38
+ /**
39
+ * Wallet tier — determines gas behavior.
40
+ */
41
+ export type WalletTier = 'auto' | 'eoa';
42
+
43
+ /**
44
+ * Information about the wallet provider.
45
+ */
46
+ export interface WalletInfo {
47
+ /** The account address used for ACTP transactions */
48
+ address: string;
49
+ /** Wallet tier */
50
+ tier: WalletTier;
51
+ /** Whether this wallet supports atomic batching (AA = true, EOA = false) */
52
+ supportsBatching: boolean;
53
+ /** Whether gas is sponsored (AA with paymaster = true) */
54
+ gasSponsored: boolean;
55
+ /** Chain ID */
56
+ chainId: number;
57
+ }
58
+
59
+ /**
60
+ * Result of a batched ACTP payment via AA wallet.
61
+ */
62
+ export interface BatchedPayResult {
63
+ /** Pre-computed ACTP transaction ID (bytes32) */
64
+ txId: string;
65
+ /** Transaction hash from the UserOp */
66
+ hash: string;
67
+ /** Whether the UserOp succeeded */
68
+ success: boolean;
69
+ }
70
+
71
+ /**
72
+ * Parameters for batched ACTP payment.
73
+ */
74
+ export interface BatchedPayParams {
75
+ provider: string;
76
+ requester: string;
77
+ amount: string;
78
+ deadline: number;
79
+ disputeWindow: number;
80
+ serviceHash: string;
81
+ agentId: string;
82
+ contracts: {
83
+ usdc: string;
84
+ actpKernel: string;
85
+ escrowVault: string;
86
+ };
87
+ }
88
+
89
+ // ============================================================================
90
+ // Interface
91
+ // ============================================================================
92
+
93
+ /**
94
+ * Wallet provider interface.
95
+ *
96
+ * All methods use plain strings (no ethers/viem types) to keep the
97
+ * interface decoupled from any specific library.
98
+ */
99
+ export interface IWalletProvider {
100
+ /**
101
+ * Get the account address used as requester in ACTP transactions.
102
+ * For AA wallets this is the Smart Wallet address (not the signer EOA).
103
+ */
104
+ getAddress(): string;
105
+
106
+ /**
107
+ * Send a single transaction.
108
+ */
109
+ sendTransaction(tx: TransactionRequest): Promise<TransactionReceipt>;
110
+
111
+ /**
112
+ * Send multiple transactions atomically (AA) or sequentially (EOA).
113
+ *
114
+ * AA wallets batch all calls into a single UserOp.
115
+ * EOA wallets execute them one by one and return the last receipt.
116
+ */
117
+ sendBatchTransaction(txs: TransactionRequest[]): Promise<TransactionReceipt>;
118
+
119
+ /**
120
+ * Get wallet metadata.
121
+ */
122
+ getWalletInfo(): WalletInfo;
123
+
124
+ /**
125
+ * Execute a batched ACTP payment atomically (approve + createTx + linkEscrow).
126
+ *
127
+ * Only available on AA wallets (supportsBatching: true).
128
+ * Handles ACTP nonce management internally via the DualNonceManager mutex.
129
+ *
130
+ * Returns undefined if batched payments are not supported.
131
+ */
132
+ payACTPBatched?(params: BatchedPayParams): Promise<BatchedPayResult>;
133
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * BundlerClient — JSON-RPC client for ERC-4337 bundlers.
3
+ *
4
+ * Supports Coinbase (primary) and Pimlico (backup) bundlers.
5
+ * Handles gas estimation, UserOp submission, and receipt polling.
6
+ * Retry with exponential backoff on transient failures.
7
+ *
8
+ * @module wallet/aa/BundlerClient
9
+ */
10
+
11
+ import { UserOperationV06 } from './constants';
12
+ import { serializeUserOp } from './UserOpBuilder';
13
+ import { ENTRYPOINT_V06 } from './constants';
14
+ import { sdkLogger } from '../../utils/Logger';
15
+
16
+ // ============================================================================
17
+ // Types
18
+ // ============================================================================
19
+
20
+ export interface BundlerConfig {
21
+ /** Primary bundler URL (Coinbase CDP) */
22
+ primaryUrl: string;
23
+ /** Backup bundler URL (Pimlico) */
24
+ backupUrl?: string;
25
+ /** Max retry attempts per endpoint */
26
+ maxRetries?: number;
27
+ /** Base delay for exponential backoff (ms) */
28
+ baseDelayMs?: number;
29
+ /** Timeout for individual requests (ms) */
30
+ timeoutMs?: number;
31
+ }
32
+
33
+ export interface UserOpReceipt {
34
+ /** UserOp hash */
35
+ userOpHash: string;
36
+ /** Transaction hash on-chain */
37
+ transactionHash: string;
38
+ /** Block number */
39
+ blockNumber: number;
40
+ /** Whether the UserOp execution succeeded */
41
+ success: boolean;
42
+ }
43
+
44
+ interface JsonRpcResponse<T = unknown> {
45
+ jsonrpc: string;
46
+ id: number;
47
+ result?: T;
48
+ error?: { code: number; message: string; data?: unknown };
49
+ }
50
+
51
+ // ============================================================================
52
+ // BundlerClient
53
+ // ============================================================================
54
+
55
+ export class BundlerClient {
56
+ private readonly primaryUrl: string;
57
+ private readonly backupUrl: string | undefined;
58
+ private readonly maxRetries: number;
59
+ private readonly baseDelayMs: number;
60
+ private readonly timeoutMs: number;
61
+ private requestId = 1;
62
+
63
+ constructor(config: BundlerConfig) {
64
+ this.primaryUrl = config.primaryUrl;
65
+ this.backupUrl = config.backupUrl;
66
+ this.maxRetries = config.maxRetries ?? 2;
67
+ this.baseDelayMs = config.baseDelayMs ?? 1000;
68
+ this.timeoutMs = config.timeoutMs ?? 30_000;
69
+ }
70
+
71
+ /**
72
+ * Estimate gas for a UserOp.
73
+ */
74
+ async estimateUserOperationGas(
75
+ userOp: UserOperationV06
76
+ ): Promise<{ callGasLimit: bigint; verificationGasLimit: bigint; preVerificationGas: bigint }> {
77
+ const result = await this.callWithFallback<{
78
+ callGasLimit: string;
79
+ verificationGasLimit: string;
80
+ preVerificationGas: string;
81
+ }>('eth_estimateUserOperationGas', [
82
+ serializeUserOp(userOp),
83
+ ENTRYPOINT_V06,
84
+ ]);
85
+
86
+ return {
87
+ callGasLimit: BigInt(result.callGasLimit),
88
+ verificationGasLimit: BigInt(result.verificationGasLimit),
89
+ preVerificationGas: BigInt(result.preVerificationGas),
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Submit a signed UserOp to the bundler.
95
+ * Returns the UserOp hash.
96
+ */
97
+ async sendUserOperation(userOp: UserOperationV06): Promise<string> {
98
+ return this.callWithFallback<string>('eth_sendUserOperation', [
99
+ serializeUserOp(userOp),
100
+ ENTRYPOINT_V06,
101
+ ]);
102
+ }
103
+
104
+ /**
105
+ * Get the receipt for a submitted UserOp.
106
+ * Returns null if not yet mined.
107
+ */
108
+ async getUserOperationReceipt(
109
+ userOpHash: string
110
+ ): Promise<UserOpReceipt | null> {
111
+ const result = await this.callWithFallback<{
112
+ userOpHash: string;
113
+ receipt: {
114
+ transactionHash: string;
115
+ blockNumber: string;
116
+ status: string;
117
+ };
118
+ success: boolean;
119
+ } | null>('eth_getUserOperationReceipt', [userOpHash]);
120
+
121
+ if (!result) return null;
122
+
123
+ return {
124
+ userOpHash: result.userOpHash,
125
+ transactionHash: result.receipt.transactionHash,
126
+ blockNumber: parseInt(result.receipt.blockNumber, 16),
127
+ success: result.success,
128
+ };
129
+ }
130
+
131
+ /**
132
+ * Wait for UserOp receipt with polling.
133
+ */
134
+ async waitForReceipt(
135
+ userOpHash: string,
136
+ timeoutMs: number = 60_000,
137
+ pollIntervalMs: number = 2_000
138
+ ): Promise<UserOpReceipt> {
139
+ const start = Date.now();
140
+ while (Date.now() - start < timeoutMs) {
141
+ const receipt = await this.getUserOperationReceipt(userOpHash);
142
+ if (receipt) return receipt;
143
+ await sleep(pollIntervalMs);
144
+ }
145
+ throw new Error(
146
+ `UserOp ${userOpHash} not mined after ${timeoutMs}ms. ` +
147
+ 'The transaction may still be pending — check the bundler or block explorer.'
148
+ );
149
+ }
150
+
151
+ // ==========================================================================
152
+ // Internal
153
+ // ==========================================================================
154
+
155
+ /**
156
+ * Call primary, fall back to backup, with retries and backoff.
157
+ */
158
+ private async callWithFallback<T>(
159
+ method: string,
160
+ params: unknown[]
161
+ ): Promise<T> {
162
+ // Try primary
163
+ try {
164
+ return await this.callWithRetry<T>(this.primaryUrl, method, params);
165
+ } catch (primaryError) {
166
+ if (!this.backupUrl) {
167
+ throw primaryError;
168
+ }
169
+ sdkLogger.warn('Primary bundler failed, trying backup', {
170
+ method,
171
+ error: primaryError instanceof Error ? primaryError.message : String(primaryError),
172
+ });
173
+ }
174
+
175
+ // Try backup
176
+ return this.callWithRetry<T>(this.backupUrl!, method, params);
177
+ }
178
+
179
+ private async callWithRetry<T>(
180
+ url: string,
181
+ method: string,
182
+ params: unknown[]
183
+ ): Promise<T> {
184
+ let lastError: Error | undefined;
185
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
186
+ try {
187
+ return await this.jsonRpc<T>(url, method, params);
188
+ } catch (error) {
189
+ lastError = error instanceof Error ? error : new Error(String(error));
190
+ // Don't retry non-transient errors
191
+ if (isNonTransient(lastError)) throw lastError;
192
+ if (attempt < this.maxRetries) {
193
+ const delay = this.baseDelayMs * Math.pow(2, attempt);
194
+ sdkLogger.warn('Bundler request failed, retrying', {
195
+ attempt: attempt + 1,
196
+ method,
197
+ delayMs: delay,
198
+ });
199
+ await sleep(delay);
200
+ }
201
+ }
202
+ }
203
+ throw lastError!;
204
+ }
205
+
206
+ private async jsonRpc<T>(
207
+ url: string,
208
+ method: string,
209
+ params: unknown[]
210
+ ): Promise<T> {
211
+ const body = JSON.stringify({
212
+ jsonrpc: '2.0',
213
+ id: this.requestId++,
214
+ method,
215
+ params,
216
+ });
217
+
218
+ const controller = new AbortController();
219
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
220
+
221
+ try {
222
+ const response = await fetch(url, {
223
+ method: 'POST',
224
+ headers: { 'Content-Type': 'application/json' },
225
+ body,
226
+ signal: controller.signal,
227
+ });
228
+
229
+ if (!response.ok) {
230
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
231
+ }
232
+
233
+ const json = (await response.json()) as JsonRpcResponse<T>;
234
+
235
+ if (json.error) {
236
+ const dataStr = json.error.data ? ` | data: ${JSON.stringify(json.error.data)}` : '';
237
+ const err = new Error(
238
+ `Bundler RPC error ${json.error.code}: ${json.error.message}${dataStr}`
239
+ );
240
+ (err as any).code = json.error.code;
241
+ (err as any).data = json.error.data;
242
+ throw err;
243
+ }
244
+
245
+ return json.result as T;
246
+ } finally {
247
+ clearTimeout(timeout);
248
+ }
249
+ }
250
+ }
251
+
252
+ // ============================================================================
253
+ // Helpers
254
+ // ============================================================================
255
+
256
+ function sleep(ms: number): Promise<void> {
257
+ return new Promise((resolve) => setTimeout(resolve, ms));
258
+ }
259
+
260
+ /**
261
+ * Detect non-transient errors that shouldn't be retried.
262
+ */
263
+ function isNonTransient(error: Error): boolean {
264
+ const code = (error as any).code;
265
+ // AA errors from bundler (invalid signature, insufficient funds, etc.)
266
+ if (typeof code === 'number' && code >= -32700 && code <= -32600) {
267
+ return true; // JSON-RPC parse/invalid request errors
268
+ }
269
+ const msg = error.message.toLowerCase();
270
+ if (msg.includes('aa') && (msg.includes('invalid') || msg.includes('rejected'))) {
271
+ return true; // AA validation errors
272
+ }
273
+ return false;
274
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * DualNonceManager — Manages both EntryPoint and ACTP nonces.
3
+ *
4
+ * ERC-4337 UserOps need two independent nonces:
5
+ * 1. EntryPoint nonce — anti-replay for the UserOp itself
6
+ * 2. ACTP nonce — used to compute deterministic txId
7
+ *
8
+ * This manager uses a sequential mutex queue to ensure:
9
+ * - Only one UserOp is in-flight at a time
10
+ * - ACTP nonce increments only on confirmed receipt
11
+ * - On failure, next call re-reads from chain
12
+ *
13
+ * @module wallet/aa/DualNonceManager
14
+ */
15
+
16
+ import { ethers } from 'ethers';
17
+ import { ENTRYPOINT_V06 } from './constants';
18
+ import { sdkLogger } from '../../utils/Logger';
19
+
20
+ // ============================================================================
21
+ // ABI fragments
22
+ // ============================================================================
23
+
24
+ const ENTRYPOINT_NONCE_ABI = [
25
+ 'function getNonce(address sender, uint192 key) view returns (uint256)',
26
+ ];
27
+
28
+ const ACTP_KERNEL_NONCE_ABI = [
29
+ 'function requesterNonces(address requester) view returns (uint256)',
30
+ ];
31
+
32
+ // ============================================================================
33
+ // Mutex
34
+ // ============================================================================
35
+
36
+ class Mutex {
37
+ private locked = false;
38
+ private queue: (() => void)[] = [];
39
+
40
+ async acquire(): Promise<void> {
41
+ if (!this.locked) {
42
+ this.locked = true;
43
+ return;
44
+ }
45
+ return new Promise<void>((resolve) => {
46
+ this.queue.push(resolve);
47
+ });
48
+ }
49
+
50
+ release(): void {
51
+ if (this.queue.length > 0) {
52
+ const next = this.queue.shift()!;
53
+ next();
54
+ } else {
55
+ this.locked = false;
56
+ }
57
+ }
58
+ }
59
+
60
+ // ============================================================================
61
+ // DualNonceManager
62
+ // ============================================================================
63
+
64
+ export class DualNonceManager {
65
+ private readonly provider: ethers.JsonRpcProvider;
66
+ private readonly senderAddress: string;
67
+ private readonly actpKernelAddress: string;
68
+ private readonly mutex = new Mutex();
69
+
70
+ /** Locally cached ACTP nonce — undefined means "re-read from chain" */
71
+ private cachedActpNonce: bigint | undefined;
72
+
73
+ constructor(
74
+ provider: ethers.JsonRpcProvider,
75
+ senderAddress: string,
76
+ actpKernelAddress: string
77
+ ) {
78
+ this.provider = provider;
79
+ this.senderAddress = senderAddress;
80
+ this.actpKernelAddress = actpKernelAddress;
81
+ }
82
+
83
+ /**
84
+ * Execute a callback while holding the nonce mutex.
85
+ *
86
+ * The callback receives current nonces and must return whether
87
+ * the operation succeeded (to decide ACTP nonce increment).
88
+ *
89
+ * @param fn Callback receiving { entryPointNonce, actpNonce }
90
+ * @param incrementsActpNonce Whether success increments the ACTP nonce
91
+ */
92
+ async enqueue<T>(
93
+ fn: (nonces: { entryPointNonce: bigint; actpNonce: bigint }) => Promise<{
94
+ result: T;
95
+ success: boolean;
96
+ }>,
97
+ incrementsActpNonce: boolean = true
98
+ ): Promise<T> {
99
+ await this.mutex.acquire();
100
+ try {
101
+ // Read nonces
102
+ const entryPointNonce = await this.readEntryPointNonce();
103
+ const actpNonce = this.cachedActpNonce ?? await this.readActpNonce();
104
+
105
+ sdkLogger.info('Nonces acquired', {
106
+ entryPointNonce: entryPointNonce.toString(),
107
+ actpNonce: actpNonce.toString(),
108
+ });
109
+
110
+ const { result, success } = await fn({ entryPointNonce, actpNonce });
111
+
112
+ if (success && incrementsActpNonce) {
113
+ this.cachedActpNonce = actpNonce + 1n;
114
+ } else if (!success) {
115
+ // Reset cache on failure — next call re-reads from chain
116
+ this.cachedActpNonce = undefined;
117
+ }
118
+
119
+ return result;
120
+ } catch (error) {
121
+ // Reset on error
122
+ this.cachedActpNonce = undefined;
123
+ throw error;
124
+ } finally {
125
+ this.mutex.release();
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Read current EntryPoint nonce for the sender.
131
+ * Key 0 is the default key for CoinbaseSmartWallet.
132
+ */
133
+ private async readEntryPointNonce(): Promise<bigint> {
134
+ const entryPoint = new ethers.Contract(
135
+ ENTRYPOINT_V06,
136
+ ENTRYPOINT_NONCE_ABI,
137
+ this.provider
138
+ );
139
+ return await entryPoint.getNonce(this.senderAddress, 0);
140
+ }
141
+
142
+ /**
143
+ * Read current ACTP nonce for the requester.
144
+ * requesterNonces is public on ACTPKernel (added in v2).
145
+ * Older deployments may not expose this — fall back to 0n.
146
+ */
147
+ private async readActpNonce(): Promise<bigint> {
148
+ try {
149
+ const kernel = new ethers.Contract(
150
+ this.actpKernelAddress,
151
+ ACTP_KERNEL_NONCE_ABI,
152
+ this.provider
153
+ );
154
+ const nonce = await kernel.requesterNonces(this.senderAddress);
155
+ this.cachedActpNonce = nonce;
156
+ return nonce;
157
+ } catch {
158
+ // Older ACTPKernel deployments don't expose requesterNonces.
159
+ // Return 0n — registration doesn't need it, and payment batches
160
+ // will fail at the contract level anyway if nonces are wrong.
161
+ sdkLogger.warn('requesterNonces not available on ACTPKernel — using 0 (older deployment?)');
162
+ this.cachedActpNonce = 0n;
163
+ return 0n;
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Invalidate cached ACTP nonce (forces re-read on next operation).
169
+ */
170
+ invalidateCache(): void {
171
+ this.cachedActpNonce = undefined;
172
+ }
173
+ }