@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.
Files changed (91) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +781 -456
  3. package/dist/answers.d.ts +11 -4
  4. package/dist/answers.js +24 -0
  5. package/dist/core.d.ts +51 -0
  6. package/dist/core.js +758 -0
  7. package/dist/http.d.ts +20 -3
  8. package/dist/http.js +32 -7
  9. package/dist/index.d.ts +12 -36
  10. package/dist/index.js +9 -162
  11. package/dist/module.d.ts +372 -0
  12. package/dist/module.js +13 -0
  13. package/dist/modules/algorand/index.d.ts +22 -0
  14. package/dist/modules/algorand/index.js +247 -0
  15. package/dist/modules/algorand/own.d.ts +26 -0
  16. package/dist/modules/algorand/own.js +231 -0
  17. package/dist/modules/aptos/index.d.ts +23 -0
  18. package/dist/modules/aptos/index.js +232 -0
  19. package/dist/modules/cardano/index.d.ts +18 -0
  20. package/dist/modules/cardano/index.js +124 -0
  21. package/dist/modules/casper/index.d.ts +120 -0
  22. package/dist/modules/casper/index.js +442 -0
  23. package/dist/modules/concordium/index.d.ts +16 -0
  24. package/dist/modules/concordium/index.js +77 -0
  25. package/dist/modules/erc7710/index.d.ts +26 -0
  26. package/dist/modules/erc7710/index.js +220 -0
  27. package/dist/modules/evm/forms.d.ts +74 -0
  28. package/dist/modules/evm/forms.js +204 -0
  29. package/dist/modules/evm/index.d.ts +40 -0
  30. package/dist/modules/evm/index.js +154 -0
  31. package/dist/modules/evm/node.d.ts +29 -0
  32. package/dist/modules/evm/node.js +222 -0
  33. package/dist/modules/hedera/executor.d.ts +63 -0
  34. package/dist/modules/hedera/executor.js +343 -0
  35. package/dist/modules/hedera/index.d.ts +23 -0
  36. package/dist/modules/hedera/index.js +136 -0
  37. package/dist/modules/hedera/mirror.d.ts +32 -0
  38. package/dist/modules/hedera/mirror.js +111 -0
  39. package/dist/modules/index.d.ts +23 -0
  40. package/dist/modules/index.js +24 -0
  41. package/dist/modules/lnbtc/index.d.ts +10 -0
  42. package/dist/modules/lnbtc/index.js +112 -0
  43. package/dist/modules/near/index.d.ts +18 -0
  44. package/dist/modules/near/index.js +246 -0
  45. package/dist/modules/polkadot/index.d.ts +12 -0
  46. package/dist/modules/polkadot/index.js +149 -0
  47. package/dist/modules/polkadot/rail.d.ts +40 -0
  48. package/dist/{polkadot.js → modules/polkadot/rail.js} +214 -288
  49. package/dist/modules/solana/index.d.ts +60 -0
  50. package/dist/modules/solana/index.js +326 -0
  51. package/dist/modules/solana/reader.d.ts +25 -0
  52. package/dist/modules/solana/reader.js +194 -0
  53. package/dist/modules/solana/state.d.ts +6 -0
  54. package/dist/modules/solana/state.js +103 -0
  55. package/dist/modules/starknet/index.d.ts +35 -0
  56. package/dist/modules/starknet/index.js +548 -0
  57. package/dist/modules/starknet/node.d.ts +78 -0
  58. package/dist/modules/starknet/node.js +339 -0
  59. package/dist/modules/stellar/index.d.ts +44 -0
  60. package/dist/modules/stellar/index.js +481 -0
  61. package/dist/modules/stellar/node.d.ts +57 -0
  62. package/dist/modules/stellar/node.js +151 -0
  63. package/dist/modules/sui/index.d.ts +16 -0
  64. package/dist/modules/sui/index.js +310 -0
  65. package/dist/modules/sui/node.d.ts +49 -0
  66. package/dist/modules/sui/node.js +197 -0
  67. package/dist/modules/ton/index.d.ts +16 -0
  68. package/dist/modules/ton/index.js +73 -0
  69. package/dist/modules/tron/index.d.ts +12 -0
  70. package/dist/modules/tron/index.js +120 -0
  71. package/dist/modules/tron/rail.d.ts +32 -0
  72. package/dist/{tron.js → modules/tron/rail.js} +206 -195
  73. package/dist/modules/xrpl/index.d.ts +28 -0
  74. package/dist/modules/xrpl/index.js +299 -0
  75. package/dist/modules/xrpl/node.d.ts +52 -0
  76. package/dist/modules/xrpl/node.js +231 -0
  77. package/dist/modules/xrpl/upto.d.ts +5 -0
  78. package/dist/modules/xrpl/upto.js +269 -0
  79. package/dist/record.d.ts +131 -0
  80. package/dist/record.js +330 -0
  81. package/dist/unexpected.d.ts +3 -2
  82. package/dist/unexpected.js +2 -1
  83. package/dist/wrapper.d.ts +68 -0
  84. package/dist/wrapper.js +126 -0
  85. package/package.json +48 -12
  86. package/dist/polkadot.d.ts +0 -21
  87. package/dist/store.d.ts +0 -59
  88. package/dist/store.js +0 -103
  89. package/dist/tron.d.ts +0 -12
  90. /package/dist/{base58check.d.ts → modules/tron/base58check.d.ts} +0 -0
  91. /package/dist/{base58check.js → modules/tron/base58check.js} +0 -0
@@ -0,0 +1,548 @@
1
+ /**
2
+ * Starknet: the settler's own facilitator for the pairing `x402/exact/starknet`, written to x402's Starknet scheme
3
+ * (`scheme_exact_starknet.md`), which x402 specifies and publishes no code for, and to lcp's profile
4
+ * `x402-exact-starknet.md`. The payer signs a SNIP-9 v2 outside execution of one `transfer`, its `Caller` the
5
+ * module's executor account and its `Nonce` the low 250 bits of H (or of the agreement value); the module executes it
6
+ * from that account, which pays the fee, one outside execution per transaction. lcp decodes the payment (`bound`,
7
+ * `reference`) and reads it (`status`); the module adds the scheme's checks: the caller binding, the call's form, the
8
+ * window, the account, the signature, the nonce, the balance and a simulation; then the settlement and its effect.
9
+ */
10
+ import { canonicalJson, fromLegalContext, isRefusal } from "@integraledger/lcp";
11
+ import { ANY_CALLER, EVENT_TRANSFER, exactStarknet, FELT_P, outsideExecution, SELECTOR_TRANSFER, STARKNET_MAX_SIGNATURE_FELTS, } from "@integraledger/lcp/starknet";
12
+ import { hash, stark, transaction, typedData } from "starknet";
13
+ import { isObject } from "../../answers.js";
14
+ import { NodeError, sleep } from "../../http.js";
15
+ import { outcomeOf } from "../../module.js";
16
+ import { settleReason as settleReasonOf, unexpectedSettle, unexpectedVerify } from "../../unexpected.js";
17
+ import { BALANCE_OF, BALANCE_OF_CAMEL, felt, IS_VALID_NONCE, IS_VALID_SIGNATURE, RPC, RpcFault, starknetNode, VALID, } from "./node.js";
18
+ const ID = exactStarknet.id;
19
+ const U128 = 1n << 128n;
20
+ const POLL_MS = 1_000;
21
+ const NETWORKS = ["starknet:SN_MAIN", "starknet:SN_SEPOLIA"];
22
+ /**
23
+ * The networks whose kind names the pairing in `extra.acceptsZero`: each holds a token on which lcp's `starknetFloor`
24
+ * answers 0 (the profile's rule 24), on Starknet Sepolia STRK and USDC. lcp's check of the option refuses an amount of
25
+ * "0" on any other token, `starknet/option-malformed`, which the module answers `invalid_payment_requirements`.
26
+ */
27
+ const ZERO_NETWORKS = ["starknet:SN_SEPOLIA"];
28
+ /** The `l2_gas` a simulation may spend, which charges no fee: Starknet's per-transaction execution bound. */
29
+ const SIMULATION_L2_GAS = 1000000000n;
30
+ const no = (reason, message) => (message === undefined ? { reason } : { reason, message });
31
+ const isNo = (v) => isObject(v) && typeof v["reason"] === "string" && Object.keys(v).every((k) => k === "reason" || k === "message");
32
+ /** lcp's refusals of the option's form: the requirements' fault where the payment echoes them unchanged. */
33
+ const OPTION_CODES = new Set([
34
+ "x402/option-not-this-pairing",
35
+ "x402/option-malformed",
36
+ "starknet/network-malformed",
37
+ "starknet/option-malformed",
38
+ "starknet/caller-forbidden",
39
+ ]);
40
+ /** The x402 reason for lcp's refusal of the payment, with lcp's code as the message. */
41
+ function refusedBy(r, payload, requirements) {
42
+ const echoed = canonicalJson(payload.accepted) === canonicalJson(requirements);
43
+ if (r.code === "starknet/caller-not-fee-payer")
44
+ return no("invalid_exact_starknet_payload_caller", r.code);
45
+ if (echoed && OPTION_CODES.has(r.code))
46
+ return no("invalid_payment_requirements", r.code);
47
+ if (echoed && r.code === "starknet/felt-malformed" && ![requirements.asset, requirements.payTo, requirements.extra?.["feePayer"]].every((v) => felt(v) !== undefined)) {
48
+ return no("invalid_payment_requirements", r.code);
49
+ }
50
+ return no("invalid_payload", r.code);
51
+ }
52
+ /** The members x402's Starknet scheme admits in the signed typed data's `domain`, `message` and each call. */
53
+ const DOMAIN_KEYS = new Set(["name", "version", "chainId", "revision"]);
54
+ const MESSAGE_KEYS = ["Caller", "Nonce", "Execute After", "Execute Before", "Calls"];
55
+ const CALL_KEYS = ["To", "Selector", "Calldata"];
56
+ function onlyKeys(o, keys, all) {
57
+ if (!isObject(o))
58
+ return false;
59
+ const have = Object.keys(o);
60
+ return have.every((k) => keys.includes(k)) && (!all || keys.every((k) => have.includes(k)));
61
+ }
62
+ /** A `Transfer` event by its layout: keyed (`[selector, from, to]`, `[low, high]`) or unkeyed (`[selector]`, `[from, to, low, high]`). */
63
+ function transferOf(e) {
64
+ if (e.keys.length === 0 || BigInt(e.keys[0]) !== BigInt(EVENT_TRANSFER))
65
+ return undefined;
66
+ const words = e.keys.length === 3 && e.data.length === 2 ? [...e.keys.slice(1), ...e.data] : e.keys.length === 1 && e.data.length === 4 ? e.data : undefined;
67
+ if (words === undefined)
68
+ return "neither";
69
+ const [from, to, low, high] = words.map((w) => BigInt(w));
70
+ if (low >= U128 || high >= U128)
71
+ return "neither";
72
+ return { from: from, to: to, amount: low + high * U128 };
73
+ }
74
+ /**
75
+ * The scheme's effect check (its rule 8, and its check of the settlement's receipt): exactly one `Transfer` emitted by the asset whose sender is
76
+ * the payer, to `payTo` for the amount. An asset event with the `Transfer` key of neither layout fails it.
77
+ */
78
+ function oneTransfer(events, i) {
79
+ const asset = BigInt(i.asset);
80
+ const payer = BigInt(i.from);
81
+ const fromPayer = [];
82
+ for (const e of events) {
83
+ if (BigInt(e.from) !== asset)
84
+ continue;
85
+ const t = transferOf(e);
86
+ if (t === undefined)
87
+ continue;
88
+ if (t === "neither")
89
+ return false;
90
+ if (t.from === payer)
91
+ fromPayer.push(t);
92
+ }
93
+ return fromPayer.length === 1 && fromPayer[0].to === BigInt(i.payTo) && fromPayer[0].amount === i.amount;
94
+ }
95
+ /** One module for the configured network, for the scheme `exact`. */
96
+ /** Starts one module per configured network, each its own registration of `exact`. */
97
+ export const starter = {
98
+ name: "starknet",
99
+ async start(config, core) {
100
+ return { registrations: config.networks.map((c) => ({ network: c.network, module: starknetModule(c, core), own: [] })) };
101
+ },
102
+ };
103
+ /**
104
+ * The module for one network. The settler's wait for the chain is the core's; the fee meter is the network's, which the
105
+ * module tells of each transaction's bound before it sends it and its fee once included.
106
+ */
107
+ export function starknetModule(c, core) {
108
+ if (!NETWORKS.includes(c.network))
109
+ throw new TypeError(`not a Starknet network: ${c.network}`);
110
+ const executor = felt(c.executor.address);
111
+ if (executor === undefined || BigInt(executor) === 0n || BigInt(executor) >= FELT_P || executor === ANY_CALLER) {
112
+ throw new TypeError("the executor's address is not an account address");
113
+ }
114
+ const network = c.network;
115
+ const node = starknetNode(network, c.rpc.replace(/\/+$/, ""));
116
+ const { log, settleWaitMs } = core;
117
+ const meter = core.meter(network);
118
+ const skew = BigInt(c.skewMarginSeconds ?? 60);
119
+ const minSettle = BigInt(c.minSettleMarginSeconds ?? 30);
120
+ const chainId = `0x${Buffer.from(network.slice("starknet:".length), "ascii").toString("hex")}`;
121
+ /** The executor's transactions are sent one at a time, each with the next nonce. */
122
+ let sending = Promise.resolve();
123
+ const about = (i) => ({ network, payer: i.from });
124
+ /** Every check of the payment that reads neither the chain nor the clock (the scheme's rules 1, 2, 4 and 7). */
125
+ async function inspect(payload, requirements) {
126
+ if (!isObject(payload) || !isObject(requirements) || !isObject(payload.payload))
127
+ return no("invalid_payload");
128
+ if (requirements.network !== network)
129
+ return no("invalid_network");
130
+ if (requirements.scheme !== "exact")
131
+ return no("unsupported_scheme");
132
+ // H, and the act: a payment's nonce is H's low 250 bits, an agreement's its agreement value's (the profile, rule 4).
133
+ let act = "payment";
134
+ let h = await exactStarknet.bound(payload);
135
+ if (isRefusal(h) && h.code === "starknet/nonce-not-bound") {
136
+ const echoed = isObject(payload.extensions) ? payload.extensions["legalContext"] : undefined;
137
+ const lc = fromLegalContext({ legalContext: isObject(echoed) ? echoed["info"] : undefined });
138
+ if (lc !== null) {
139
+ const agreed = await exactStarknet.bound(payload, { act: "agreement", h: lc.h });
140
+ if (!isRefusal(agreed)) {
141
+ act = "agreement";
142
+ h = agreed;
143
+ }
144
+ }
145
+ }
146
+ if (isRefusal(h))
147
+ return refusedBy(h, payload, requirements);
148
+ const ref = await exactStarknet.reference(payload, requirements, { act, h });
149
+ if (isRefusal(ref))
150
+ return refusedBy(ref, payload, requirements);
151
+ // A feePayer the module cannot settle through would give an authorization only another party could execute.
152
+ if (felt(requirements.extra["feePayer"]) !== executor)
153
+ return no("invalid_payment_requirements", "starknet/fee-payer-not-executor");
154
+ if (BigInt(requirements.maxTimeoutSeconds) <= minSettle)
155
+ return no("invalid_payment_requirements", "starknet/timeout-below-settle-margin");
156
+ const oe = payload.payload["outsideExecution"];
157
+ const td = oe["typedData"];
158
+ if (!onlyKeys(td["domain"], [...DOMAIN_KEYS], true) || !onlyKeys(td["message"], MESSAGE_KEYS, true)) {
159
+ return no("invalid_payload", "starknet/typed-data-keys");
160
+ }
161
+ const calls = td["message"]["Calls"];
162
+ if (!calls.every((k) => onlyKeys(k, CALL_KEYS, true)))
163
+ return no("invalid_payload", "starknet/typed-data-keys");
164
+ const signature = oe["signature"];
165
+ if (!Array.isArray(signature) || signature.length < 1 || signature.length > STARKNET_MAX_SIGNATURE_FELTS) {
166
+ return no("invalid_payload", "starknet/signature-malformed");
167
+ }
168
+ const sig = signature.map(felt);
169
+ if (sig.some((s) => s === undefined || BigInt(s) >= FELT_P))
170
+ return no("invalid_payload", "starknet/signature-malformed");
171
+ const p = ref.presented;
172
+ if (p.calls.length !== 1)
173
+ return no("invalid_payload", "starknet/not-one-call");
174
+ const call = p.calls[0];
175
+ if (BigInt(call.to) !== BigInt(ref.asset))
176
+ return no("invalid_exact_starknet_payload_asset_mismatch");
177
+ if (BigInt(call.selector) !== BigInt(SELECTOR_TRANSFER) || call.calldata.length !== 3)
178
+ return no("invalid_payload", "starknet/call-malformed");
179
+ const [to, low, high] = call.calldata.map((x) => BigInt(x));
180
+ if (low >= U128 || high >= U128)
181
+ return no("invalid_payload", "starknet/call-malformed");
182
+ if (to !== BigInt(requirements.payTo))
183
+ return no("invalid_exact_starknet_payload_recipient_mismatch");
184
+ if (low + high * U128 !== BigInt(requirements.amount))
185
+ return no("invalid_exact_starknet_payload_amount_mismatch");
186
+ if (BigInt(ref.from) === BigInt(executor))
187
+ return no("invalid_payment_requirements", "starknet/payer-is-fee-payer");
188
+ // An outside execution the payee's account signed is no payment and no agreement (the profile, rule 5).
189
+ if (BigInt(ref.from) === BigInt(requirements.payTo))
190
+ return no("invalid_payload", "starknet/payee-signed");
191
+ return {
192
+ network,
193
+ act,
194
+ h,
195
+ ref,
196
+ from: ref.from,
197
+ payTo: felt(requirements.payTo),
198
+ asset: ref.asset,
199
+ amount: BigInt(requirements.amount),
200
+ nonce: ref.nonce,
201
+ executeAfter: BigInt(p.executeAfter),
202
+ executeBefore: BigInt(p.executeBefore),
203
+ signature: sig,
204
+ maxTimeoutSeconds: requirements.maxTimeoutSeconds,
205
+ };
206
+ }
207
+ /** The scheme's window (its *Timeout Mapping*): at `/verify` the freshness band and the floor; at settlement the floor and the upper bound. */
208
+ function windowRefusal(i, phase) {
209
+ const now = BigInt(Math.floor(Date.now() / 1000));
210
+ const timeout = BigInt(i.maxTimeoutSeconds);
211
+ if (phase === "verify" && i.executeAfter >= now - skew)
212
+ return no("invalid_payload", "starknet/execute-after-not-past");
213
+ if (phase === "verify" && i.executeBefore < now + timeout - skew)
214
+ return no("outside_execution_expired");
215
+ if (i.executeBefore > now + timeout + skew)
216
+ return no("outside_execution_window_exceeds_max_timeout");
217
+ if (i.executeBefore <= now + minSettle)
218
+ return no("outside_execution_expired");
219
+ return undefined;
220
+ }
221
+ /** The SNIP-12 hash of the typed data rebuilt from the signed values (the scheme's rule 2), never of the typed data received. */
222
+ function messageHash(i) {
223
+ const td = outsideExecution({
224
+ network,
225
+ feePayer: i.ref.presented.caller,
226
+ asset: i.asset,
227
+ payTo: i.payTo,
228
+ amount: i.amount,
229
+ executeBefore: Number(i.executeBefore),
230
+ nonce: i.nonce,
231
+ });
232
+ if (isRefusal(td))
233
+ throw new Error(`lcp refused the canonical typed data: ${td.code}`);
234
+ const message = { ...td.message, "Execute After": i.executeAfter.toString() };
235
+ return typedData.getMessageHash({ ...td, message }, i.from);
236
+ }
237
+ /** The executor's call of `execute_from_outside_v2` on the payer's account, the outside execution as presented. */
238
+ function executeCall(i) {
239
+ const p = i.ref.presented;
240
+ const call = p.calls[0];
241
+ const calldata = [p.caller, p.nonce, p.executeAfter, p.executeBefore, "0x1", call.to, call.selector, `0x${call.calldata.length.toString(16)}`, ...call.calldata, `0x${i.signature.length.toString(16)}`, ...i.signature];
242
+ return { contractAddress: i.from, entrypoint: "execute_from_outside_v2", calldata };
243
+ }
244
+ const hex = (v) => `0x${v.toString(16)}`;
245
+ const rpcBounds = (b) => Object.fromEntries(Object.entries(b).map(([k, r]) => [k, { max_amount: hex(r.max_amount), max_price_per_unit: hex(r.max_price_per_unit) }]));
246
+ /** The transaction the executor sends, unsigned: its calldata, its nonce and its resource bounds. */
247
+ function invokeOf(i, nonce, bounds, signature) {
248
+ return {
249
+ type: "INVOKE",
250
+ version: "0x3",
251
+ sender_address: executor,
252
+ calldata: transaction.getExecuteCalldata([executeCall(i)], "1").map((x) => hex(BigInt(x))),
253
+ signature,
254
+ nonce: hex(nonce),
255
+ resource_bounds: rpcBounds(bounds),
256
+ tip: "0x0",
257
+ paymaster_data: [],
258
+ account_deployment_data: [],
259
+ nonce_data_availability_mode: "L1",
260
+ fee_data_availability_mode: "L1",
261
+ };
262
+ }
263
+ /** The resource bounds a simulated fee gives: half again each amount and each price, as starknet.js's default overhead. */
264
+ function boundsOf(f) {
265
+ const up = (v) => v + v / 2n;
266
+ return {
267
+ l1_gas: { max_amount: up(f.l1Gas), max_price_per_unit: up(f.l1GasPrice) },
268
+ l2_gas: { max_amount: up(f.l2Gas), max_price_per_unit: up(f.l2GasPrice) },
269
+ l1_data_gas: { max_amount: up(f.l1DataGas), max_price_per_unit: up(f.l1DataGasPrice) },
270
+ };
271
+ }
272
+ const feeBound = (b) => Object.values(b).reduce((sum, r) => sum + r.max_amount * r.max_price_per_unit, 0n);
273
+ /**
274
+ * The checks that read the chain, in the scheme's order: the account deployed, its signature, the nonce unused, the
275
+ * balance, and a simulation of the settlement showing the one `Transfer`. A node that could not answer is no
276
+ * verdict: `unexpected_verify_error`, once its entry is in the operator log.
277
+ */
278
+ async function chainChecks(i, deadline) {
279
+ const failedRead = (call, e) => no(unexpectedVerify(log, { event: "node-call-failed", ...about(i), call }, e));
280
+ try {
281
+ await node.classHashAt(i.from, deadline);
282
+ }
283
+ catch (e) {
284
+ if (e instanceof RpcFault && e.code === RPC.CONTRACT_NOT_FOUND)
285
+ return no("account_not_deployed");
286
+ return failedRead("starknet_getClassHashAt", e);
287
+ }
288
+ try {
289
+ const out = await node.call(i.from, IS_VALID_SIGNATURE, [felt(messageHash(i)), hex(BigInt(i.signature.length)), ...i.signature], "latest", deadline);
290
+ if (out.length !== 1 || out[0] !== VALID)
291
+ return no("invalid_exact_starknet_payload_signature");
292
+ }
293
+ catch (e) {
294
+ if (e instanceof RpcFault)
295
+ return no("invalid_exact_starknet_payload_signature", `starknet/rpc-${e.code}`);
296
+ return failedRead("is_valid_signature", e);
297
+ }
298
+ try {
299
+ const out = await node.call(i.from, IS_VALID_NONCE, [i.nonce], "latest", deadline);
300
+ if (out.length !== 1 || out[0] !== "0x1")
301
+ return no("nonce_already_used");
302
+ }
303
+ catch (e) {
304
+ if (e instanceof RpcFault)
305
+ return no("nonce_already_used", `starknet/rpc-${e.code}`);
306
+ return failedRead("is_valid_outside_execution_nonce", e);
307
+ }
308
+ let balance;
309
+ for (const entry of [BALANCE_OF, BALANCE_OF_CAMEL]) {
310
+ try {
311
+ balance = await node.call(i.asset, entry, [i.from], "latest", deadline);
312
+ break;
313
+ }
314
+ catch (e) {
315
+ if (!(e instanceof RpcFault))
316
+ return failedRead("balance_of", e);
317
+ }
318
+ }
319
+ if (balance === undefined)
320
+ return no("invalid_payment_requirements", "starknet/no-balance-getter");
321
+ if (balance.length !== 2 || BigInt(balance[0]) >= U128 || BigInt(balance[1]) >= U128)
322
+ return failedRead("balance_of", new NodeError("malformed", true, "balance"));
323
+ if (BigInt(balance[0]) + BigInt(balance[1]) * U128 < i.amount)
324
+ return no("insufficient_funds");
325
+ let simulated;
326
+ try {
327
+ const nonce = await node.nonce(executor, "latest", deadline);
328
+ const free = {
329
+ l1_gas: { max_amount: 0n, max_price_per_unit: 0n },
330
+ l2_gas: { max_amount: SIMULATION_L2_GAS, max_price_per_unit: 0n },
331
+ l1_data_gas: { max_amount: 0n, max_price_per_unit: 0n },
332
+ };
333
+ simulated = await node.simulate(invokeOf(i, nonce, free, []), deadline);
334
+ }
335
+ catch (e) {
336
+ if (e instanceof RpcFault && e.code === RPC.TRANSACTION_EXECUTION_ERROR)
337
+ return no("simulation_failed");
338
+ return failedRead("starknet_simulateTransactions", e);
339
+ }
340
+ if (simulated.reverted || !oneTransfer(simulated.events, i))
341
+ return no("simulation_failed");
342
+ return simulated;
343
+ }
344
+ async function verify(payload, requirements) {
345
+ const deadline = performance.now() + settleWaitMs;
346
+ const i = await inspect(payload, requirements);
347
+ if (isNo(i))
348
+ return refusedVerify(i);
349
+ const w = windowRefusal(i, "verify");
350
+ if (w !== undefined)
351
+ return refusedVerify(w);
352
+ const checked = await chainChecks(i, deadline);
353
+ if (isNo(checked))
354
+ return refusedVerify(checked);
355
+ return { isValid: true, payer: i.from };
356
+ }
357
+ async function settle(payload, requirements) {
358
+ const deadline = performance.now() + settleWaitMs;
359
+ const i = await inspect(payload, requirements);
360
+ if (isNo(i))
361
+ return failed(settleReason(i.reason), "", i.message);
362
+ const w = windowRefusal(i, "settle");
363
+ if (w !== undefined)
364
+ return failed(w.reason, "", w.message);
365
+ const simulated = await chainChecks(i, deadline);
366
+ if (isNo(simulated))
367
+ return failed(settleReason(simulated.reason), "", simulated.message);
368
+ const bounds = boundsOf(simulated.fee);
369
+ const bound = feeBound(bounds);
370
+ if (c.maxFee !== undefined && bound > c.maxFee) {
371
+ log({ event: "fee-over-bound", ...about(i), bound: bound.toString() });
372
+ return failed("invalid_transaction", "", "starknet/fee-over-bound");
373
+ }
374
+ const run = sending.then(() => send(i, bounds, bound, deadline));
375
+ sending = run.catch(() => undefined);
376
+ const out = await run;
377
+ if ("answer" in out)
378
+ return out.answer;
379
+ return watch(i, out.transaction, deadline);
380
+ }
381
+ /**
382
+ * Signs and sends the executor's transaction with the executor's next nonce, after the fee meter allows it. A request
383
+ * that cannot have reached the node sends nothing: `unexpected_settle_error` with no transaction, as does a node that
384
+ * refuses it. One that may have reached it is read for its receipt.
385
+ */
386
+ async function send(i, bounds, bound, deadline) {
387
+ let nonce;
388
+ try {
389
+ nonce = await node.nonce(executor, "pre_confirmed", deadline);
390
+ }
391
+ catch (e) {
392
+ return { answer: unexpected({ event: "node-call-failed", ...about(i), call: "starknet_getNonce" }, e) };
393
+ }
394
+ const call = executeCall(i);
395
+ const details = {
396
+ walletAddress: executor,
397
+ cairoVersion: "1",
398
+ chainId: chainId,
399
+ nonce,
400
+ version: "0x3",
401
+ resourceBounds: bounds,
402
+ tip: 0n,
403
+ paymasterData: [],
404
+ accountDeploymentData: [],
405
+ nonceDataAvailabilityMode: "L1",
406
+ feeDataAvailabilityMode: "L1",
407
+ };
408
+ const txHash = felt(hash.calculateInvokeTransactionHash({
409
+ senderAddress: executor,
410
+ version: "0x3",
411
+ compiledCalldata: transaction.getExecuteCalldata([call], "1"),
412
+ chainId: chainId,
413
+ nonce,
414
+ accountDeploymentData: [],
415
+ nonceDataAvailabilityMode: 0,
416
+ feeDataAvailabilityMode: 0,
417
+ resourceBounds: bounds,
418
+ tip: 0n,
419
+ paymasterData: [],
420
+ }));
421
+ if (!(await meter.sending({ network: network, transaction: txHash, bound }))) {
422
+ return { answer: failed("fee_budget_spent", "") };
423
+ }
424
+ let signature;
425
+ try {
426
+ signature = stark.signatureToHexArray(await c.executor.signer.signTransaction([call], details));
427
+ }
428
+ catch (e) {
429
+ return { answer: unexpected({ event: "executor-sign-failed", ...about(i) }, e) };
430
+ }
431
+ try {
432
+ const got = await node.add(invokeOf(i, nonce, bounds, signature), deadline);
433
+ if (BigInt(got) !== BigInt(txHash))
434
+ log({ event: "transaction-hash-differs", ...about(i), transaction: got, computed: txHash });
435
+ }
436
+ catch (e) {
437
+ const entry = { event: "node-call-failed", ...about(i), call: "starknet_addInvokeTransaction", transaction: txHash };
438
+ if (e instanceof RpcFault || (e instanceof NodeError && !e.sent))
439
+ return { answer: unexpected(entry, e) };
440
+ log(entry, e);
441
+ }
442
+ return { transaction: txHash };
443
+ }
444
+ /**
445
+ * Reads the transaction's receipt every second until `deadline`: once it is in an accepted block, its fee goes to the
446
+ * meter, and it succeeded only with execution `SUCCEEDED` and exactly the expected `Transfer`; a `REVERTED` one, or
447
+ * one without that transfer, is `invalid_transaction_state` naming it. Not yet shown: `settlement_pending`.
448
+ */
449
+ async function watch(i, tx, deadline) {
450
+ for (;;) {
451
+ let r = null;
452
+ try {
453
+ r = await node.receipt(tx, deadline);
454
+ }
455
+ catch (e) {
456
+ if (!(e instanceof NodeError && e.code === "spent"))
457
+ log({ event: "node-call-failed", ...about(i), call: "starknet_getTransactionReceipt", transaction: tx }, e);
458
+ }
459
+ if (r !== null && r.finality !== "PRE_CONFIRMED" && r.blockNumber !== null) {
460
+ meter.included({ network: network, transaction: tx, fee: r.fee });
461
+ const events = r.events.map((e) => ({ from: e.fromAddress, keys: [...e.keys], data: [...e.data] }));
462
+ if (r.execution === "SUCCEEDED" && oneTransfer(events, i))
463
+ return { success: true, transaction: tx, network, payer: i.from };
464
+ log({ event: "settlement-failed", ...about(i), transaction: tx, execution: r.execution });
465
+ return failed("invalid_transaction_state", tx);
466
+ }
467
+ if (performance.now() + POLL_MS > deadline)
468
+ return failed("settlement_pending", tx);
469
+ await sleep(POLL_MS);
470
+ }
471
+ }
472
+ /** `unexpected_settle_error` with no transaction, once its entry is in the operator log. */
473
+ function unexpected(entry, cause) {
474
+ const a = unexpectedSettle(log, { ...entry, network }, cause);
475
+ return { ...a, network: network };
476
+ }
477
+ function failed(errorReason, tx, errorMessage) {
478
+ return { success: false, errorReason, ...(errorMessage === undefined ? {} : { errorMessage }), transaction: tx, network };
479
+ }
480
+ const facilitator = {
481
+ scheme: "exact",
482
+ caipFamily: "starknet:*",
483
+ // x402's Starknet scheme: the kind states the address the payer names as `Caller`, and `signers` the account that
484
+ // signs the settlement transaction, here the same executor.
485
+ getExtra: () => ({ feePayer: executor }),
486
+ getSigners: () => [executor],
487
+ verify,
488
+ settle,
489
+ };
490
+ return {
491
+ descriptor: {
492
+ name: "starknet",
493
+ key: "relayer",
494
+ pairings: [ID],
495
+ // A `transfer` of 0 of STRK and of USDC on Starknet Sepolia emits a `Transfer` of 0 (`starknet_simulateTransactions`
496
+ // at block 18422698, lcp's test/fixtures/starknet-zero-transfer-sepolia.json).
497
+ acceptsZero: ZERO_NETWORKS.includes(network) ? [ID] : [],
498
+ },
499
+ network: network,
500
+ facilitator,
501
+ record: {
502
+ async instrument(p) {
503
+ const i = await inspect(p.payload, p.requirements);
504
+ if (isNo(i))
505
+ return i.message === undefined ? { refused: i.reason } : { refused: i.reason, message: i.message };
506
+ return {
507
+ pairing: ID,
508
+ // The account keys a used nonce by its value alone: the payer and the signed nonce (an agreement's is its own
509
+ // value's low bits, so one payer's agreement and payment under one H are two instruments).
510
+ instrument: { by: "single-use", network: network, signer: i.from, value: i.nonce },
511
+ nonce: exactStarknet.data.nonce,
512
+ keep: { until: "lapse", at: Number(i.executeBefore) * 1000 },
513
+ };
514
+ },
515
+ /** The newest block, read just before the claim: no settlement of the payment can land at or before it. */
516
+ async position(_p, at) {
517
+ return (await node.head("ACCEPTED_ON_L2", at.deadline)).number;
518
+ },
519
+ async read(p, at) {
520
+ const i = await inspect(p.payload, p.requirements);
521
+ if (isNo(i))
522
+ return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
523
+ // The transaction the module's settle named is read first; the search starts at the block before the claim.
524
+ const named = felt(at.transaction);
525
+ const ref = { ...i.ref, h: i.h, ...(named === undefined ? {} : { transaction: named }) };
526
+ const query = {
527
+ act: i.act,
528
+ finality: "ACCEPTED_ON_L1",
529
+ ...(typeof at.from === "bigint" ? { after: at.from } : {}),
530
+ ...(at.search === undefined ? {} : { search: at.search }),
531
+ };
532
+ return outcomeOf(await exactStarknet.status(ref, node.reader(at.deadline), query));
533
+ },
534
+ },
535
+ fees: {
536
+ // The executor sends and pays for every settlement; the payer never broadcasts it, its `Caller` being the executor.
537
+ paysFee: () => true,
538
+ payerBroadcast: () => false,
539
+ },
540
+ };
541
+ }
542
+ function refusedVerify(r) {
543
+ return { isValid: false, invalidReason: r.reason, ...(r.message === undefined ? {} : { invalidMessage: r.message }) };
544
+ }
545
+ /** A verify reason as a settle answer's: a node or store that could not be read before submission is a settle error. */
546
+ function settleReason(reason) {
547
+ return settleReasonOf(reason);
548
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The seller's Starknet node, over Starknet's JSON-RPC (specification 0.9 or later, whose block tags are `latest`,
3
+ * `pre_confirmed` and `l1_accepted`): the calls the module's checks and its settlement make, and the reader lcp's
4
+ * `x402/exact/starknet` read takes. Every call is bounded by the node bound of `../../http.js` and by its deadline.
5
+ */
6
+ import { type Felt, type StarknetEventPage, type StarknetEventQuery, type StarknetHead, type StarknetInvocation, type StarknetMark, type StarknetNetwork, type StarknetReader, type StarknetReceipt } from "@integraledger/lcp/starknet";
7
+ /** A JSON-RPC error the node answered: the request reached it, and it refused it with this code. */
8
+ export declare class RpcFault extends Error {
9
+ readonly code: number;
10
+ readonly data?: unknown;
11
+ constructor(code: number, message: string, data?: unknown);
12
+ }
13
+ /** Starknet JSON-RPC error codes the module reads (the specification's `starknet_api_openrpc.json`). */
14
+ export declare const RPC: {
15
+ readonly CONTRACT_NOT_FOUND: 20;
16
+ readonly ENTRYPOINT_NOT_FOUND: 21;
17
+ readonly BLOCK_NOT_FOUND: 24;
18
+ readonly TXN_HASH_NOT_FOUND: 29;
19
+ readonly CONTRACT_ERROR: 40;
20
+ readonly TRANSACTION_EXECUTION_ERROR: 41;
21
+ };
22
+ /**
23
+ * A felt in its shortest lowercase spelling, or undefined for a value that is not `0x` and 1 to 64 hex digits below the
24
+ * STARK prime.
25
+ */
26
+ export declare function felt(v: unknown): Felt | undefined;
27
+ /** One block a call reads: a tag, or a number. */
28
+ export type BlockId = "latest" | "pre_confirmed" | "l1_accepted" | {
29
+ block_number: number;
30
+ };
31
+ /** An event of a receipt or a trace, as the node gives it. */
32
+ export interface NodeEvent {
33
+ from: Felt;
34
+ keys: Felt[];
35
+ data: Felt[];
36
+ }
37
+ /** A receipt as the module reads it: lcp's receipt and the fee the transaction paid, in the fee token's smallest unit. */
38
+ export interface NodeReceipt extends StarknetReceipt {
39
+ fee: bigint;
40
+ }
41
+ /** What one simulation of the settlement shows: its execution, the events by the contract that emitted them, and its fee. */
42
+ export interface Simulated {
43
+ reverted: boolean;
44
+ events: NodeEvent[];
45
+ fee: {
46
+ l1Gas: bigint;
47
+ l1GasPrice: bigint;
48
+ l2Gas: bigint;
49
+ l2GasPrice: bigint;
50
+ l1DataGas: bigint;
51
+ l1DataGasPrice: bigint;
52
+ };
53
+ }
54
+ export interface StarknetNode {
55
+ readonly network: StarknetNetwork;
56
+ call(contract: Felt, entrypoint: Felt, calldata: readonly Felt[], block: BlockId, deadline: number): Promise<Felt[]>;
57
+ classHashAt(contract: Felt, deadline: number): Promise<Felt>;
58
+ nonce(account: Felt, block: BlockId, deadline: number): Promise<bigint>;
59
+ head(mark: StarknetMark, deadline: number): Promise<StarknetHead>;
60
+ receipt(tx: Felt, deadline: number): Promise<NodeReceipt | null>;
61
+ trace(tx: Felt, deadline: number): Promise<StarknetInvocation | null>;
62
+ events(query: StarknetEventQuery, deadline: number): Promise<StarknetEventPage | null>;
63
+ simulate(invoke: Record<string, unknown>, deadline: number): Promise<Simulated>;
64
+ add(invoke: Record<string, unknown>, deadline: number): Promise<Felt>;
65
+ /** lcp's reader over this node, its calls ending by `deadline`. */
66
+ reader(deadline: number): StarknetReader;
67
+ }
68
+ export declare function starknetNode(network: StarknetNetwork, url: string): StarknetNode;
69
+ /** sn_keccak("is_valid_outside_execution_nonce") */
70
+ export declare const IS_VALID_NONCE: Felt;
71
+ /** sn_keccak("is_valid_signature") */
72
+ export declare const IS_VALID_SIGNATURE: Felt;
73
+ /** sn_keccak("balance_of") */
74
+ export declare const BALANCE_OF: Felt;
75
+ /** sn_keccak("balanceOf") */
76
+ export declare const BALANCE_OF_CAMEL: Felt;
77
+ /** SNIP-6's `VALID`, the short string `VALID`. */
78
+ export declare const VALID: Felt;