@wasit-dev/core 0.5.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 +12 -4
- 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 +93 -105
- package/dist/settlement.d.ts +93 -0
- package/dist/settlement.js +220 -0
- 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 +41 -2
- package/dist/x402/simulator.js +576 -165
- package/package.json +12 -7
package/dist/mpp/charge.js
CHANGED
|
@@ -4,7 +4,10 @@
|
|
|
4
4
|
* The target's own 402 challenge is the source of truth for what should be
|
|
5
5
|
* paid. Verifying against it rather than against this run's configuration is
|
|
6
6
|
* what makes the check meaningful against a third-party service: it asks
|
|
7
|
-
* whether the service settled what it advertised, not what we assumed.
|
|
7
|
+
* whether the service settled what it advertised, not what we assumed. The
|
|
8
|
+
* one term it does not get to choose is the network: Wasit signs only for the
|
|
9
|
+
* network the run names, so a target cannot redirect the payer's key to
|
|
10
|
+
* mainnet by asking for it.
|
|
8
11
|
*
|
|
9
12
|
* Settlement is verified from the CAP-46 `transfer` contract event rather than
|
|
10
13
|
* the transaction envelope, because those can disagree. The envelope records
|
|
@@ -14,17 +17,14 @@
|
|
|
14
17
|
* @stellar/mpp's own client guards against when it refuses to sign a
|
|
15
18
|
* non-transfer authorization.
|
|
16
19
|
*/
|
|
17
|
-
import { Address, rpc, scValToNative, xdr } from "@stellar/stellar-sdk";
|
|
18
20
|
import { Mppx, charge } from "@stellar/mpp/charge/client";
|
|
19
21
|
import { Challenge, Receipt } from "mppx";
|
|
20
22
|
import { Keypair } from "@stellar/stellar-sdk";
|
|
21
23
|
import { ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
|
|
22
|
-
import { assertMppNetwork, resolveRpcUrl } from "./network.js";
|
|
24
|
+
import { assertMppNetwork, isMppNetwork, resolveRpcUrl } from "./network.js";
|
|
25
|
+
import { verifySettlement } from "../settlement.js";
|
|
23
26
|
const CHECK_ID = "MPP-01";
|
|
24
27
|
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
28
|
function asRecord(value) {
|
|
29
29
|
return typeof value === "object" && value !== null
|
|
30
30
|
? value
|
|
@@ -90,47 +90,67 @@ export function parseChargeChallenge(challenge) {
|
|
|
90
90
|
throw new MalformedResponseError(`Challenge advertises a non-numeric amount ("${amountRaw}"). The spec ` +
|
|
91
91
|
`requires base units, e.g. "10000" for 0.001 of a 7-decimal token.`);
|
|
92
92
|
}
|
|
93
|
-
return { amount, currency, recipient };
|
|
93
|
+
return { amount, currency, recipient, network: chargeNetwork(request) };
|
|
94
94
|
}
|
|
95
95
|
/**
|
|
96
|
-
*
|
|
96
|
+
* The network @stellar/mpp's charge client signs a challenge for.
|
|
97
97
|
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
* nested per operation. Calling `.event()` on these would throw at runtime.
|
|
98
|
+
* The client takes it from the challenge, `methodDetails.network`, and signs a
|
|
99
|
+
* challenge that names none for testnet (`resolveNetworkId`,
|
|
100
|
+
* dist/shared/validation.js in 0.7.1). This reads it the same way, because
|
|
101
|
+
* what matters is the network the signature will be valid on.
|
|
103
102
|
*/
|
|
104
|
-
function
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
103
|
+
function chargeNetwork(request) {
|
|
104
|
+
const network = asRecord(request["methodDetails"])?.["network"];
|
|
105
|
+
if (network === undefined || network === null)
|
|
106
|
+
return "stellar:testnet";
|
|
107
|
+
if (typeof network === "string" && isMppNetwork(network))
|
|
108
|
+
return network;
|
|
109
|
+
throw new MalformedResponseError(`Charge challenge names network ${JSON.stringify(network)}. A Stellar ` +
|
|
110
|
+
`network is "stellar:testnet" or "stellar:pubnet" (CAIP-2).`);
|
|
111
|
+
}
|
|
112
|
+
/** Refuses a challenge for any network but the run's, before anything is signed. */
|
|
113
|
+
function assertRunNetwork(asked, network) {
|
|
114
|
+
if (asked !== network) {
|
|
115
|
+
throw new ConfigurationError(`The target asks to be paid on ${asked}, and this run pays on ${network} ` +
|
|
116
|
+
`only, so nothing was signed.`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* `method`, refusing to sign a challenge for any network but `network`.
|
|
121
|
+
*
|
|
122
|
+
* Checking the unpaid challenge is not enough on its own: mppx requests the
|
|
123
|
+
* target again and pays the challenge in that answer, which the target is
|
|
124
|
+
* free to change. So the check also sits here, on the exact challenge about to
|
|
125
|
+
* be signed. Without it a target asking for `stellar:pubnet` gets a mainnet
|
|
126
|
+
* transfer signed, sent through the SDK's own default pubnet RPC endpoint.
|
|
127
|
+
*/
|
|
128
|
+
function onNetwork(method, network) {
|
|
129
|
+
return {
|
|
130
|
+
...method,
|
|
131
|
+
createCredential: async (parameters) => {
|
|
132
|
+
assertRunNetwork(chargeNetwork(asRecord(parameters.challenge.request) ?? {}), network);
|
|
133
|
+
return method.createCredential(parameters);
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Pays `target` through `method` once at most, and only a challenge for
|
|
139
|
+
* `network`.
|
|
140
|
+
*
|
|
141
|
+
* mppx answers a 402 that follows a payment by paying the new challenge, up to
|
|
142
|
+
* `maxPaymentRetries` attempts (3 by default, dist/client/internal/Fetch.js in
|
|
143
|
+
* 0.8.14). MPP-01 judges one payment: a target that answers 402 after being
|
|
144
|
+
* paid has that 402 reported, rather than being paid twice more.
|
|
145
|
+
*/
|
|
146
|
+
export async function payCharge(target, network, method) {
|
|
147
|
+
const mppx = Mppx.create({
|
|
148
|
+
methods: [onNetwork(method, network)],
|
|
149
|
+
polyfill: false,
|
|
150
|
+
maxPaymentRetries: 1,
|
|
151
|
+
});
|
|
152
|
+
return mppx.fetch(target);
|
|
132
153
|
}
|
|
133
|
-
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
134
154
|
function fail(detail) {
|
|
135
155
|
return [{ id: CHECK_ID, name: CHECK_NAME, pass: false, detail }];
|
|
136
156
|
}
|
|
@@ -143,7 +163,8 @@ function pass(detail) {
|
|
|
143
163
|
* Runs a real payment against the target every time it is called. See
|
|
144
164
|
* docs/CHECKS.md — this check spends funds by design.
|
|
145
165
|
*
|
|
146
|
-
* @throws {ConfigurationError} Invalid target URL, network, or missing key
|
|
166
|
+
* @throws {ConfigurationError} Invalid target URL, network, or missing key, or
|
|
167
|
+
* a challenge for another network than the run's (nothing is signed).
|
|
147
168
|
* @throws {TargetUnreachableError} The target never answered.
|
|
148
169
|
* @throws {MalformedResponseError} The target answered, non-conformantly.
|
|
149
170
|
* @throws {Error} RPC failure — reported as `harness`, never as a target defect.
|
|
@@ -151,7 +172,7 @@ function pass(detail) {
|
|
|
151
172
|
export async function runMppChargeChecks(options) {
|
|
152
173
|
const { target, network, payerSecretKey, rpcUrl } = options;
|
|
153
174
|
assertHttpUrl(target);
|
|
154
|
-
assertMppNetwork(network);
|
|
175
|
+
const runNetwork = assertMppNetwork(network);
|
|
155
176
|
if (!payerSecretKey) {
|
|
156
177
|
throw new ConfigurationError("No payer secret key. MPP-01 settles a real payment and cannot run without one.");
|
|
157
178
|
}
|
|
@@ -165,20 +186,35 @@ export async function runMppChargeChecks(options) {
|
|
|
165
186
|
// Resolve the endpoint before spending anything: a bad RPC URL discovered
|
|
166
187
|
// after settlement would leave money moved and no verdict to show for it.
|
|
167
188
|
const endpoint = resolveRpcUrl(network, rpcUrl);
|
|
189
|
+
// The SDK's charge client builds its RPC client without `allowHttp`, so it
|
|
190
|
+
// cannot pay through an http endpoint, though settlement could be read from
|
|
191
|
+
// one. Say so before paying, instead of reporting the SDK's refusal as the
|
|
192
|
+
// target's failure.
|
|
193
|
+
if (endpoint.startsWith("http://")) {
|
|
194
|
+
throw new ConfigurationError(`MPP-01 pays through @stellar/mpp's charge client, which accepts only an ` +
|
|
195
|
+
`https RPC endpoint, and ${endpoint} is http. Nothing was sent.`);
|
|
196
|
+
}
|
|
168
197
|
const advertised = await fetchChargeChallenge(target);
|
|
169
|
-
|
|
198
|
+
assertRunNetwork(advertised.network, runNetwork);
|
|
170
199
|
let paid;
|
|
171
200
|
try {
|
|
172
|
-
|
|
201
|
+
// The payment goes through the run's endpoint too. Left to itself the SDK
|
|
202
|
+
// picks its own per network, so `--rpc-url` would cover only the
|
|
203
|
+
// settlement read, and pubnet would get a default endpoint after all.
|
|
204
|
+
paid = await payCharge(target, runNetwork, charge({ secretKey: payerSecretKey, rpcUrl: endpoint }));
|
|
173
205
|
}
|
|
174
206
|
catch (error) {
|
|
207
|
+
if (error instanceof ConfigurationError)
|
|
208
|
+
throw error;
|
|
175
209
|
// The target was reachable moments ago, so this is the payment path
|
|
176
210
|
// failing, not the network. Report it as a conformance failure.
|
|
177
211
|
throw new MalformedResponseError(`Payment attempt failed: ${error.message}`);
|
|
178
212
|
}
|
|
179
213
|
if (!paid.ok) {
|
|
180
|
-
return fail(`
|
|
181
|
-
`answered HTTP ${paid.status} instead of
|
|
214
|
+
return fail(`Submitted a payment for the advertised ${advertised.amount} base ` +
|
|
215
|
+
`units, but the target answered HTTP ${paid.status} instead of ` +
|
|
216
|
+
`serving the resource. Nothing is claimed about settlement: a target ` +
|
|
217
|
+
`that refuses may never have broadcast the transaction.`);
|
|
182
218
|
}
|
|
183
219
|
let reference;
|
|
184
220
|
try {
|
|
@@ -188,62 +224,14 @@ export async function runMppChargeChecks(options) {
|
|
|
188
224
|
return fail(`Target returned ${paid.status} but no valid Payment-Receipt header: ` +
|
|
189
225
|
`${error.message}`);
|
|
190
226
|
}
|
|
191
|
-
const
|
|
192
|
-
|
|
227
|
+
const verdict = await verifySettlement(endpoint, reference, {
|
|
228
|
+
amount: advertised.amount,
|
|
229
|
+
token: advertised.currency,
|
|
230
|
+
recipient: advertised.recipient,
|
|
231
|
+
payer: payer.publicKey(),
|
|
193
232
|
});
|
|
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}).`);
|
|
233
|
+
// Same sentence MPP-01 has always printed, capitalised and closed.
|
|
234
|
+
return verdict.pass
|
|
235
|
+
? pass(`${verdict.detail.charAt(0).toUpperCase()}${verdict.detail.slice(1)}.`)
|
|
236
|
+
: fail(verdict.detail);
|
|
249
237
|
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `exact` scheme on EVM, with the EIP-3009 transfer method (USDC's
|
|
3
|
+
* `transferWithAuthorization`): the payer signs an authorization off-chain,
|
|
4
|
+
* the facilitator submits it and pays the gas (`scheme_exact_evm.md`). So a
|
|
5
|
+
* payer needs the token and nothing else. A target that advertises the
|
|
6
|
+
* Permit2 method instead is paid through Permit2; with the
|
|
7
|
+
* `eip2612GasSponsoring` extension its one-time approval is a signed permit
|
|
8
|
+
* the facilitator submits, so that path needs no gas either.
|
|
9
|
+
*
|
|
10
|
+
* Settlement is read from the transaction receipt: the token contract's own
|
|
11
|
+
* ERC-20 `Transfer` log is held to the advertised terms, as the Stellar
|
|
12
|
+
* adapter holds the `transfer` event. Base Sepolia, where the official SDK
|
|
13
|
+
* ships its USDC and the public facilitator settles, and Ethereum
|
|
14
|
+
* Sepolia, which Circle's USDC with EIP-3009 also serves but no public
|
|
15
|
+
* facilitator settles.
|
|
16
|
+
*/
|
|
17
|
+
import type { ExpectedSettlement, SettlementVerdict } from "../../settlement.js";
|
|
18
|
+
import type { PaymentChain } from "./types.js";
|
|
19
|
+
/**
|
|
20
|
+
* Circle's USDC on Ethereum Sepolia: EIP-3009, EIP-712 domain "USDC" version
|
|
21
|
+
* "2", 6 decimals (read from the contract, 2026-10-05). Not an SDK default.
|
|
22
|
+
*/
|
|
23
|
+
export declare const ETHEREUM_SEPOLIA_USDC = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238";
|
|
24
|
+
/** One ERC-20 `Transfer`, as the token contract logged it. */
|
|
25
|
+
export interface EvmTransfer {
|
|
26
|
+
readonly token: string;
|
|
27
|
+
readonly from: string;
|
|
28
|
+
readonly to: string;
|
|
29
|
+
readonly value: bigint;
|
|
30
|
+
}
|
|
31
|
+
/** A log as RPC returns it, reduced to what a transfer is read from. */
|
|
32
|
+
export interface EvmLog {
|
|
33
|
+
readonly address: string;
|
|
34
|
+
readonly topics: readonly string[];
|
|
35
|
+
readonly data: string;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The ERC-20 `Transfer` logs in a receipt. ERC-721 shares the event
|
|
39
|
+
* signature but indexes the token id as a fourth topic, so only logs with
|
|
40
|
+
* exactly three topics and a 32-byte value are read as token transfers.
|
|
41
|
+
*/
|
|
42
|
+
export declare function evmTransfers(logs: readonly EvmLog[]): EvmTransfer[];
|
|
43
|
+
/**
|
|
44
|
+
* Holds a settled transaction's receipt to what the target advertised.
|
|
45
|
+
*
|
|
46
|
+
* The same rules as on Stellar: the transaction succeeded, it moved exactly
|
|
47
|
+
* one token transfer, and that transfer is the advertised amount of the
|
|
48
|
+
* advertised token, to the advertised recipient, from this run's own payer,
|
|
49
|
+
* so a target cannot cite some other transaction that happens to match.
|
|
50
|
+
*/
|
|
51
|
+
export declare function verifyEvmReceipt(receipt: {
|
|
52
|
+
readonly status: string;
|
|
53
|
+
readonly logs: readonly EvmLog[];
|
|
54
|
+
}, reference: string, expected: ExpectedSettlement): SettlementVerdict;
|
|
55
|
+
/**
|
|
56
|
+
* Corrupts the payer's signature, and nothing else.
|
|
57
|
+
*
|
|
58
|
+
* The EIP-3009 payload is `{ signature, authorization }`; Permit2's carries a
|
|
59
|
+
* `signature` too. Flipping the first byte of `r` leaves a signature of the
|
|
60
|
+
* same length whose recovered signer is no longer `authorization.from`, while
|
|
61
|
+
* the amount, recipient and validity window stay intact. A target can refuse
|
|
62
|
+
* it only by verifying the signature (spec, verification step 1).
|
|
63
|
+
*/
|
|
64
|
+
export declare function corruptEvmSignature(payload: Record<string, unknown>): Record<string, unknown>;
|
|
65
|
+
export declare const evmChain: PaymentChain;
|