@wasit-dev/core 0.6.0 → 0.8.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -4
- package/dist/baseline.d.ts +109 -0
- package/dist/baseline.js +351 -0
- package/dist/catalogue.d.ts +10 -0
- package/dist/catalogue.js +69 -3
- package/dist/check.d.ts +78 -2
- package/dist/check.js +69 -10
- package/dist/ci-report.d.ts +74 -0
- package/dist/ci-report.js +391 -0
- package/dist/config.d.ts +205 -0
- package/dist/config.js +1011 -0
- package/dist/denied-env.d.ts +33 -0
- package/dist/denied-env.js +86 -0
- package/dist/errors.d.ts +44 -1
- package/dist/errors.js +151 -2
- package/dist/guard/budget.d.ts +135 -0
- package/dist/guard/budget.js +199 -0
- package/dist/guard/ci-event.d.ts +50 -0
- package/dist/guard/ci-event.js +125 -0
- package/dist/guard/mainnet-optin.d.ts +58 -0
- package/dist/guard/mainnet-optin.js +95 -0
- package/dist/guard/networks.d.ts +50 -0
- package/dist/guard/networks.js +80 -0
- package/dist/guard/rpc-identity.d.ts +45 -0
- package/dist/guard/rpc-identity.js +156 -0
- package/dist/guard/rpc-in-use.d.ts +48 -0
- package/dist/guard/rpc-in-use.js +84 -0
- package/dist/index.d.ts +34 -3
- package/dist/index.js +31 -2
- package/dist/mpp/channel-commitment.d.ts +48 -2
- package/dist/mpp/channel-commitment.js +80 -4
- package/dist/mpp/channel-credential.js +3 -0
- package/dist/mpp/channel.js +29 -0
- package/dist/mpp/charge.d.ts +25 -2
- package/dist/mpp/charge.js +100 -8
- package/dist/mpp/network.js +4 -1
- package/dist/mpp/suite.js +10 -2
- package/dist/report.d.ts +163 -0
- package/dist/report.js +282 -0
- package/dist/sanitize.d.ts +52 -0
- package/dist/sanitize.js +106 -0
- package/dist/settlement.d.ts +14 -0
- package/dist/settlement.js +1 -1
- package/dist/verdict.d.ts +24 -0
- package/dist/verdict.js +46 -0
- package/dist/versions.d.ts +50 -0
- package/dist/versions.js +123 -0
- package/dist/x402/chains/evm.d.ts +65 -0
- package/dist/x402/chains/evm.js +237 -0
- package/dist/x402/chains/index.d.ts +18 -0
- package/dist/x402/chains/index.js +28 -0
- package/dist/x402/chains/stellar.d.ts +38 -0
- package/dist/x402/chains/stellar.js +277 -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 +152 -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/plan.d.ts +82 -0
- package/dist/x402/plan.js +146 -0
- package/dist/x402/rejected-request.d.ts +146 -0
- package/dist/x402/rejected-request.js +269 -0
- package/dist/x402/requirements.d.ts +46 -0
- package/dist/x402/requirements.js +359 -0
- package/dist/x402/simulator.d.ts +74 -17
- package/dist/x402/simulator.js +907 -246
- package/package.json +11 -6
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `exact` scheme on Stellar: Soroban authorization entries signed by the
|
|
3
|
+
* payer, settlement read from the token contract's `transfer` event on
|
|
4
|
+
* Stellar RPC (settlement.ts). This is the chain Wasit was built on, and the
|
|
5
|
+
* only one with MPP as well.
|
|
6
|
+
*/
|
|
7
|
+
import { createEd25519Signer } from "@x402/stellar";
|
|
8
|
+
import { ExactStellarScheme as ExactStellarClientScheme } from "@x402/stellar/exact/client";
|
|
9
|
+
import { Account, Address, Asset, Contract, Keypair, StrKey, TransactionBuilder, rpc, scValToNative, xdr, } from "@stellar/stellar-sdk";
|
|
10
|
+
import { CheckSetupError } from "../../errors.js";
|
|
11
|
+
import { networkPassphrase, resolveRpcUrl } from "../../mpp/network.js";
|
|
12
|
+
import { readTransferData, verifySettlement } from "../../settlement.js";
|
|
13
|
+
/** A Stellar transaction hash: 64 hex characters. */
|
|
14
|
+
const TRANSACTION_HASH = /^[0-9a-f]{64}$/i;
|
|
15
|
+
/**
|
|
16
|
+
* Corrupts the client's authorization signature, and nothing else.
|
|
17
|
+
*
|
|
18
|
+
* In the `exact` scheme on Stellar the client signs a Soroban authorization
|
|
19
|
+
* entry, not the envelope: the facilitator signs the envelope later. So the
|
|
20
|
+
* signature that proves the payer consented is the address credential's
|
|
21
|
+
* `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
|
|
22
|
+
* leaves a transaction that still decodes, carries the same amount, payer and
|
|
23
|
+
* recipient, and fails only signature verification. A target can refuse it
|
|
24
|
+
* only by verifying the signature.
|
|
25
|
+
*
|
|
26
|
+
* Throws {@link CheckSetupError} if the payload carries no such signature, so
|
|
27
|
+
* the check reports no verdict rather than one it did not establish.
|
|
28
|
+
*/
|
|
29
|
+
export function corruptAuthSignature(transaction) {
|
|
30
|
+
const envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64");
|
|
31
|
+
const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : [];
|
|
32
|
+
let corrupted = false;
|
|
33
|
+
for (const operation of operations) {
|
|
34
|
+
if (operation.body().switch().name !== "invokeHostFunction")
|
|
35
|
+
continue;
|
|
36
|
+
for (const entry of operation.body().invokeHostFunctionOp().auth()) {
|
|
37
|
+
const credentials = entry.credentials();
|
|
38
|
+
if (credentials.switch().name !== "sorobanCredentialsAddress")
|
|
39
|
+
continue;
|
|
40
|
+
const signature = credentials.address().signature();
|
|
41
|
+
if (signature.switch().name !== "scvVec")
|
|
42
|
+
continue;
|
|
43
|
+
for (const item of signature.vec() ?? []) {
|
|
44
|
+
if (item.switch().name !== "scvMap")
|
|
45
|
+
continue;
|
|
46
|
+
for (const field of item.map() ?? []) {
|
|
47
|
+
if (field.key().switch().name !== "scvSymbol")
|
|
48
|
+
continue;
|
|
49
|
+
if (field.key().sym().toString() !== "signature")
|
|
50
|
+
continue;
|
|
51
|
+
const bytes = Buffer.from(field.val().bytes());
|
|
52
|
+
bytes[0] = bytes[0] ^ 0xff;
|
|
53
|
+
field.val(xdr.ScVal.scvBytes(bytes));
|
|
54
|
+
corrupted = true;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (!corrupted) {
|
|
60
|
+
throw new CheckSetupError("The payment payload carries no authorization-entry signature to " +
|
|
61
|
+
"corrupt, so a corrupted signature cannot be tested.");
|
|
62
|
+
}
|
|
63
|
+
return envelope.toXDR("base64");
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* A format-valid all-zero account, as the simulation source: a read-only
|
|
67
|
+
* simulation never touches it, so it need not exist (channel-commitment.ts
|
|
68
|
+
* uses the same).
|
|
69
|
+
*/
|
|
70
|
+
const SIMULATION_SOURCE = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF";
|
|
71
|
+
/** A read-only contract call, simulated; undefined unless it succeeds with a value. */
|
|
72
|
+
async function simulateTokenRead(server, passphrase, contractId, method, args) {
|
|
73
|
+
const transaction = new TransactionBuilder(new Account(SIMULATION_SOURCE, "0"), {
|
|
74
|
+
fee: "100",
|
|
75
|
+
networkPassphrase: passphrase,
|
|
76
|
+
})
|
|
77
|
+
.addOperation(new Contract(contractId).call(method, ...args))
|
|
78
|
+
.setTimeout(30)
|
|
79
|
+
.build();
|
|
80
|
+
const simulation = await server.simulateTransaction(transaction);
|
|
81
|
+
if (!rpc.Api.isSimulationSuccess(simulation) ||
|
|
82
|
+
rpc.Api.isSimulationRestore(simulation) ||
|
|
83
|
+
simulation.result === undefined) {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
return scValToNative(simulation.result.retval);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The classic asset a Stellar Asset Contract wraps, from the `name` it
|
|
90
|
+
* reports ("CODE:ISSUER", CAP-46-06), only when that asset's contract id is
|
|
91
|
+
* `contractId`: any contract can return such a name, but only the SAC has
|
|
92
|
+
* the id derived from the asset.
|
|
93
|
+
*/
|
|
94
|
+
export function sacAssetFromName(name, contractId, passphrase) {
|
|
95
|
+
if (typeof name !== "string")
|
|
96
|
+
return undefined;
|
|
97
|
+
const match = /^([A-Za-z0-9]{1,12}):(G[A-Z2-7]{55})$/.exec(name);
|
|
98
|
+
if (match === null || !StrKey.isValidEd25519PublicKey(match[2]))
|
|
99
|
+
return undefined;
|
|
100
|
+
const asset = new Asset(match[1], match[2]);
|
|
101
|
+
return asset.contractId(passphrase) === contractId ? asset : undefined;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The payer's balance of a SEP-41 token, read by simulating its `balance`.
|
|
105
|
+
*
|
|
106
|
+
* A Stellar Asset Contract reports a payer without a trustline as an error,
|
|
107
|
+
* not as zero, and an unfunded payer is the usual case. So when `balance`
|
|
108
|
+
* gives no value and the token is a SAC, the trustline is looked up: none
|
|
109
|
+
* means the payer holds nothing. The asset's issuer needs no trustline, so it
|
|
110
|
+
* is left unread. Anything else gives undefined.
|
|
111
|
+
*/
|
|
112
|
+
async function stellarTokenBalance(network, rpcUrl, payer, asset) {
|
|
113
|
+
if (!StrKey.isValidContract(asset) || !StrKey.isValidEd25519PublicKey(payer))
|
|
114
|
+
return undefined;
|
|
115
|
+
const passphrase = networkPassphrase(network);
|
|
116
|
+
const server = new rpc.Server(rpcUrl);
|
|
117
|
+
const balance = await simulateTokenRead(server, passphrase, asset, "balance", [
|
|
118
|
+
new Address(payer).toScVal(),
|
|
119
|
+
]);
|
|
120
|
+
if (typeof balance === "bigint")
|
|
121
|
+
return balance;
|
|
122
|
+
const classic = sacAssetFromName(await simulateTokenRead(server, passphrase, asset, "name", []), asset, passphrase);
|
|
123
|
+
if (classic === undefined || classic.getIssuer() === payer)
|
|
124
|
+
return undefined;
|
|
125
|
+
const { entries } = await server.getLedgerEntries(xdr.LedgerKey.trustline(new xdr.LedgerKeyTrustLine({
|
|
126
|
+
accountId: Keypair.fromPublicKey(payer).xdrAccountId(),
|
|
127
|
+
asset: classic.toTrustLineXDRObject(),
|
|
128
|
+
})));
|
|
129
|
+
return entries.length === 0 ? 0n : undefined;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* X402-11 reads (D-032, spec B16.4): the authorization a payment carries, as
|
|
133
|
+
* the payer signed it. Only an address credential is read; another form (the
|
|
134
|
+
* newer `AddressV2`, one with delegates) is not, and gives no reading rather
|
|
135
|
+
* than a guess, since its nonce handling was not read.
|
|
136
|
+
*/
|
|
137
|
+
export function decodeStellarAuthorization(payload) {
|
|
138
|
+
const transaction = payload["transaction"];
|
|
139
|
+
if (typeof transaction !== "string") {
|
|
140
|
+
throw new CheckSetupError("The payment payload carries no transaction to read its authorization from.");
|
|
141
|
+
}
|
|
142
|
+
let envelope;
|
|
143
|
+
try {
|
|
144
|
+
envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64");
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
throw new CheckSetupError("The payment payload's transaction does not decode, so its authorization cannot be read.");
|
|
148
|
+
}
|
|
149
|
+
const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : [];
|
|
150
|
+
const found = [];
|
|
151
|
+
let otherForms = 0;
|
|
152
|
+
for (const operation of operations) {
|
|
153
|
+
if (operation.body().switch().name !== "invokeHostFunction")
|
|
154
|
+
continue;
|
|
155
|
+
for (const entry of operation.body().invokeHostFunctionOp().auth()) {
|
|
156
|
+
const credentials = entry.credentials();
|
|
157
|
+
const kind = credentials.switch().name;
|
|
158
|
+
if (kind === "sorobanCredentialsSourceAccount")
|
|
159
|
+
continue;
|
|
160
|
+
if (kind !== "sorobanCredentialsAddress") {
|
|
161
|
+
otherForms += 1;
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
const address = credentials.address();
|
|
165
|
+
found.push({
|
|
166
|
+
payer: Address.fromScAddress(address.address()).toString(),
|
|
167
|
+
nonce: address.nonce().toString(),
|
|
168
|
+
expiresAt: address.signatureExpirationLedger(),
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (otherForms > 0) {
|
|
173
|
+
throw new CheckSetupError("The payment's authorization uses a credential form this check does not read (it reads address credentials), " +
|
|
174
|
+
"so whether it was used cannot be read.");
|
|
175
|
+
}
|
|
176
|
+
if (found.length !== 1) {
|
|
177
|
+
throw new CheckSetupError(`The payment carries ${found.length} address authorizations; this check reads exactly one.`);
|
|
178
|
+
}
|
|
179
|
+
return found[0];
|
|
180
|
+
}
|
|
181
|
+
/** The ledger entry the host writes when it consumes the nonce: TEMPORARY contract data of the signer. */
|
|
182
|
+
function nonceKey(authorization) {
|
|
183
|
+
return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({
|
|
184
|
+
contract: new Address(authorization.payer).toScAddress(),
|
|
185
|
+
key: xdr.ScVal.scvLedgerKeyNonce(new xdr.ScNonceKey({ nonce: xdr.Int64.fromString(authorization.nonce) })),
|
|
186
|
+
durability: xdr.ContractDataDurability.temporary(),
|
|
187
|
+
}));
|
|
188
|
+
}
|
|
189
|
+
function rpcServer(rpcUrl) {
|
|
190
|
+
return new rpc.Server(rpcUrl, { allowHttp: rpcUrl.startsWith("http://") });
|
|
191
|
+
}
|
|
192
|
+
/** The most events read for one X402-11 window: far more than one run makes. */
|
|
193
|
+
const EVENTS_PAGE = 100;
|
|
194
|
+
const EVENTS_MAX_PAGES = 20;
|
|
195
|
+
const stellarAuthorizations = {
|
|
196
|
+
unit: "ledger",
|
|
197
|
+
unitMs: 5_000,
|
|
198
|
+
// The x402 Stellar client's own default (DEFAULT_ESTIMATED_LEDGER_SECONDS in
|
|
199
|
+
// @x402/stellar 2.28.0); it estimates from recent ledgers when it can.
|
|
200
|
+
unitSeconds: 5,
|
|
201
|
+
decode: decodeStellarAuthorization,
|
|
202
|
+
async read(_network, rpcUrl, authorizations) {
|
|
203
|
+
const keys = authorizations.map(nonceKey);
|
|
204
|
+
const response = await rpcServer(rpcUrl).getLedgerEntries(...keys);
|
|
205
|
+
const byKey = new Map(response.entries.map((entry) => [entry.key.toXDR("base64"), entry]));
|
|
206
|
+
return {
|
|
207
|
+
latest: response.latestLedger,
|
|
208
|
+
used: keys.map((key) => {
|
|
209
|
+
const entry = byKey.get(key.toXDR("base64"));
|
|
210
|
+
return entry === undefined ? undefined : (entry.lastModifiedLedgerSeq ?? response.latestLedger);
|
|
211
|
+
}),
|
|
212
|
+
};
|
|
213
|
+
},
|
|
214
|
+
async transfers(_network, rpcUrl, query) {
|
|
215
|
+
const server = rpcServer(rpcUrl);
|
|
216
|
+
const name = xdr.ScVal.scvSymbol("transfer").toXDR("base64");
|
|
217
|
+
const from = new Address(query.from).toScVal().toXDR("base64");
|
|
218
|
+
const to = new Address(query.to).toScVal().toXDR("base64");
|
|
219
|
+
// A Stellar Asset Contract adds the asset as a fourth topic (CAP-67); a SEP-41 token may not.
|
|
220
|
+
const filters = [
|
|
221
|
+
{ type: "contract", contractIds: [query.asset], topics: [[name, from, to, "*"], [name, from, to]] },
|
|
222
|
+
];
|
|
223
|
+
const transfers = [];
|
|
224
|
+
let response = await server.getEvents({ startLedger: query.fromLedger, filters, limit: EVENTS_PAGE });
|
|
225
|
+
for (let page = 1;; page += 1) {
|
|
226
|
+
for (const event of response.events) {
|
|
227
|
+
// Only an event the RPC marks as from a failed call is left out. The testnet RPC no
|
|
228
|
+
// longer sends the field at all (observed 2026-11-16, run of slice 4's live check):
|
|
229
|
+
// reading its absence as "failed" dropped every transfer.
|
|
230
|
+
if (event.inSuccessfulContractCall === false)
|
|
231
|
+
continue;
|
|
232
|
+
const [topic, sender, receiver] = event.topic;
|
|
233
|
+
if (topic?.switch().name !== "scvSymbol" || topic.sym().toString() !== "transfer")
|
|
234
|
+
continue;
|
|
235
|
+
if (sender === undefined || receiver === undefined)
|
|
236
|
+
continue;
|
|
237
|
+
if (Address.fromScVal(sender).toString() !== query.from || Address.fromScVal(receiver).toString() !== query.to)
|
|
238
|
+
continue;
|
|
239
|
+
const data = readTransferData(event.value);
|
|
240
|
+
if (data === undefined)
|
|
241
|
+
continue;
|
|
242
|
+
transfers.push({ amount: data.amount, reference: event.txHash, ledger: event.ledger });
|
|
243
|
+
}
|
|
244
|
+
if (response.events.length < EVENTS_PAGE)
|
|
245
|
+
break;
|
|
246
|
+
// Never a partial answer read as complete.
|
|
247
|
+
if (page >= EVENTS_MAX_PAGES)
|
|
248
|
+
throw new Error("more transfer events than can be read in full");
|
|
249
|
+
response = await server.getEvents({ cursor: response.cursor, filters, limit: EVENTS_PAGE });
|
|
250
|
+
}
|
|
251
|
+
return { latest: response.latestLedger, transfers };
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
export const stellarChain = {
|
|
255
|
+
name: "Stellar",
|
|
256
|
+
networks: ["stellar:testnet", "stellar:pubnet"],
|
|
257
|
+
payerKeyEnv: "STELLAR_PRIVATE_KEY",
|
|
258
|
+
referenceKind: "a settled Stellar transaction hash",
|
|
259
|
+
resolveRpcUrl: (network, override) => resolveRpcUrl(network, override),
|
|
260
|
+
registerPayer(client, network, payerKey, _rpcUrl) {
|
|
261
|
+
const signer = createEd25519Signer(payerKey, network);
|
|
262
|
+
client.register("stellar:*", new ExactStellarClientScheme(signer));
|
|
263
|
+
},
|
|
264
|
+
// A one-second lifetime is one ledger (ceil(1 / 5)); ledgers close about
|
|
265
|
+
// every 5 to 6 seconds, so 20 seconds is three or more ledgers past it.
|
|
266
|
+
expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 20_000 }),
|
|
267
|
+
payerAddress: (payerKey) => Keypair.fromSecret(payerKey).publicKey(),
|
|
268
|
+
payerBalance: stellarTokenBalance,
|
|
269
|
+
generatePayerKey: () => Keypair.random().secret(),
|
|
270
|
+
isSettlementReference: (reference) => TRANSACTION_HASH.test(reference),
|
|
271
|
+
verifySettlement: (_network, rpcUrl, reference, expected) => verifySettlement(rpcUrl, reference, expected),
|
|
272
|
+
corruptPayload: (payload) => ({
|
|
273
|
+
...payload,
|
|
274
|
+
transaction: corruptAuthSignature(payload["transaction"]),
|
|
275
|
+
}),
|
|
276
|
+
authorizations: stellarAuthorizations,
|
|
277
|
+
};
|
|
@@ -0,0 +1,69 @@
|
|
|
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 type { ExpectedSettlement, SettlementVerdict } from "../../settlement.js";
|
|
16
|
+
import type { PaymentChain } from "./types.js";
|
|
17
|
+
/** A token account's balance in a transaction's metadata, as RPC reports it. */
|
|
18
|
+
export interface SvmTokenBalance {
|
|
19
|
+
readonly accountIndex: number | bigint;
|
|
20
|
+
readonly mint: string;
|
|
21
|
+
readonly owner?: string;
|
|
22
|
+
readonly uiTokenAmount: {
|
|
23
|
+
readonly amount: string;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/** A confirmed transaction, reduced to what a settlement is read from. */
|
|
27
|
+
export interface SvmTransaction {
|
|
28
|
+
readonly meta: {
|
|
29
|
+
readonly err: unknown;
|
|
30
|
+
readonly preTokenBalances?: readonly SvmTokenBalance[] | null;
|
|
31
|
+
readonly postTokenBalances?: readonly SvmTokenBalance[] | null;
|
|
32
|
+
} | null;
|
|
33
|
+
}
|
|
34
|
+
/** How one token account's balance moved in a transaction. */
|
|
35
|
+
export interface SvmBalanceChange {
|
|
36
|
+
readonly mint: string;
|
|
37
|
+
readonly owner: string;
|
|
38
|
+
readonly delta: bigint;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The token balances a transaction changed, from its pre- and post-balances.
|
|
42
|
+
*
|
|
43
|
+
* An account missing from the pre-balances was created in the transaction,
|
|
44
|
+
* and one missing from the post-balances was closed; both count from zero.
|
|
45
|
+
* Throws when RPC leaves out an account's owner, since then the recipient and
|
|
46
|
+
* the payer cannot be read, and that says nothing about the target.
|
|
47
|
+
*/
|
|
48
|
+
export declare function svmBalanceChanges(meta: NonNullable<SvmTransaction["meta"]>): SvmBalanceChange[];
|
|
49
|
+
/**
|
|
50
|
+
* Holds a confirmed transaction to what the target advertised.
|
|
51
|
+
*
|
|
52
|
+
* The same rules as on Stellar and EVM: the transaction succeeded, it moved
|
|
53
|
+
* exactly one token transfer (one account debited, one credited, by the same
|
|
54
|
+
* amount of the same mint), and that transfer is the advertised amount of the
|
|
55
|
+
* advertised mint, to an account `payTo` owns, from this run's own payer, so
|
|
56
|
+
* a target cannot cite some other transaction that happens to match.
|
|
57
|
+
*/
|
|
58
|
+
export declare function verifySvmTransaction(transaction: SvmTransaction, reference: string, expected: ExpectedSettlement): SettlementVerdict;
|
|
59
|
+
/**
|
|
60
|
+
* Corrupts the payer's signature, and nothing else.
|
|
61
|
+
*
|
|
62
|
+
* The payload is a partially signed transaction: the payer has signed, and
|
|
63
|
+
* the fee payer's slot is still empty until the sponsor signs at settlement.
|
|
64
|
+
* Flipping the first byte of the one signature present leaves a transaction
|
|
65
|
+
* that decodes, with the same transfer, amount and blockhash, whose payer
|
|
66
|
+
* signature no longer verifies. A target can refuse it only by verifying it.
|
|
67
|
+
*/
|
|
68
|
+
export declare function corruptSvmSignature(payload: Record<string, unknown>): Record<string, unknown>;
|
|
69
|
+
export declare const svmChain: PaymentChain;
|
|
@@ -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
|
+
};
|