mppx 0.8.5 → 0.8.6

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 (38) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/Receipt.d.ts +20 -2
  3. package/dist/Receipt.d.ts.map +1 -1
  4. package/dist/Receipt.js +19 -12
  5. package/dist/Receipt.js.map +1 -1
  6. package/dist/cli/cli.d.ts.map +1 -1
  7. package/dist/cli/cli.js +6 -4
  8. package/dist/cli/cli.js.map +1 -1
  9. package/dist/cli/plugins/tempo.d.ts.map +1 -1
  10. package/dist/cli/plugins/tempo.js +4 -2
  11. package/dist/cli/plugins/tempo.js.map +1 -1
  12. package/dist/client/internal/Fetch.d.ts.map +1 -1
  13. package/dist/client/internal/Fetch.js +6 -1
  14. package/dist/client/internal/Fetch.js.map +1 -1
  15. package/dist/tempo/client/Charge.d.ts.map +1 -1
  16. package/dist/tempo/client/Charge.js +6 -2
  17. package/dist/tempo/client/Charge.js.map +1 -1
  18. package/dist/tempo/server/internal/html.gen.d.ts +1 -1
  19. package/dist/tempo/server/internal/html.gen.d.ts.map +1 -1
  20. package/dist/tempo/server/internal/html.gen.js +1 -1
  21. package/dist/tempo/server/internal/html.gen.js.map +1 -1
  22. package/dist/tempo/session/precompile/Chain.d.ts +26 -2
  23. package/dist/tempo/session/precompile/Chain.d.ts.map +1 -1
  24. package/dist/tempo/session/precompile/Chain.js +38 -5
  25. package/dist/tempo/session/precompile/Chain.js.map +1 -1
  26. package/package.json +1 -1
  27. package/src/Receipt.test.ts +53 -0
  28. package/src/Receipt.ts +26 -13
  29. package/src/cli/cli.test.ts +41 -5
  30. package/src/cli/cli.ts +7 -4
  31. package/src/cli/plugins/tempo.ts +6 -2
  32. package/src/client/internal/Fetch.test.ts +44 -0
  33. package/src/client/internal/Fetch.ts +5 -1
  34. package/src/tempo/client/Charge.test.ts +61 -0
  35. package/src/tempo/client/Charge.ts +6 -1
  36. package/src/tempo/server/internal/html.gen.ts +1 -1
  37. package/src/tempo/session/precompile/Chain.test.ts +121 -2
  38. package/src/tempo/session/precompile/Chain.ts +56 -6
@@ -51,6 +51,7 @@ function createMockClient(
51
51
  channel?: { descriptor: Channel.ChannelDescriptor; state: Chain.ChannelState } | undefined
52
52
  receipt?: Record<string, unknown> | null | undefined
53
53
  rpcMethods?: string[] | undefined
54
+ onRequest?: ((method: string, params: unknown) => void) | undefined
54
55
  } = {},
55
56
  ) {
56
57
  return createClient({
@@ -59,6 +60,7 @@ function createMockClient(
59
60
  transport: custom({
60
61
  async request(args) {
61
62
  parameters.rpcMethods?.push(args.method)
63
+ parameters.onRequest?.(args.method, args.params)
62
64
  if (args.method === 'eth_chainId') return `0x${chainId.toString(16)}`
63
65
  if (args.method === 'eth_sendRawTransaction') return txHash
64
66
  if (args.method === 'eth_sendRawTransactionSync') return parameters.receipt ?? receipt([])
@@ -91,7 +93,7 @@ function createMockClient(
91
93
  })
92
94
  }
93
95
 
94
- function receipt(logs: readonly Record<string, unknown>[]) {
96
+ function receipt(logs: readonly Record<string, unknown>[], transactionHash: Hex = txHash) {
95
97
  return {
96
98
  blockHash: `0x${'01'.repeat(32)}`,
97
99
  blockNumber: '0x1',
@@ -104,7 +106,7 @@ function receipt(logs: readonly Record<string, unknown>[]) {
104
106
  logsBloom: `0x${'00'.repeat(256)}`,
105
107
  status: '0x1',
106
108
  to: tip20ChannelEscrow,
107
- transactionHash: txHash,
109
+ transactionHash,
108
110
  transactionIndex: '0x0',
109
111
  type: '0x76',
110
112
  }
@@ -253,6 +255,41 @@ function expectedExpiringNonceHash(serializedTransaction: `0x${string}`) {
253
255
  )
254
256
  }
255
257
 
258
+ describe('precompile receipt wait', () => {
259
+ test('does not run replacement detection while waiting for Tempo receipts', async () => {
260
+ const requestedHash = `0x${'12'.repeat(32)}` as Hex
261
+ const rpcMethods: string[] = []
262
+ let receiptReads = 0
263
+ let blockNumber = 0n
264
+ const client = createClient({
265
+ chain: { id: chainId } as never,
266
+ pollingInterval: 1,
267
+ transport: custom({
268
+ async request(args) {
269
+ rpcMethods.push(args.method)
270
+ if (args.method === 'eth_chainId') return `0x${chainId.toString(16)}`
271
+ if (args.method === 'eth_blockNumber') {
272
+ blockNumber += 1n
273
+ return `0x${blockNumber.toString(16)}`
274
+ }
275
+ if (args.method === 'eth_getTransactionReceipt') {
276
+ receiptReads += 1
277
+ if (receiptReads === 1) return null
278
+ return receipt([], requestedHash)
279
+ }
280
+ throw new Error(`unexpected rpc request: ${args.method}`)
281
+ },
282
+ }),
283
+ })
284
+
285
+ const result = await Chain.waitForSuccessfulReceipt(client, requestedHash)
286
+
287
+ expect(result.transactionHash).toBe(requestedHash)
288
+ expect(rpcMethods).not.toContain('eth_getTransactionByHash')
289
+ expect(rpcMethods).not.toContain('eth_getBlockByNumber')
290
+ })
291
+ })
292
+
256
293
  describe('precompile open calldata parsing', () => {
257
294
  test('parseOpenCall accepts TIP-1034 open calldata', () => {
258
295
  const data = encodeFunctionData({
@@ -641,6 +678,44 @@ describe('precompile broadcastOpenTransaction', () => {
641
678
  })
642
679
  })
643
680
 
681
+ test('pins the read-back to the block that included the open transaction', async () => {
682
+ const serializedTransaction = await createOpenTransaction()
683
+ const expiringNonceHash = expectedExpiringNonceHash(serializedTransaction)
684
+ const expectedDescriptor = { ...descriptor, expiringNonceHash }
685
+ const channelId = Channel.computeId({
686
+ ...expectedDescriptor,
687
+ chainId,
688
+ escrow: tip20ChannelEscrow,
689
+ })
690
+ const state = { settled: 0n, deposit, closeRequestedAt: 0 }
691
+ // The open tx is mined in block 0x1 (see `receipt`). The read-back must be
692
+ // pinned to that block, not `latest`, so a lagging RPC replica cannot
693
+ // answer with stale/empty state.
694
+ const ethCallBlockTags: unknown[] = []
695
+
696
+ await Chain.broadcastOpenTransaction({
697
+ chainId,
698
+ client: createMockClient({
699
+ channel: { descriptor: expectedDescriptor, state },
700
+ receipt: receipt([openedLog({ channelId, expiringNonceHash })]),
701
+ onRequest: (method, params) => {
702
+ if (method === 'eth_call') ethCallBlockTags.push((params as unknown[])[1])
703
+ },
704
+ }),
705
+ escrowContract: tip20ChannelEscrow,
706
+ expectedAuthorizedSigner: descriptor.authorizedSigner,
707
+ expectedChannelId: channelId,
708
+ expectedCurrency: descriptor.token,
709
+ expectedExpiringNonceHash: expiringNonceHash,
710
+ expectedOperator: descriptor.operator,
711
+ expectedPayee: descriptor.payee,
712
+ expectedPayer: descriptor.payer,
713
+ serializedTransaction,
714
+ })
715
+
716
+ expect(ethCallBlockTags).toEqual(['0x1'])
717
+ })
718
+
644
719
  test('rejects ChannelOpened receipt deposit mismatches', async () => {
645
720
  const serializedTransaction = await createOpenTransaction()
646
721
  const expiringNonceHash = expectedExpiringNonceHash(serializedTransaction)
@@ -1256,3 +1331,47 @@ describe('Chain.assertPrecompileFeePayerPolicy', () => {
1256
1331
  }
1257
1332
  })
1258
1333
  })
1334
+
1335
+ describe('Chain.readbackWithRetry', () => {
1336
+ test('returns immediately when the read succeeds on the first attempt', async () => {
1337
+ let calls = 0
1338
+ const result = await Chain.readbackWithRetry(
1339
+ async () => {
1340
+ calls++
1341
+ return 'ok'
1342
+ },
1343
+ { delayMs: 0 },
1344
+ )
1345
+ expect(result).toBe('ok')
1346
+ expect(calls).toBe(1)
1347
+ })
1348
+
1349
+ test('retries a lagging read until it resolves', async () => {
1350
+ let calls = 0
1351
+ const result = await Chain.readbackWithRetry(
1352
+ async () => {
1353
+ calls++
1354
+ if (calls < 3) throw new Error('header not found')
1355
+ return 'ok'
1356
+ },
1357
+ { retries: 5, delayMs: 0 },
1358
+ )
1359
+ expect(result).toBe('ok')
1360
+ expect(calls).toBe(3)
1361
+ })
1362
+
1363
+ test('rethrows the last error after exhausting retries', async () => {
1364
+ let calls = 0
1365
+ await expect(
1366
+ Chain.readbackWithRetry(
1367
+ async () => {
1368
+ calls++
1369
+ throw new Error(`attempt ${calls}`)
1370
+ },
1371
+ { retries: 2, delayMs: 0 },
1372
+ ),
1373
+ ).rejects.toThrow('attempt 3')
1374
+ // 1 initial attempt + 2 retries.
1375
+ expect(calls).toBe(3)
1376
+ })
1377
+ })
@@ -293,12 +293,14 @@ export async function getChannel(
293
293
  client: Client,
294
294
  descriptor: ChannelDescriptor,
295
295
  escrow: Address = tip20ChannelEscrow,
296
+ blockNumber?: bigint,
296
297
  ): Promise<Channel> {
297
298
  const channel = await readContract(client, {
298
299
  address: escrow,
299
300
  abi: escrowAbi,
300
301
  functionName: 'getChannel',
301
302
  args: [descriptorTuple(descriptor)],
303
+ ...(blockNumber !== undefined ? { blockNumber } : {}),
302
304
  })
303
305
  return {
304
306
  descriptor: channel.descriptor,
@@ -313,12 +315,14 @@ export async function getChannelState(
313
315
  client: Client,
314
316
  channelId: Hex,
315
317
  escrow: Address = tip20ChannelEscrow,
318
+ blockNumber?: bigint,
316
319
  ): Promise<ChannelState> {
317
320
  const state = await readContract(client, {
318
321
  address: escrow,
319
322
  abi: escrowAbi,
320
323
  functionName: 'getChannelState',
321
324
  args: [channelId],
325
+ ...(blockNumber !== undefined ? { blockNumber } : {}),
322
326
  })
323
327
  return stateFromTuple(state)
324
328
  }
@@ -340,6 +344,47 @@ export async function getChannelStatesBatch(
340
344
  return states.map(stateFromTuple)
341
345
  }
342
346
 
347
+ /** Tuning for {@link readbackWithRetry}. */
348
+ export type ReadbackRetryOptions = {
349
+ /** Additional attempts after the first, before giving up. @default 5 */
350
+ retries?: number | undefined
351
+ /** Delay between attempts, in milliseconds. @default 250 */
352
+ delayMs?: number | undefined
353
+ }
354
+
355
+ /**
356
+ * Retry an on-chain readback that is pinned to the block containing a just-sent
357
+ * transaction.
358
+ *
359
+ * The escrow state read is served by a load-balanced RPC whose replicas can lag
360
+ * behind the block that produced the transaction receipt. Callers pin the read
361
+ * to that block number (via the `blockNumber` arg on {@link getChannel} /
362
+ * {@link getChannelState}) so a node that has imported the block returns
363
+ * authoritative state; replicas that have not yet imported it throw (e.g.
364
+ * "header not found"), so we retry with a short backoff until one catches up.
365
+ *
366
+ * This closes the read-after-write race behind
367
+ * `on-chain channel state does not match open receipt` — without it, a stale
368
+ * `latest` read on a lagging replica returns an empty channel and fails
369
+ * verification even though the open transaction succeeded.
370
+ */
371
+ export async function readbackWithRetry<T>(
372
+ read: () => Promise<T>,
373
+ options: ReadbackRetryOptions = {},
374
+ ): Promise<T> {
375
+ const { retries = 5, delayMs = 250 } = options
376
+ let lastError: unknown
377
+ for (let attempt = 0; attempt <= retries; attempt++) {
378
+ try {
379
+ return await read()
380
+ } catch (error) {
381
+ lastError = error
382
+ if (attempt < retries) await new Promise((resolve) => setTimeout(resolve, delayMs))
383
+ }
384
+ }
385
+ throw lastError
386
+ }
387
+
343
388
  /** Options accepted by low-level TIP-1034 on-chain management helpers. */
344
389
  export type ChannelTransactionOptions = {
345
390
  /** Account used to send the transaction when the viem client has no default account. */
@@ -586,7 +631,7 @@ export async function sendTransaction(client: TransactionClient, transaction: He
586
631
 
587
632
  /** Wait for a receipt and reject reverted precompile transactions. */
588
633
  export async function waitForSuccessfulReceipt(client: TransactionClient, hash: Hex) {
589
- const receipt = await waitForTransactionReceipt(client, { hash })
634
+ const receipt = await waitForTransactionReceipt(client, { hash, checkReplacement: false })
590
635
  if (receipt.status !== 'success')
591
636
  throw new VerificationFailedError({ reason: 'precompile transaction reverted' })
592
637
  return receipt
@@ -808,7 +853,9 @@ export async function broadcastOpenTransaction(
808
853
  expectedChannelId: parameters.expectedChannelId,
809
854
  openDeposit: open.deposit,
810
855
  })
811
- const chainChannel = await getChannel(parameters.client, descriptor, parameters.escrowContract)
856
+ const chainChannel = await readbackWithRetry(() =>
857
+ getChannel(parameters.client, descriptor, parameters.escrowContract, receipt.blockNumber),
858
+ )
812
859
  const state = chainChannel.state
813
860
  validateOpenReadbackState({ emittedDeposit: opened.deposit, state })
814
861
  return {
@@ -896,10 +943,13 @@ export async function broadcastTopUpTransaction(
896
943
  emittedChannelId: toppedUp.channelId,
897
944
  expectedChannelId: parameters.expectedChannelId,
898
945
  })
899
- const state = await getChannelState(
900
- parameters.client,
901
- toppedUp.channelId,
902
- parameters.escrowContract,
946
+ const state = await readbackWithRetry(() =>
947
+ getChannelState(
948
+ parameters.client,
949
+ toppedUp.channelId,
950
+ parameters.escrowContract,
951
+ receipt.blockNumber,
952
+ ),
903
953
  )
904
954
  validateTopUpReadbackState({ newDeposit: toppedUp.newDeposit, state })
905
955
  return { txHash: receipt.transactionHash, newDeposit: toppedUp.newDeposit, state }