@integraledger/profile-facilitator 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +107 -0
- package/README.md +781 -456
- package/dist/answers.d.ts +11 -4
- package/dist/answers.js +24 -0
- package/dist/core.d.ts +51 -0
- package/dist/core.js +758 -0
- package/dist/http.d.ts +20 -3
- package/dist/http.js +32 -7
- package/dist/index.d.ts +12 -36
- package/dist/index.js +9 -162
- package/dist/module.d.ts +372 -0
- package/dist/module.js +13 -0
- package/dist/modules/algorand/index.d.ts +22 -0
- package/dist/modules/algorand/index.js +247 -0
- package/dist/modules/algorand/own.d.ts +26 -0
- package/dist/modules/algorand/own.js +231 -0
- package/dist/modules/aptos/index.d.ts +23 -0
- package/dist/modules/aptos/index.js +232 -0
- package/dist/modules/cardano/index.d.ts +18 -0
- package/dist/modules/cardano/index.js +124 -0
- package/dist/modules/casper/index.d.ts +120 -0
- package/dist/modules/casper/index.js +442 -0
- package/dist/modules/concordium/index.d.ts +16 -0
- package/dist/modules/concordium/index.js +77 -0
- package/dist/modules/erc7710/index.d.ts +26 -0
- package/dist/modules/erc7710/index.js +220 -0
- package/dist/modules/evm/forms.d.ts +74 -0
- package/dist/modules/evm/forms.js +204 -0
- package/dist/modules/evm/index.d.ts +40 -0
- package/dist/modules/evm/index.js +154 -0
- package/dist/modules/evm/node.d.ts +29 -0
- package/dist/modules/evm/node.js +222 -0
- package/dist/modules/hedera/executor.d.ts +63 -0
- package/dist/modules/hedera/executor.js +343 -0
- package/dist/modules/hedera/index.d.ts +23 -0
- package/dist/modules/hedera/index.js +136 -0
- package/dist/modules/hedera/mirror.d.ts +32 -0
- package/dist/modules/hedera/mirror.js +111 -0
- package/dist/modules/index.d.ts +23 -0
- package/dist/modules/index.js +24 -0
- package/dist/modules/lnbtc/index.d.ts +10 -0
- package/dist/modules/lnbtc/index.js +112 -0
- package/dist/modules/near/index.d.ts +18 -0
- package/dist/modules/near/index.js +246 -0
- package/dist/modules/polkadot/index.d.ts +12 -0
- package/dist/modules/polkadot/index.js +149 -0
- package/dist/modules/polkadot/rail.d.ts +40 -0
- package/dist/{polkadot.js → modules/polkadot/rail.js} +214 -288
- package/dist/modules/solana/index.d.ts +60 -0
- package/dist/modules/solana/index.js +326 -0
- package/dist/modules/solana/reader.d.ts +25 -0
- package/dist/modules/solana/reader.js +194 -0
- package/dist/modules/solana/state.d.ts +6 -0
- package/dist/modules/solana/state.js +103 -0
- package/dist/modules/starknet/index.d.ts +35 -0
- package/dist/modules/starknet/index.js +548 -0
- package/dist/modules/starknet/node.d.ts +78 -0
- package/dist/modules/starknet/node.js +339 -0
- package/dist/modules/stellar/index.d.ts +44 -0
- package/dist/modules/stellar/index.js +481 -0
- package/dist/modules/stellar/node.d.ts +57 -0
- package/dist/modules/stellar/node.js +151 -0
- package/dist/modules/sui/index.d.ts +16 -0
- package/dist/modules/sui/index.js +310 -0
- package/dist/modules/sui/node.d.ts +49 -0
- package/dist/modules/sui/node.js +197 -0
- package/dist/modules/ton/index.d.ts +16 -0
- package/dist/modules/ton/index.js +73 -0
- package/dist/modules/tron/index.d.ts +12 -0
- package/dist/modules/tron/index.js +120 -0
- package/dist/modules/tron/rail.d.ts +32 -0
- package/dist/{tron.js → modules/tron/rail.js} +206 -195
- package/dist/modules/xrpl/index.d.ts +28 -0
- package/dist/modules/xrpl/index.js +299 -0
- package/dist/modules/xrpl/node.d.ts +52 -0
- package/dist/modules/xrpl/node.js +231 -0
- package/dist/modules/xrpl/upto.d.ts +5 -0
- package/dist/modules/xrpl/upto.js +269 -0
- package/dist/record.d.ts +131 -0
- package/dist/record.js +330 -0
- package/dist/unexpected.d.ts +3 -2
- package/dist/unexpected.js +2 -1
- package/dist/wrapper.d.ts +68 -0
- package/dist/wrapper.js +126 -0
- package/package.json +48 -12
- package/dist/polkadot.d.ts +0 -21
- package/dist/store.d.ts +0 -59
- package/dist/store.js +0 -103
- package/dist/tron.d.ts +0 -12
- /package/dist/{base58check.d.ts → modules/tron/base58check.d.ts} +0 -0
- /package/dist/{base58check.js → modules/tron/base58check.js} +0 -0
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stellar: the settler's own facilitator for the pairing `x402/exact/stellar/precondition`, the agreement on x402's
|
|
3
|
+
* `exact` scheme, told from every other Stellar option by `extra.assetTransferMethod` `"lcp-precondition"`. The buyer
|
|
4
|
+
* signs a Soroban authorization of `transfer(buyer, payTo, amount)` and the 40-byte payload of H and that
|
|
5
|
+
* authorization's nonce, which the transaction carries as its one signed-payload signer (CAP-40); the payload's
|
|
6
|
+
* signature rides as a decorated signature of the envelope the buyer presents. The module is the transaction's source:
|
|
7
|
+
* it builds the transaction it submits around the buyer's operation and preconditions, unchanged, with its own source
|
|
8
|
+
* account, sequence number, fee and resource data, signs it, and carries the buyer's payload signature beside its own
|
|
9
|
+
* (lcp's profile `x402-exact-stellar-precondition.md`, rule 11). x402's published Stellar facilitator keeps a
|
|
10
|
+
* transaction's preconditions when it rebuilds it but signs it alone, so the payload's signature never reaches the
|
|
11
|
+
* chain and the network refuses the transaction (`txBAD_AUTH`).
|
|
12
|
+
*
|
|
13
|
+
* lcp decodes the payment (`bound`, `reference`, `decodeStellarTx`) and reads it (`status`); the module adds x402's
|
|
14
|
+
* Stellar scheme's checks (`scheme_exact_stellar.md`: the transfer against the requirements, the facilitator's safety,
|
|
15
|
+
* the authorization entries, the simulation and its events, the fee ceiling), with the reasons of x402's own Stellar
|
|
16
|
+
* facilitator (`@x402/stellar` 2.31.0), and the payload signature's.
|
|
17
|
+
*/
|
|
18
|
+
import { canonicalJson, isRefusal } from "@integraledger/lcp";
|
|
19
|
+
import { decodeStellarTx, PASSPHRASE, transferEventOf } from "@integraledger/lcp/stellar";
|
|
20
|
+
import { exactStellarPrecondition } from "@integraledger/lcp/x402-exact-stellar";
|
|
21
|
+
import { Keypair, StrKey, Transaction, xdr } from "@stellar/stellar-sdk/base";
|
|
22
|
+
import { isObject } from "../../answers.js";
|
|
23
|
+
import { NodeError, sleep } from "../../http.js";
|
|
24
|
+
import { outcomeOf } from "../../module.js";
|
|
25
|
+
import { settleReason, unexpectedSettle, unexpectedVerify } from "../../unexpected.js";
|
|
26
|
+
import { RpcFault, stellarNode } from "./node.js";
|
|
27
|
+
const ID = exactStellarPrecondition.id;
|
|
28
|
+
const NETWORKS = ["stellar:pubnet", "stellar:testnet"];
|
|
29
|
+
/** The seconds per ledger by which an option's `maxTimeoutSeconds` becomes a ledger count: the profile's (rule 5), and x402's fallback. */
|
|
30
|
+
const LEDGER_SECONDS = 5;
|
|
31
|
+
/** The ledgers past that count that x402's Stellar facilitator admits an entry's expiration (2.31.0, `SIGNATURE_EXPIRATION_LEDGER_TOLERANCE`). */
|
|
32
|
+
const EXPIRATION_TOLERANCE = 2;
|
|
33
|
+
const DEFAULT_MAX_FEE = 50_000;
|
|
34
|
+
const DEFAULT_INCLUSION_FEE = 100;
|
|
35
|
+
const POLL_MS = 1_000;
|
|
36
|
+
/** `txBAD_SEQ` (`Stellar-transaction.x`, `TransactionResultCode`). */
|
|
37
|
+
const TX_BAD_SEQ = -5;
|
|
38
|
+
const no = (reason, message) => (message === undefined ? { reason } : { reason, message });
|
|
39
|
+
const isNo = (v) => isObject(v) && typeof v["reason"] === "string" && Object.keys(v).every((k) => k === "reason" || k === "message");
|
|
40
|
+
/** lcp's refusals of the option's form: the requirements' fault where the payment echoes them unchanged. */
|
|
41
|
+
const OPTION_CODES = new Set(["x402/option-malformed", "x402/option-not-this-pairing", "stellar/option-malformed", "stellar/network-malformed"]);
|
|
42
|
+
/** The x402 reason for lcp's refusal of the payment, with lcp's code as the message. */
|
|
43
|
+
function refusedBy(r, payload, requirements) {
|
|
44
|
+
if (r.code === "x402/not-v2")
|
|
45
|
+
return no("invalid_x402_version", r.code);
|
|
46
|
+
const echoed = canonicalJson(payload.accepted) === canonicalJson(requirements);
|
|
47
|
+
return no(echoed && OPTION_CODES.has(r.code) ? "invalid_payment_requirements" : "invalid_payload", r.code);
|
|
48
|
+
}
|
|
49
|
+
const toHex = (b) => Buffer.from(b).toString("hex");
|
|
50
|
+
const sameBytes = (a, b) => Buffer.from(a).equals(Buffer.from(b));
|
|
51
|
+
/** A muxed account's base account, as a `G…` strkey. */
|
|
52
|
+
function accountOf(m) {
|
|
53
|
+
return StrKey.encodeEd25519PublicKey(Buffer.from(m.type === 0 ? m.ed25519 : m.med25519.ed25519));
|
|
54
|
+
}
|
|
55
|
+
/** An `ScAddress`'s strkey, or "" where it is neither an account nor a contract. */
|
|
56
|
+
function addressOf(a) {
|
|
57
|
+
if (a.type === 0 && a.accountId.type === 0)
|
|
58
|
+
return StrKey.encodeEd25519PublicKey(Buffer.from(a.accountId.ed25519));
|
|
59
|
+
if (a.type === 1)
|
|
60
|
+
return StrKey.encodeContract(Buffer.from(a.contractId));
|
|
61
|
+
return "";
|
|
62
|
+
}
|
|
63
|
+
/** Starts one module per configured network, each its own registration of `exact`. */
|
|
64
|
+
export const starter = {
|
|
65
|
+
name: "stellar",
|
|
66
|
+
async start(config, core) {
|
|
67
|
+
return { registrations: config.networks.map((c) => ({ network: c.network, module: stellarModule(c, core), own: [] })) };
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* The module for one network. The settler's wait for the chain is the core's; the fee meter is the network's, which
|
|
72
|
+
* the module tells of each transaction's fee before it sends it and of the fee charged once it is included.
|
|
73
|
+
*/
|
|
74
|
+
export function stellarModule(c, core) {
|
|
75
|
+
if (!NETWORKS.includes(c.network))
|
|
76
|
+
throw new TypeError(`not a Stellar network: ${c.network}`);
|
|
77
|
+
const source = c.source.address;
|
|
78
|
+
if (!StrKey.isValidEd25519PublicKey(source))
|
|
79
|
+
throw new TypeError("the source account's address is not an account strkey");
|
|
80
|
+
const maxFee = BigInt(c.maxTransactionFeeStroops ?? DEFAULT_MAX_FEE);
|
|
81
|
+
const inclusion = BigInt(c.inclusionFeeStroops ?? DEFAULT_INCLUSION_FEE);
|
|
82
|
+
if (maxFee <= 0n || inclusion < 100n)
|
|
83
|
+
throw new TypeError("the fee ceiling must be positive, and the inclusion fee at least 100 stroops");
|
|
84
|
+
const network = c.network;
|
|
85
|
+
const passphrase = PASSPHRASE[network];
|
|
86
|
+
const sourceKey = Keypair.fromPublicKey(source).rawPublicKey();
|
|
87
|
+
const node = stellarNode(c.rpc.replace(/\/+$/, ""));
|
|
88
|
+
const { log, settleWaitMs } = core;
|
|
89
|
+
const meter = core.meter(network);
|
|
90
|
+
/** The source account's transactions are sent one at a time; `last` is the sequence number of the last one sent. */
|
|
91
|
+
let sending = Promise.resolve();
|
|
92
|
+
let last;
|
|
93
|
+
const about = (i) => ({ network, payer: i.ref.buyer });
|
|
94
|
+
/**
|
|
95
|
+
* Every check of the payment that reads neither the chain nor the clock: lcp's (the option, the envelope, the carrier,
|
|
96
|
+
* the reference), x402's of the transfer against the requirements, of the facilitator's safety and of the
|
|
97
|
+
* authorization entries, and that the envelope carries the buyer's signature of the signed payload.
|
|
98
|
+
*/
|
|
99
|
+
async function inspect(payload, requirements) {
|
|
100
|
+
if (!isObject(payload) || !isObject(requirements) || !isObject(payload.payload))
|
|
101
|
+
return no("invalid_payload");
|
|
102
|
+
if (requirements.network !== network)
|
|
103
|
+
return no("invalid_network");
|
|
104
|
+
if (requirements.scheme !== "exact")
|
|
105
|
+
return no("unsupported_scheme");
|
|
106
|
+
const h = await exactStellarPrecondition.bound(payload);
|
|
107
|
+
if (isRefusal(h))
|
|
108
|
+
return refusedBy(h, payload, requirements);
|
|
109
|
+
const ref = await exactStellarPrecondition.reference(payload, requirements);
|
|
110
|
+
if (isRefusal(ref))
|
|
111
|
+
return refusedBy(ref, payload, requirements);
|
|
112
|
+
const presented = payload.payload.transaction;
|
|
113
|
+
const p = decodeStellarTx(presented, network);
|
|
114
|
+
if (isRefusal(p))
|
|
115
|
+
return refusedBy(p, payload, requirements);
|
|
116
|
+
// x402's checks of the transfer against the requirements, in its order.
|
|
117
|
+
if (p.asset !== requirements.asset)
|
|
118
|
+
return no("invalid_exact_stellar_payload_wrong_asset");
|
|
119
|
+
if (p.from === source)
|
|
120
|
+
return no("invalid_exact_stellar_payload_facilitator_is_payer");
|
|
121
|
+
if (p.to !== requirements.payTo)
|
|
122
|
+
return no("invalid_exact_stellar_payload_wrong_recipient");
|
|
123
|
+
if (p.amount !== BigInt(requirements.amount))
|
|
124
|
+
return no("invalid_exact_stellar_payload_wrong_amount");
|
|
125
|
+
const env = xdr.TransactionEnvelope.fromXdr(presented, "base64").toXdrObject();
|
|
126
|
+
const v1 = env.type === 2 ? env.v1 : env.type === 5 && env.feeBump.tx.innerTx.type === 2 ? env.feeBump.tx.innerTx.v1 : undefined;
|
|
127
|
+
if (v1 === undefined)
|
|
128
|
+
return no("invalid_payload", "stellar/tx-malformed");
|
|
129
|
+
const op = v1.tx.operations[0];
|
|
130
|
+
if (accountOf(v1.tx.sourceAccount) === source || (op.sourceAccount !== null && accountOf(op.sourceAccount) === source)) {
|
|
131
|
+
return no("invalid_exact_stellar_payload_unsafe_tx_or_op_source");
|
|
132
|
+
}
|
|
133
|
+
if (op.body.type !== 24)
|
|
134
|
+
return no("invalid_payload", "stellar/not-one-transfer");
|
|
135
|
+
// Every entry must be an address's: one with source-account credentials is authorised by the transaction's
|
|
136
|
+
// source, the module's account, whose signature covers the whole transaction.
|
|
137
|
+
const auth = op.body.invokeHostFunctionOp.auth;
|
|
138
|
+
if (auth.length === 0)
|
|
139
|
+
return no("invalid_exact_stellar_payload_no_auth_entries");
|
|
140
|
+
const unsigned = [];
|
|
141
|
+
for (const e of auth) {
|
|
142
|
+
const k = e.credentials;
|
|
143
|
+
if (k.type !== 1 && k.type !== 2)
|
|
144
|
+
return no("invalid_exact_stellar_payload_unsupported_credential_type");
|
|
145
|
+
const a = k.type === 1 ? k.address : k.addressV2;
|
|
146
|
+
const who = addressOf(a.address);
|
|
147
|
+
if (who === source)
|
|
148
|
+
return no("invalid_exact_stellar_payload_facilitator_in_auth");
|
|
149
|
+
if (e.rootInvocation.subInvocations.length > 0)
|
|
150
|
+
return no("invalid_exact_stellar_payload_has_subinvocations");
|
|
151
|
+
if (a.signature.type === 1)
|
|
152
|
+
unsigned.push(who);
|
|
153
|
+
}
|
|
154
|
+
if (unsigned.includes(p.from))
|
|
155
|
+
return no("invalid_exact_stellar_payload_missing_payer_signature");
|
|
156
|
+
if (unsigned.length > 0)
|
|
157
|
+
return no("invalid_exact_stellar_payload_unexpected_pending_signatures");
|
|
158
|
+
// The buyer's signature of the signed payload: a decorated signature whose hint is the key's last 4 bytes XOR the
|
|
159
|
+
// payload's last 4 (CAP-40), which verifies over the payload. Without it the network refuses the transaction.
|
|
160
|
+
const cond = v1.tx.cond;
|
|
161
|
+
const signer = cond.type === 2 ? cond.v2.extraSigners.find((s) => s.type === 3) : undefined;
|
|
162
|
+
if (signer === undefined || signer.type !== 3)
|
|
163
|
+
return no("invalid_payload", "stellar/no-carrier");
|
|
164
|
+
const { ed25519: key, payload: signedPayload } = signer.ed25519SignedPayload;
|
|
165
|
+
const hint = Uint8Array.from(key.subarray(28), (b, j) => b ^ signedPayload[signedPayload.length - 4 + j]);
|
|
166
|
+
const buyerKey = Keypair.fromPublicKey(StrKey.encodeEd25519PublicKey(Buffer.from(key)));
|
|
167
|
+
const payloadSignature = v1.signatures.find((s) => sameBytes(s.hint, hint) && buyerKey.verify(Buffer.from(signedPayload), Buffer.from(s.signature)));
|
|
168
|
+
if (payloadSignature === undefined)
|
|
169
|
+
return no("invalid_payload", "no signature of the signed payload");
|
|
170
|
+
return {
|
|
171
|
+
ref,
|
|
172
|
+
presented,
|
|
173
|
+
tx: v1.tx,
|
|
174
|
+
payloadSignature,
|
|
175
|
+
amount: p.amount,
|
|
176
|
+
asset: p.asset,
|
|
177
|
+
payTo: requirements.payTo,
|
|
178
|
+
maxTimeoutSeconds: requirements.maxTimeoutSeconds,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* x402's check of the simulation's events: only contract events of a `transfer` on the asset, exactly one, from the
|
|
183
|
+
* buyer to the payee's plain account, for the amount. Each event is read by lcp's reader of a Stellar Asset Contract's
|
|
184
|
+
* events.
|
|
185
|
+
*/
|
|
186
|
+
function eventsRefusal(events, i) {
|
|
187
|
+
const transfers = [];
|
|
188
|
+
for (const b64 of events) {
|
|
189
|
+
const d = xdr.DiagnosticEvent.fromXdr(b64, "base64").toXdrObject();
|
|
190
|
+
// ContractEventType: SYSTEM 0, CONTRACT 1, DIAGNOSTIC 2.
|
|
191
|
+
if (d.event.type !== 1)
|
|
192
|
+
continue;
|
|
193
|
+
const v0 = d.event.body.v0;
|
|
194
|
+
const ev = transferEventOf(v0.topics.map((t) => xdr.ScVal.fromXdrObject(t).toXdr("base64")), xdr.ScVal.fromXdrObject(v0.data).toXdr("base64"));
|
|
195
|
+
if (isRefusal(ev) || ev.kind !== "transfer")
|
|
196
|
+
return no("invalid_exact_stellar_payload_event_not_transfer");
|
|
197
|
+
if (d.event.contractId === null)
|
|
198
|
+
return no("invalid_exact_stellar_payload_event_missing_contract_id");
|
|
199
|
+
if (StrKey.encodeContract(Buffer.from(d.event.contractId)) !== i.asset)
|
|
200
|
+
return no("invalid_exact_stellar_payload_event_wrong_asset");
|
|
201
|
+
transfers.push(ev);
|
|
202
|
+
}
|
|
203
|
+
if (transfers.length === 0)
|
|
204
|
+
return no("invalid_exact_stellar_payload_no_transfer_events");
|
|
205
|
+
if (transfers.length > 1)
|
|
206
|
+
return no("invalid_exact_stellar_payload_multiple_transfers");
|
|
207
|
+
const t = transfers[0];
|
|
208
|
+
if (t.from !== i.ref.buyer)
|
|
209
|
+
return no("invalid_exact_stellar_payload_event_wrong_from");
|
|
210
|
+
if (t.toBase !== i.payTo || t.toMuxedId !== null)
|
|
211
|
+
return no("invalid_exact_stellar_payload_event_wrong_to");
|
|
212
|
+
if (t.amount !== i.amount)
|
|
213
|
+
return no("invalid_exact_stellar_payload_event_wrong_amount");
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* The checks that read the chain, in x402's order: a simulation of the presented transaction that succeeds, a fee
|
|
218
|
+
* within the ceiling, the events, and an entry whose expiration ledger is within the option's timeout of the latest
|
|
219
|
+
* ledger. A node that could not answer is no verdict: `unexpected_verify_error`, once its entry is in the operator
|
|
220
|
+
* log.
|
|
221
|
+
*/
|
|
222
|
+
async function chainChecks(i, deadline) {
|
|
223
|
+
const failedRead = (call, e) => no(unexpectedVerify(log, { event: "node-call-failed", ...about(i), call }, e));
|
|
224
|
+
let sim;
|
|
225
|
+
try {
|
|
226
|
+
sim = await node.simulate(i.presented, deadline);
|
|
227
|
+
}
|
|
228
|
+
catch (e) {
|
|
229
|
+
if (e instanceof RpcFault)
|
|
230
|
+
return no("invalid_exact_stellar_payload_simulation_failed", e.message);
|
|
231
|
+
return failedRead("simulateTransaction", e);
|
|
232
|
+
}
|
|
233
|
+
if (!sim.ok)
|
|
234
|
+
return no("invalid_exact_stellar_payload_simulation_failed", sim.error);
|
|
235
|
+
const fee = sim.minResourceFee + inclusion;
|
|
236
|
+
if (fee > maxFee || fee > 0xffffffffn) {
|
|
237
|
+
return no("invalid_exact_stellar_payload_fee_exceeds_maximum", `simulation-derived fee ${fee} stroops exceeds ceiling ${maxFee} stroops`);
|
|
238
|
+
}
|
|
239
|
+
let events;
|
|
240
|
+
try {
|
|
241
|
+
events = eventsRefusal(sim.events, i);
|
|
242
|
+
}
|
|
243
|
+
catch (e) {
|
|
244
|
+
return failedRead("simulateTransaction", e);
|
|
245
|
+
}
|
|
246
|
+
if (events !== undefined)
|
|
247
|
+
return events;
|
|
248
|
+
let latest;
|
|
249
|
+
try {
|
|
250
|
+
latest = (await node.latestLedger(deadline)).sequence;
|
|
251
|
+
}
|
|
252
|
+
catch (e) {
|
|
253
|
+
return failedRead("getLatestLedger", e);
|
|
254
|
+
}
|
|
255
|
+
if (i.ref.expiration > latest + Math.ceil(i.maxTimeoutSeconds / LEDGER_SECONDS) + EXPIRATION_TOLERANCE) {
|
|
256
|
+
return no("invalid_exact_stellar_signature_expiration_too_far");
|
|
257
|
+
}
|
|
258
|
+
return { sim, fee };
|
|
259
|
+
}
|
|
260
|
+
async function verify(payload, requirements) {
|
|
261
|
+
const deadline = performance.now() + settleWaitMs;
|
|
262
|
+
const i = await inspect(payload, requirements);
|
|
263
|
+
if (isNo(i))
|
|
264
|
+
return refusedVerify(i);
|
|
265
|
+
const checked = await chainChecks(i, deadline);
|
|
266
|
+
if (isNo(checked))
|
|
267
|
+
return refusedVerify({ ...checked, payer: i.ref.buyer });
|
|
268
|
+
return { isValid: true, payer: i.ref.buyer };
|
|
269
|
+
}
|
|
270
|
+
async function settle(payload, requirements) {
|
|
271
|
+
const deadline = performance.now() + settleWaitMs;
|
|
272
|
+
const i = await inspect(payload, requirements);
|
|
273
|
+
if (isNo(i))
|
|
274
|
+
return failed(i.reason, "", i.message);
|
|
275
|
+
const checked = await chainChecks(i, deadline);
|
|
276
|
+
if (isNo(checked))
|
|
277
|
+
return failed(settleReason(checked.reason), "", checked.message);
|
|
278
|
+
const run = sending.then(() => send(i, checked.sim, checked.fee, deadline));
|
|
279
|
+
sending = run.catch(() => undefined);
|
|
280
|
+
const out = await run;
|
|
281
|
+
if ("answer" in out)
|
|
282
|
+
return out.answer;
|
|
283
|
+
return watch(i, out.transaction, deadline);
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Builds the transaction the module submits: the buyer's, its preconditions, memo and operation (the buyer's entry
|
|
287
|
+
* among it) unchanged, with the source account, the next sequence number, the fee and the simulation's resource data
|
|
288
|
+
* the module's own. The fee meter allows it, the source account's signer signs it, and the buyer's signature of the
|
|
289
|
+
* signed payload goes beside that signature. A request that cannot have reached the node sends nothing: the module's
|
|
290
|
+
* own failure with no transaction, as does a node that refuses it. One that may have reached it is read for its
|
|
291
|
+
* result.
|
|
292
|
+
*/
|
|
293
|
+
async function send(i, sim, fee, deadline) {
|
|
294
|
+
let seq;
|
|
295
|
+
try {
|
|
296
|
+
seq = await node.sequence(source, deadline);
|
|
297
|
+
}
|
|
298
|
+
catch (e) {
|
|
299
|
+
return { answer: unexpected({ event: "node-call-failed", ...about(i), call: "getLedgerEntries" }, e) };
|
|
300
|
+
}
|
|
301
|
+
if (seq === null)
|
|
302
|
+
return { answer: unexpected({ event: "source-account-missing", ...about(i), account: source }) };
|
|
303
|
+
const next = (last !== undefined && last > seq ? last : seq) + 1n;
|
|
304
|
+
const tx = {
|
|
305
|
+
...i.tx,
|
|
306
|
+
sourceAccount: { type: 0, ed25519: sourceKey },
|
|
307
|
+
fee: Number(fee),
|
|
308
|
+
seqNum: next,
|
|
309
|
+
ext: { v: 1, sorobanData: xdr.SorobanTransactionData.fromXdr(sim.transactionData, "base64").toXdrObject() },
|
|
310
|
+
};
|
|
311
|
+
const unsigned = xdr.TransactionEnvelope.fromXdrObject({ type: 2, v1: { tx, signatures: [] } }).toXdr("base64");
|
|
312
|
+
const hash = toHex(new Transaction(unsigned, passphrase).hash());
|
|
313
|
+
if (!(await meter.sending({ network: network, transaction: hash, bound: fee }))) {
|
|
314
|
+
return { answer: failed("fee_budget_spent", "") };
|
|
315
|
+
}
|
|
316
|
+
let signed;
|
|
317
|
+
try {
|
|
318
|
+
const r = await c.source.signTransaction(unsigned, { networkPassphrase: passphrase, address: source });
|
|
319
|
+
if (r.error !== undefined && r.error !== null)
|
|
320
|
+
throw r.error;
|
|
321
|
+
const back = xdr.TransactionEnvelope.fromXdr(r.signedTxXdr, "base64").toXdrObject();
|
|
322
|
+
// The signer signs the transaction it is given, and nothing else.
|
|
323
|
+
if (back.type !== 2 || xdr.Transaction.fromXdrObject(back.v1.tx).toXdr("base64") !== xdr.Transaction.fromXdrObject(tx).toXdr("base64")) {
|
|
324
|
+
throw new Error("the signer returned another transaction");
|
|
325
|
+
}
|
|
326
|
+
signed = back.v1.signatures;
|
|
327
|
+
}
|
|
328
|
+
catch (e) {
|
|
329
|
+
log({ event: "source-sign-failed", ...about(i), transaction: hash }, e);
|
|
330
|
+
return { answer: failed("settle_exact_stellar_transaction_signing_failed", "") };
|
|
331
|
+
}
|
|
332
|
+
const envelope = xdr.TransactionEnvelope.fromXdrObject({ type: 2, v1: { tx, signatures: [...signed, i.payloadSignature] } }).toXdr("base64");
|
|
333
|
+
try {
|
|
334
|
+
const sent = await node.send(envelope, deadline);
|
|
335
|
+
if (sent.status === "PENDING" || sent.status === "DUPLICATE") {
|
|
336
|
+
last = next;
|
|
337
|
+
if (sent.hash !== hash)
|
|
338
|
+
log({ event: "transaction-hash-differs", ...about(i), transaction: sent.hash, computed: hash });
|
|
339
|
+
return { transaction: hash };
|
|
340
|
+
}
|
|
341
|
+
if (sent.status === "TRY_AGAIN_LATER")
|
|
342
|
+
return { answer: failed("settle_exact_stellar_transaction_submission_retryable", "") };
|
|
343
|
+
const code = resultCode(sent.errorResultXdr);
|
|
344
|
+
if (code === TX_BAD_SEQ)
|
|
345
|
+
last = undefined;
|
|
346
|
+
log({ event: "submission-refused", ...about(i), transaction: hash, ...(code === undefined ? {} : { result: code }) });
|
|
347
|
+
return {
|
|
348
|
+
answer: failed("settle_exact_stellar_transaction_submission_failed", "", `sendTransaction answered ERROR${code === undefined ? "" : ` (result code ${code})`}`),
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
catch (e) {
|
|
352
|
+
const entry = { event: "node-call-failed", ...about(i), call: "sendTransaction", transaction: hash };
|
|
353
|
+
if (e instanceof RpcFault || (e instanceof NodeError && !e.sent))
|
|
354
|
+
return { answer: unexpected(entry, e) };
|
|
355
|
+
log(entry, e);
|
|
356
|
+
return { transaction: hash };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Reads the transaction every second until `deadline`: once the node shows it in a ledger, its fee charged goes to the
|
|
361
|
+
* meter, and it succeeded only where its status is `SUCCESS`; a `FAILED` one is x402's failure naming it. Not yet
|
|
362
|
+
* shown: `settlement_pending`.
|
|
363
|
+
*/
|
|
364
|
+
async function watch(i, tx, deadline) {
|
|
365
|
+
for (;;) {
|
|
366
|
+
let t;
|
|
367
|
+
try {
|
|
368
|
+
t = await node.transaction(tx, deadline);
|
|
369
|
+
}
|
|
370
|
+
catch (e) {
|
|
371
|
+
if (!(e instanceof NodeError && e.code === "spent"))
|
|
372
|
+
log({ event: "node-call-failed", ...about(i), call: "getTransaction", transaction: tx }, e);
|
|
373
|
+
}
|
|
374
|
+
if (t !== undefined && (t.status === "SUCCESS" || t.status === "FAILED")) {
|
|
375
|
+
const charged = feeCharged(t.resultXdr);
|
|
376
|
+
if (charged !== undefined)
|
|
377
|
+
meter.included({ network: network, transaction: tx, fee: charged });
|
|
378
|
+
else
|
|
379
|
+
log({ event: "fee-unread", ...about(i), transaction: tx });
|
|
380
|
+
if (t.status === "SUCCESS")
|
|
381
|
+
return { success: true, transaction: tx, network: network, payer: i.ref.buyer };
|
|
382
|
+
log({ event: "settlement-failed", ...about(i), transaction: tx });
|
|
383
|
+
return failed("settle_exact_stellar_transaction_failed", tx);
|
|
384
|
+
}
|
|
385
|
+
if (performance.now() + POLL_MS > deadline)
|
|
386
|
+
return failed("settlement_pending", tx);
|
|
387
|
+
await sleep(POLL_MS);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
/** `unexpected_settle_error` with no transaction, once its entry is in the operator log. */
|
|
391
|
+
function unexpected(entry, cause) {
|
|
392
|
+
const a = unexpectedSettle(log, { ...entry, network }, cause);
|
|
393
|
+
return { ...a, network: network };
|
|
394
|
+
}
|
|
395
|
+
function failed(errorReason, tx, errorMessage) {
|
|
396
|
+
return { success: false, errorReason, ...(errorMessage === undefined ? {} : { errorMessage }), transaction: tx, network: network };
|
|
397
|
+
}
|
|
398
|
+
const facilitator = {
|
|
399
|
+
scheme: "exact",
|
|
400
|
+
caipFamily: "stellar:*",
|
|
401
|
+
// x402's Stellar facilitator states `areFeesSponsored`; the option of this form must carry it `true`.
|
|
402
|
+
getExtra: () => ({ areFeesSponsored: true }),
|
|
403
|
+
getSigners: () => [source],
|
|
404
|
+
verify,
|
|
405
|
+
settle,
|
|
406
|
+
};
|
|
407
|
+
return {
|
|
408
|
+
descriptor: {
|
|
409
|
+
name: "stellar",
|
|
410
|
+
key: "relayer",
|
|
411
|
+
pairings: [ID],
|
|
412
|
+
// The Stellar Asset Contract refuses only a negative amount and emits its event at zero (the profile, rule 13).
|
|
413
|
+
acceptsZero: [ID],
|
|
414
|
+
},
|
|
415
|
+
network: network,
|
|
416
|
+
facilitator,
|
|
417
|
+
record: {
|
|
418
|
+
async instrument(p) {
|
|
419
|
+
const i = await inspect(p.payload, p.requirements);
|
|
420
|
+
if (isNo(i))
|
|
421
|
+
return { refused: i.reason };
|
|
422
|
+
return {
|
|
423
|
+
pairing: ID,
|
|
424
|
+
// The single-use value is the buyer's entry's nonce (the profile, rule 12), which the host keeps per
|
|
425
|
+
// authorizing address, whatever contract the entry invokes.
|
|
426
|
+
instrument: { by: "single-use", network: network, signer: i.ref.buyer, value: i.ref.nonce },
|
|
427
|
+
nonce: exactStellarPrecondition.data.nonce,
|
|
428
|
+
// The entry lapses at a ledger, which no clock time bounds: kept for the settler's life.
|
|
429
|
+
keep: { until: "settler" },
|
|
430
|
+
};
|
|
431
|
+
},
|
|
432
|
+
/**
|
|
433
|
+
* lcp's read, its search starting at the earliest ledger the buyer's entry can land in: the ledger it was signed
|
|
434
|
+
* for, its expiration less the option's timeout in ledgers (the profile, rule 5), less x402's tolerance.
|
|
435
|
+
*/
|
|
436
|
+
async read(p, at) {
|
|
437
|
+
const i = await inspect(p.payload, p.requirements);
|
|
438
|
+
if (isNo(i))
|
|
439
|
+
return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
|
|
440
|
+
const fromLedger = Math.max(0, i.ref.expiration - Math.ceil(i.maxTimeoutSeconds / LEDGER_SECONDS) - EXPIRATION_TOLERANCE);
|
|
441
|
+
const query = { act: "agreement", finality: "finalized", ...(typeof at.search === "string" ? { search: at.search } : {}) };
|
|
442
|
+
return outcomeOf(await exactStellarPrecondition.status({ ...i.ref, fromLedger }, node.reader(at.deadline), query));
|
|
443
|
+
},
|
|
444
|
+
},
|
|
445
|
+
fees: {
|
|
446
|
+
// The source account sends and pays for every settlement; the buyer signs no envelope and never broadcasts it.
|
|
447
|
+
paysFee: () => true,
|
|
448
|
+
payerBroadcast: () => false,
|
|
449
|
+
},
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
/** The `TransactionResult`'s code, or undefined where it does not decode. */
|
|
453
|
+
function resultCode(resultXdr) {
|
|
454
|
+
if (resultXdr === undefined)
|
|
455
|
+
return undefined;
|
|
456
|
+
try {
|
|
457
|
+
return xdr.TransactionResult.fromXdr(resultXdr, "base64").toXdrObject().result.code;
|
|
458
|
+
}
|
|
459
|
+
catch {
|
|
460
|
+
return undefined;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
/** The fee a `TransactionResult` shows charged, in stroops, or undefined where it does not decode. */
|
|
464
|
+
function feeCharged(resultXdr) {
|
|
465
|
+
if (resultXdr === undefined)
|
|
466
|
+
return undefined;
|
|
467
|
+
try {
|
|
468
|
+
return xdr.TransactionResult.fromXdr(resultXdr, "base64").toXdrObject().feeCharged;
|
|
469
|
+
}
|
|
470
|
+
catch {
|
|
471
|
+
return undefined;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
function refusedVerify(r) {
|
|
475
|
+
return {
|
|
476
|
+
isValid: false,
|
|
477
|
+
invalidReason: r.reason,
|
|
478
|
+
...(r.message === undefined ? {} : { invalidMessage: r.message }),
|
|
479
|
+
...(r.payer === undefined ? {} : { payer: r.payer }),
|
|
480
|
+
};
|
|
481
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Stellar RPC node: JSON-RPC 2.0 over HTTP, the methods `getNetwork`, `getLatestLedger`, `getLedgerEntries`,
|
|
3
|
+
* `simulateTransaction`, `sendTransaction`, `getTransaction` and `getEvents` (Stellar RPC's API reference), each call
|
|
4
|
+
* bounded as every node call of the settler is and ending by its caller's deadline; and lcp's `StellarReader` over it.
|
|
5
|
+
*/
|
|
6
|
+
import type { StellarReader } from "@integraledger/lcp/stellar";
|
|
7
|
+
/** A JSON-RPC error the node answered: it read the request and refused it. */
|
|
8
|
+
export declare class RpcFault extends Error {
|
|
9
|
+
readonly code: number;
|
|
10
|
+
constructor(code: number, message: string);
|
|
11
|
+
}
|
|
12
|
+
/** `simulateTransaction`'s answer, as the module reads it. */
|
|
13
|
+
export type Simulated = {
|
|
14
|
+
readonly ok: false;
|
|
15
|
+
readonly error: string;
|
|
16
|
+
} | {
|
|
17
|
+
readonly ok: true;
|
|
18
|
+
/** The smallest resource fee the transaction needs, in stroops. */
|
|
19
|
+
readonly minResourceFee: bigint;
|
|
20
|
+
/** The `SorobanTransactionData` the transaction is to carry, base64. */
|
|
21
|
+
readonly transactionData: string;
|
|
22
|
+
/** Each `DiagnosticEvent` the simulation emitted, base64. */
|
|
23
|
+
readonly events: readonly string[];
|
|
24
|
+
};
|
|
25
|
+
/** `sendTransaction`'s answer. */
|
|
26
|
+
export interface Sent {
|
|
27
|
+
readonly status: "PENDING" | "DUPLICATE" | "TRY_AGAIN_LATER" | "ERROR";
|
|
28
|
+
readonly hash: string;
|
|
29
|
+
/** For `ERROR`: the `TransactionResult` the node refused it with, base64. */
|
|
30
|
+
readonly errorResultXdr?: string;
|
|
31
|
+
}
|
|
32
|
+
/** `getTransaction`'s answer. */
|
|
33
|
+
export interface Got {
|
|
34
|
+
readonly status: "SUCCESS" | "FAILED" | "NOT_FOUND";
|
|
35
|
+
readonly ledger?: number;
|
|
36
|
+
readonly applicationOrder?: number;
|
|
37
|
+
readonly envelopeXdr?: string;
|
|
38
|
+
/** The `TransactionResult`, base64, which holds the fee charged. */
|
|
39
|
+
readonly resultXdr?: string;
|
|
40
|
+
readonly oldestLedger: number;
|
|
41
|
+
readonly latestLedger: number;
|
|
42
|
+
}
|
|
43
|
+
export interface StellarNode {
|
|
44
|
+
passphrase(deadline: number): Promise<string>;
|
|
45
|
+
latestLedger(deadline: number): Promise<{
|
|
46
|
+
sequence: number;
|
|
47
|
+
closeTime?: number;
|
|
48
|
+
}>;
|
|
49
|
+
/** An account's sequence number, or null where the account does not exist. */
|
|
50
|
+
sequence(account: string, deadline: number): Promise<bigint | null>;
|
|
51
|
+
simulate(transaction: string, deadline: number): Promise<Simulated>;
|
|
52
|
+
send(transaction: string, deadline: number): Promise<Sent>;
|
|
53
|
+
transaction(hash: string, deadline: number): Promise<Got>;
|
|
54
|
+
/** lcp's reader over this node, each of its calls ending by `deadline`. */
|
|
55
|
+
reader(deadline: number): StellarReader;
|
|
56
|
+
}
|
|
57
|
+
export declare function stellarNode(url: string): StellarNode;
|