@wasit-dev/core 0.6.0 → 0.7.0
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/README.md +11 -3
- package/dist/catalogue.d.ts +10 -0
- package/dist/catalogue.js +59 -3
- package/dist/check.d.ts +21 -0
- package/dist/check.js +27 -8
- package/dist/index.d.ts +5 -3
- package/dist/index.js +5 -2
- package/dist/mpp/charge.d.ts +23 -2
- package/dist/mpp/charge.js +83 -7
- package/dist/x402/chains/evm.d.ts +65 -0
- package/dist/x402/chains/evm.js +234 -0
- package/dist/x402/chains/index.d.ts +10 -0
- package/dist/x402/chains/index.js +17 -0
- package/dist/x402/chains/stellar.d.ts +31 -0
- package/dist/x402/chains/stellar.js +153 -0
- package/dist/x402/chains/svm.d.ts +69 -0
- package/dist/x402/chains/svm.js +333 -0
- package/dist/x402/chains/types.d.ts +84 -0
- package/dist/x402/chains/types.js +10 -0
- package/dist/x402/chains/wait.d.ts +36 -0
- package/dist/x402/chains/wait.js +42 -0
- package/dist/x402/requirements.d.ts +45 -0
- package/dist/x402/requirements.js +326 -0
- package/dist/x402/simulator.d.ts +22 -16
- package/dist/x402/simulator.js +508 -217
- package/package.json +11 -6
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `exact` scheme on Solana: the payer signs a transaction carrying one
|
|
3
|
+
* `TransferChecked` to the payee's associated token account, and the sponsor
|
|
4
|
+
* named in `extra.feePayer` (usually the facilitator) adds its signature as
|
|
5
|
+
* fee payer and submits it (`scheme_exact_svm.md`). So a payer needs the
|
|
6
|
+
* token, and no SOL.
|
|
7
|
+
*
|
|
8
|
+
* Settlement is read from the confirmed transaction's token balances, the
|
|
9
|
+
* outcome the spec defines a payment by: exactly one transfer of the
|
|
10
|
+
* advertised amount of the advertised mint, from this run's payer to an
|
|
11
|
+
* account `payTo` owns, as the other adapters hold the token's own transfer
|
|
12
|
+
* record. Only Solana devnet for now: the official SDK ships its
|
|
13
|
+
* USDC and the public facilitator settles there.
|
|
14
|
+
*/
|
|
15
|
+
import { createPrivateKey, generateKeyPairSync } from "node:crypto";
|
|
16
|
+
import { DEVNET_RPC_URL, SOLANA_DEVNET_CAIP2 } from "@x402/svm";
|
|
17
|
+
import { ExactSvmScheme } from "@x402/svm/exact/client";
|
|
18
|
+
import { address, createKeyPairSignerFromBytes, createSolanaRpc, getBase58Decoder, getBase58Encoder, getBase64Decoder, getBase64Encoder, getTransactionDecoder, getTransactionEncoder, isSignature, signature, } from "@solana/kit";
|
|
19
|
+
import { CheckSetupError, ConfigurationError } from "../../errors.js";
|
|
20
|
+
import { waitForReceipt } from "./wait.js";
|
|
21
|
+
/** The networks this adapter pays on, with the SDK's default RPC for each. */
|
|
22
|
+
const NETWORKS = {
|
|
23
|
+
[SOLANA_DEVNET_CAIP2]: DEVNET_RPC_URL,
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* How long to look for the settled transaction, in slots: 150, the lifetime
|
|
27
|
+
* of a blockhash. Devnet produced 152 slots in about 37 seconds on
|
|
28
|
+
* 2026-10-05. The facilitator answers only once the transaction is confirmed,
|
|
29
|
+
* so a real settlement is visible at once; a cited signature still missing
|
|
30
|
+
* after this was never broadcast.
|
|
31
|
+
*/
|
|
32
|
+
const SLOTS_BEFORE_MISSING = 150n;
|
|
33
|
+
/**
|
|
34
|
+
* How far back X402-10 takes its blockhash. A transaction is valid for 150
|
|
35
|
+
* blocks after its blockhash; 300 slots back is past that even if half the
|
|
36
|
+
* slots in between were skipped, and the RPC confirms it before it is used.
|
|
37
|
+
*/
|
|
38
|
+
const EXPIRED_SLOTS_BACK = 300n;
|
|
39
|
+
/** RFC 8410's PKCS#8 prefix for a raw 32-byte Ed25519 seed. */
|
|
40
|
+
const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
|
|
41
|
+
/** Whether the public half of a 64-byte Solana keypair belongs to its seed. */
|
|
42
|
+
function keypairMatches(bytes) {
|
|
43
|
+
// An Ed25519 private JWK carries its public key as `x`.
|
|
44
|
+
const { x } = createPrivateKey({
|
|
45
|
+
key: Buffer.concat([ED25519_PKCS8_PREFIX, bytes.subarray(0, 32)]),
|
|
46
|
+
format: "der",
|
|
47
|
+
type: "pkcs8",
|
|
48
|
+
}).export({ format: "jwk" });
|
|
49
|
+
return x !== undefined && Buffer.from(x, "base64url").equals(bytes.subarray(32));
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The payer's 64-byte keypair from its base58 export, as wallets and the
|
|
53
|
+
* SDK's examples write `SVM_PRIVATE_KEY`.
|
|
54
|
+
*
|
|
55
|
+
* A keypair whose public half is not its seed's would sign as one address
|
|
56
|
+
* while Wasit holds the settlement to another, so it is refused here, before
|
|
57
|
+
* any payment. The message never echoes the key: it is a secret, and a
|
|
58
|
+
* malformed one is often a real key pasted with a character missing.
|
|
59
|
+
*/
|
|
60
|
+
function secretKeyBytes(payerKey) {
|
|
61
|
+
let bytes;
|
|
62
|
+
try {
|
|
63
|
+
bytes = new Uint8Array(getBase58Encoder().encode(payerKey));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
bytes = undefined;
|
|
67
|
+
}
|
|
68
|
+
if (bytes === undefined || bytes.length !== 64 || !keypairMatches(bytes)) {
|
|
69
|
+
throw new ConfigurationError("SVM_PRIVATE_KEY is not a Solana keypair: expected the base58 encoding of " +
|
|
70
|
+
"its 64 bytes (seed, then public key), as wallets export it.");
|
|
71
|
+
}
|
|
72
|
+
return bytes;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The token balances a transaction changed, from its pre- and post-balances.
|
|
76
|
+
*
|
|
77
|
+
* An account missing from the pre-balances was created in the transaction,
|
|
78
|
+
* and one missing from the post-balances was closed; both count from zero.
|
|
79
|
+
* Throws when RPC leaves out an account's owner, since then the recipient and
|
|
80
|
+
* the payer cannot be read, and that says nothing about the target.
|
|
81
|
+
*/
|
|
82
|
+
export function svmBalanceChanges(meta) {
|
|
83
|
+
const accounts = new Map();
|
|
84
|
+
const record = (balance, side) => {
|
|
85
|
+
const key = `${balance.accountIndex}:${balance.mint}`;
|
|
86
|
+
const entry = accounts.get(key) ?? { mint: balance.mint, pre: 0n, post: 0n };
|
|
87
|
+
entry.owner ??= balance.owner;
|
|
88
|
+
entry[side] = BigInt(balance.uiTokenAmount.amount);
|
|
89
|
+
accounts.set(key, entry);
|
|
90
|
+
};
|
|
91
|
+
for (const balance of meta.preTokenBalances ?? [])
|
|
92
|
+
record(balance, "pre");
|
|
93
|
+
for (const balance of meta.postTokenBalances ?? [])
|
|
94
|
+
record(balance, "post");
|
|
95
|
+
const changes = [];
|
|
96
|
+
for (const entry of accounts.values()) {
|
|
97
|
+
if (entry.post === entry.pre)
|
|
98
|
+
continue;
|
|
99
|
+
if (entry.owner === undefined) {
|
|
100
|
+
throw new Error("RPC reported a token balance change without the account's owner, so the " +
|
|
101
|
+
"settlement's payer and recipient cannot be read. Point --rpc-url at an " +
|
|
102
|
+
"endpoint that returns token balance owners.");
|
|
103
|
+
}
|
|
104
|
+
changes.push({ mint: entry.mint, owner: entry.owner, delta: entry.post - entry.pre });
|
|
105
|
+
}
|
|
106
|
+
return changes;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Holds a confirmed transaction to what the target advertised.
|
|
110
|
+
*
|
|
111
|
+
* The same rules as on Stellar and EVM: the transaction succeeded, it moved
|
|
112
|
+
* exactly one token transfer (one account debited, one credited, by the same
|
|
113
|
+
* amount of the same mint), and that transfer is the advertised amount of the
|
|
114
|
+
* advertised mint, to an account `payTo` owns, from this run's own payer, so
|
|
115
|
+
* a target cannot cite some other transaction that happens to match.
|
|
116
|
+
*/
|
|
117
|
+
export function verifySvmTransaction(transaction, reference, expected) {
|
|
118
|
+
const fail = (detail) => ({ pass: false, detail });
|
|
119
|
+
if (transaction.meta === null) {
|
|
120
|
+
throw new Error(`RPC returned transaction ${reference} without its status, so whether it ` +
|
|
121
|
+
`succeeded cannot be read. Re-run, or point --rpc-url at another endpoint.`);
|
|
122
|
+
}
|
|
123
|
+
if (transaction.meta.err !== null) {
|
|
124
|
+
return fail(`Transaction ${reference} exists on-chain but failed ` +
|
|
125
|
+
`(${JSON.stringify(transaction.meta.err)}). The target reported success for ` +
|
|
126
|
+
`a settlement that did not settle.`);
|
|
127
|
+
}
|
|
128
|
+
const changes = svmBalanceChanges(transaction.meta);
|
|
129
|
+
if (changes.length === 0) {
|
|
130
|
+
return fail(`Transaction ${reference} succeeded but changed no token balance, so no ` +
|
|
131
|
+
`token movement can be verified.`);
|
|
132
|
+
}
|
|
133
|
+
const credit = changes.find((change) => change.delta > 0n);
|
|
134
|
+
const debit = changes.find((change) => change.delta < 0n);
|
|
135
|
+
if (changes.length !== 2 ||
|
|
136
|
+
credit === undefined ||
|
|
137
|
+
debit === undefined ||
|
|
138
|
+
credit.mint !== debit.mint ||
|
|
139
|
+
credit.delta !== -debit.delta) {
|
|
140
|
+
return fail(`Transaction ${reference} changed ${changes.length} token balances in a way ` +
|
|
141
|
+
`that is not one transfer; exactly one was expected. Additional balance ` +
|
|
142
|
+
`changes mean the settlement moved more than what was advertised.`);
|
|
143
|
+
}
|
|
144
|
+
const mismatches = [];
|
|
145
|
+
if (credit.delta !== expected.amount) {
|
|
146
|
+
mismatches.push(`amount: advertised ${expected.amount} base units, moved ${credit.delta}`);
|
|
147
|
+
}
|
|
148
|
+
if (credit.owner !== expected.recipient) {
|
|
149
|
+
mismatches.push(`recipient: advertised ${expected.recipient}, paid ${credit.owner}`);
|
|
150
|
+
}
|
|
151
|
+
if (credit.mint !== expected.token) {
|
|
152
|
+
mismatches.push(`token: advertised ${expected.token}, moved ${credit.mint}`);
|
|
153
|
+
}
|
|
154
|
+
if (debit.owner !== expected.payer) {
|
|
155
|
+
mismatches.push(`payer: this run paid from ${expected.payer}, but the referenced transfer ` +
|
|
156
|
+
`came from ${debit.owner}`);
|
|
157
|
+
}
|
|
158
|
+
if (mismatches.length > 0) {
|
|
159
|
+
return fail(`Settlement does not match what the target advertised — ` +
|
|
160
|
+
`${mismatches.join("; ")} (tx ${reference}).`);
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
pass: true,
|
|
164
|
+
detail: `settled on-chain for exactly the advertised ${expected.amount} base ` +
|
|
165
|
+
`units of ${expected.token} to ${expected.recipient}, verified from the ` +
|
|
166
|
+
`transaction's token balances (tx ${reference})`,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
async function verifySvmSettlement(rpcUrl, reference, expected) {
|
|
170
|
+
const rpc = createSolanaRpc(rpcUrl);
|
|
171
|
+
const lookup = await waitForReceipt(async () => (await rpc
|
|
172
|
+
.getTransaction(signature(reference), {
|
|
173
|
+
encoding: "jsonParsed",
|
|
174
|
+
maxSupportedTransactionVersion: 0,
|
|
175
|
+
commitment: "confirmed",
|
|
176
|
+
})
|
|
177
|
+
.send()) ?? undefined, () => rpc.getSlot({ commitment: "confirmed" }).send(), { blocks: SLOTS_BEFORE_MISSING });
|
|
178
|
+
if (lookup.kind === "stalled") {
|
|
179
|
+
// An RPC that is not advancing says nothing about the target: no verdict.
|
|
180
|
+
throw new Error(`RPC at ${rpcUrl} advanced only ${lookup.blocksWatched} slots in ` +
|
|
181
|
+
`${Math.round(lookup.waitedMs / 1000)} seconds while looking for tx ` +
|
|
182
|
+
`${reference}, so its absence says nothing about the target. Re-run, ` +
|
|
183
|
+
`or point --rpc-url at another endpoint.`);
|
|
184
|
+
}
|
|
185
|
+
if (lookup.kind === "missing") {
|
|
186
|
+
return {
|
|
187
|
+
pass: false,
|
|
188
|
+
detail: `Target reported settlement as tx ${reference}, but the chain advanced ` +
|
|
189
|
+
`${lookup.blocksWatched} more slots without it. Either it was never ` +
|
|
190
|
+
`broadcast, or the target referenced a transaction that does not exist.`,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
return verifySvmTransaction(lookup.receipt, reference, expected);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* A real blockhash that is already past its lifetime.
|
|
197
|
+
*
|
|
198
|
+
* On Solana a payment's lifetime is its transaction's recent blockhash, not
|
|
199
|
+
* `maxTimeoutSeconds`, which the SDK client does not read. The client builds
|
|
200
|
+
* on `extra.recentBlockhash` when it is given one (spec: a hint the server
|
|
201
|
+
* may supply), so X402-10 hands it one that has expired, rather than holding
|
|
202
|
+
* a fresh payment for the minute or more it takes to expire. The RPC is asked
|
|
203
|
+
* whether it is still valid, so the check never sends a payment that might
|
|
204
|
+
* yet land.
|
|
205
|
+
*/
|
|
206
|
+
async function expiredBlockhash(rpcUrl) {
|
|
207
|
+
const rpc = createSolanaRpc(rpcUrl);
|
|
208
|
+
const slot = await rpc.getSlot({ commitment: "finalized" }).send();
|
|
209
|
+
const [old] = await rpc
|
|
210
|
+
.getBlocksWithLimit(slot - EXPIRED_SLOTS_BACK, 1, { commitment: "finalized" })
|
|
211
|
+
.send();
|
|
212
|
+
const block = old === undefined
|
|
213
|
+
? null
|
|
214
|
+
: await rpc
|
|
215
|
+
.getBlock(old, {
|
|
216
|
+
commitment: "finalized",
|
|
217
|
+
maxSupportedTransactionVersion: 0,
|
|
218
|
+
rewards: false,
|
|
219
|
+
transactionDetails: "none",
|
|
220
|
+
})
|
|
221
|
+
.send();
|
|
222
|
+
if (block === null) {
|
|
223
|
+
throw new CheckSetupError(`RPC at ${rpcUrl} returned no block from ${EXPIRED_SLOTS_BACK} slots back, so ` +
|
|
224
|
+
`an expired payment cannot be built.`);
|
|
225
|
+
}
|
|
226
|
+
const { value: valid } = await rpc
|
|
227
|
+
.isBlockhashValid(block.blockhash, { commitment: "finalized" })
|
|
228
|
+
.send();
|
|
229
|
+
if (valid) {
|
|
230
|
+
throw new CheckSetupError(`RPC at ${rpcUrl} still accepts blockhash ${block.blockhash} from ` +
|
|
231
|
+
`${EXPIRED_SLOTS_BACK} slots back, so a payment built on it might land.`);
|
|
232
|
+
}
|
|
233
|
+
return block.blockhash;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Corrupts the payer's signature, and nothing else.
|
|
237
|
+
*
|
|
238
|
+
* The payload is a partially signed transaction: the payer has signed, and
|
|
239
|
+
* the fee payer's slot is still empty until the sponsor signs at settlement.
|
|
240
|
+
* Flipping the first byte of the one signature present leaves a transaction
|
|
241
|
+
* that decodes, with the same transfer, amount and blockhash, whose payer
|
|
242
|
+
* signature no longer verifies. A target can refuse it only by verifying it.
|
|
243
|
+
*/
|
|
244
|
+
export function corruptSvmSignature(payload) {
|
|
245
|
+
const wire = payload["transaction"];
|
|
246
|
+
let transaction;
|
|
247
|
+
try {
|
|
248
|
+
transaction =
|
|
249
|
+
typeof wire === "string" ? getTransactionDecoder().decode(getBase64Encoder().encode(wire)) : undefined;
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
transaction = undefined;
|
|
253
|
+
}
|
|
254
|
+
const signed = Object.entries(transaction?.signatures ?? {}).filter(([, bytes]) => bytes !== null);
|
|
255
|
+
if (transaction === undefined || signed.length !== 1) {
|
|
256
|
+
throw new CheckSetupError("The payment payload carries no partially signed Solana transaction with " +
|
|
257
|
+
"exactly one signature, the payer's, so a corrupted signature cannot be tested.");
|
|
258
|
+
}
|
|
259
|
+
const [signer, bytes] = signed[0];
|
|
260
|
+
const forged = new Uint8Array(bytes);
|
|
261
|
+
forged[0] = forged[0] ^ 0xff;
|
|
262
|
+
const corrupted = {
|
|
263
|
+
...transaction,
|
|
264
|
+
signatures: { ...transaction.signatures, [signer]: forged },
|
|
265
|
+
};
|
|
266
|
+
return {
|
|
267
|
+
...payload,
|
|
268
|
+
transaction: getBase64Decoder().decode(getTransactionEncoder().encode(corrupted)),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
export const svmChain = {
|
|
272
|
+
name: "Solana",
|
|
273
|
+
networks: Object.keys(NETWORKS),
|
|
274
|
+
payerKeyEnv: "SVM_PRIVATE_KEY",
|
|
275
|
+
referenceKind: "a Solana transaction signature",
|
|
276
|
+
resolveRpcUrl(network, override) {
|
|
277
|
+
const fallback = NETWORKS[network];
|
|
278
|
+
if (fallback === undefined) {
|
|
279
|
+
throw new ConfigurationError(`No Solana network "${network}" in Wasit's payment checks.`);
|
|
280
|
+
}
|
|
281
|
+
return override || fallback;
|
|
282
|
+
},
|
|
283
|
+
async registerPayer(client, _network, payerKey, rpcUrl) {
|
|
284
|
+
// The client reads the chain while building: the mint's token program and
|
|
285
|
+
// decimals, and a recent blockhash unless the target supplies one.
|
|
286
|
+
const signer = await createKeyPairSignerFromBytes(secretKeyBytes(payerKey));
|
|
287
|
+
client.register("solana:*", new ExactSvmScheme(signer, { rpcUrl }));
|
|
288
|
+
},
|
|
289
|
+
async expiredSigning(selected, rpcUrl) {
|
|
290
|
+
return {
|
|
291
|
+
terms: { extra: { ...selected.extra, recentBlockhash: await expiredBlockhash(rpcUrl) } },
|
|
292
|
+
holdMs: 0,
|
|
293
|
+
};
|
|
294
|
+
},
|
|
295
|
+
payerAddress: (payerKey) => getBase58Decoder().decode(secretKeyBytes(payerKey).subarray(32)),
|
|
296
|
+
generatePayerKey() {
|
|
297
|
+
// The wallet export form: base58 of the seed followed by the public key.
|
|
298
|
+
const { d, x } = generateKeyPairSync("ed25519").privateKey.export({ format: "jwk" });
|
|
299
|
+
return getBase58Decoder().decode(new Uint8Array([...Buffer.from(d, "base64url"), ...Buffer.from(x, "base64url")]));
|
|
300
|
+
},
|
|
301
|
+
async payerBalance(_network, rpcUrl, payer, asset) {
|
|
302
|
+
// Every token account the payer holds for the mint, summed: the client
|
|
303
|
+
// pays from the associated one only, so this is never less than what it
|
|
304
|
+
// can spend, and a sum below the price means the payment cannot settle.
|
|
305
|
+
const { value } = await createSolanaRpc(rpcUrl)
|
|
306
|
+
.getTokenAccountsByOwner(address(payer), { mint: address(asset) }, {
|
|
307
|
+
encoding: "jsonParsed",
|
|
308
|
+
commitment: "confirmed",
|
|
309
|
+
})
|
|
310
|
+
.send();
|
|
311
|
+
let total = 0n;
|
|
312
|
+
for (const account of value) {
|
|
313
|
+
const amount = account.account.data
|
|
314
|
+
.parsed?.info?.tokenAmount?.amount;
|
|
315
|
+
if (typeof amount !== "string" || !/^\d+$/.test(amount))
|
|
316
|
+
return undefined;
|
|
317
|
+
total += BigInt(amount);
|
|
318
|
+
}
|
|
319
|
+
return total;
|
|
320
|
+
},
|
|
321
|
+
isSettlementReference(reference) {
|
|
322
|
+
// kit's isSignature throws, rather than answering false, on a string of
|
|
323
|
+
// the right length outside the base58 alphabet (an EVM hash, for one).
|
|
324
|
+
try {
|
|
325
|
+
return isSignature(reference);
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
},
|
|
331
|
+
verifySettlement: (_network, rpcUrl, reference, expected) => verifySvmSettlement(rpcUrl, reference, expected),
|
|
332
|
+
corruptPayload: corruptSvmSignature,
|
|
333
|
+
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the x402 payment checks need that differs from chain to chain.
|
|
3
|
+
*
|
|
4
|
+
* X402-01 through X402-05 need none of it: they read the challenge only, and
|
|
5
|
+
* apply to an x402 service on any chain. X402-06 to X402-10 build real
|
|
6
|
+
* payments, so they need a signer, a way to look the settlement up, and a way
|
|
7
|
+
* to forge only the payer's signature. One adapter per chain family supplies
|
|
8
|
+
* those, and the checks themselves stay the same everywhere.
|
|
9
|
+
*/
|
|
10
|
+
import type { PaymentRequirements } from "@x402/core/types";
|
|
11
|
+
import type { x402Client } from "@x402/fetch";
|
|
12
|
+
import type { ExpectedSettlement, SettlementVerdict } from "../../settlement.js";
|
|
13
|
+
/**
|
|
14
|
+
* What a negative check signs differently from the honest payment. The
|
|
15
|
+
* payload still claims, in `accepted`, the terms the target advertised, so the
|
|
16
|
+
* only thing wrong with it is what was signed.
|
|
17
|
+
*/
|
|
18
|
+
export interface AlteredSigning {
|
|
19
|
+
readonly amount?: string;
|
|
20
|
+
readonly maxTimeoutSeconds?: number;
|
|
21
|
+
readonly extra?: Record<string, unknown>;
|
|
22
|
+
}
|
|
23
|
+
/** How X402-10 builds a payment that has expired by the time it is sent. */
|
|
24
|
+
export interface ExpiredSigning {
|
|
25
|
+
/** The terms to sign the payment for. */
|
|
26
|
+
readonly terms: AlteredSigning;
|
|
27
|
+
/** How long to hold the signed payment before sending it. */
|
|
28
|
+
readonly holdMs: number;
|
|
29
|
+
}
|
|
30
|
+
export interface PaymentChain {
|
|
31
|
+
/** The chain family's name, for reports. */
|
|
32
|
+
readonly name: string;
|
|
33
|
+
/** The CAIP-2 networks Wasit pays on with this adapter. */
|
|
34
|
+
readonly networks: readonly string[];
|
|
35
|
+
/** The environment variable front ends read the payer key from. */
|
|
36
|
+
readonly payerKeyEnv: string;
|
|
37
|
+
/** What a settlement reference is on this chain, for a report ("a ... hash"). */
|
|
38
|
+
readonly referenceKind: string;
|
|
39
|
+
/**
|
|
40
|
+
* The RPC endpoint X402-06 verifies the settlement on. Throws
|
|
41
|
+
* `ConfigurationError` when there is none, before any payment is made.
|
|
42
|
+
*/
|
|
43
|
+
resolveRpcUrl(network: string, override?: string): string;
|
|
44
|
+
/**
|
|
45
|
+
* Registers this chain's `exact` client scheme, signing with `payerKey`.
|
|
46
|
+
* `rpcUrl` is for client schemes that read the chain while building a
|
|
47
|
+
* payment (EVM Permit2 checks the token allowance, Solana fetches the mint
|
|
48
|
+
* and a blockhash); others ignore it.
|
|
49
|
+
*/
|
|
50
|
+
registerPayer(client: x402Client, network: string, payerKey: string, rpcUrl: string): void | Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* How X402-10 makes a payment that has expired when it arrives, for the
|
|
53
|
+
* option `selected`. Where the client derives the lifetime from
|
|
54
|
+
* `maxTimeoutSeconds`, a one-second lifetime and a hold long enough for the
|
|
55
|
+
* chain to pass it.
|
|
56
|
+
*/
|
|
57
|
+
expiredSigning(selected: PaymentRequirements, rpcUrl: string): Promise<ExpiredSigning>;
|
|
58
|
+
/** The payer's address, which the settlement must come from. */
|
|
59
|
+
payerAddress(payerKey: string): string;
|
|
60
|
+
/** A new random payer key, in the form `payerKeyEnv` takes. */
|
|
61
|
+
generatePayerKey(): string;
|
|
62
|
+
/**
|
|
63
|
+
* The payer's balance of `asset`, in base units, as the chain reports it,
|
|
64
|
+
* or at most what the payer can spend from (never more than it holds).
|
|
65
|
+
* Undefined, or a throw, when the chain gives no clear answer: X402-06 then
|
|
66
|
+
* pays as if the balance were enough, so a failed read never becomes a
|
|
67
|
+
* verdict.
|
|
68
|
+
*/
|
|
69
|
+
payerBalance(network: string, rpcUrl: string, payer: string, asset: string): Promise<bigint | undefined>;
|
|
70
|
+
/** Whether `reference` has the shape of a settlement on this chain. */
|
|
71
|
+
isSettlementReference(reference: string): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Looks the settlement up on `network` and holds it to the advertised
|
|
74
|
+
* terms. Returns a verdict about the target; throws when the chain's RPC
|
|
75
|
+
* gives no answer, which says nothing about the target.
|
|
76
|
+
*/
|
|
77
|
+
verifySettlement(network: string, rpcUrl: string, reference: string, expected: ExpectedSettlement): Promise<SettlementVerdict>;
|
|
78
|
+
/**
|
|
79
|
+
* The payment payload's inner `payload` with the payer's signature, and
|
|
80
|
+
* nothing else, corrupted. Throws `CheckSetupError` when there is no
|
|
81
|
+
* signature to corrupt.
|
|
82
|
+
*/
|
|
83
|
+
corruptPayload(payload: Record<string, unknown>): Record<string, unknown>;
|
|
84
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the x402 payment checks need that differs from chain to chain.
|
|
3
|
+
*
|
|
4
|
+
* X402-01 through X402-05 need none of it: they read the challenge only, and
|
|
5
|
+
* apply to an x402 service on any chain. X402-06 to X402-10 build real
|
|
6
|
+
* payments, so they need a signer, a way to look the settlement up, and a way
|
|
7
|
+
* to forge only the payer's signature. One adapter per chain family supplies
|
|
8
|
+
* those, and the checks themselves stay the same everywhere.
|
|
9
|
+
*/
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Waiting for a settled transaction to appear on chains whose RPC reports
|
|
3
|
+
* progress as a block (or slot) number: EVM and Solana.
|
|
4
|
+
*/
|
|
5
|
+
/** What looking for a settled transaction established. */
|
|
6
|
+
export type ReceiptLookup<R> = {
|
|
7
|
+
readonly kind: "found";
|
|
8
|
+
readonly receipt: R;
|
|
9
|
+
} | {
|
|
10
|
+
readonly kind: "missing";
|
|
11
|
+
readonly blocksWatched: bigint;
|
|
12
|
+
} | {
|
|
13
|
+
readonly kind: "stalled";
|
|
14
|
+
readonly blocksWatched: bigint;
|
|
15
|
+
readonly waitedMs: number;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Polls for a settled transaction until it appears, until the chain has
|
|
19
|
+
* produced enough blocks (slots, on Solana) without it to call it missing, or
|
|
20
|
+
* until the RPC stops advancing.
|
|
21
|
+
*
|
|
22
|
+
* A fixed wall-clock wait cannot tell a transaction that does not exist from
|
|
23
|
+
* an RPC that is behind, so the wait is counted in the chain's own progress,
|
|
24
|
+
* and an RPC that stops advancing gives no verdict at all.
|
|
25
|
+
*
|
|
26
|
+
* `getReceipt` returns undefined while the transaction is unknown; any other
|
|
27
|
+
* failure is the harness's and propagates. Clock and sleep are parameters so
|
|
28
|
+
* the three outcomes can be exercised without a network.
|
|
29
|
+
*/
|
|
30
|
+
export declare function waitForReceipt<R>(getReceipt: () => Promise<R | undefined>, getBlockNumber: () => Promise<bigint>, options: {
|
|
31
|
+
readonly blocks: bigint;
|
|
32
|
+
readonly maxWaitMs?: number;
|
|
33
|
+
readonly delayMs?: number;
|
|
34
|
+
readonly now?: () => number;
|
|
35
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
36
|
+
}): Promise<ReceiptLookup<R>>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Waiting for a settled transaction to appear on chains whose RPC reports
|
|
3
|
+
* progress as a block (or slot) number: EVM and Solana.
|
|
4
|
+
*/
|
|
5
|
+
const MAX_WAIT_MS = 120_000;
|
|
6
|
+
const POLL_DELAY_MS = 1_000;
|
|
7
|
+
/**
|
|
8
|
+
* Polls for a settled transaction until it appears, until the chain has
|
|
9
|
+
* produced enough blocks (slots, on Solana) without it to call it missing, or
|
|
10
|
+
* until the RPC stops advancing.
|
|
11
|
+
*
|
|
12
|
+
* A fixed wall-clock wait cannot tell a transaction that does not exist from
|
|
13
|
+
* an RPC that is behind, so the wait is counted in the chain's own progress,
|
|
14
|
+
* and an RPC that stops advancing gives no verdict at all.
|
|
15
|
+
*
|
|
16
|
+
* `getReceipt` returns undefined while the transaction is unknown; any other
|
|
17
|
+
* failure is the harness's and propagates. Clock and sleep are parameters so
|
|
18
|
+
* the three outcomes can be exercised without a network.
|
|
19
|
+
*/
|
|
20
|
+
export async function waitForReceipt(getReceipt, getBlockNumber, options) {
|
|
21
|
+
const blocks = options.blocks;
|
|
22
|
+
const maxWaitMs = options.maxWaitMs ?? MAX_WAIT_MS;
|
|
23
|
+
const delayMs = options.delayMs ?? POLL_DELAY_MS;
|
|
24
|
+
const now = options.now ?? Date.now;
|
|
25
|
+
const pause = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
|
|
26
|
+
const startedAt = now();
|
|
27
|
+
let firstBlock;
|
|
28
|
+
for (;;) {
|
|
29
|
+
const receipt = await getReceipt();
|
|
30
|
+
if (receipt !== undefined)
|
|
31
|
+
return { kind: "found", receipt };
|
|
32
|
+
const block = await getBlockNumber();
|
|
33
|
+
firstBlock ??= block;
|
|
34
|
+
const blocksWatched = block - firstBlock;
|
|
35
|
+
if (blocksWatched >= blocks)
|
|
36
|
+
return { kind: "missing", blocksWatched };
|
|
37
|
+
const waitedMs = now() - startedAt;
|
|
38
|
+
if (waitedMs >= maxWaitMs)
|
|
39
|
+
return { kind: "stalled", blocksWatched, waitedMs };
|
|
40
|
+
await pause(delayMs);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The payment terms an x402 challenge advertises, and the rules X402-04 and
|
|
3
|
+
* X402-05 hold them to.
|
|
4
|
+
*
|
|
5
|
+
* Split from the HTTP calls in simulator.ts so the rules can be exercised
|
|
6
|
+
* without a network. Nothing here is specific to one chain: x402 v2 names the
|
|
7
|
+
* network of every payment option with a CAIP-2 identifier, and a challenge
|
|
8
|
+
* may offer several options on several chains at once.
|
|
9
|
+
*/
|
|
10
|
+
import { type CheckResult } from "../check.js";
|
|
11
|
+
/**
|
|
12
|
+
* Every payment option a challenge offers, in order.
|
|
13
|
+
*
|
|
14
|
+
* x402 v2 nests the payment terms inside `accepts[]`. Each entry is a separate
|
|
15
|
+
* option, typically one per network or asset, so each is checked on its own:
|
|
16
|
+
* judging only the first would pass a challenge whose other options are broken,
|
|
17
|
+
* and fail one whose first option is on a chain the reader did not expect.
|
|
18
|
+
* An entry that is not an object is kept as `undefined`, so it reads as an
|
|
19
|
+
* option with every field missing rather than disappearing from the count.
|
|
20
|
+
*/
|
|
21
|
+
export declare function acceptsOf(payload: unknown): ReadonlyArray<Record<string, unknown> | undefined> | undefined;
|
|
22
|
+
/** X402-04: every payment option must carry the fields its version requires. */
|
|
23
|
+
export declare function checkRequiredFields(payload: unknown): CheckResult;
|
|
24
|
+
/** What X402-05 established about one network identifier. */
|
|
25
|
+
export type NetworkVerdict = {
|
|
26
|
+
readonly valid: true;
|
|
27
|
+
readonly namespace: string;
|
|
28
|
+
readonly known: boolean;
|
|
29
|
+
} | {
|
|
30
|
+
readonly valid: false;
|
|
31
|
+
readonly reason: string;
|
|
32
|
+
readonly fix: string;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Validates one network identifier against CAIP-2, which x402 v2 requires,
|
|
36
|
+
* and against its namespace's own rules where Wasit knows them.
|
|
37
|
+
*
|
|
38
|
+
* A well-formed identifier in a namespace Wasit has no rules for is valid:
|
|
39
|
+
* x402 v2 asks for CAIP-2 and nothing more, and even encourages non-blockchain
|
|
40
|
+
* networks to follow it (`ach:us`). Failing it would report Wasit's own
|
|
41
|
+
* ignorance as the target's defect.
|
|
42
|
+
*/
|
|
43
|
+
export declare function validateNetwork(network: string): NetworkVerdict;
|
|
44
|
+
/** X402-05: every advertised network identifier must be CAIP-2. */
|
|
45
|
+
export declare function checkNetworkIdentifier(payload: unknown): CheckResult;
|