mppx 0.8.4 → 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.
- package/CHANGELOG.md +18 -0
- package/dist/Receipt.d.ts +20 -2
- package/dist/Receipt.d.ts.map +1 -1
- package/dist/Receipt.js +19 -12
- package/dist/Receipt.js.map +1 -1
- package/dist/cli/cli.d.ts.map +1 -1
- package/dist/cli/cli.js +6 -4
- package/dist/cli/cli.js.map +1 -1
- package/dist/cli/plugins/tempo.d.ts.map +1 -1
- package/dist/cli/plugins/tempo.js +4 -2
- package/dist/cli/plugins/tempo.js.map +1 -1
- package/dist/client/internal/Fetch.d.ts.map +1 -1
- package/dist/client/internal/Fetch.js +6 -1
- package/dist/client/internal/Fetch.js.map +1 -1
- package/dist/evm/client/Charge.d.ts +2 -2
- package/dist/evm/client/Charge.d.ts.map +1 -1
- package/dist/evm/client/Charge.js +11 -17
- package/dist/evm/client/Charge.js.map +1 -1
- package/dist/evm/server/Charge.d.ts +5 -5
- package/dist/evm/server/Charge.d.ts.map +1 -1
- package/dist/evm/server/Charge.js +15 -7
- package/dist/evm/server/Charge.js.map +1 -1
- package/dist/tempo/client/Charge.d.ts.map +1 -1
- package/dist/tempo/client/Charge.js +6 -2
- package/dist/tempo/client/Charge.js.map +1 -1
- package/dist/tempo/server/internal/html.gen.d.ts +1 -1
- package/dist/tempo/server/internal/html.gen.d.ts.map +1 -1
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/server/internal/html.gen.js.map +1 -1
- package/dist/tempo/session/precompile/Chain.d.ts +26 -2
- package/dist/tempo/session/precompile/Chain.d.ts.map +1 -1
- package/dist/tempo/session/precompile/Chain.js +38 -5
- package/dist/tempo/session/precompile/Chain.js.map +1 -1
- package/dist/x402/Assets.d.ts +40 -0
- package/dist/x402/Assets.d.ts.map +1 -1
- package/dist/x402/Assets.js +73 -0
- package/dist/x402/Assets.js.map +1 -1
- package/dist/x402/client/Exact.d.ts +2 -2
- package/dist/x402/client/Exact.d.ts.map +1 -1
- package/dist/x402/client/Exact.js +6 -13
- package/dist/x402/client/Exact.js.map +1 -1
- package/package.json +1 -1
- package/src/Receipt.test.ts +53 -0
- package/src/Receipt.ts +26 -13
- package/src/cli/cli.test.ts +41 -5
- package/src/cli/cli.ts +7 -4
- package/src/cli/plugins/tempo.ts +6 -2
- package/src/client/internal/Fetch.test.ts +44 -0
- package/src/client/internal/Fetch.ts +5 -1
- package/src/evm/PublicInterface.test-d.ts +15 -2
- package/src/evm/client/Charge.test.ts +248 -0
- package/src/evm/client/Charge.ts +12 -23
- package/src/evm/server/Charge.test.ts +140 -0
- package/src/evm/server/Charge.ts +19 -12
- package/src/tempo/client/Charge.test.ts +61 -0
- package/src/tempo/client/Charge.ts +6 -1
- package/src/tempo/server/internal/html.gen.ts +1 -1
- package/src/tempo/session/precompile/Chain.test.ts +121 -2
- package/src/tempo/session/precompile/Chain.ts +56 -6
- package/src/x402/Assets.test.ts +211 -0
- package/src/x402/Assets.ts +116 -0
- package/src/x402/client/Exact.test.ts +129 -0
- package/src/x402/client/Exact.ts +7 -19
|
@@ -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
|
|
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
|
|
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
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
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 }
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { usdc } from 'viem/tokens'
|
|
2
|
+
import { describe, expect, test } from 'vp/test'
|
|
3
|
+
|
|
4
|
+
import * as Assets from './Assets.js'
|
|
5
|
+
|
|
6
|
+
describe('x402 assets', () => {
|
|
7
|
+
test('defines branded asset metadata', () => {
|
|
8
|
+
const asset = Assets.define({
|
|
9
|
+
address: '0x1111111111111111111111111111111111111111',
|
|
10
|
+
decimals: 18,
|
|
11
|
+
network: 'eip155:1',
|
|
12
|
+
transfer: {
|
|
13
|
+
name: 'USD Coin',
|
|
14
|
+
type: 'eip3009',
|
|
15
|
+
version: '2',
|
|
16
|
+
},
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
expect(Assets.isAsset(asset)).toBe(true)
|
|
20
|
+
expect(asset).toMatchObject({
|
|
21
|
+
address: '0x1111111111111111111111111111111111111111',
|
|
22
|
+
decimals: 18,
|
|
23
|
+
network: 'eip155:1',
|
|
24
|
+
transfer: {
|
|
25
|
+
name: 'USD Coin',
|
|
26
|
+
type: 'eip3009',
|
|
27
|
+
version: '2',
|
|
28
|
+
},
|
|
29
|
+
})
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
test('rejects unbranded values', () => {
|
|
33
|
+
expect(Assets.isAsset(null)).toBe(false)
|
|
34
|
+
expect(Assets.isAsset('0x1111111111111111111111111111111111111111')).toBe(false)
|
|
35
|
+
expect(
|
|
36
|
+
Assets.isAsset({
|
|
37
|
+
address: '0x1111111111111111111111111111111111111111',
|
|
38
|
+
decimals: 18,
|
|
39
|
+
network: 'eip155:1',
|
|
40
|
+
transfer: {
|
|
41
|
+
name: 'USD Coin',
|
|
42
|
+
type: 'eip3009',
|
|
43
|
+
version: '2',
|
|
44
|
+
},
|
|
45
|
+
}),
|
|
46
|
+
).toBe(false)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
test('defines asset metadata from viem tokens', () => {
|
|
50
|
+
const asset = Assets.fromToken(usdc, {
|
|
51
|
+
chainId: 84532,
|
|
52
|
+
transfer: {
|
|
53
|
+
type: 'eip3009',
|
|
54
|
+
version: '2',
|
|
55
|
+
},
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
expect(Assets.isAsset(asset)).toBe(true)
|
|
59
|
+
expect(asset).toMatchObject({
|
|
60
|
+
address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',
|
|
61
|
+
decimals: 6,
|
|
62
|
+
network: 'eip155:84532',
|
|
63
|
+
transfer: {
|
|
64
|
+
name: 'USD Coin',
|
|
65
|
+
type: 'eip3009',
|
|
66
|
+
version: '2',
|
|
67
|
+
},
|
|
68
|
+
})
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
test('allows viem token transfer metadata overrides', () => {
|
|
72
|
+
const eip3009Asset = Assets.fromToken(usdc, {
|
|
73
|
+
chainId: 84532,
|
|
74
|
+
transfer: {
|
|
75
|
+
name: 'USDC',
|
|
76
|
+
type: 'eip3009',
|
|
77
|
+
version: '2',
|
|
78
|
+
},
|
|
79
|
+
})
|
|
80
|
+
const permit2Asset = Assets.fromToken(usdc, {
|
|
81
|
+
chainId: 84532,
|
|
82
|
+
transfer: {
|
|
83
|
+
type: 'permit2',
|
|
84
|
+
},
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
expect(eip3009Asset.transfer).toEqual({
|
|
88
|
+
name: 'USDC',
|
|
89
|
+
type: 'eip3009',
|
|
90
|
+
version: '2',
|
|
91
|
+
})
|
|
92
|
+
expect(permit2Asset.transfer).toEqual({
|
|
93
|
+
type: 'permit2',
|
|
94
|
+
})
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
test('requires token names for EIP-3009 viem token assets', () => {
|
|
98
|
+
const tokenWithoutName = Object.assign(
|
|
99
|
+
() => ({
|
|
100
|
+
address: '0x1111111111111111111111111111111111111111',
|
|
101
|
+
decimals: 6,
|
|
102
|
+
symbol: 'TEST',
|
|
103
|
+
}),
|
|
104
|
+
{
|
|
105
|
+
addresses: { 1: '0x1111111111111111111111111111111111111111' },
|
|
106
|
+
decimals: 6,
|
|
107
|
+
},
|
|
108
|
+
) as unknown as Assets.ViemToken
|
|
109
|
+
|
|
110
|
+
expect(() =>
|
|
111
|
+
Assets.fromToken(tokenWithoutName, {
|
|
112
|
+
chainId: 1,
|
|
113
|
+
transfer: {
|
|
114
|
+
type: 'eip3009',
|
|
115
|
+
version: '2',
|
|
116
|
+
},
|
|
117
|
+
}),
|
|
118
|
+
).toThrow('EIP-3009 token assets require a token name.')
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
test('identifies currency kinds and converts networks', () => {
|
|
122
|
+
expect(Assets.isToken(usdc)).toBe(true)
|
|
123
|
+
expect(Assets.isToken(Assets.baseSepolia.USDC)).toBe(false)
|
|
124
|
+
expect(Assets.isRawAddress('0x1111111111111111111111111111111111111111')).toBe(true)
|
|
125
|
+
expect(Assets.isRawAddress(Assets.baseSepolia.USDC)).toBe(false)
|
|
126
|
+
expect(Assets.toNetwork(84532)).toBe('eip155:84532')
|
|
127
|
+
expect(Assets.toChainId('eip155:84532')).toBe(84532)
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
test('resolves and matches raw addresses, known assets, and viem tokens', () => {
|
|
131
|
+
expect(Assets.resolve('0x1111111111111111111111111111111111111111', 'eip155:84532')).toEqual({
|
|
132
|
+
address: '0x1111111111111111111111111111111111111111',
|
|
133
|
+
})
|
|
134
|
+
expect(Assets.resolve(Assets.baseSepolia.USDC, 'eip155:84532')).toEqual({
|
|
135
|
+
address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',
|
|
136
|
+
decimals: 6,
|
|
137
|
+
transfer: {
|
|
138
|
+
name: 'USDC',
|
|
139
|
+
type: 'eip3009',
|
|
140
|
+
version: '2',
|
|
141
|
+
},
|
|
142
|
+
})
|
|
143
|
+
expect(Assets.resolve(Assets.baseSepolia.USDC, 'eip155:8453')).toBeUndefined()
|
|
144
|
+
expect(Assets.resolve(usdc, 'eip155:84532')).toEqual({
|
|
145
|
+
address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',
|
|
146
|
+
decimals: 6,
|
|
147
|
+
name: 'USD Coin',
|
|
148
|
+
})
|
|
149
|
+
expect(Assets.resolve(usdc, 'eip155:999999')).toBeUndefined()
|
|
150
|
+
expect(Assets.matches(usdc, '0x036CbD53842c5426634e7929541eC2318f3dCF7e', 'eip155:84532')).toBe(
|
|
151
|
+
true,
|
|
152
|
+
)
|
|
153
|
+
expect(Assets.matches(usdc, '0x036cbd53842c5426634e7929541ec2318f3dcf7e', 'eip155:84532')).toBe(
|
|
154
|
+
true,
|
|
155
|
+
)
|
|
156
|
+
expect(
|
|
157
|
+
Assets.matches(
|
|
158
|
+
'0x1111111111111111111111111111111111111111',
|
|
159
|
+
'0x1111111111111111111111111111111111111111',
|
|
160
|
+
'eip155:84532',
|
|
161
|
+
),
|
|
162
|
+
).toBe(true)
|
|
163
|
+
expect(
|
|
164
|
+
Assets.matches(
|
|
165
|
+
Assets.baseSepolia.USDC,
|
|
166
|
+
'0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
|
|
167
|
+
'eip155:84532',
|
|
168
|
+
),
|
|
169
|
+
).toBe(false)
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
test('throws when creating assets from tokens unavailable on a chain', () => {
|
|
173
|
+
expect(() =>
|
|
174
|
+
Assets.fromToken(usdc, {
|
|
175
|
+
chainId: 999_999,
|
|
176
|
+
transfer: {
|
|
177
|
+
type: 'eip3009',
|
|
178
|
+
version: '2',
|
|
179
|
+
},
|
|
180
|
+
}),
|
|
181
|
+
).toThrow('Token has no address for chain id "999999".')
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
test('exports Base USDC metadata', () => {
|
|
185
|
+
expect(Assets.isAsset(Assets.base.USDC)).toBe(true)
|
|
186
|
+
expect(Assets.base.USDC).toMatchObject({
|
|
187
|
+
address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
|
|
188
|
+
decimals: 6,
|
|
189
|
+
network: 'eip155:8453',
|
|
190
|
+
transfer: {
|
|
191
|
+
name: 'USD Coin',
|
|
192
|
+
type: 'eip3009',
|
|
193
|
+
version: '2',
|
|
194
|
+
},
|
|
195
|
+
})
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
test('exports Base Sepolia USDC metadata', () => {
|
|
199
|
+
expect(Assets.isAsset(Assets.baseSepolia.USDC)).toBe(true)
|
|
200
|
+
expect(Assets.baseSepolia.USDC).toMatchObject({
|
|
201
|
+
address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',
|
|
202
|
+
decimals: 6,
|
|
203
|
+
network: 'eip155:84532',
|
|
204
|
+
transfer: {
|
|
205
|
+
name: 'USDC',
|
|
206
|
+
type: 'eip3009',
|
|
207
|
+
version: '2',
|
|
208
|
+
},
|
|
209
|
+
})
|
|
210
|
+
})
|
|
211
|
+
})
|
package/src/x402/Assets.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { getAddress } from 'viem'
|
|
2
|
+
import type { Token } from 'viem/tokens'
|
|
3
|
+
|
|
1
4
|
import type { Asset, EvmNetwork, ExactTransfer } from './Types.js'
|
|
2
5
|
|
|
3
6
|
const knownAsset = Symbol('mppx.x402.asset')
|
|
@@ -8,6 +11,12 @@ export type KnownAsset = Asset & {
|
|
|
8
11
|
network: EvmNetwork
|
|
9
12
|
}
|
|
10
13
|
|
|
14
|
+
/** Viem token metadata from `viem/tokens`. */
|
|
15
|
+
export type ViemToken = Token
|
|
16
|
+
|
|
17
|
+
/** Currency metadata accepted by EVM and x402 payment config. */
|
|
18
|
+
export type Currency = `0x${string}` | KnownAsset | ViemToken
|
|
19
|
+
|
|
11
20
|
/** Creates typed x402 asset metadata for custom tokens. */
|
|
12
21
|
export function define(parameters: define.Parameters): KnownAsset {
|
|
13
22
|
return {
|
|
@@ -28,6 +37,30 @@ export declare namespace define {
|
|
|
28
37
|
}
|
|
29
38
|
}
|
|
30
39
|
|
|
40
|
+
/** Creates x402 asset metadata from a `viem/tokens` token definition. */
|
|
41
|
+
export function fromToken(token: ViemToken, parameters: fromToken.Parameters): KnownAsset {
|
|
42
|
+
const resolved = token(parameters.chainId)
|
|
43
|
+
return define({
|
|
44
|
+
address: resolved.address,
|
|
45
|
+
decimals: resolved.decimals,
|
|
46
|
+
network: toNetwork(parameters.chainId),
|
|
47
|
+
transfer: withTokenDefaults(parameters.transfer, resolved),
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export declare namespace fromToken {
|
|
52
|
+
type Parameters = {
|
|
53
|
+
chainId: number
|
|
54
|
+
transfer: Transfer
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
type Transfer =
|
|
58
|
+
| (Omit<Extract<ExactTransfer, { type: 'eip3009' }>, 'name'> & {
|
|
59
|
+
name?: string | undefined
|
|
60
|
+
})
|
|
61
|
+
| Extract<ExactTransfer, { type: 'permit2' }>
|
|
62
|
+
}
|
|
63
|
+
|
|
31
64
|
/** Base network known assets. */
|
|
32
65
|
export const base = {
|
|
33
66
|
USDC: define({
|
|
@@ -63,3 +96,86 @@ export function isAsset(value: unknown): value is KnownAsset {
|
|
|
63
96
|
if (typeof value !== 'object' || value === null) return false
|
|
64
97
|
return (value as Partial<KnownAsset>)[knownAsset] === true
|
|
65
98
|
}
|
|
99
|
+
|
|
100
|
+
/** Returns true when a value is a `viem/tokens` token definition. */
|
|
101
|
+
export function isToken(value: unknown): value is ViemToken {
|
|
102
|
+
return (
|
|
103
|
+
typeof value === 'function' &&
|
|
104
|
+
typeof (value as Partial<ViemToken>).addresses === 'object' &&
|
|
105
|
+
typeof (value as Partial<ViemToken>).decimals === 'number'
|
|
106
|
+
)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Returns true when a currency is a raw address without chain metadata. */
|
|
110
|
+
export function isRawAddress(currency: Currency): currency is `0x${string}` {
|
|
111
|
+
return typeof currency === 'string'
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Resolves currency metadata for an EVM network. */
|
|
115
|
+
export function resolve(currency: Currency, network: EvmNetwork): resolve.Result | undefined {
|
|
116
|
+
if (isAsset(currency)) {
|
|
117
|
+
if (currency.network !== network) return undefined
|
|
118
|
+
return {
|
|
119
|
+
address: currency.address,
|
|
120
|
+
decimals: currency.decimals,
|
|
121
|
+
transfer: currency.transfer,
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (isToken(currency)) {
|
|
126
|
+
const address = currency.addresses[toChainId(network)]
|
|
127
|
+
if (!address) return undefined
|
|
128
|
+
return {
|
|
129
|
+
address,
|
|
130
|
+
decimals: currency.decimals,
|
|
131
|
+
name: currency.name,
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
address: currency,
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export declare namespace resolve {
|
|
141
|
+
type Result = {
|
|
142
|
+
address: `0x${string}`
|
|
143
|
+
decimals?: number | undefined
|
|
144
|
+
name?: string | undefined
|
|
145
|
+
transfer?: ExactTransfer | undefined
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Returns true when a currency resolves to the accepted address on the network. */
|
|
150
|
+
export function matches(
|
|
151
|
+
currency: Currency,
|
|
152
|
+
acceptedCurrency: `0x${string}`,
|
|
153
|
+
network: EvmNetwork,
|
|
154
|
+
): boolean {
|
|
155
|
+
const resolved = resolve(currency, network)
|
|
156
|
+
if (!resolved) return false
|
|
157
|
+
return getAddress(resolved.address) === getAddress(acceptedCurrency)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Converts an EVM chain ID to a CAIP-2 network identifier. */
|
|
161
|
+
export function toNetwork(chainId: number): EvmNetwork {
|
|
162
|
+
return `eip155:${chainId}`
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Converts a CAIP-2 EVM network identifier to a chain ID. */
|
|
166
|
+
export function toChainId(network: EvmNetwork): number {
|
|
167
|
+
return Number(network.slice('eip155:'.length))
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function withTokenDefaults(
|
|
171
|
+
transfer: fromToken.Transfer,
|
|
172
|
+
token: ReturnType<ViemToken>,
|
|
173
|
+
): ExactTransfer {
|
|
174
|
+
if (transfer.type !== 'eip3009') return transfer
|
|
175
|
+
if (transfer.name) return { ...transfer, name: transfer.name }
|
|
176
|
+
if (!token.name) throw new Error('EIP-3009 token assets require a token name.')
|
|
177
|
+
return {
|
|
178
|
+
...transfer,
|
|
179
|
+
name: token.name,
|
|
180
|
+
}
|
|
181
|
+
}
|