@totalreclaw/totalreclaw 3.3.12-rc.2 → 3.3.12-rc.21

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 (87) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/SKILL.md +34 -249
  3. package/api-client.ts +17 -9
  4. package/batch-gate.ts +42 -0
  5. package/billing-cache.ts +25 -20
  6. package/claims-helper.ts +7 -1
  7. package/config.ts +54 -12
  8. package/consolidation.ts +6 -13
  9. package/contradiction-sync.ts +19 -14
  10. package/credential-provider.ts +184 -0
  11. package/crypto.ts +27 -160
  12. package/dist/api-client.js +17 -9
  13. package/dist/batch-gate.js +40 -0
  14. package/dist/billing-cache.js +19 -21
  15. package/dist/claims-helper.js +7 -1
  16. package/dist/config.js +54 -12
  17. package/dist/consolidation.js +6 -15
  18. package/dist/contradiction-sync.js +15 -15
  19. package/dist/credential-provider.js +145 -0
  20. package/dist/crypto.js +17 -137
  21. package/dist/download-ux.js +11 -7
  22. package/dist/embedder-loader.js +266 -0
  23. package/dist/embedding.js +36 -3
  24. package/dist/entry.js +123 -0
  25. package/dist/extractor.js +134 -0
  26. package/dist/fs-helpers.js +116 -241
  27. package/dist/import-adapters/chatgpt-adapter.js +14 -0
  28. package/dist/import-adapters/claude-adapter.js +14 -0
  29. package/dist/import-adapters/gemini-adapter.js +43 -159
  30. package/dist/import-adapters/mcp-memory-adapter.js +14 -0
  31. package/dist/import-state-manager.js +100 -0
  32. package/dist/index.js +1130 -2520
  33. package/dist/llm-client.js +69 -1
  34. package/dist/memory-runtime.js +459 -0
  35. package/dist/native-memory.js +123 -0
  36. package/dist/onboarding-cli.js +3 -2
  37. package/dist/pair-cli.js +1 -1
  38. package/dist/pair-crypto.js +16 -358
  39. package/dist/pair-http.js +147 -4
  40. package/dist/relay.js +140 -0
  41. package/dist/reranker.js +13 -8
  42. package/dist/semantic-dedup.js +5 -7
  43. package/dist/skill-register.js +97 -0
  44. package/dist/subgraph-search.js +3 -1
  45. package/dist/subgraph-store.js +315 -282
  46. package/dist/tool-gating.js +39 -26
  47. package/dist/tools.js +367 -0
  48. package/dist/tr-cli-export-helper.js +103 -0
  49. package/dist/tr-cli.js +220 -127
  50. package/dist/trajectory-poller.js +155 -9
  51. package/dist/vault-crypto.js +551 -0
  52. package/download-ux.ts +12 -6
  53. package/embedder-loader.ts +293 -1
  54. package/embedding.ts +43 -3
  55. package/entry.ts +132 -0
  56. package/extractor.ts +167 -0
  57. package/fs-helpers.ts +166 -292
  58. package/import-adapters/chatgpt-adapter.ts +18 -0
  59. package/import-adapters/claude-adapter.ts +18 -0
  60. package/import-adapters/gemini-adapter.ts +56 -183
  61. package/import-adapters/mcp-memory-adapter.ts +18 -0
  62. package/import-adapters/types.ts +1 -1
  63. package/import-state-manager.ts +139 -0
  64. package/index.ts +1432 -3002
  65. package/llm-client.ts +74 -1
  66. package/memory-runtime.ts +723 -0
  67. package/native-memory.ts +196 -0
  68. package/onboarding-cli.ts +3 -2
  69. package/openclaw.plugin.json +5 -17
  70. package/package.json +7 -4
  71. package/pair-cli.ts +1 -1
  72. package/pair-crypto.ts +41 -483
  73. package/pair-http.ts +194 -5
  74. package/postinstall.mjs +138 -0
  75. package/relay.ts +172 -0
  76. package/reranker.ts +13 -8
  77. package/semantic-dedup.ts +5 -6
  78. package/skill-register.ts +146 -0
  79. package/skill.json +1 -1
  80. package/subgraph-search.ts +3 -1
  81. package/subgraph-store.ts +334 -299
  82. package/tool-gating.ts +39 -26
  83. package/tools.ts +499 -0
  84. package/tr-cli-export-helper.ts +138 -0
  85. package/tr-cli.ts +263 -133
  86. package/trajectory-poller.ts +162 -10
  87. package/vault-crypto.ts +705 -0
package/subgraph-store.ts CHANGED
@@ -2,12 +2,13 @@
2
2
  * Subgraph store path — writes facts on-chain via ERC-4337 UserOps.
3
3
  *
4
4
  * Used when the managed service is active (TOTALRECLAW_SELF_HOSTED is not
5
- * "true"). Replaces the HTTP POST to /v1/store with an on-chain transaction
5
+ * "true"). Replaces the HTTP request to /v1/store with an on-chain transaction
6
6
  * flow.
7
7
  *
8
- * Uses @totalreclaw/core WASM for calldata encoding, UserOp hashing, and
9
- * ECDSA signing. Raw fetch() for all JSON-RPC calls to the relay bundler
10
- * and chain RPCs. No viem, no permissionless.
8
+ * Uses @totalreclaw/core WASM for calldata encoding and UserOp hashing;
9
+ * `signUserOp` (ECDSA) lives in `vault-crypto.ts`. All JSON-RPC calls to
10
+ * the relay bundler and chain RPCs go through `relay.ts` (the plugin's
11
+ * single network site). No viem, no permissionless.
11
12
  */
12
13
 
13
14
  // Lazy-load WASM via createRequire — the shipped bundle is ESM-only and
@@ -22,61 +23,8 @@ function getWasm() {
22
23
  }
23
24
  import { CONFIG } from './config.js';
24
25
  import { buildRelayHeaders } from './relay-headers.js';
25
-
26
- // ---------------------------------------------------------------------------
27
- // Pimlico 429 retry helper
28
- // ---------------------------------------------------------------------------
29
-
30
- /**
31
- * Wrap a fetch-based JSON-RPC call with exponential backoff for HTTP 429
32
- * (rate limit) responses from Pimlico. Max 5 retries with 5s base delay,
33
- * doubling each attempt, capped at 60s, plus random jitter (0-1000ms).
34
- * Total retry window: ~135s (5+10+20+40+60 plus jitter).
35
- * All other HTTP errors throw immediately.
36
- */
37
- async function rpcWithRetry(
38
- url: string,
39
- headers: Record<string, string>,
40
- method: string,
41
- params: unknown[],
42
- ): Promise<any> {
43
- const maxRetries = 5;
44
- const baseDelay = 5000; // 5 seconds
45
- const maxDelay = 60_000; // 60 seconds cap
46
- const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
47
-
48
- for (let attempt = 1; attempt <= maxRetries + 1; attempt++) {
49
- const resp = await fetch(url, { method: 'POST', headers, body });
50
-
51
- if (resp.ok) {
52
- const json = await resp.json() as { result?: any; error?: { message: string } };
53
- if (json.error) {
54
- // Check if the RPC-level error message indicates a rate limit
55
- if (attempt <= maxRetries && /429|rate limit/i.test(json.error.message)) {
56
- const delay = Math.min(Math.pow(2, attempt - 1) * baseDelay, maxDelay) + Math.floor(Math.random() * 1000);
57
- console.error(`Pimlico rate limited, retrying in ${delay}ms (attempt ${attempt}/${maxRetries})...`);
58
- await new Promise(r => setTimeout(r, delay));
59
- continue;
60
- }
61
- throw new Error(`RPC ${method}: ${json.error.message}`);
62
- }
63
- return json.result;
64
- }
65
-
66
- // HTTP-level 429 — retry with backoff
67
- if (resp.status === 429 && attempt <= maxRetries) {
68
- const delay = Math.min(Math.pow(2, attempt - 1) * baseDelay, maxDelay) + Math.floor(Math.random() * 1000);
69
- console.error(`Pimlico rate limited, retrying in ${delay}ms (attempt ${attempt}/${maxRetries})...`);
70
- await new Promise(r => setTimeout(r, delay));
71
- continue;
72
- }
73
-
74
- throw new Error(`Relay returned HTTP ${resp.status} for ${method}`);
75
- }
76
-
77
- // Should not be reached, but satisfies TypeScript
78
- throw new Error(`RPC ${method}: max retries exceeded`);
79
- }
26
+ import { rpcRequest, rpcWithRetry } from './relay.js';
27
+ import { signUserOp } from './vault-crypto.js';
80
28
 
81
29
  // ---------------------------------------------------------------------------
82
30
  // Types
@@ -86,7 +34,7 @@ export interface SubgraphStoreConfig {
86
34
  relayUrl: string; // TotalReclaw relay server URL (proxies bundler + subgraph)
87
35
  mnemonic: string; // BIP-39 mnemonic for key derivation
88
36
  cachePath: string; // Hot cache file path
89
- chainId: number; // 100 for Gnosis mainnet, 84532 for Base Sepolia
37
+ chainId: number; // Gnosis mainnet (100) after ops-1; from relay chain_id (#402)
90
38
  dataEdgeAddress: string; // EventfulDataEdge contract address
91
39
  entryPointAddress: string; // ERC-4337 EntryPoint v0.7
92
40
  authKeyHex?: string; // HKDF auth key for relay server Authorization header
@@ -173,9 +121,12 @@ function getDefaultRpcUrl(chainId: number): string {
173
121
  case 100:
174
122
  return 'https://rpc.gnosischain.com';
175
123
  case 84532:
124
+ // Retained for the legacy Base Sepolia chain id, but after ops-1 nothing
125
+ // should resolve here — the relay's authoritative chain_id is 100 (#402).
176
126
  return 'https://sepolia.base.org';
177
127
  default:
178
- return 'https://sepolia.base.org';
128
+ // Unknown chain id → Gnosis mainnet (after ops-1 default), NOT Base Sepolia.
129
+ return 'https://rpc.gnosischain.com';
179
130
  }
180
131
  }
181
132
 
@@ -191,7 +142,9 @@ function getDefaultRpcUrl(chainId: number): string {
191
142
  */
192
143
  export async function deriveSmartAccountAddress(mnemonic: string, chainId?: number): Promise<string> {
193
144
  const eoa = getWasm().deriveEoa(mnemonic) as { private_key: string; address: string };
194
- const resolvedChainId = chainId ?? 84532;
145
+ // Default to Gnosis mainnet (100) after ops-1 — the SA address is CREATE2 and
146
+ // byte-equal across chains, but the RPC we query must be the live one (#402).
147
+ const resolvedChainId = chainId ?? 100;
195
148
 
196
149
  // SimpleAccountFactory.getAddress(address owner, uint256 salt) — view function
197
150
  // Selector: 0x8cb84e18 = keccak256("getAddress(address,uint256)")[0:4]
@@ -202,17 +155,12 @@ export async function deriveSmartAccountAddress(mnemonic: string, chainId?: numb
202
155
  const calldata = `0x${selector}${ownerPadded}${saltPadded}`;
203
156
 
204
157
  const rpcUrl = CONFIG.rpcUrl || getDefaultRpcUrl(resolvedChainId);
205
- const response = await fetch(rpcUrl, {
206
- method: 'POST',
158
+ const json = await rpcRequest({
159
+ url: rpcUrl,
207
160
  headers: { 'Content-Type': 'application/json' },
208
- body: JSON.stringify({
209
- jsonrpc: '2.0',
210
- id: 1,
211
- method: 'eth_call',
212
- params: [{ to: factoryAddress, data: calldata }, 'latest'],
213
- }),
161
+ method: 'eth_call',
162
+ params: [{ to: factoryAddress, data: calldata }, 'latest'],
214
163
  });
215
- const json = await response.json() as { result?: string; error?: { message: string } };
216
164
  if (json.error) {
217
165
  throw new Error(`Failed to resolve Smart Account address: ${json.error.message}`);
218
166
  }
@@ -220,21 +168,74 @@ export async function deriveSmartAccountAddress(mnemonic: string, chainId?: numb
220
168
  throw new Error('Failed to resolve Smart Account address: empty result');
221
169
  }
222
170
  // Result is a 32-byte ABI-encoded address — take last 20 bytes
223
- return `0x${json.result.slice(-40)}`.toLowerCase();
171
+ return `0x${(json.result as string).slice(-40)}`.toLowerCase();
224
172
  }
225
173
 
226
174
  // ---------------------------------------------------------------------------
227
- // Smart Account deployment check (with session cache)
175
+ // Smart Account deployment check
228
176
  // ---------------------------------------------------------------------------
177
+ //
178
+ // NOTE on the removed session cache (2026-06-28, AA10 fix):
179
+ //
180
+ // A module-level `Set<string>` of "already deployed" accounts used to skip
181
+ // the `eth_getCode` RPC after the first successful submission. That cache
182
+ // was the single largest source of AA10 "sender already constructed"
183
+ // failures in production:
184
+ //
185
+ // - A process restart emptied the cache → the next submission relied on
186
+ // ONE `eth_getCode` read that could return stale `0x` from a lagging
187
+ // RPC node (the deploy tx was mined but the node hadn't caught up) →
188
+ // initCode was re-added → the EntryPoint rejected with AA10.
189
+ // - A receipt poll that timed out (success undetected within the 120s
190
+ // window) left the cache unpopulated → the next submission hit the
191
+ // same stale-`eth_getCode` path → AA10.
192
+ // - The AA25 retry path (`deployedAccounts.delete(...)`) existed ONLY to
193
+ // paper over the cache; with no cache there is nothing to invalidate.
194
+ //
195
+ // Fix: `getInitCode` calls `eth_getCode` on EVERY invocation. The
196
+ // per-sender submission mutex (`withSenderLock`) already serializes
197
+ // submissions per account, so the extra RPC cannot introduce a nonce
198
+ // race. The cost is one extra RPC read per submission — negligible
199
+ // against a relay round-trip — and the behavior is correct by
200
+ // construction: the plugin asserts on-chain state at submit time rather
201
+ // than trusting an in-memory guess that can be invalidated by anything
202
+ // the plugin doesn't observe (relayer retries, parallel clients, node
203
+ // reorgs, process restarts).
229
204
 
230
205
  /**
231
- * Session-level cache for account deployment status.
232
- * Once an account is deployed (first successful UserOp), we skip the
233
- * eth_getCode check and omit factory/factoryData for all subsequent calls.
234
- * This prevents AA10 "duplicate deployment" errors when multiple facts
235
- * are stored in rapid succession for a first-time user.
206
+ * Test-only RPC probe counter. Incremented each time `getInitCode` issues
207
+ * an `eth_getCode` read. The lifecycle test uses this to assert the cache
208
+ * is truly gone (every call hits the wire). Not part of the public API.
236
209
  */
237
- const deployedAccounts = new Set<string>();
210
+ let _ethGetCodeProbeCount = 0;
211
+
212
+ /** Test-only seam: drive the private `getInitCode` logic. */
213
+ export async function __getInitCodeForTests(
214
+ sender: string,
215
+ eoaAddress: string,
216
+ rpcUrl: string,
217
+ ): Promise<{ factory: string | null; factoryData: string | null }> {
218
+ return getInitCode(sender, eoaAddress, rpcUrl);
219
+ }
220
+
221
+ /** Test-only seam: read the RPC probe counter. */
222
+ export function __getRpcProbeCountForTests(): number {
223
+ return _ethGetCodeProbeCount;
224
+ }
225
+
226
+ /** Test-only seam: reset the RPC probe counter. */
227
+ export function __resetRpcProbeCountForTests(): void {
228
+ _ethGetCodeProbeCount = 0;
229
+ }
230
+
231
+ /**
232
+ * Test-only seam: previously reset the deployment cache. The cache was
233
+ * removed in the AA10 fix; this function is retained as a no-op so the
234
+ * lifecycle test (and any future test that imports it) doesn't break.
235
+ */
236
+ export function __resetDeployedAccountsForTests(): void {
237
+ /* no-op: session cache removed; getInitCode always re-checks eth_getCode */
238
+ }
238
239
 
239
240
  // ---------------------------------------------------------------------------
240
241
  // Per-account submission mutex — 3.3.1-rc.3 AA25 serialization
@@ -298,36 +299,80 @@ export function __resetSenderLocksForTests(): void {
298
299
  _senderSubmissionLocks.clear();
299
300
  }
300
301
 
302
+ // ---------------------------------------------------------------------------
303
+ // Test-only WASM mock seams (AA10 submit-path retry test)
304
+ // ---------------------------------------------------------------------------
305
+
306
+ /**
307
+ * Test-only seam: inject a mock WASM module.
308
+ *
309
+ * The AA10 submit-path retry test needs to drive the real submitFactBatchOnChain
310
+ * while controlling WASM behavior (deriveEoa, encodeBatchCall, hashUserOp,
311
+ * signUserOp, getEntryPointAddress). This seam swaps the module-level _wasm
312
+ * reference so the test can provide stubs.
313
+ *
314
+ * MUST be followed by __clearWasmForTests() in teardown.
315
+ */
316
+ export function __setWasmForTests(mock: any): void {
317
+ _wasm = mock;
318
+ }
319
+
320
+ /**
321
+ * Test-only seam: restore the real WASM module.
322
+ *
323
+ * Clears a test-injected mock WASM and resets the module to null so the next
324
+ * getWasm() call reloads the real @totalreclaw/core.
325
+ */
326
+ export function __clearWasmForTests(): void {
327
+ _wasm = null;
328
+ }
329
+
301
330
  /**
302
331
  * Check if a Smart Account is deployed and return factory/factoryData if not.
303
332
  *
304
- * For ERC-4337 v0.7, undeployed accounts need `factory` and `factoryData`
305
- * in the UserOp so the EntryPoint can deploy them during the first transaction.
333
+ * For ERC-4337 v0.7, undeployed (counterfactual) accounts need `factory`
334
+ * and `factoryData` in the UserOp so the EntryPoint deploys the SA + runs
335
+ * signature validation in one transaction.
336
+ *
337
+ * Re-checks `eth_getCode` on EVERY call — no session cache. The previous
338
+ * in-memory cache was the source of AA10 "sender already constructed"
339
+ * errors: it could be stale (process restart, missed receipt, lagging RPC
340
+ * node) and re-add initCode to a UserOp whose sender was already
341
+ * constructed. Each submission now pays one extra RPC read to assert the
342
+ * on-chain deployment state at submit time, which is the only source of
343
+ * truth the EntryPoint will enforce. See the note above on the removed
344
+ * cache for the full failure taxonomy.
306
345
  */
307
346
  async function getInitCode(
308
347
  sender: string,
309
348
  eoaAddress: string,
310
349
  rpcUrl: string,
311
350
  ): Promise<{ factory: string | null; factoryData: string | null }> {
312
- // Session cache: if we already deployed this account, skip the RPC check
313
- if (deployedAccounts.has(sender.toLowerCase())) {
314
- return { factory: null, factoryData: null };
315
- }
316
-
317
- // Check if the Smart Account contract is deployed
318
- const codeResp = await fetch(rpcUrl, {
319
- method: 'POST',
351
+ // Check if the Smart Account contract is deployed. Always re-read — never
352
+ // cache. The per-sender submission mutex serializes calls for the same
353
+ // account, so this cannot race a nonce fetch.
354
+ _ethGetCodeProbeCount++;
355
+ const codeJson = await rpcRequest({
356
+ url: rpcUrl,
320
357
  headers: { 'Content-Type': 'application/json' },
321
- body: JSON.stringify({
322
- jsonrpc: '2.0', id: 1, method: 'eth_getCode',
323
- params: [sender, 'latest'],
324
- }),
358
+ method: 'eth_getCode',
359
+ params: [sender, 'latest'],
325
360
  });
326
- const codeJson = await codeResp.json() as { result?: string };
327
- const isDeployed = codeJson.result && codeJson.result !== '0x' && codeJson.result !== '0x0';
361
+ // A JSON-RPC error envelope (e.g. a rate-limited public RPC) or a
362
+ // non-string result is NOT evidence the account is undeployed. Treat it as
363
+ // a hard failure and throw — otherwise we would attach initCode to a
364
+ // possibly-deployed sender, guaranteeing AA10 "sender already constructed"
365
+ // at the paymaster. The thrown error propagates to the submit retry-loop
366
+ // catch; it does not match the AA25/AA10 regex, so it fails fast with an
367
+ // accurate message rather than poisoning a UserOp. Only a literal '0x' /
368
+ // '0x0' result means "not deployed" (#402).
369
+ const codeResult = codeJson.result;
370
+ if (codeJson.error || typeof codeResult !== 'string') {
371
+ throw new Error('eth_getCode failed: ' + (codeJson.error?.message || 'no result'));
372
+ }
373
+ const isDeployed = codeResult !== '0x' && codeResult !== '0x0';
328
374
 
329
375
  if (isDeployed) {
330
- deployedAccounts.add(sender.toLowerCase());
331
376
  return { factory: null, factoryData: null };
332
377
  }
333
378
 
@@ -344,7 +389,7 @@ async function getInitCode(
344
389
  }
345
390
 
346
391
  // ---------------------------------------------------------------------------
347
- // On-chain submission (ERC-4337 UserOps via raw fetch)
392
+ // On-chain submission (ERC-4337 UserOps via relay.ts network site)
348
393
  // ---------------------------------------------------------------------------
349
394
 
350
395
  /**
@@ -356,7 +401,7 @@ async function getInitCode(
356
401
  * 3. UserOp hashing (ERC-4337 v0.7)
357
402
  * 4. ECDSA signing (EIP-191 prefixed)
358
403
  *
359
- * All JSON-RPC calls go through raw fetch() to the relay bundler endpoint.
404
+ * All JSON-RPC calls go through `relay.ts` to the relay bundler endpoint.
360
405
  */
361
406
  export async function submitFactOnChain(
362
407
  protobufPayload: Buffer,
@@ -397,7 +442,7 @@ async function submitFactOnChainLocked(
397
442
 
398
443
  // Helper for JSON-RPC calls to relay bundler (with 429 retry)
399
444
  async function rpc(method: string, params: unknown[]): Promise<any> {
400
- return rpcWithRetry(bundlerUrl, headers, method, params);
445
+ return rpcWithRetry({ url: bundlerUrl, headers, method, params });
401
446
  }
402
447
 
403
448
  const entryPoint = config.entryPointAddress || getWasm().getEntryPointAddress();
@@ -412,9 +457,6 @@ async function submitFactOnChainLocked(
412
457
 
413
458
  const rpcUrl = config.rpcUrl || CONFIG.rpcUrl || getDefaultRpcUrl(config.chainId);
414
459
 
415
- // 4. Check if Smart Account is deployed (needed for factory/factoryData)
416
- const { factory, factoryData } = await getInitCode(sender, eoa.address, rpcUrl);
417
-
418
460
  // 5. Get nonce from EntryPoint via bundler RPC.
419
461
  // Routing through the bundler lets Pimlico account for pending mempool
420
462
  // UserOps, preventing AA25 nonce conflicts on rapid submissions.
@@ -425,89 +467,56 @@ async function submitFactOnChainLocked(
425
467
  const keyPadded = '0'.repeat(64);
426
468
  const nonceCalldata = `0x35567e1a${senderPadded}${keyPadded}`;
427
469
 
428
- let nonce: string;
429
- try {
430
- const nonceResult = await rpc('eth_call', [{ to: entryPoint, data: nonceCalldata }, 'latest']);
431
- nonce = nonceResult || '0x0';
432
- } catch {
433
- // Fallback to public RPC if bundler doesn't support eth_call
434
- const nonceResp = await fetch(rpcUrl, {
435
- method: 'POST',
436
- headers: { 'Content-Type': 'application/json' },
437
- body: JSON.stringify({
438
- jsonrpc: '2.0', id: 1, method: 'eth_call',
470
+ // Helper to fetch nonce (with bundler fallback)
471
+ async function fetchNonce(): Promise<string> {
472
+ try {
473
+ const nonceResult = await rpc('eth_call', [{ to: entryPoint, data: nonceCalldata }, 'latest']);
474
+ return nonceResult || '0x0';
475
+ } catch {
476
+ // Fallback to public RPC if bundler doesn't support eth_call
477
+ const nonceJson = await rpcRequest({
478
+ url: rpcUrl,
479
+ headers: { 'Content-Type': 'application/json' },
480
+ method: 'eth_call',
439
481
  params: [{ to: entryPoint, data: nonceCalldata }, 'latest'],
440
- }),
441
- });
442
- const nonceJson = await nonceResp.json() as { result?: string };
443
- nonce = nonceJson.result || '0x0';
482
+ });
483
+ return (nonceJson.result as string) || '0x0';
484
+ }
444
485
  }
445
486
 
446
- // 6. Build unsigned UserOp (v0.7 fields, camelCase for Rust JSON serde)
447
- const unsignedOp: Record<string, any> = {
448
- sender,
449
- nonce,
450
- callData,
451
- callGasLimit: '0x0',
452
- verificationGasLimit: '0x0',
453
- preVerificationGas: '0x0',
454
- maxFeePerGas: fast.maxFeePerGas,
455
- maxPriorityFeePerGas: fast.maxPriorityFeePerGas,
456
- signature: DUMMY_SIGNATURE,
457
- };
458
- if (factory) {
459
- unsignedOp.factory = factory;
460
- unsignedOp.factoryData = factoryData;
461
- }
487
+ // Track force-deployed senders for AA10 retry (local to this submission attempt)
488
+ const forceDeployed = new Set<string>();
462
489
 
463
- // 7. Get paymaster sponsorship (fills gas limits + paymaster fields)
464
- const sponsorResult = await rpc('pm_sponsorUserOperation', [unsignedOp, entryPoint]);
465
- Object.assign(unsignedOp, sponsorResult);
490
+ // Single retry loop: getInitCode build UserOp sponsor → sign → send
491
+ // On AA10 "sender already constructed", mark sender as force-deployed and retry.
492
+ // AA10 can occur at pm_sponsorUserOperation (initCode present on deployed sender)
493
+ // or eth_sendUserOperation (same root cause). This loop handles both.
494
+ let userOpHash: string | undefined;
495
+ let lastErr: any;
496
+ let attempt = 0;
497
+ const maxAttempts = 2;
466
498
 
467
- // 8. Hash and sign the UserOp via WASM
468
- const opJson = JSON.stringify(unsignedOp);
469
- const hashHex = getWasm().hashUserOp(opJson, entryPoint, BigInt(config.chainId));
470
- const sigHex = getWasm().signUserOp(hashHex, eoa.private_key);
471
- unsignedOp.signature = `0x${sigHex}`;
499
+ while (attempt < maxAttempts) {
500
+ attempt++;
472
501
 
473
- // 9. Submit the signed UserOp (with AA25 nonce conflict retry)
474
- let userOpHash: string;
475
- try {
476
- userOpHash = await rpc('eth_sendUserOperation', [unsignedOp, entryPoint]);
477
- } catch (err: any) {
478
- const msg = err?.message || '';
479
- if (/AA25|AA10|invalid account nonce|already being processed/i.test(msg)) {
480
- console.error('AA25/AA10 nonce conflict detected, rebuilding UserOp with fresh nonce...');
481
- // Bust deployment cache so getInitCode re-checks on-chain
482
- deployedAccounts.delete(sender.toLowerCase());
483
-
484
- // Wait for previous UserOp to mine before retrying with fresh nonce.
485
- // Public RPC won't reflect the new nonce until the tx is on-chain.
486
- await new Promise(r => setTimeout(r, 15000));
487
-
488
- // Re-fetch initCode and nonce
489
- const { factory: retryFactory, factoryData: retryFactoryData } = await getInitCode(sender, eoa.address, rpcUrl);
490
- let retryNonce: string;
491
- try {
492
- const retryNonceResult = await rpc('eth_call', [{ to: entryPoint, data: nonceCalldata }, 'latest']);
493
- retryNonce = retryNonceResult || '0x0';
494
- } catch {
495
- const retryNonceResp = await fetch(rpcUrl, {
496
- method: 'POST',
497
- headers: { 'Content-Type': 'application/json' },
498
- body: JSON.stringify({
499
- jsonrpc: '2.0', id: 1, method: 'eth_call',
500
- params: [{ to: entryPoint, data: nonceCalldata }, 'latest'],
501
- }),
502
- });
503
- const retryNonceJson = await retryNonceResp.json() as { result?: string };
504
- retryNonce = retryNonceJson.result || '0x0';
502
+ try {
503
+ // 4. Check if Smart Account is deployed (needed for factory/factoryData)
504
+ // If force-deployed, skip eth_getCode and return null initCode.
505
+ let factory: string | null = null;
506
+ let factoryData: string | null = null;
507
+ if (!forceDeployed.has(sender.toLowerCase())) {
508
+ const initCode = await getInitCode(sender, eoa.address, rpcUrl);
509
+ factory = initCode.factory;
510
+ factoryData = initCode.factoryData;
505
511
  }
506
512
 
507
- // Rebuild unsigned UserOp with fresh nonce and initCode
508
- const retryOp: Record<string, any> = {
513
+ // Fetch fresh nonce for each attempt
514
+ const nonce = await fetchNonce();
515
+
516
+ // 6. Build unsigned UserOp (v0.7 fields, camelCase for Rust JSON serde)
517
+ const unsignedOp: Record<string, any> = {
509
518
  sender,
510
- nonce: retryNonce,
519
+ nonce,
511
520
  callData,
512
521
  callGasLimit: '0x0',
513
522
  verificationGasLimit: '0x0',
@@ -516,25 +525,57 @@ async function submitFactOnChainLocked(
516
525
  maxPriorityFeePerGas: fast.maxPriorityFeePerGas,
517
526
  signature: DUMMY_SIGNATURE,
518
527
  };
519
- if (retryFactory) {
520
- retryOp.factory = retryFactory;
521
- retryOp.factoryData = retryFactoryData;
528
+ if (factory) {
529
+ unsignedOp.factory = factory;
530
+ unsignedOp.factoryData = factoryData;
522
531
  }
523
532
 
524
- // Re-sponsor and re-sign
525
- const retrySponsor = await rpc('pm_sponsorUserOperation', [retryOp, entryPoint]);
526
- Object.assign(retryOp, retrySponsor);
527
- const retryOpJson = JSON.stringify(retryOp);
528
- const retryHashHex = getWasm().hashUserOp(retryOpJson, entryPoint, BigInt(config.chainId));
529
- const retrySigHex = getWasm().signUserOp(retryHashHex, eoa.private_key);
530
- retryOp.signature = `0x${retrySigHex}`;
531
-
532
- userOpHash = await rpc('eth_sendUserOperation', [retryOp, entryPoint]);
533
- } else {
533
+ // 7. Get paymaster sponsorship (fills gas limits + paymaster fields)
534
+ // This is where AA10 "sender already constructed" can occur if initCode
535
+ // is present but the sender is already deployed.
536
+ const sponsorResult = await rpc('pm_sponsorUserOperation', [unsignedOp, entryPoint]);
537
+ Object.assign(unsignedOp, sponsorResult);
538
+
539
+ // 8. Hash and sign the UserOp via WASM
540
+ const opJson = JSON.stringify(unsignedOp);
541
+ const hashHex = getWasm().hashUserOp(opJson, entryPoint, BigInt(config.chainId));
542
+ const sigHex = signUserOp(hashHex, eoa.private_key);
543
+ unsignedOp.signature = `0x${sigHex}`;
544
+
545
+ // 9. Submit the signed UserOp
546
+ userOpHash = await rpc('eth_sendUserOperation', [unsignedOp, entryPoint]);
547
+ // Success — break out of retry loop
548
+ break;
549
+ } catch (err: any) {
550
+ const msg = err?.message || '';
551
+ // AA10 "sender already constructed" or AA25 invalid nonce → retry
552
+ if (/AA25|AA10|invalid account nonce|already being processed/i.test(msg)) {
553
+ lastErr = err;
554
+ console.error(`AA25/AA10 detected (attempt ${attempt}/${maxAttempts}), retrying...`);
555
+ // On AA10, force-mark sender as deployed so next retry omits initCode
556
+ if (/AA10/i.test(msg)) {
557
+ forceDeployed.add(sender.toLowerCase());
558
+ console.error('AA10: force-marking sender as deployed, retrying without initCode');
559
+ }
560
+ // Wait for previous UserOp to mine before retrying with fresh nonce.
561
+ // Public RPC won't reflect the new nonce until the tx is on-chain.
562
+ await new Promise(r => setTimeout(r, 15000));
563
+ // Continue to next iteration of retry loop
564
+ continue;
565
+ }
566
+ // Not a retryable error — re-throw
534
567
  throw err;
535
568
  }
536
569
  }
537
570
 
571
+ // Retry budget exhausted with no successful submission — throw the last
572
+ // retryable error instead of falling through to a receipt poll against an
573
+ // undefined userOpHash (which used to burn 120s and surface a misleading
574
+ // 'submission failed (tx=…)'). See #402.
575
+ if (userOpHash == null) {
576
+ throw lastErr ?? new Error('eth_sendUserOperation returned no result');
577
+ }
578
+
538
579
  // 10. Wait for receipt (poll up to 120s)
539
580
  let receipt = null;
540
581
  for (let i = 0; i < 60; i++) {
@@ -547,10 +588,10 @@ async function submitFactOnChainLocked(
547
588
 
548
589
  const success = receipt?.success ?? false;
549
590
 
550
- // Mark account as deployed after first successful submission
551
- if (success) {
552
- deployedAccounts.add(sender.toLowerCase());
553
- }
591
+ // No session-deployment cache to update getInitCode always re-checks
592
+ // eth_getCode on the next submission, so a successful receipt needs no
593
+ // bookkeeping here. (Previous cache removed in the AA10 fix — see note
594
+ // at the top of this section.)
554
595
 
555
596
  return {
556
597
  txHash: receipt?.receipt?.transactionHash || '',
@@ -614,7 +655,7 @@ async function submitFactBatchOnChainLocked(
614
655
 
615
656
  // Helper for JSON-RPC calls to relay bundler (with 429 retry)
616
657
  async function rpc(method: string, params: unknown[]): Promise<any> {
617
- return rpcWithRetry(bundlerUrl, headers, method, params);
658
+ return rpcWithRetry({ url: bundlerUrl, headers, method, params });
618
659
  }
619
660
  const entryPoint = config.entryPointAddress || getWasm().getEntryPointAddress();
620
661
 
@@ -630,110 +671,58 @@ async function submitFactBatchOnChainLocked(
630
671
 
631
672
  const rpcUrl = config.rpcUrl || CONFIG.rpcUrl || getDefaultRpcUrl(config.chainId);
632
673
 
633
- // Check if Smart Account is deployed (needed for factory/factoryData)
634
- const { factory, factoryData } = await getInitCode(sender, eoa.address, rpcUrl);
635
-
636
674
  // Get nonce via bundler (accounts for pending mempool UserOps) with public RPC fallback
637
675
  const senderPadded = sender.slice(2).toLowerCase().padStart(64, '0');
638
676
  const keyPadded = '0'.repeat(64);
639
677
  const nonceCalldata = `0x35567e1a${senderPadded}${keyPadded}`;
640
678
 
641
- let nonce: string;
642
- try {
643
- const nonceResult = await rpc('eth_call', [{ to: entryPoint, data: nonceCalldata }, 'latest']);
644
- nonce = nonceResult || '0x0';
645
- } catch {
646
- const nonceResp = await fetch(rpcUrl, {
647
- method: 'POST',
648
- headers: { 'Content-Type': 'application/json' },
649
- body: JSON.stringify({
650
- jsonrpc: '2.0', id: 1, method: 'eth_call',
651
- params: [{ to: entryPoint, data: nonceCalldata }, 'latest'],
652
- }),
653
- });
654
- const nonceJson = await nonceResp.json() as { result?: string };
655
- nonce = nonceJson.result || '0x0';
656
- }
657
-
658
- // Build unsigned UserOp
659
- const unsignedOp: Record<string, any> = {
660
- sender,
661
- nonce,
662
- callData,
663
- callGasLimit: '0x0',
664
- verificationGasLimit: '0x0',
665
- preVerificationGas: '0x0',
666
- maxFeePerGas: fast.maxFeePerGas,
667
- maxPriorityFeePerGas: fast.maxPriorityFeePerGas,
668
- signature: DUMMY_SIGNATURE,
669
- };
670
- if (factory) {
671
- unsignedOp.factory = factory;
672
- unsignedOp.factoryData = factoryData;
673
- }
674
-
675
- // Gas estimation for batch operations — get accurate gas limits from Pimlico
676
- // before paymaster sponsorship (can't bump after sponsorship as it invalidates
677
- // the paymaster's signature, causing AA34).
678
- if (protobufPayloads.length > 1) {
679
+ // Helper to fetch nonce (with bundler fallback)
680
+ async function fetchNonce(): Promise<string> {
679
681
  try {
680
- const gasEstimate = await rpc('eth_estimateUserOperationGas', [unsignedOp, entryPoint]);
681
- if (gasEstimate.callGasLimit) unsignedOp.callGasLimit = gasEstimate.callGasLimit;
682
- if (gasEstimate.verificationGasLimit) unsignedOp.verificationGasLimit = gasEstimate.verificationGasLimit;
683
- if (gasEstimate.preVerificationGas) unsignedOp.preVerificationGas = gasEstimate.preVerificationGas;
682
+ const nonceResult = await rpc('eth_call', [{ to: entryPoint, data: nonceCalldata }, 'latest']);
683
+ return nonceResult || '0x0';
684
684
  } catch {
685
- // If estimation fails, let the paymaster handle it (default behavior)
685
+ const nonceJson = await rpcRequest({
686
+ url: rpcUrl,
687
+ headers: { 'Content-Type': 'application/json' },
688
+ method: 'eth_call',
689
+ params: [{ to: entryPoint, data: nonceCalldata }, 'latest'],
690
+ });
691
+ return (nonceJson.result as string) || '0x0';
686
692
  }
687
693
  }
688
694
 
689
- // Paymaster sponsorship (uses gas limits from estimation above for batches)
690
- const sponsorResult = await rpc('pm_sponsorUserOperation', [unsignedOp, entryPoint]);
691
- Object.assign(unsignedOp, sponsorResult);
695
+ // Track force-deployed senders for AA10 retry (local to this submission attempt)
696
+ const forceDeployed = new Set<string>();
692
697
 
693
- // Hash and sign via WASM
694
- const opJson = JSON.stringify(unsignedOp);
695
- const hashHex = getWasm().hashUserOp(opJson, entryPoint, BigInt(config.chainId));
696
- const sigHex = getWasm().signUserOp(hashHex, eoa.private_key);
697
- unsignedOp.signature = `0x${sigHex}`;
698
+ // Single retry loop: getInitCode → build UserOp → estimate → sponsor → sign send
699
+ // On AA10 "sender already constructed", mark sender as force-deployed and retry.
700
+ let userOpHash: string | undefined;
701
+ let lastErr: any;
702
+ let attempt = 0;
703
+ const maxAttempts = 2;
698
704
 
699
- // Submit (with AA25 nonce conflict retry)
700
- let userOpHash: string;
701
- try {
702
- userOpHash = await rpc('eth_sendUserOperation', [unsignedOp, entryPoint]);
703
- } catch (err: any) {
704
- const msg = err?.message || '';
705
- if (/AA25|AA10|invalid account nonce|already being processed/i.test(msg)) {
706
- console.error('AA25/AA10 nonce conflict detected (batch), rebuilding UserOp with fresh nonce...');
707
- // Bust deployment cache so getInitCode re-checks on-chain
708
- deployedAccounts.delete(sender.toLowerCase());
709
-
710
- // Wait for previous UserOp to mine before retrying with fresh nonce.
711
- // Public RPC won't reflect the new nonce until the tx is on-chain.
712
- await new Promise(r => setTimeout(r, 15000));
713
-
714
- // Re-fetch initCode and nonce
715
- const { factory: retryFactory, factoryData: retryFactoryData } = await getInitCode(sender, eoa.address, rpcUrl);
716
- let retryNonce: string;
717
- try {
718
- const retryNonceResult = await rpc('eth_call', [{ to: entryPoint, data: nonceCalldata }, 'latest']);
719
- retryNonce = retryNonceResult || '0x0';
720
- } catch {
721
- const retryNonceResp = await fetch(rpcUrl, {
722
- method: 'POST',
723
- headers: { 'Content-Type': 'application/json' },
724
- body: JSON.stringify({
725
- jsonrpc: '2.0', id: 1, method: 'eth_call',
726
- params: [{ to: entryPoint, data: nonceCalldata }, 'latest'],
727
- }),
728
- });
729
- const retryNonceJson = await retryNonceResp.json() as { result?: string };
730
- retryNonce = retryNonceJson.result || '0x0';
705
+ while (attempt < maxAttempts) {
706
+ attempt++;
707
+
708
+ try {
709
+ // Check if Smart Account is deployed (needed for factory/factoryData)
710
+ // If force-deployed, skip eth_getCode and return null initCode.
711
+ let factory: string | null = null;
712
+ let factoryData: string | null = null;
713
+ if (!forceDeployed.has(sender.toLowerCase())) {
714
+ const initCode = await getInitCode(sender, eoa.address, rpcUrl);
715
+ factory = initCode.factory;
716
+ factoryData = initCode.factoryData;
731
717
  }
732
718
 
733
- // Rebuild unsigned UserOp with fresh nonce and initCode
734
- const retryOp: Record<string, any> = {
719
+ // Fetch fresh nonce for each attempt
720
+ const nonce = await fetchNonce();
721
+
722
+ // Build unsigned UserOp
723
+ const unsignedOp: Record<string, any> = {
735
724
  sender,
736
- nonce: retryNonce,
725
+ nonce,
737
726
  callData,
738
727
  callGasLimit: '0x0',
739
728
  verificationGasLimit: '0x0',
@@ -742,25 +731,71 @@ async function submitFactBatchOnChainLocked(
742
731
  maxPriorityFeePerGas: fast.maxPriorityFeePerGas,
743
732
  signature: DUMMY_SIGNATURE,
744
733
  };
745
- if (retryFactory) {
746
- retryOp.factory = retryFactory;
747
- retryOp.factoryData = retryFactoryData;
734
+ if (factory) {
735
+ unsignedOp.factory = factory;
736
+ unsignedOp.factoryData = factoryData;
748
737
  }
749
738
 
750
- // Re-sponsor and re-sign
751
- const retrySponsor = await rpc('pm_sponsorUserOperation', [retryOp, entryPoint]);
752
- Object.assign(retryOp, retrySponsor);
753
- const retryOpJson = JSON.stringify(retryOp);
754
- const retryHashHex = getWasm().hashUserOp(retryOpJson, entryPoint, BigInt(config.chainId));
755
- const retrySigHex = getWasm().signUserOp(retryHashHex, eoa.private_key);
756
- retryOp.signature = `0x${retrySigHex}`;
739
+ // Gas estimation for batch operations — get accurate gas limits from Pimlico
740
+ // before paymaster sponsorship (can't bump after sponsorship as it invalidates
741
+ // the paymaster's signature, causing AA34).
742
+ if (protobufPayloads.length > 1) {
743
+ try {
744
+ const gasEstimate = await rpc('eth_estimateUserOperationGas', [unsignedOp, entryPoint]);
745
+ if (gasEstimate.callGasLimit) unsignedOp.callGasLimit = gasEstimate.callGasLimit;
746
+ if (gasEstimate.verificationGasLimit) unsignedOp.verificationGasLimit = gasEstimate.verificationGasLimit;
747
+ if (gasEstimate.preVerificationGas) unsignedOp.preVerificationGas = gasEstimate.preVerificationGas;
748
+ } catch {
749
+ // If estimation fails, let the paymaster handle it (default behavior)
750
+ }
751
+ }
757
752
 
758
- userOpHash = await rpc('eth_sendUserOperation', [retryOp, entryPoint]);
759
- } else {
753
+ // Paymaster sponsorship (uses gas limits from estimation above for batches)
754
+ // This is where AA10 "sender already constructed" can occur if initCode
755
+ // is present but the sender is already deployed.
756
+ const sponsorResult = await rpc('pm_sponsorUserOperation', [unsignedOp, entryPoint]);
757
+ Object.assign(unsignedOp, sponsorResult);
758
+
759
+ // Hash and sign via WASM
760
+ const opJson = JSON.stringify(unsignedOp);
761
+ const hashHex = getWasm().hashUserOp(opJson, entryPoint, BigInt(config.chainId));
762
+ const sigHex = signUserOp(hashHex, eoa.private_key);
763
+ unsignedOp.signature = `0x${sigHex}`;
764
+
765
+ // Submit the signed UserOp
766
+ userOpHash = await rpc('eth_sendUserOperation', [unsignedOp, entryPoint]);
767
+ // Success — break out of retry loop
768
+ break;
769
+ } catch (err: any) {
770
+ const msg = err?.message || '';
771
+ // AA10 "sender already constructed" or AA25 invalid nonce → retry
772
+ if (/AA25|AA10|invalid account nonce|already being processed/i.test(msg)) {
773
+ lastErr = err;
774
+ console.error(`AA25/AA10 detected (batch, attempt ${attempt}/${maxAttempts}), retrying...`);
775
+ // On AA10, force-mark sender as deployed so next retry omits initCode
776
+ if (/AA10/i.test(msg)) {
777
+ forceDeployed.add(sender.toLowerCase());
778
+ console.error('AA10: force-marking sender as deployed, retrying without initCode');
779
+ }
780
+ // Wait for previous UserOp to mine before retrying with fresh nonce.
781
+ // Public RPC won't reflect the new nonce until the tx is on-chain.
782
+ await new Promise(r => setTimeout(r, 15000));
783
+ // Continue to next iteration of retry loop
784
+ continue;
785
+ }
786
+ // Not a retryable error — re-throw
760
787
  throw err;
761
788
  }
762
789
  }
763
790
 
791
+ // Retry budget exhausted with no successful submission — throw the last
792
+ // retryable error instead of polling for a receipt against an undefined
793
+ // userOpHash (which used to burn 120s and surface a misleading
794
+ // 'submission failed (tx=…)'). See #402.
795
+ if (userOpHash == null) {
796
+ throw lastErr ?? new Error('eth_sendUserOperation returned no result');
797
+ }
798
+
764
799
  // Wait for receipt (poll up to 120s)
765
800
  let receipt = null;
766
801
  for (let i = 0; i < 60; i++) {
@@ -773,10 +808,10 @@ async function submitFactBatchOnChainLocked(
773
808
 
774
809
  const batchSuccess = receipt?.success ?? false;
775
810
 
776
- // Mark account as deployed after first successful submission
777
- if (batchSuccess) {
778
- deployedAccounts.add(sender.toLowerCase());
779
- }
811
+ // No session-deployment cache to update getInitCode always re-checks
812
+ // eth_getCode on the next submission, so a successful receipt needs no
813
+ // bookkeeping here. (Previous cache removed in the AA10 fix — see note
814
+ // at the top of the Smart Account deployment-check section.)
780
815
 
781
816
  return {
782
817
  txHash: receipt?.receipt?.transactionHash || '',