@agirails/sdk 2.2.3 → 2.3.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 (211) hide show
  1. package/README.md +65 -31
  2. package/dist/ACTPClient.d.ts +42 -1
  3. package/dist/ACTPClient.d.ts.map +1 -1
  4. package/dist/ACTPClient.js +207 -22
  5. package/dist/ACTPClient.js.map +1 -1
  6. package/dist/abi/AgentRegistry.json +133 -0
  7. package/dist/adapters/AdapterRouter.d.ts.map +1 -1
  8. package/dist/adapters/AdapterRouter.js.map +1 -1
  9. package/dist/adapters/BasicAdapter.d.ts +10 -1
  10. package/dist/adapters/BasicAdapter.d.ts.map +1 -1
  11. package/dist/adapters/BasicAdapter.js +36 -1
  12. package/dist/adapters/BasicAdapter.js.map +1 -1
  13. package/dist/adapters/X402Adapter.d.ts +34 -7
  14. package/dist/adapters/X402Adapter.d.ts.map +1 -1
  15. package/dist/adapters/X402Adapter.js +36 -8
  16. package/dist/adapters/X402Adapter.js.map +1 -1
  17. package/dist/adapters/index.d.ts +1 -1
  18. package/dist/adapters/index.d.ts.map +1 -1
  19. package/dist/adapters/index.js.map +1 -1
  20. package/dist/cli/commands/diff.d.ts +11 -0
  21. package/dist/cli/commands/diff.d.ts.map +1 -0
  22. package/dist/cli/commands/diff.js +115 -0
  23. package/dist/cli/commands/diff.js.map +1 -0
  24. package/dist/cli/commands/init.d.ts +1 -0
  25. package/dist/cli/commands/init.d.ts.map +1 -1
  26. package/dist/cli/commands/init.js +260 -19
  27. package/dist/cli/commands/init.js.map +1 -1
  28. package/dist/cli/commands/publish.d.ts +11 -0
  29. package/dist/cli/commands/publish.d.ts.map +1 -0
  30. package/dist/cli/commands/publish.js +170 -0
  31. package/dist/cli/commands/publish.js.map +1 -0
  32. package/dist/cli/commands/pull.d.ts +12 -0
  33. package/dist/cli/commands/pull.d.ts.map +1 -0
  34. package/dist/cli/commands/pull.js +99 -0
  35. package/dist/cli/commands/pull.js.map +1 -0
  36. package/dist/cli/commands/register.d.ts +16 -0
  37. package/dist/cli/commands/register.d.ts.map +1 -0
  38. package/dist/cli/commands/register.js +211 -0
  39. package/dist/cli/commands/register.js.map +1 -0
  40. package/dist/cli/index.js +10 -0
  41. package/dist/cli/index.js.map +1 -1
  42. package/dist/cli/utils/config.d.ts +6 -0
  43. package/dist/cli/utils/config.d.ts.map +1 -1
  44. package/dist/cli/utils/config.js.map +1 -1
  45. package/dist/config/agirailsmd.d.ts +94 -0
  46. package/dist/config/agirailsmd.d.ts.map +1 -0
  47. package/dist/config/agirailsmd.js +209 -0
  48. package/dist/config/agirailsmd.js.map +1 -0
  49. package/dist/config/networks.d.ts +22 -4
  50. package/dist/config/networks.d.ts.map +1 -1
  51. package/dist/config/networks.js +64 -26
  52. package/dist/config/networks.js.map +1 -1
  53. package/dist/config/publishPipeline.d.ts +75 -0
  54. package/dist/config/publishPipeline.d.ts.map +1 -0
  55. package/dist/config/publishPipeline.js +193 -0
  56. package/dist/config/publishPipeline.js.map +1 -0
  57. package/dist/config/syncOperations.d.ts +67 -0
  58. package/dist/config/syncOperations.d.ts.map +1 -0
  59. package/dist/config/syncOperations.js +208 -0
  60. package/dist/config/syncOperations.js.map +1 -0
  61. package/dist/erc8004/ERC8004Bridge.d.ts.map +1 -1
  62. package/dist/erc8004/ERC8004Bridge.js +6 -5
  63. package/dist/erc8004/ERC8004Bridge.js.map +1 -1
  64. package/dist/erc8004/ReputationReporter.d.ts.map +1 -1
  65. package/dist/erc8004/ReputationReporter.js +9 -12
  66. package/dist/erc8004/ReputationReporter.js.map +1 -1
  67. package/dist/index.d.ts +5 -0
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +11 -3
  70. package/dist/index.js.map +1 -1
  71. package/dist/level0/request.d.ts.map +1 -1
  72. package/dist/level0/request.js +23 -86
  73. package/dist/level0/request.js.map +1 -1
  74. package/dist/level1/Agent.d.ts +0 -11
  75. package/dist/level1/Agent.d.ts.map +1 -1
  76. package/dist/level1/Agent.js +19 -36
  77. package/dist/level1/Agent.js.map +1 -1
  78. package/dist/protocol/ACTPKernel.d.ts +7 -1
  79. package/dist/protocol/ACTPKernel.d.ts.map +1 -1
  80. package/dist/protocol/ACTPKernel.js +13 -10
  81. package/dist/protocol/ACTPKernel.js.map +1 -1
  82. package/dist/protocol/EventMonitor.d.ts +14 -0
  83. package/dist/protocol/EventMonitor.d.ts.map +1 -1
  84. package/dist/protocol/EventMonitor.js +14 -0
  85. package/dist/protocol/EventMonitor.js.map +1 -1
  86. package/dist/registry/AgentRegistryClient.d.ts +75 -0
  87. package/dist/registry/AgentRegistryClient.d.ts.map +1 -0
  88. package/dist/registry/AgentRegistryClient.js +160 -0
  89. package/dist/registry/AgentRegistryClient.js.map +1 -0
  90. package/dist/runtime/BlockchainRuntime.d.ts +5 -0
  91. package/dist/runtime/BlockchainRuntime.d.ts.map +1 -1
  92. package/dist/runtime/BlockchainRuntime.js +1 -1
  93. package/dist/runtime/BlockchainRuntime.js.map +1 -1
  94. package/dist/storage/ArchiveBundleBuilder.d.ts.map +1 -1
  95. package/dist/storage/ArchiveBundleBuilder.js.map +1 -1
  96. package/dist/storage/ArweaveClient.d.ts.map +1 -1
  97. package/dist/storage/ArweaveClient.js +2 -0
  98. package/dist/storage/ArweaveClient.js.map +1 -1
  99. package/dist/storage/FilebaseClient.d.ts.map +1 -1
  100. package/dist/storage/FilebaseClient.js +2 -0
  101. package/dist/storage/FilebaseClient.js.map +1 -1
  102. package/dist/types/adapter.d.ts +39 -0
  103. package/dist/types/adapter.d.ts.map +1 -1
  104. package/dist/types/adapter.js +7 -0
  105. package/dist/types/adapter.js.map +1 -1
  106. package/dist/types/x402.d.ts +23 -0
  107. package/dist/types/x402.d.ts.map +1 -1
  108. package/dist/types/x402.js.map +1 -1
  109. package/dist/utils/ErrorRecoveryGuide.d.ts.map +1 -1
  110. package/dist/utils/ErrorRecoveryGuide.js +3 -2
  111. package/dist/utils/ErrorRecoveryGuide.js.map +1 -1
  112. package/dist/utils/IPFSClient.d.ts +3 -2
  113. package/dist/utils/IPFSClient.d.ts.map +1 -1
  114. package/dist/utils/IPFSClient.js +7 -5
  115. package/dist/utils/IPFSClient.js.map +1 -1
  116. package/dist/utils/computeTypeHash.js +1 -3
  117. package/dist/utils/computeTypeHash.js.map +1 -1
  118. package/dist/utils/retry.d.ts.map +1 -1
  119. package/dist/utils/retry.js +0 -1
  120. package/dist/utils/retry.js.map +1 -1
  121. package/dist/utils/validation.d.ts +2 -2
  122. package/dist/utils/validation.d.ts.map +1 -1
  123. package/dist/utils/validation.js +2 -2
  124. package/dist/utils/validation.js.map +1 -1
  125. package/dist/wallet/AutoWalletProvider.d.ts +77 -0
  126. package/dist/wallet/AutoWalletProvider.d.ts.map +1 -0
  127. package/dist/wallet/AutoWalletProvider.js +197 -0
  128. package/dist/wallet/AutoWalletProvider.js.map +1 -0
  129. package/dist/wallet/EOAWalletProvider.d.ts +21 -0
  130. package/dist/wallet/EOAWalletProvider.d.ts.map +1 -0
  131. package/dist/wallet/EOAWalletProvider.js +57 -0
  132. package/dist/wallet/EOAWalletProvider.js.map +1 -0
  133. package/dist/wallet/IWalletProvider.d.ts +115 -0
  134. package/dist/wallet/IWalletProvider.d.ts.map +1 -0
  135. package/dist/wallet/IWalletProvider.js +12 -0
  136. package/dist/wallet/IWalletProvider.js.map +1 -0
  137. package/dist/wallet/aa/BundlerClient.d.ts +70 -0
  138. package/dist/wallet/aa/BundlerClient.d.ts.map +1 -0
  139. package/dist/wallet/aa/BundlerClient.js +183 -0
  140. package/dist/wallet/aa/BundlerClient.js.map +1 -0
  141. package/dist/wallet/aa/DualNonceManager.d.ts +55 -0
  142. package/dist/wallet/aa/DualNonceManager.d.ts.map +1 -0
  143. package/dist/wallet/aa/DualNonceManager.js +131 -0
  144. package/dist/wallet/aa/DualNonceManager.js.map +1 -0
  145. package/dist/wallet/aa/PaymasterClient.d.ts +52 -0
  146. package/dist/wallet/aa/PaymasterClient.d.ts.map +1 -0
  147. package/dist/wallet/aa/PaymasterClient.js +115 -0
  148. package/dist/wallet/aa/PaymasterClient.js.map +1 -0
  149. package/dist/wallet/aa/TransactionBatcher.d.ts +87 -0
  150. package/dist/wallet/aa/TransactionBatcher.d.ts.map +1 -0
  151. package/dist/wallet/aa/TransactionBatcher.js +148 -0
  152. package/dist/wallet/aa/TransactionBatcher.js.map +1 -0
  153. package/dist/wallet/aa/UserOpBuilder.d.ts +71 -0
  154. package/dist/wallet/aa/UserOpBuilder.d.ts.map +1 -0
  155. package/dist/wallet/aa/UserOpBuilder.js +196 -0
  156. package/dist/wallet/aa/UserOpBuilder.js.map +1 -0
  157. package/dist/wallet/aa/constants.d.ts +54 -0
  158. package/dist/wallet/aa/constants.d.ts.map +1 -0
  159. package/dist/wallet/aa/constants.js +18 -0
  160. package/dist/wallet/aa/constants.js.map +1 -0
  161. package/dist/wallet/keystore.d.ts +16 -0
  162. package/dist/wallet/keystore.d.ts.map +1 -0
  163. package/dist/wallet/keystore.js +132 -0
  164. package/dist/wallet/keystore.js.map +1 -0
  165. package/package.json +5 -2
  166. package/src/ACTPClient.ts +275 -27
  167. package/src/abi/AgentRegistry.json +133 -0
  168. package/src/adapters/AdapterRouter.ts +0 -1
  169. package/src/adapters/BasicAdapter.ts +41 -1
  170. package/src/adapters/X402Adapter.ts +94 -16
  171. package/src/adapters/index.ts +9 -1
  172. package/src/cli/commands/diff.ts +141 -0
  173. package/src/cli/commands/init.ts +311 -22
  174. package/src/cli/commands/publish.ts +208 -0
  175. package/src/cli/commands/pull.ts +124 -0
  176. package/src/cli/commands/register.ts +233 -0
  177. package/src/cli/index.ts +12 -0
  178. package/src/cli/utils/config.ts +9 -0
  179. package/src/config/agirailsmd.ts +262 -0
  180. package/src/config/networks.ts +89 -26
  181. package/src/config/publishPipeline.ts +276 -0
  182. package/src/config/syncOperations.ts +279 -0
  183. package/src/erc8004/ERC8004Bridge.ts +6 -5
  184. package/src/erc8004/ReputationReporter.ts +14 -18
  185. package/src/index.ts +15 -0
  186. package/src/level0/request.ts +27 -88
  187. package/src/level1/Agent.ts +21 -37
  188. package/src/protocol/ACTPKernel.ts +20 -10
  189. package/src/protocol/EventMonitor.ts +14 -0
  190. package/src/registry/AgentRegistryClient.ts +202 -0
  191. package/src/runtime/BlockchainRuntime.ts +7 -1
  192. package/src/storage/ArchiveBundleBuilder.ts +0 -2
  193. package/src/storage/ArweaveClient.ts +2 -1
  194. package/src/storage/FilebaseClient.ts +3 -3
  195. package/src/types/adapter.ts +14 -0
  196. package/src/types/x402.ts +32 -0
  197. package/src/utils/ErrorRecoveryGuide.ts +4 -2
  198. package/src/utils/IPFSClient.ts +9 -7
  199. package/src/utils/computeTypeHash.ts +1 -3
  200. package/src/utils/retry.ts +0 -1
  201. package/src/utils/validation.ts +2 -2
  202. package/src/wallet/AutoWalletProvider.ts +294 -0
  203. package/src/wallet/EOAWalletProvider.ts +69 -0
  204. package/src/wallet/IWalletProvider.ts +133 -0
  205. package/src/wallet/aa/BundlerClient.ts +273 -0
  206. package/src/wallet/aa/DualNonceManager.ts +163 -0
  207. package/src/wallet/aa/PaymasterClient.ts +173 -0
  208. package/src/wallet/aa/TransactionBatcher.ts +240 -0
  209. package/src/wallet/aa/UserOpBuilder.ts +246 -0
  210. package/src/wallet/aa/constants.ts +60 -0
  211. package/src/wallet/keystore.ts +119 -0
@@ -0,0 +1,273 @@
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 err = new Error(
237
+ `Bundler RPC error ${json.error.code}: ${json.error.message}`
238
+ );
239
+ (err as any).code = json.error.code;
240
+ (err as any).data = json.error.data;
241
+ throw err;
242
+ }
243
+
244
+ return json.result as T;
245
+ } finally {
246
+ clearTimeout(timeout);
247
+ }
248
+ }
249
+ }
250
+
251
+ // ============================================================================
252
+ // Helpers
253
+ // ============================================================================
254
+
255
+ function sleep(ms: number): Promise<void> {
256
+ return new Promise((resolve) => setTimeout(resolve, ms));
257
+ }
258
+
259
+ /**
260
+ * Detect non-transient errors that shouldn't be retried.
261
+ */
262
+ function isNonTransient(error: Error): boolean {
263
+ const code = (error as any).code;
264
+ // AA errors from bundler (invalid signature, insufficient funds, etc.)
265
+ if (typeof code === 'number' && code >= -32700 && code <= -32600) {
266
+ return true; // JSON-RPC parse/invalid request errors
267
+ }
268
+ const msg = error.message.toLowerCase();
269
+ if (msg.includes('aa') && (msg.includes('invalid') || msg.includes('rejected'))) {
270
+ return true; // AA validation errors
271
+ }
272
+ return false;
273
+ }
@@ -0,0 +1,163 @@
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.
145
+ */
146
+ private async readActpNonce(): Promise<bigint> {
147
+ const kernel = new ethers.Contract(
148
+ this.actpKernelAddress,
149
+ ACTP_KERNEL_NONCE_ABI,
150
+ this.provider
151
+ );
152
+ const nonce = await kernel.requesterNonces(this.senderAddress);
153
+ this.cachedActpNonce = nonce;
154
+ return nonce;
155
+ }
156
+
157
+ /**
158
+ * Invalidate cached ACTP nonce (forces re-read on next operation).
159
+ */
160
+ invalidateCache(): void {
161
+ this.cachedActpNonce = undefined;
162
+ }
163
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * PaymasterClient — Gas sponsorship via ERC-7677 paymasters.
3
+ *
4
+ * Fallback chain: Coinbase CDP (primary) → Pimlico (backup).
5
+ * Both implement ERC-7677 pm_getPaymasterStubData / pm_getPaymasterData.
6
+ *
7
+ * The paymaster fills the `paymasterAndData` field of the UserOp,
8
+ * which the EntryPoint uses to debit gas from the paymaster instead
9
+ * of the sender's ETH balance.
10
+ *
11
+ * @module wallet/aa/PaymasterClient
12
+ */
13
+
14
+ import { UserOperationV06 } from './constants';
15
+ import { serializeUserOp } from './UserOpBuilder';
16
+ import { ENTRYPOINT_V06 } from './constants';
17
+ import { sdkLogger } from '../../utils/Logger';
18
+
19
+ // ============================================================================
20
+ // Types
21
+ // ============================================================================
22
+
23
+ export interface PaymasterConfig {
24
+ /** Primary paymaster URL (Coinbase CDP) */
25
+ primaryUrl: string;
26
+ /** Backup paymaster URL (Pimlico) */
27
+ backupUrl?: string;
28
+ /** Chain ID (8453 for Base Mainnet, 84532 for Sepolia) */
29
+ chainId: number;
30
+ /** Request timeout (ms) */
31
+ timeoutMs?: number;
32
+ }
33
+
34
+ interface JsonRpcResponse<T = unknown> {
35
+ jsonrpc: string;
36
+ id: number;
37
+ result?: T;
38
+ error?: { code: number; message: string; data?: unknown };
39
+ }
40
+
41
+ // ============================================================================
42
+ // PaymasterClient
43
+ // ============================================================================
44
+
45
+ export class PaymasterClient {
46
+ private readonly primaryUrl: string;
47
+ private readonly backupUrl: string | undefined;
48
+ private readonly chainId: number;
49
+ private readonly timeoutMs: number;
50
+ private requestId = 1;
51
+
52
+ constructor(config: PaymasterConfig) {
53
+ this.primaryUrl = config.primaryUrl;
54
+ this.backupUrl = config.backupUrl;
55
+ this.chainId = config.chainId;
56
+ this.timeoutMs = config.timeoutMs ?? 15_000;
57
+ }
58
+
59
+ /**
60
+ * Get stub paymaster data for gas estimation.
61
+ *
62
+ * Returns approximate paymasterAndData that the bundler can use
63
+ * for gas estimation (exact values come from getPaymasterData).
64
+ */
65
+ async getPaymasterStubData(
66
+ userOp: UserOperationV06
67
+ ): Promise<{ paymasterAndData: string }> {
68
+ return this.callWithFallback<{ paymasterAndData: string }>(
69
+ 'pm_getPaymasterStubData',
70
+ [
71
+ serializeUserOp(userOp),
72
+ ENTRYPOINT_V06,
73
+ '0x' + this.chainId.toString(16),
74
+ {}, // context
75
+ ]
76
+ );
77
+ }
78
+
79
+ /**
80
+ * Get final paymaster data for the signed UserOp.
81
+ *
82
+ * This is called after gas estimation with final gas values.
83
+ * Returns the paymaster signature that goes into paymasterAndData.
84
+ */
85
+ async getPaymasterData(
86
+ userOp: UserOperationV06
87
+ ): Promise<{ paymasterAndData: string }> {
88
+ return this.callWithFallback<{ paymasterAndData: string }>(
89
+ 'pm_getPaymasterData',
90
+ [
91
+ serializeUserOp(userOp),
92
+ ENTRYPOINT_V06,
93
+ '0x' + this.chainId.toString(16),
94
+ {}, // context
95
+ ]
96
+ );
97
+ }
98
+
99
+ // ==========================================================================
100
+ // Internal
101
+ // ==========================================================================
102
+
103
+ private async callWithFallback<T>(
104
+ method: string,
105
+ params: unknown[]
106
+ ): Promise<T> {
107
+ try {
108
+ return await this.jsonRpc<T>(this.primaryUrl, method, params);
109
+ } catch (primaryError) {
110
+ if (!this.backupUrl) {
111
+ throw new Error(
112
+ `Gas sponsorship unavailable: ${primaryError instanceof Error ? primaryError.message : String(primaryError)}. ` +
113
+ 'No backup paymaster configured.'
114
+ );
115
+ }
116
+ sdkLogger.warn('Primary paymaster failed, trying backup', {
117
+ method,
118
+ error: primaryError instanceof Error ? primaryError.message : String(primaryError),
119
+ });
120
+ }
121
+
122
+ try {
123
+ return await this.jsonRpc<T>(this.backupUrl!, method, params);
124
+ } catch (backupError) {
125
+ throw new Error(
126
+ 'Gas sponsorship temporarily unavailable — both Coinbase and Pimlico paymasters failed. ' +
127
+ 'Please retry later. ' +
128
+ `Primary: ${backupError instanceof Error ? backupError.message : String(backupError)}`
129
+ );
130
+ }
131
+ }
132
+
133
+ private async jsonRpc<T>(
134
+ url: string,
135
+ method: string,
136
+ params: unknown[]
137
+ ): Promise<T> {
138
+ const body = JSON.stringify({
139
+ jsonrpc: '2.0',
140
+ id: this.requestId++,
141
+ method,
142
+ params,
143
+ });
144
+
145
+ const controller = new AbortController();
146
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
147
+
148
+ try {
149
+ const response = await fetch(url, {
150
+ method: 'POST',
151
+ headers: { 'Content-Type': 'application/json' },
152
+ body,
153
+ signal: controller.signal,
154
+ });
155
+
156
+ if (!response.ok) {
157
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
158
+ }
159
+
160
+ const json = (await response.json()) as JsonRpcResponse<T>;
161
+
162
+ if (json.error) {
163
+ throw new Error(
164
+ `Paymaster RPC error ${json.error.code}: ${json.error.message}`
165
+ );
166
+ }
167
+
168
+ return json.result as T;
169
+ } finally {
170
+ clearTimeout(timeout);
171
+ }
172
+ }
173
+ }