@wasit-dev/core 0.5.0 → 0.6.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 +2 -2
- package/dist/mpp/charge.js +14 -102
- package/dist/settlement.d.ts +93 -0
- package/dist/settlement.js +220 -0
- package/dist/x402/simulator.d.ts +33 -0
- package/dist/x402/simulator.js +149 -29
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Most people should reach for [`@wasit-dev/cli`](https://www.npmjs.com/package/@w
|
|
|
14
14
|
npm install @wasit-dev/core
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
Requires Node.js `>=
|
|
17
|
+
Requires Node.js `>=22`. Ships ESM only (`"type": "module"`), with TypeScript types included (`dist/index.d.ts`).
|
|
18
18
|
|
|
19
19
|
## Usage
|
|
20
20
|
|
|
@@ -51,7 +51,7 @@ Every check function returns `Promise<CheckResult[]>` and never rejects for a ta
|
|
|
51
51
|
| Function | Checks | Cost |
|
|
52
52
|
|---|---|---|
|
|
53
53
|
| `runX402ReadChecks({ target, method?, body?, headers? })` | `X402-01`–`05` | Free |
|
|
54
|
-
| `runX402PaymentChecks({ target, network, payerSecretKey, method?, body?, headers? })` | `X402-06`, `07` | **Settles a real payment every call** |
|
|
54
|
+
| `runX402PaymentChecks({ target, network, payerSecretKey, rpcUrl?, method?, body?, headers? })` | `X402-06`, `07` | **Settles a real payment every call** |
|
|
55
55
|
|
|
56
56
|
### MPP — charge mode
|
|
57
57
|
|
package/dist/mpp/charge.js
CHANGED
|
@@ -14,17 +14,14 @@
|
|
|
14
14
|
* @stellar/mpp's own client guards against when it refuses to sign a
|
|
15
15
|
* non-transfer authorization.
|
|
16
16
|
*/
|
|
17
|
-
import { Address, rpc, scValToNative, xdr } from "@stellar/stellar-sdk";
|
|
18
17
|
import { Mppx, charge } from "@stellar/mpp/charge/client";
|
|
19
18
|
import { Challenge, Receipt } from "mppx";
|
|
20
19
|
import { Keypair } from "@stellar/stellar-sdk";
|
|
21
20
|
import { ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
|
|
22
21
|
import { assertMppNetwork, resolveRpcUrl } from "./network.js";
|
|
22
|
+
import { verifySettlement } from "../settlement.js";
|
|
23
23
|
const CHECK_ID = "MPP-01";
|
|
24
24
|
const CHECK_NAME = "Charge Settlement On-Chain";
|
|
25
|
-
/** How long to wait for the settled transaction to become visible to RPC. */
|
|
26
|
-
const POLL_ATTEMPTS = 12;
|
|
27
|
-
const POLL_DELAY_MS = 1_000;
|
|
28
25
|
function asRecord(value) {
|
|
29
26
|
return typeof value === "object" && value !== null
|
|
30
27
|
? value
|
|
@@ -92,45 +89,6 @@ export function parseChargeChallenge(challenge) {
|
|
|
92
89
|
}
|
|
93
90
|
return { amount, currency, recipient };
|
|
94
91
|
}
|
|
95
|
-
/**
|
|
96
|
-
* Extracts CAP-46 `transfer` events from a settled transaction.
|
|
97
|
-
*
|
|
98
|
-
* Adapted from @stellar/mpp's own `validateSimulationEvents`, with one
|
|
99
|
-
* necessary difference: that function reads `xdr.DiagnosticEvent[]` from a
|
|
100
|
-
* simulation and unwraps each via `.event()`. RPC's `getTransaction` returns
|
|
101
|
-
* `contractEventsXdr` as `xdr.ContractEvent[][]` — already unwrapped, and
|
|
102
|
-
* nested per operation. Calling `.event()` on these would throw at runtime.
|
|
103
|
-
*/
|
|
104
|
-
function collectTransferEvents(contractEventsXdr) {
|
|
105
|
-
const transfers = [];
|
|
106
|
-
for (const perOperation of contractEventsXdr) {
|
|
107
|
-
for (const contractEvent of perOperation) {
|
|
108
|
-
if (contractEvent.type().name !== "contract")
|
|
109
|
-
continue;
|
|
110
|
-
const body = contractEvent.body().v0();
|
|
111
|
-
const topics = body.topics();
|
|
112
|
-
if (topics.length < 3)
|
|
113
|
-
continue;
|
|
114
|
-
// CAP-46: topic[0] = "transfer", topic[1] = from, topic[2] = to.
|
|
115
|
-
if (topics[0]?.sym?.()?.toString() !== "transfer")
|
|
116
|
-
continue;
|
|
117
|
-
const amount = scValToNative(body.data());
|
|
118
|
-
if (typeof amount !== "bigint")
|
|
119
|
-
continue;
|
|
120
|
-
const contractId = contractEvent.contractId();
|
|
121
|
-
if (!contractId)
|
|
122
|
-
continue;
|
|
123
|
-
transfers.push({
|
|
124
|
-
from: Address.fromScVal(topics[1]).toString(),
|
|
125
|
-
to: Address.fromScVal(topics[2]).toString(),
|
|
126
|
-
amount,
|
|
127
|
-
contract: Address.fromScAddress(xdr.ScAddress.scAddressTypeContract(contractId)).toString(),
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
return transfers;
|
|
132
|
-
}
|
|
133
|
-
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
134
92
|
function fail(detail) {
|
|
135
93
|
return [{ id: CHECK_ID, name: CHECK_NAME, pass: false, detail }];
|
|
136
94
|
}
|
|
@@ -177,8 +135,10 @@ export async function runMppChargeChecks(options) {
|
|
|
177
135
|
throw new MalformedResponseError(`Payment attempt failed: ${error.message}`);
|
|
178
136
|
}
|
|
179
137
|
if (!paid.ok) {
|
|
180
|
-
return fail(`
|
|
181
|
-
`answered HTTP ${paid.status} instead of
|
|
138
|
+
return fail(`Submitted a payment for the advertised ${advertised.amount} base ` +
|
|
139
|
+
`units, but the target answered HTTP ${paid.status} instead of ` +
|
|
140
|
+
`serving the resource. Nothing is claimed about settlement: a target ` +
|
|
141
|
+
`that refuses may never have broadcast the transaction.`);
|
|
182
142
|
}
|
|
183
143
|
let reference;
|
|
184
144
|
try {
|
|
@@ -188,62 +148,14 @@ export async function runMppChargeChecks(options) {
|
|
|
188
148
|
return fail(`Target returned ${paid.status} but no valid Payment-Receipt header: ` +
|
|
189
149
|
`${error.message}`);
|
|
190
150
|
}
|
|
191
|
-
const
|
|
192
|
-
|
|
151
|
+
const verdict = await verifySettlement(endpoint, reference, {
|
|
152
|
+
amount: advertised.amount,
|
|
153
|
+
token: advertised.currency,
|
|
154
|
+
recipient: advertised.recipient,
|
|
155
|
+
payer: payer.publicKey(),
|
|
193
156
|
});
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
if (current.status !== rpc.Api.GetTransactionStatus.NOT_FOUND) {
|
|
199
|
-
settled = current;
|
|
200
|
-
break;
|
|
201
|
-
}
|
|
202
|
-
await sleep(POLL_DELAY_MS);
|
|
203
|
-
}
|
|
204
|
-
if (!settled || settled.status === rpc.Api.GetTransactionStatus.NOT_FOUND) {
|
|
205
|
-
return fail(`Target reported settlement as tx ${reference}, but RPC still has no ` +
|
|
206
|
-
`such transaction after ${POLL_ATTEMPTS} seconds. Either it was never ` +
|
|
207
|
-
`broadcast, or the receipt references a transaction that does not exist.`);
|
|
208
|
-
}
|
|
209
|
-
if (settled.status !== rpc.Api.GetTransactionStatus.SUCCESS) {
|
|
210
|
-
return fail(`Transaction ${reference} exists on-chain but failed (status ` +
|
|
211
|
-
`${settled.status}). The target reported success for a settlement that ` +
|
|
212
|
-
`did not settle.`);
|
|
213
|
-
}
|
|
214
|
-
const transfers = collectTransferEvents(settled.events.contractEventsXdr);
|
|
215
|
-
if (transfers.length === 0) {
|
|
216
|
-
return fail(`Transaction ${reference} succeeded but emitted no CAP-46 transfer ` +
|
|
217
|
-
`event, so no token movement can be verified.`);
|
|
218
|
-
}
|
|
219
|
-
// Per the MPP spec, events must show only the expected balance change.
|
|
220
|
-
if (transfers.length !== 1) {
|
|
221
|
-
return fail(`Transaction ${reference} emitted ${transfers.length} transfer events; ` +
|
|
222
|
-
`exactly one was expected. Additional balance changes mean the ` +
|
|
223
|
-
`settlement moved more than what was advertised.`);
|
|
224
|
-
}
|
|
225
|
-
const actual = transfers[0];
|
|
226
|
-
const mismatches = [];
|
|
227
|
-
if (actual.amount !== advertised.amount) {
|
|
228
|
-
mismatches.push(`amount: advertised ${advertised.amount} base units, moved ${actual.amount}`);
|
|
229
|
-
}
|
|
230
|
-
if (actual.to !== advertised.recipient) {
|
|
231
|
-
mismatches.push(`recipient: advertised ${advertised.recipient}, paid ${actual.to}`);
|
|
232
|
-
}
|
|
233
|
-
if (actual.contract !== advertised.currency) {
|
|
234
|
-
mismatches.push(`token: advertised ${advertised.currency}, moved ${actual.contract}`);
|
|
235
|
-
}
|
|
236
|
-
// Without this, a target could reference any pre-existing transaction that
|
|
237
|
-
// happens to match the amount and recipient, and never take payment at all.
|
|
238
|
-
if (actual.from !== payer.publicKey()) {
|
|
239
|
-
mismatches.push(`payer: this run paid from ${payer.publicKey()}, but the referenced ` +
|
|
240
|
-
`transfer came from ${actual.from}`);
|
|
241
|
-
}
|
|
242
|
-
if (mismatches.length > 0) {
|
|
243
|
-
return fail(`Settlement does not match what the target advertised — ` +
|
|
244
|
-
`${mismatches.join("; ")} (tx ${reference}).`);
|
|
245
|
-
}
|
|
246
|
-
return pass(`Settled on-chain for exactly the advertised ${advertised.amount} base ` +
|
|
247
|
-
`units of ${advertised.currency} to ${advertised.recipient}, verified ` +
|
|
248
|
-
`from the transfer event (tx ${reference}).`);
|
|
157
|
+
// Same sentence MPP-01 has always printed, capitalised and closed.
|
|
158
|
+
return verdict.pass
|
|
159
|
+
? pass(`${verdict.detail.charAt(0).toUpperCase()}${verdict.detail.slice(1)}.`)
|
|
160
|
+
: fail(verdict.detail);
|
|
249
161
|
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-chain settlement verification, shared by every check that pays.
|
|
3
|
+
*
|
|
4
|
+
* A target's claim that it settled is only a claim. These helpers look the
|
|
5
|
+
* referenced transaction up on Stellar RPC and read what the token contract
|
|
6
|
+
* actually did from its `transfer` event, so MPP-01 and X402-06 hold every
|
|
7
|
+
* target to the same standard, with the same reading of the event formats and
|
|
8
|
+
* the same rules for when a missing transaction is the target's fault.
|
|
9
|
+
*/
|
|
10
|
+
import { rpc, xdr } from "@stellar/stellar-sdk";
|
|
11
|
+
/** What the token contract actually did, read from the settled transaction. */
|
|
12
|
+
export interface TransferEvent {
|
|
13
|
+
readonly from: string;
|
|
14
|
+
/** The destination's base address. CAP-67 never puts a muxed address in a topic. */
|
|
15
|
+
readonly to: string;
|
|
16
|
+
/**
|
|
17
|
+
* The destination's multiplexing id, when the transfer went to a muxed
|
|
18
|
+
* address (CAP-67). A `u64` id is kept as its decimal string; a memo-derived
|
|
19
|
+
* string or bytes value is kept as given (bytes as hex).
|
|
20
|
+
*/
|
|
21
|
+
readonly toMuxedId?: string;
|
|
22
|
+
readonly amount: bigint;
|
|
23
|
+
readonly contract: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Extracts CAP-46 `transfer` events from a settled transaction.
|
|
27
|
+
*
|
|
28
|
+
* Adapted from @stellar/mpp's own `validateSimulationEvents`, with one
|
|
29
|
+
* necessary difference: that function reads `xdr.DiagnosticEvent[]` from a
|
|
30
|
+
* simulation and unwraps each via `.event()`. RPC's `getTransaction` returns
|
|
31
|
+
* `contractEventsXdr` as `xdr.ContractEvent[][]` — already unwrapped, and
|
|
32
|
+
* nested per operation. Calling `.event()` on these would throw at runtime.
|
|
33
|
+
* Both the CAP-46 and the CAP-67 data formats are read; see
|
|
34
|
+
* {@link readTransferData}.
|
|
35
|
+
*/
|
|
36
|
+
export declare function collectTransferEvents(contractEventsXdr: xdr.ContractEvent[][]): TransferEvent[];
|
|
37
|
+
/**
|
|
38
|
+
* Whether a transfer reached the recipient the target advertised.
|
|
39
|
+
*
|
|
40
|
+
* A muxed recipient (`M...`) is one base account plus an id, and CAP-67
|
|
41
|
+
* reports it that way: the base address in the topic, the id in the data. So
|
|
42
|
+
* an advertised muxed recipient matches only when both parts do. Any other
|
|
43
|
+
* recipient is compared by address, as before.
|
|
44
|
+
*/
|
|
45
|
+
export declare function transferReachedRecipient(advertised: string, transfer: TransferEvent): boolean;
|
|
46
|
+
/** What looking for a settled transaction on RPC established. */
|
|
47
|
+
export type TransactionLookup = {
|
|
48
|
+
readonly kind: "found";
|
|
49
|
+
readonly response: rpc.Api.GetTransactionResponse;
|
|
50
|
+
} | {
|
|
51
|
+
readonly kind: "missing";
|
|
52
|
+
readonly ledgersWatched: number;
|
|
53
|
+
} | {
|
|
54
|
+
readonly kind: "stalled";
|
|
55
|
+
readonly ledgersWatched: number;
|
|
56
|
+
readonly waitedMs: number;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Polls RPC for a transaction until it appears, until RPC has closed enough
|
|
60
|
+
* ledgers without it to say it is missing, or until RPC stops advancing.
|
|
61
|
+
*
|
|
62
|
+
* Takes the lookup, the clock and the sleep as parameters so the three
|
|
63
|
+
* outcomes can be exercised without a network.
|
|
64
|
+
*/
|
|
65
|
+
export declare function waitForTransaction(getTransaction: () => Promise<rpc.Api.GetTransactionResponse>, options?: {
|
|
66
|
+
readonly ledgers?: number;
|
|
67
|
+
readonly maxWaitMs?: number;
|
|
68
|
+
readonly delayMs?: number;
|
|
69
|
+
readonly now?: () => number;
|
|
70
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
71
|
+
}): Promise<TransactionLookup>;
|
|
72
|
+
/** What a target advertised it would be paid, and who this run paid from. */
|
|
73
|
+
export interface ExpectedSettlement {
|
|
74
|
+
/** In base units, directly comparable to the event's `i128`. */
|
|
75
|
+
readonly amount: bigint;
|
|
76
|
+
/** The token contract (`C...`). */
|
|
77
|
+
readonly token: string;
|
|
78
|
+
readonly recipient: string;
|
|
79
|
+
/** This run's own payer, so an unrelated transaction cannot pass. */
|
|
80
|
+
readonly payer: string;
|
|
81
|
+
}
|
|
82
|
+
/** A verdict about the target's settlement. */
|
|
83
|
+
export interface SettlementVerdict {
|
|
84
|
+
readonly pass: boolean;
|
|
85
|
+
readonly detail: string;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Verifies that `reference` settled exactly what was expected.
|
|
89
|
+
*
|
|
90
|
+
* Returns a verdict about the target. Throws when RPC stops advancing, which
|
|
91
|
+
* says nothing about the target; callers report that as no verdict.
|
|
92
|
+
*/
|
|
93
|
+
export declare function verifySettlement(rpcUrl: string, reference: string, expected: ExpectedSettlement): Promise<SettlementVerdict>;
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-chain settlement verification, shared by every check that pays.
|
|
3
|
+
*
|
|
4
|
+
* A target's claim that it settled is only a claim. These helpers look the
|
|
5
|
+
* referenced transaction up on Stellar RPC and read what the token contract
|
|
6
|
+
* actually did from its `transfer` event, so MPP-01 and X402-06 hold every
|
|
7
|
+
* target to the same standard, with the same reading of the event formats and
|
|
8
|
+
* the same rules for when a missing transaction is the target's fault.
|
|
9
|
+
*/
|
|
10
|
+
import { Address, MuxedAccount, StrKey, rpc, scValToNative, xdr } from "@stellar/stellar-sdk";
|
|
11
|
+
/**
|
|
12
|
+
* How long to look for the settled transaction.
|
|
13
|
+
*
|
|
14
|
+
* A fixed wall-clock wait cannot tell a transaction that does not exist from
|
|
15
|
+
* an RPC that is behind, and reporting the second as the first blames the
|
|
16
|
+
* target for our infrastructure. So the wait is measured in ledgers RPC has
|
|
17
|
+
* closed: once it has closed this many more without the transaction, the
|
|
18
|
+
* transaction is not coming. An RPC that stops advancing before then gives no
|
|
19
|
+
* verdict at all.
|
|
20
|
+
*/
|
|
21
|
+
const LEDGERS_BEFORE_MISSING = 10;
|
|
22
|
+
const MAX_WAIT_MS = 120_000;
|
|
23
|
+
const POLL_DELAY_MS = 1_000;
|
|
24
|
+
function asRecord(value) {
|
|
25
|
+
return typeof value === "object" && value !== null
|
|
26
|
+
? value
|
|
27
|
+
: undefined;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Reads the amount, and the destination's muxed id if any, from a `transfer`
|
|
31
|
+
* event's data.
|
|
32
|
+
*
|
|
33
|
+
* CAP-46 made the data a bare `i128` amount. CAP-67 keeps that when no muxed
|
|
34
|
+
* information is emitted, and otherwise makes it a map
|
|
35
|
+
* `{ amount: i128, to_muxed_id: u64 | bytes | string }`. Reading only the bare
|
|
36
|
+
* form would drop every payment to a muxed address, and report a settlement
|
|
37
|
+
* that happened as one that did not.
|
|
38
|
+
*/
|
|
39
|
+
function readTransferData(data) {
|
|
40
|
+
const native = scValToNative(data);
|
|
41
|
+
if (typeof native === "bigint")
|
|
42
|
+
return { amount: native };
|
|
43
|
+
const map = asRecord(native);
|
|
44
|
+
if (!map || typeof map["amount"] !== "bigint")
|
|
45
|
+
return undefined;
|
|
46
|
+
const id = map["to_muxed_id"];
|
|
47
|
+
if (id === undefined)
|
|
48
|
+
return { amount: map["amount"] };
|
|
49
|
+
if (typeof id === "bigint" || typeof id === "number") {
|
|
50
|
+
return { amount: map["amount"], toMuxedId: id.toString() };
|
|
51
|
+
}
|
|
52
|
+
if (typeof id === "string")
|
|
53
|
+
return { amount: map["amount"], toMuxedId: id };
|
|
54
|
+
if (id instanceof Uint8Array) {
|
|
55
|
+
return { amount: map["amount"], toMuxedId: Buffer.from(id).toString("hex") };
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Extracts CAP-46 `transfer` events from a settled transaction.
|
|
61
|
+
*
|
|
62
|
+
* Adapted from @stellar/mpp's own `validateSimulationEvents`, with one
|
|
63
|
+
* necessary difference: that function reads `xdr.DiagnosticEvent[]` from a
|
|
64
|
+
* simulation and unwraps each via `.event()`. RPC's `getTransaction` returns
|
|
65
|
+
* `contractEventsXdr` as `xdr.ContractEvent[][]` — already unwrapped, and
|
|
66
|
+
* nested per operation. Calling `.event()` on these would throw at runtime.
|
|
67
|
+
* Both the CAP-46 and the CAP-67 data formats are read; see
|
|
68
|
+
* {@link readTransferData}.
|
|
69
|
+
*/
|
|
70
|
+
export function collectTransferEvents(contractEventsXdr) {
|
|
71
|
+
const transfers = [];
|
|
72
|
+
for (const perOperation of contractEventsXdr) {
|
|
73
|
+
for (const contractEvent of perOperation) {
|
|
74
|
+
if (contractEvent.type().name !== "contract")
|
|
75
|
+
continue;
|
|
76
|
+
const body = contractEvent.body().v0();
|
|
77
|
+
const topics = body.topics();
|
|
78
|
+
if (topics.length < 3)
|
|
79
|
+
continue;
|
|
80
|
+
// CAP-46: topic[0] = "transfer", topic[1] = from, topic[2] = to.
|
|
81
|
+
if (topics[0]?.sym?.()?.toString() !== "transfer")
|
|
82
|
+
continue;
|
|
83
|
+
const data = readTransferData(body.data());
|
|
84
|
+
if (!data)
|
|
85
|
+
continue;
|
|
86
|
+
const contractId = contractEvent.contractId();
|
|
87
|
+
if (!contractId)
|
|
88
|
+
continue;
|
|
89
|
+
transfers.push({
|
|
90
|
+
from: Address.fromScVal(topics[1]).toString(),
|
|
91
|
+
to: Address.fromScVal(topics[2]).toString(),
|
|
92
|
+
...(data.toMuxedId !== undefined ? { toMuxedId: data.toMuxedId } : {}),
|
|
93
|
+
amount: data.amount,
|
|
94
|
+
contract: Address.fromScAddress(xdr.ScAddress.scAddressTypeContract(contractId)).toString(),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return transfers;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Whether a transfer reached the recipient the target advertised.
|
|
102
|
+
*
|
|
103
|
+
* A muxed recipient (`M...`) is one base account plus an id, and CAP-67
|
|
104
|
+
* reports it that way: the base address in the topic, the id in the data. So
|
|
105
|
+
* an advertised muxed recipient matches only when both parts do. Any other
|
|
106
|
+
* recipient is compared by address, as before.
|
|
107
|
+
*/
|
|
108
|
+
export function transferReachedRecipient(advertised, transfer) {
|
|
109
|
+
if (StrKey.isValidMed25519PublicKey(advertised)) {
|
|
110
|
+
const muxed = MuxedAccount.fromAddress(advertised, "0");
|
|
111
|
+
return (transfer.to === muxed.baseAccount().accountId() &&
|
|
112
|
+
transfer.toMuxedId === muxed.id());
|
|
113
|
+
}
|
|
114
|
+
return transfer.to === advertised;
|
|
115
|
+
}
|
|
116
|
+
/** How a transfer's destination reads in a report. */
|
|
117
|
+
function describeDestination(transfer) {
|
|
118
|
+
return transfer.toMuxedId === undefined
|
|
119
|
+
? transfer.to
|
|
120
|
+
: `${transfer.to} (muxed id ${transfer.toMuxedId})`;
|
|
121
|
+
}
|
|
122
|
+
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
123
|
+
/**
|
|
124
|
+
* Polls RPC for a transaction until it appears, until RPC has closed enough
|
|
125
|
+
* ledgers without it to say it is missing, or until RPC stops advancing.
|
|
126
|
+
*
|
|
127
|
+
* Takes the lookup, the clock and the sleep as parameters so the three
|
|
128
|
+
* outcomes can be exercised without a network.
|
|
129
|
+
*/
|
|
130
|
+
export async function waitForTransaction(getTransaction, options = {}) {
|
|
131
|
+
const ledgers = options.ledgers ?? LEDGERS_BEFORE_MISSING;
|
|
132
|
+
const maxWaitMs = options.maxWaitMs ?? MAX_WAIT_MS;
|
|
133
|
+
const delayMs = options.delayMs ?? POLL_DELAY_MS;
|
|
134
|
+
const now = options.now ?? Date.now;
|
|
135
|
+
const pause = options.sleep ?? sleep;
|
|
136
|
+
const startedAt = now();
|
|
137
|
+
let firstLedger;
|
|
138
|
+
for (;;) {
|
|
139
|
+
// An RPC failure is a harness problem: it says nothing about the target.
|
|
140
|
+
const current = await getTransaction();
|
|
141
|
+
if (current.status !== rpc.Api.GetTransactionStatus.NOT_FOUND) {
|
|
142
|
+
return { kind: "found", response: current };
|
|
143
|
+
}
|
|
144
|
+
firstLedger ??= current.latestLedger;
|
|
145
|
+
const ledgersWatched = current.latestLedger - firstLedger;
|
|
146
|
+
if (ledgersWatched >= ledgers)
|
|
147
|
+
return { kind: "missing", ledgersWatched };
|
|
148
|
+
const waitedMs = now() - startedAt;
|
|
149
|
+
if (waitedMs >= maxWaitMs)
|
|
150
|
+
return { kind: "stalled", ledgersWatched, waitedMs };
|
|
151
|
+
await pause(delayMs);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Verifies that `reference` settled exactly what was expected.
|
|
156
|
+
*
|
|
157
|
+
* Returns a verdict about the target. Throws when RPC stops advancing, which
|
|
158
|
+
* says nothing about the target; callers report that as no verdict.
|
|
159
|
+
*/
|
|
160
|
+
export async function verifySettlement(rpcUrl, reference, expected) {
|
|
161
|
+
const fail = (detail) => ({ pass: false, detail });
|
|
162
|
+
const server = new rpc.Server(rpcUrl, { allowHttp: rpcUrl.startsWith("http://") });
|
|
163
|
+
const lookup = await waitForTransaction(() => server.getTransaction(reference));
|
|
164
|
+
if (lookup.kind === "stalled") {
|
|
165
|
+
// RPC not advancing says nothing about the target: no verdict.
|
|
166
|
+
throw new Error(`RPC at ${rpcUrl} closed only ${lookup.ledgersWatched} ledgers in ` +
|
|
167
|
+
`${Math.round(lookup.waitedMs / 1000)} seconds while looking for tx ` +
|
|
168
|
+
`${reference}, so its absence says nothing about the target. Re-run, ` +
|
|
169
|
+
`or point --rpc-url at another endpoint.`);
|
|
170
|
+
}
|
|
171
|
+
if (lookup.kind === "missing") {
|
|
172
|
+
return fail(`Target reported settlement as tx ${reference}, but RPC closed ` +
|
|
173
|
+
`${lookup.ledgersWatched} more ledgers without it. Either it was never ` +
|
|
174
|
+
`broadcast, or the target referenced a transaction that does not exist.`);
|
|
175
|
+
}
|
|
176
|
+
const settled = lookup.response;
|
|
177
|
+
if (settled.status !== rpc.Api.GetTransactionStatus.SUCCESS) {
|
|
178
|
+
return fail(`Transaction ${reference} exists on-chain but failed (status ` +
|
|
179
|
+
`${settled.status}). The target reported success for a settlement that ` +
|
|
180
|
+
`did not settle.`);
|
|
181
|
+
}
|
|
182
|
+
const transfers = collectTransferEvents(settled.events.contractEventsXdr);
|
|
183
|
+
if (transfers.length === 0) {
|
|
184
|
+
return fail(`Transaction ${reference} succeeded but emitted no CAP-46 transfer ` +
|
|
185
|
+
`event, so no token movement can be verified.`);
|
|
186
|
+
}
|
|
187
|
+
// Both specs require the events to show only the expected balance change.
|
|
188
|
+
if (transfers.length !== 1) {
|
|
189
|
+
return fail(`Transaction ${reference} emitted ${transfers.length} transfer events; ` +
|
|
190
|
+
`exactly one was expected. Additional balance changes mean the ` +
|
|
191
|
+
`settlement moved more than what was advertised.`);
|
|
192
|
+
}
|
|
193
|
+
const actual = transfers[0];
|
|
194
|
+
const mismatches = [];
|
|
195
|
+
if (actual.amount !== expected.amount) {
|
|
196
|
+
mismatches.push(`amount: advertised ${expected.amount} base units, moved ${actual.amount}`);
|
|
197
|
+
}
|
|
198
|
+
if (!transferReachedRecipient(expected.recipient, actual)) {
|
|
199
|
+
mismatches.push(`recipient: advertised ${expected.recipient}, paid ${describeDestination(actual)}`);
|
|
200
|
+
}
|
|
201
|
+
if (actual.contract !== expected.token) {
|
|
202
|
+
mismatches.push(`token: advertised ${expected.token}, moved ${actual.contract}`);
|
|
203
|
+
}
|
|
204
|
+
// Without this, a target could reference any pre-existing transaction that
|
|
205
|
+
// happens to match the amount and recipient, and never take payment at all.
|
|
206
|
+
if (actual.from !== expected.payer) {
|
|
207
|
+
mismatches.push(`payer: this run paid from ${expected.payer}, but the referenced ` +
|
|
208
|
+
`transfer came from ${actual.from}`);
|
|
209
|
+
}
|
|
210
|
+
if (mismatches.length > 0) {
|
|
211
|
+
return fail(`Settlement does not match what the target advertised — ` +
|
|
212
|
+
`${mismatches.join("; ")} (tx ${reference}).`);
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
pass: true,
|
|
216
|
+
detail: `settled on-chain for exactly the advertised ${expected.amount} base ` +
|
|
217
|
+
`units of ${expected.token} to ${expected.recipient}, verified from the ` +
|
|
218
|
+
`transfer event (tx ${reference})`,
|
|
219
|
+
};
|
|
220
|
+
}
|
package/dist/x402/simulator.d.ts
CHANGED
|
@@ -47,9 +47,42 @@ export interface X402PaymentCheckOptions extends RequestShape {
|
|
|
47
47
|
readonly target: string;
|
|
48
48
|
readonly network: string;
|
|
49
49
|
readonly payerSecretKey: string;
|
|
50
|
+
/** Overrides the default RPC endpoint used to verify settlement. */
|
|
51
|
+
readonly rpcUrl?: string;
|
|
50
52
|
/** See {@link X402SimulatorOptions.onResult} — same contract. */
|
|
51
53
|
readonly onResult?: (result: CheckResult) => void;
|
|
52
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* Reads the settlement a paid response reports, before anything is looked up.
|
|
57
|
+
*
|
|
58
|
+
* Takes the header decoder rather than the response so the rules can be
|
|
59
|
+
* exercised without a network. `readSettlement` throws when the response
|
|
60
|
+
* carries no `PAYMENT-RESPONSE` header, as `x402HTTPClient` does.
|
|
61
|
+
*/
|
|
62
|
+
export declare function readSettlementReference(status: number, readSettlement: () => {
|
|
63
|
+
readonly success: boolean;
|
|
64
|
+
readonly transaction?: string;
|
|
65
|
+
readonly errorReason?: string;
|
|
66
|
+
}): {
|
|
67
|
+
readonly reference: string;
|
|
68
|
+
} | {
|
|
69
|
+
readonly failure: string;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Corrupts the client's authorization signature, and nothing else.
|
|
73
|
+
*
|
|
74
|
+
* In the `exact` scheme on Stellar the client signs a Soroban authorization
|
|
75
|
+
* entry, not the envelope: the facilitator signs the envelope later. So the
|
|
76
|
+
* signature that proves the payer consented is the address credential's
|
|
77
|
+
* `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
|
|
78
|
+
* leaves a transaction that still decodes, carries the same amount, payer and
|
|
79
|
+
* recipient, and fails only signature verification. A target can refuse it
|
|
80
|
+
* only by verifying the signature.
|
|
81
|
+
*
|
|
82
|
+
* Throws {@link CheckSetupError} if the payload carries no such signature, so
|
|
83
|
+
* the check reports no verdict rather than one it did not establish.
|
|
84
|
+
*/
|
|
85
|
+
export declare function corruptAuthSignature(transaction: string): string;
|
|
53
86
|
/**
|
|
54
87
|
* Runs X402-06 and X402-07 against a target.
|
|
55
88
|
*
|
package/dist/x402/simulator.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { errored, skipped } from "../check.js";
|
|
2
|
-
import { ConfigurationError, assertHttpUrl, fetchTarget, } from "../errors.js";
|
|
2
|
+
import { CheckSetupError, ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
|
|
3
3
|
const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
|
|
4
4
|
const KNOWN_METHODS = new Set([
|
|
5
5
|
"GET",
|
|
@@ -318,6 +318,9 @@ export async function runX402ReadChecks(options) {
|
|
|
318
318
|
import { x402Client, x402HTTPClient } from "@x402/fetch";
|
|
319
319
|
import { createEd25519Signer } from "@x402/stellar";
|
|
320
320
|
import { ExactStellarScheme as ExactStellarClientScheme } from "@x402/stellar/exact/client";
|
|
321
|
+
import { Keypair, xdr } from "@stellar/stellar-sdk";
|
|
322
|
+
import { resolveRpcUrl } from "../mpp/network.js";
|
|
323
|
+
import { verifySettlement } from "../settlement.js";
|
|
321
324
|
/** The payment flow was never started, so neither payment check has a verdict. */
|
|
322
325
|
class PaymentNotAttemptedError extends Error {
|
|
323
326
|
constructor(reason) {
|
|
@@ -361,56 +364,173 @@ async function preparePayment(options) {
|
|
|
361
364
|
const paymentPayload = await client.createPaymentPayload(paymentRequired);
|
|
362
365
|
return { httpClient, paymentPayload };
|
|
363
366
|
}
|
|
364
|
-
/**
|
|
367
|
+
/** A Stellar transaction hash: 64 hex characters. */
|
|
368
|
+
const TRANSACTION_HASH = /^[0-9a-f]{64}$/i;
|
|
369
|
+
/**
|
|
370
|
+
* Reads the settlement a paid response reports, before anything is looked up.
|
|
371
|
+
*
|
|
372
|
+
* Takes the header decoder rather than the response so the rules can be
|
|
373
|
+
* exercised without a network. `readSettlement` throws when the response
|
|
374
|
+
* carries no `PAYMENT-RESPONSE` header, as `x402HTTPClient` does.
|
|
375
|
+
*/
|
|
376
|
+
export function readSettlementReference(status, readSettlement) {
|
|
377
|
+
let settlement;
|
|
378
|
+
try {
|
|
379
|
+
settlement = readSettlement();
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
return {
|
|
383
|
+
failure: `Valid payment accepted (HTTP ${status}), but the response carried no ` +
|
|
384
|
+
`PAYMENT-RESPONSE header, which the x402 v2 HTTP transport uses to ` +
|
|
385
|
+
`report settlement. Whether the payment settled cannot be verified.`,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
const reference = settlement.transaction ?? "";
|
|
389
|
+
// `settlement_pending` means broadcast but unconfirmed; the x402 spec has the
|
|
390
|
+
// caller reconcile on chain, which is exactly what X402-06 goes on to do.
|
|
391
|
+
const pending = !settlement.success && settlement.errorReason === "settlement_pending";
|
|
392
|
+
if ((!settlement.success && !pending) || !TRANSACTION_HASH.test(reference)) {
|
|
393
|
+
return {
|
|
394
|
+
failure: `Valid payment accepted (HTTP ${status}), but its PAYMENT-RESPONSE ` +
|
|
395
|
+
`reports ${settlement.success ? "success" : "failure"} with transaction ` +
|
|
396
|
+
`${JSON.stringify(reference)}, not a settled Stellar transaction hash.`,
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
return { reference };
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* X402-06: a valid payment must be accepted, and must settle on-chain.
|
|
403
|
+
*
|
|
404
|
+
* A 2xx proves only that the target served the resource. The x402 v2 HTTP
|
|
405
|
+
* transport reports settlement in the `PAYMENT-RESPONSE` header, whose
|
|
406
|
+
* `transaction` is, for the `exact` scheme on Stellar, the settlement's hash.
|
|
407
|
+
* That hash is looked up on RPC and the token contract's own transfer event is
|
|
408
|
+
* held to what the target advertised, as MPP-01 does: a target that serves
|
|
409
|
+
* the resource without settling, or settles something else, fails here.
|
|
410
|
+
*/
|
|
365
411
|
async function checkSignatureAccepted(options) {
|
|
412
|
+
const id = "X402-06";
|
|
413
|
+
const name = "Signature Resubmit Accepted";
|
|
414
|
+
const fail = (detail) => ({ id, name, pass: false, detail });
|
|
366
415
|
const { httpClient, paymentPayload } = await preparePayment(options);
|
|
367
416
|
const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
|
|
368
417
|
const paid = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
418
|
+
if (paid.status < 200 || paid.status >= 300) {
|
|
419
|
+
return fail(`Expected 2xx after a valid payment, got ${paid.status}.`);
|
|
420
|
+
}
|
|
421
|
+
const read = readSettlementReference(paid.status, () => httpClient.getPaymentSettleResponse((header) => paid.headers.get(header)));
|
|
422
|
+
if ("failure" in read)
|
|
423
|
+
return fail(read.failure);
|
|
424
|
+
const reference = read.reference;
|
|
425
|
+
const accepted = paymentPayload.accepted;
|
|
426
|
+
let amount;
|
|
427
|
+
try {
|
|
428
|
+
amount = BigInt(accepted.amount);
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
throw new MalformedResponseError(`The accepted payment requirements carry a non-numeric amount ` +
|
|
432
|
+
`(${JSON.stringify(accepted.amount)}).`);
|
|
433
|
+
}
|
|
434
|
+
const rpcUrl = resolveRpcUrl(options.network, options.rpcUrl);
|
|
435
|
+
const verdict = await verifySettlement(rpcUrl, reference, {
|
|
436
|
+
amount,
|
|
437
|
+
token: accepted.asset,
|
|
438
|
+
recipient: accepted.payTo,
|
|
439
|
+
payer: Keypair.fromSecret(options.payerSecretKey).publicKey(),
|
|
440
|
+
});
|
|
441
|
+
return verdict.pass
|
|
442
|
+
? {
|
|
443
|
+
id,
|
|
444
|
+
name,
|
|
445
|
+
pass: true,
|
|
446
|
+
detail: `Valid payment accepted (HTTP ${paid.status}) and ${verdict.detail}.`,
|
|
447
|
+
}
|
|
448
|
+
: fail(verdict.detail);
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Corrupts the client's authorization signature, and nothing else.
|
|
452
|
+
*
|
|
453
|
+
* In the `exact` scheme on Stellar the client signs a Soroban authorization
|
|
454
|
+
* entry, not the envelope: the facilitator signs the envelope later. So the
|
|
455
|
+
* signature that proves the payer consented is the address credential's
|
|
456
|
+
* `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
|
|
457
|
+
* leaves a transaction that still decodes, carries the same amount, payer and
|
|
458
|
+
* recipient, and fails only signature verification. A target can refuse it
|
|
459
|
+
* only by verifying the signature.
|
|
460
|
+
*
|
|
461
|
+
* Throws {@link CheckSetupError} if the payload carries no such signature, so
|
|
462
|
+
* the check reports no verdict rather than one it did not establish.
|
|
463
|
+
*/
|
|
464
|
+
export function corruptAuthSignature(transaction) {
|
|
465
|
+
const envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64");
|
|
466
|
+
const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : [];
|
|
467
|
+
let corrupted = false;
|
|
468
|
+
for (const operation of operations) {
|
|
469
|
+
if (operation.body().switch().name !== "invokeHostFunction")
|
|
470
|
+
continue;
|
|
471
|
+
for (const entry of operation.body().invokeHostFunctionOp().auth()) {
|
|
472
|
+
const credentials = entry.credentials();
|
|
473
|
+
if (credentials.switch().name !== "sorobanCredentialsAddress")
|
|
474
|
+
continue;
|
|
475
|
+
const signature = credentials.address().signature();
|
|
476
|
+
if (signature.switch().name !== "scvVec")
|
|
477
|
+
continue;
|
|
478
|
+
for (const item of signature.vec() ?? []) {
|
|
479
|
+
if (item.switch().name !== "scvMap")
|
|
480
|
+
continue;
|
|
481
|
+
for (const field of item.map() ?? []) {
|
|
482
|
+
if (field.key().switch().name !== "scvSymbol")
|
|
483
|
+
continue;
|
|
484
|
+
if (field.key().sym().toString() !== "signature")
|
|
485
|
+
continue;
|
|
486
|
+
const bytes = Buffer.from(field.val().bytes());
|
|
487
|
+
bytes[0] = bytes[0] ^ 0xff;
|
|
488
|
+
field.val(xdr.ScVal.scvBytes(bytes));
|
|
489
|
+
corrupted = true;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (!corrupted) {
|
|
495
|
+
throw new CheckSetupError("The payment payload carries no authorization-entry signature to " +
|
|
496
|
+
"corrupt, so a corrupted signature cannot be tested.");
|
|
497
|
+
}
|
|
498
|
+
return envelope.toXDR("base64");
|
|
378
499
|
}
|
|
379
500
|
/**
|
|
380
501
|
* X402-07 (negative): a corrupted signature must be rejected.
|
|
381
502
|
*
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
*
|
|
503
|
+
* The payment is built exactly as for X402-06, then only the client's
|
|
504
|
+
* authorization signature is corrupted (see {@link corruptAuthSignature}), so
|
|
505
|
+
* the envelope still decodes and a target can refuse it only by verifying the
|
|
506
|
+
* signature. Before 0.6.0 the base64 envelope's tail was overwritten instead,
|
|
507
|
+
* which broke XDR decoding: a target that parsed the envelope and skipped
|
|
508
|
+
* signature verification entirely still passed.
|
|
509
|
+
*
|
|
510
|
+
* A rejection is any non-2xx answer. A rejection is only established by an
|
|
511
|
+
* answer: anything that prevents one produces no verdict.
|
|
386
512
|
*/
|
|
387
513
|
async function checkInvalidSignatureRejected(options) {
|
|
388
514
|
const { httpClient, paymentPayload } = await preparePayment(options);
|
|
389
|
-
// Corrupt the signed transaction after signing. This overwrites the tail of
|
|
390
|
-
// the base64 envelope, which also drops its padding — so the decoded envelope
|
|
391
|
-
// gains two bytes and stops parsing as XDR. Against the reference facilitator
|
|
392
|
-
// in stellar/x402-stellar the rejection therefore happens at decoding, not at
|
|
393
|
-
// signature verification, which is weaker than this check should be: a target
|
|
394
|
-
// that parsed the envelope and skipped verification entirely would still pass.
|
|
395
|
-
// Corrupting only the signature bytes, preserving a decodable envelope, is a
|
|
396
|
-
// tracked for 0.6.0. See docs/CHECKS.md's X402-07 row.
|
|
397
515
|
const corrupted = {
|
|
398
516
|
...paymentPayload,
|
|
399
517
|
payload: {
|
|
400
518
|
...paymentPayload.payload,
|
|
401
|
-
transaction: paymentPayload.payload.transaction
|
|
519
|
+
transaction: corruptAuthSignature(paymentPayload.payload.transaction),
|
|
402
520
|
},
|
|
403
521
|
};
|
|
404
522
|
const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted);
|
|
405
523
|
const response = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
|
|
406
|
-
const
|
|
524
|
+
const accepted = response.status >= 200 && response.status < 300;
|
|
407
525
|
return {
|
|
408
526
|
id: "X402-07",
|
|
409
527
|
name: "Invalid Signature Rejected",
|
|
410
|
-
pass,
|
|
411
|
-
detail:
|
|
412
|
-
? `
|
|
413
|
-
|
|
528
|
+
pass: !accepted,
|
|
529
|
+
detail: accepted
|
|
530
|
+
? `A payment with a corrupted authorization signature was accepted with ` +
|
|
531
|
+
`HTTP ${response.status} — security-relevant failure.`
|
|
532
|
+
: `Payment with a corrupted authorization signature correctly rejected ` +
|
|
533
|
+
`(HTTP ${response.status}).`,
|
|
414
534
|
};
|
|
415
535
|
}
|
|
416
536
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wasit-dev/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Check suite for x402/MPP protocol-conformance testing on Stellar. Powers the wasit CLI and wasit-mcp server.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"author": "Muhammad Dzakwan Najmi",
|
|
29
29
|
"license": "Apache-2.0",
|
|
30
30
|
"engines": {
|
|
31
|
-
"node": ">=
|
|
31
|
+
"node": ">=22"
|
|
32
32
|
},
|
|
33
33
|
"publishConfig": {
|
|
34
34
|
"access": "public"
|