@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
|
@@ -0,0 +1,234 @@
|
|
|
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 { toClientEvmSigner } from "@x402/evm";
|
|
18
|
+
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
19
|
+
import { TransactionReceiptNotFoundError, createPublicClient, erc20Abi, http, isAddress, isAddressEqual, toEventSelector, } from "viem";
|
|
20
|
+
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
|
|
21
|
+
import { baseSepolia, sepolia } from "viem/chains";
|
|
22
|
+
import { CheckSetupError, ConfigurationError } from "../../errors.js";
|
|
23
|
+
import { waitForReceipt } from "./wait.js";
|
|
24
|
+
/**
|
|
25
|
+
* Circle's USDC on Ethereum Sepolia: EIP-3009, EIP-712 domain "USDC" version
|
|
26
|
+
* "2", 6 decimals (read from the contract, 2026-10-05). Not an SDK default.
|
|
27
|
+
*/
|
|
28
|
+
export const ETHEREUM_SEPOLIA_USDC = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238";
|
|
29
|
+
const NETWORKS = {
|
|
30
|
+
// A block every 2 seconds: 30 blocks is about a minute.
|
|
31
|
+
"eip155:84532": { chain: baseSepolia, blocksBeforeMissing: 30n, maxWaitMs: 120_000 },
|
|
32
|
+
// A block every 12 seconds: 10 blocks is about two minutes.
|
|
33
|
+
"eip155:11155111": {
|
|
34
|
+
chain: sepolia,
|
|
35
|
+
blocksBeforeMissing: 10n,
|
|
36
|
+
maxWaitMs: 240_000,
|
|
37
|
+
allowedAssets: [{ asset: ETHEREUM_SEPOLIA_USDC, maxAmountPerPayment: "1000000" }],
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
/** An EVM transaction hash: 0x and 32 bytes of hex. */
|
|
41
|
+
const TRANSACTION_HASH = /^0x[0-9a-fA-F]{64}$/;
|
|
42
|
+
/** A raw secp256k1 private key: 0x and 32 bytes of hex. */
|
|
43
|
+
const PRIVATE_KEY = /^0x[0-9a-fA-F]{64}$/;
|
|
44
|
+
/** `Transfer(address indexed from, address indexed to, uint256 value)`. */
|
|
45
|
+
const TRANSFER_TOPIC = toEventSelector("Transfer(address,address,uint256)");
|
|
46
|
+
function payerAccount(payerKey) {
|
|
47
|
+
// The message never echoes the key: it is a secret, and a malformed one is
|
|
48
|
+
// often a real key pasted with a character missing.
|
|
49
|
+
if (!PRIVATE_KEY.test(payerKey)) {
|
|
50
|
+
throw new ConfigurationError("EVM_PRIVATE_KEY is not an EVM private key: expected 0x followed by 64 hex characters.");
|
|
51
|
+
}
|
|
52
|
+
return privateKeyToAccount(payerKey);
|
|
53
|
+
}
|
|
54
|
+
/** The last 20 bytes of a 32-byte topic: an indexed address. */
|
|
55
|
+
function topicAddress(topic) {
|
|
56
|
+
return `0x${topic.slice(-40)}`;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The ERC-20 `Transfer` logs in a receipt. ERC-721 shares the event
|
|
60
|
+
* signature but indexes the token id as a fourth topic, so only logs with
|
|
61
|
+
* exactly three topics and a 32-byte value are read as token transfers.
|
|
62
|
+
*/
|
|
63
|
+
export function evmTransfers(logs) {
|
|
64
|
+
return logs
|
|
65
|
+
.filter((log) => log.topics.length === 3 &&
|
|
66
|
+
log.topics[0]?.toLowerCase() === TRANSFER_TOPIC &&
|
|
67
|
+
/^0x[0-9a-fA-F]{64}$/.test(log.data))
|
|
68
|
+
.map((log) => ({
|
|
69
|
+
token: log.address,
|
|
70
|
+
from: topicAddress(log.topics[1]),
|
|
71
|
+
to: topicAddress(log.topics[2]),
|
|
72
|
+
value: BigInt(log.data),
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Holds a settled transaction's receipt to what the target advertised.
|
|
77
|
+
*
|
|
78
|
+
* The same rules as on Stellar: the transaction succeeded, it moved exactly
|
|
79
|
+
* one token transfer, and that transfer is the advertised amount of the
|
|
80
|
+
* advertised token, to the advertised recipient, from this run's own payer,
|
|
81
|
+
* so a target cannot cite some other transaction that happens to match.
|
|
82
|
+
*/
|
|
83
|
+
export function verifyEvmReceipt(receipt, reference, expected) {
|
|
84
|
+
const fail = (detail) => ({ pass: false, detail });
|
|
85
|
+
if (receipt.status !== "success") {
|
|
86
|
+
return fail(`Transaction ${reference} exists on-chain but reverted. The target reported ` +
|
|
87
|
+
`success for a settlement that did not settle.`);
|
|
88
|
+
}
|
|
89
|
+
const transfers = evmTransfers(receipt.logs);
|
|
90
|
+
if (transfers.length === 0) {
|
|
91
|
+
return fail(`Transaction ${reference} succeeded but logged no ERC-20 Transfer, so no ` +
|
|
92
|
+
`token movement can be verified.`);
|
|
93
|
+
}
|
|
94
|
+
if (transfers.length !== 1) {
|
|
95
|
+
return fail(`Transaction ${reference} logged ${transfers.length} ERC-20 Transfers; ` +
|
|
96
|
+
`exactly one was expected. Additional balance changes mean the settlement ` +
|
|
97
|
+
`moved more than what was advertised.`);
|
|
98
|
+
}
|
|
99
|
+
const actual = transfers[0];
|
|
100
|
+
const same = (a, b) => {
|
|
101
|
+
try {
|
|
102
|
+
return isAddressEqual(a, b);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const mismatches = [];
|
|
109
|
+
if (actual.value !== expected.amount) {
|
|
110
|
+
mismatches.push(`amount: advertised ${expected.amount} base units, moved ${actual.value}`);
|
|
111
|
+
}
|
|
112
|
+
if (!same(actual.to, expected.recipient)) {
|
|
113
|
+
mismatches.push(`recipient: advertised ${expected.recipient}, paid ${actual.to}`);
|
|
114
|
+
}
|
|
115
|
+
if (!same(actual.token, expected.token)) {
|
|
116
|
+
mismatches.push(`token: advertised ${expected.token}, moved ${actual.token}`);
|
|
117
|
+
}
|
|
118
|
+
if (!same(actual.from, expected.payer)) {
|
|
119
|
+
mismatches.push(`payer: this run paid from ${expected.payer}, but the referenced transfer ` +
|
|
120
|
+
`came from ${actual.from}`);
|
|
121
|
+
}
|
|
122
|
+
if (mismatches.length > 0) {
|
|
123
|
+
return fail(`Settlement does not match what the target advertised — ` +
|
|
124
|
+
`${mismatches.join("; ")} (tx ${reference}).`);
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
pass: true,
|
|
128
|
+
detail: `settled on-chain for exactly the advertised ${expected.amount} base ` +
|
|
129
|
+
`units of ${expected.token} to ${expected.recipient}, verified from the ` +
|
|
130
|
+
`Transfer log (tx ${reference})`,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
async function verifyEvmSettlement(network, rpcUrl, reference, expected) {
|
|
134
|
+
const profile = NETWORKS[network];
|
|
135
|
+
if (profile === undefined) {
|
|
136
|
+
throw new ConfigurationError(`No EVM network "${network}" in Wasit's payment checks.`);
|
|
137
|
+
}
|
|
138
|
+
const client = createPublicClient({ transport: http(rpcUrl) });
|
|
139
|
+
const lookup = await waitForReceipt(async () => {
|
|
140
|
+
try {
|
|
141
|
+
return await client.getTransactionReceipt({ hash: reference });
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (error instanceof TransactionReceiptNotFoundError)
|
|
145
|
+
return undefined;
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
}, () => client.getBlockNumber(), { blocks: profile.blocksBeforeMissing, maxWaitMs: profile.maxWaitMs });
|
|
149
|
+
if (lookup.kind === "stalled") {
|
|
150
|
+
// An RPC that is not advancing says nothing about the target: no verdict.
|
|
151
|
+
throw new Error(`RPC at ${rpcUrl} produced only ${lookup.blocksWatched} blocks in ` +
|
|
152
|
+
`${Math.round(lookup.waitedMs / 1000)} seconds while looking for tx ` +
|
|
153
|
+
`${reference}, so its absence says nothing about the target. Re-run, ` +
|
|
154
|
+
`or point --rpc-url at another endpoint.`);
|
|
155
|
+
}
|
|
156
|
+
if (lookup.kind === "missing") {
|
|
157
|
+
return {
|
|
158
|
+
pass: false,
|
|
159
|
+
detail: `Target reported settlement as tx ${reference}, but the chain produced ` +
|
|
160
|
+
`${lookup.blocksWatched} more blocks without it. Either it was never ` +
|
|
161
|
+
`broadcast, or the target referenced a transaction that does not exist.`,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
return verifyEvmReceipt(lookup.receipt, reference, expected);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Corrupts the payer's signature, and nothing else.
|
|
168
|
+
*
|
|
169
|
+
* The EIP-3009 payload is `{ signature, authorization }`; Permit2's carries a
|
|
170
|
+
* `signature` too. Flipping the first byte of `r` leaves a signature of the
|
|
171
|
+
* same length whose recovered signer is no longer `authorization.from`, while
|
|
172
|
+
* the amount, recipient and validity window stay intact. A target can refuse
|
|
173
|
+
* it only by verifying the signature (spec, verification step 1).
|
|
174
|
+
*/
|
|
175
|
+
export function corruptEvmSignature(payload) {
|
|
176
|
+
const signature = payload["signature"];
|
|
177
|
+
// 65 bytes for an EOA; a contract wallet's signature is longer, never shorter.
|
|
178
|
+
if (typeof signature !== "string" || !/^0x(?:[0-9a-fA-F]{2}){65,}$/.test(signature)) {
|
|
179
|
+
throw new CheckSetupError("The payment payload carries no EVM signature to corrupt, so a corrupted " +
|
|
180
|
+
"signature cannot be tested.");
|
|
181
|
+
}
|
|
182
|
+
const first = (Number.parseInt(signature.slice(2, 4), 16) ^ 0xff).toString(16).padStart(2, "0");
|
|
183
|
+
return { ...payload, signature: `0x${first}${signature.slice(4)}` };
|
|
184
|
+
}
|
|
185
|
+
export const evmChain = {
|
|
186
|
+
name: "EVM",
|
|
187
|
+
networks: Object.keys(NETWORKS),
|
|
188
|
+
payerKeyEnv: "EVM_PRIVATE_KEY",
|
|
189
|
+
referenceKind: "an EVM transaction hash",
|
|
190
|
+
resolveRpcUrl(network, override) {
|
|
191
|
+
const profile = NETWORKS[network];
|
|
192
|
+
if (profile === undefined) {
|
|
193
|
+
throw new ConfigurationError(`No EVM network "${network}" in Wasit's payment checks.`);
|
|
194
|
+
}
|
|
195
|
+
if (override)
|
|
196
|
+
return override;
|
|
197
|
+
const fallback = profile.chain.rpcUrls.default.http[0];
|
|
198
|
+
if (fallback === undefined) {
|
|
199
|
+
throw new ConfigurationError(`No default RPC endpoint for ${network}. Pass an explicit rpcUrl.`);
|
|
200
|
+
}
|
|
201
|
+
return fallback;
|
|
202
|
+
},
|
|
203
|
+
registerPayer(client, network, payerKey, rpcUrl) {
|
|
204
|
+
// The signer can read the chain: the SDK needs that only on the Permit2
|
|
205
|
+
// path (allowance, permit nonce). EIP-3009 signing stays offline.
|
|
206
|
+
const signer = toClientEvmSigner(payerAccount(payerKey), createPublicClient({ transport: http(rpcUrl) }));
|
|
207
|
+
client.register("eip155:*", new ExactEvmScheme(signer, { rpcUrl }));
|
|
208
|
+
const allowed = NETWORKS[network]?.allowedAssets;
|
|
209
|
+
if (allowed !== undefined) {
|
|
210
|
+
client.setSpendControls({
|
|
211
|
+
allowedAssets: allowed.map((entry) => ({ network: network, ...entry })),
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
// validBefore is now + 1 second. Held 5 seconds, it has passed by the
|
|
216
|
+
// clock, and any block that could include it is later still, whatever
|
|
217
|
+
// the chain's block time.
|
|
218
|
+
expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 5_000 }),
|
|
219
|
+
payerAddress: (payerKey) => payerAccount(payerKey).address,
|
|
220
|
+
generatePayerKey: () => generatePrivateKey(),
|
|
221
|
+
async payerBalance(_network, rpcUrl, payer, asset) {
|
|
222
|
+
if (!isAddress(asset) || !isAddress(payer))
|
|
223
|
+
return undefined;
|
|
224
|
+
return createPublicClient({ transport: http(rpcUrl) }).readContract({
|
|
225
|
+
address: asset,
|
|
226
|
+
abi: erc20Abi,
|
|
227
|
+
functionName: "balanceOf",
|
|
228
|
+
args: [payer],
|
|
229
|
+
});
|
|
230
|
+
},
|
|
231
|
+
isSettlementReference: (reference) => TRANSACTION_HASH.test(reference),
|
|
232
|
+
verifySettlement: verifyEvmSettlement,
|
|
233
|
+
corruptPayload: corruptEvmSignature,
|
|
234
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The chains the x402 payment checks can pay on. Adding one is adding an
|
|
3
|
+
* adapter here; the checks do not change.
|
|
4
|
+
*/
|
|
5
|
+
import type { PaymentChain } from "./types.js";
|
|
6
|
+
export type { PaymentChain } from "./types.js";
|
|
7
|
+
/** The adapter that pays on `network`, if Wasit has one. */
|
|
8
|
+
export declare function paymentChainFor(network: string): PaymentChain | undefined;
|
|
9
|
+
/** Every network the payment checks can pay on, in adapter order. */
|
|
10
|
+
export declare function paymentNetworks(): readonly string[];
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The chains the x402 payment checks can pay on. Adding one is adding an
|
|
3
|
+
* adapter here; the checks do not change.
|
|
4
|
+
*/
|
|
5
|
+
import { evmChain } from "./evm.js";
|
|
6
|
+
import { stellarChain } from "./stellar.js";
|
|
7
|
+
import { svmChain } from "./svm.js";
|
|
8
|
+
// Stellar first: it is the default network, and the only chain with MPP.
|
|
9
|
+
const CHAINS = [stellarChain, evmChain, svmChain];
|
|
10
|
+
/** The adapter that pays on `network`, if Wasit has one. */
|
|
11
|
+
export function paymentChainFor(network) {
|
|
12
|
+
return CHAINS.find((chain) => chain.networks.includes(network));
|
|
13
|
+
}
|
|
14
|
+
/** Every network the payment checks can pay on, in adapter order. */
|
|
15
|
+
export function paymentNetworks() {
|
|
16
|
+
return CHAINS.flatMap((chain) => chain.networks);
|
|
17
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
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 { Asset } from "@stellar/stellar-sdk";
|
|
8
|
+
import type { PaymentChain } from "./types.js";
|
|
9
|
+
/**
|
|
10
|
+
* Corrupts the client's authorization signature, and nothing else.
|
|
11
|
+
*
|
|
12
|
+
* In the `exact` scheme on Stellar the client signs a Soroban authorization
|
|
13
|
+
* entry, not the envelope: the facilitator signs the envelope later. So the
|
|
14
|
+
* signature that proves the payer consented is the address credential's
|
|
15
|
+
* `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
|
|
16
|
+
* leaves a transaction that still decodes, carries the same amount, payer and
|
|
17
|
+
* recipient, and fails only signature verification. A target can refuse it
|
|
18
|
+
* only by verifying the signature.
|
|
19
|
+
*
|
|
20
|
+
* Throws {@link CheckSetupError} if the payload carries no such signature, so
|
|
21
|
+
* the check reports no verdict rather than one it did not establish.
|
|
22
|
+
*/
|
|
23
|
+
export declare function corruptAuthSignature(transaction: string): string;
|
|
24
|
+
/**
|
|
25
|
+
* The classic asset a Stellar Asset Contract wraps, from the `name` it
|
|
26
|
+
* reports ("CODE:ISSUER", CAP-46-06), only when that asset's contract id is
|
|
27
|
+
* `contractId`: any contract can return such a name, but only the SAC has
|
|
28
|
+
* the id derived from the asset.
|
|
29
|
+
*/
|
|
30
|
+
export declare function sacAssetFromName(name: unknown, contractId: string, passphrase: string): Asset | undefined;
|
|
31
|
+
export declare const stellarChain: PaymentChain;
|
|
@@ -0,0 +1,153 @@
|
|
|
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 { 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
|
+
export const stellarChain = {
|
|
132
|
+
name: "Stellar",
|
|
133
|
+
networks: ["stellar:testnet", "stellar:pubnet"],
|
|
134
|
+
payerKeyEnv: "STELLAR_PRIVATE_KEY",
|
|
135
|
+
referenceKind: "a settled Stellar transaction hash",
|
|
136
|
+
resolveRpcUrl: (network, override) => resolveRpcUrl(network, override),
|
|
137
|
+
registerPayer(client, network, payerKey, _rpcUrl) {
|
|
138
|
+
const signer = createEd25519Signer(payerKey, network);
|
|
139
|
+
client.register("stellar:*", new ExactStellarClientScheme(signer));
|
|
140
|
+
},
|
|
141
|
+
// A one-second lifetime is one ledger (ceil(1 / 5)); ledgers close about
|
|
142
|
+
// every 5 to 6 seconds, so 20 seconds is three or more ledgers past it.
|
|
143
|
+
expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 20_000 }),
|
|
144
|
+
payerAddress: (payerKey) => Keypair.fromSecret(payerKey).publicKey(),
|
|
145
|
+
payerBalance: stellarTokenBalance,
|
|
146
|
+
generatePayerKey: () => Keypair.random().secret(),
|
|
147
|
+
isSettlementReference: (reference) => TRANSACTION_HASH.test(reference),
|
|
148
|
+
verifySettlement: (_network, rpcUrl, reference, expected) => verifySettlement(rpcUrl, reference, expected),
|
|
149
|
+
corruptPayload: (payload) => ({
|
|
150
|
+
...payload,
|
|
151
|
+
transaction: corruptAuthSignature(payload["transaction"]),
|
|
152
|
+
}),
|
|
153
|
+
};
|
|
@@ -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;
|