@integraledger/profile-facilitator 0.4.0 → 0.5.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.
Files changed (90) hide show
  1. package/README.md +642 -456
  2. package/dist/answers.d.ts +11 -4
  3. package/dist/answers.js +24 -0
  4. package/dist/core.d.ts +51 -0
  5. package/dist/core.js +758 -0
  6. package/dist/http.d.ts +20 -3
  7. package/dist/http.js +32 -7
  8. package/dist/index.d.ts +12 -36
  9. package/dist/index.js +9 -162
  10. package/dist/module.d.ts +372 -0
  11. package/dist/module.js +13 -0
  12. package/dist/modules/algorand/index.d.ts +22 -0
  13. package/dist/modules/algorand/index.js +247 -0
  14. package/dist/modules/algorand/own.d.ts +26 -0
  15. package/dist/modules/algorand/own.js +231 -0
  16. package/dist/modules/aptos/index.d.ts +23 -0
  17. package/dist/modules/aptos/index.js +232 -0
  18. package/dist/modules/cardano/index.d.ts +18 -0
  19. package/dist/modules/cardano/index.js +124 -0
  20. package/dist/modules/casper/index.d.ts +120 -0
  21. package/dist/modules/casper/index.js +442 -0
  22. package/dist/modules/concordium/index.d.ts +16 -0
  23. package/dist/modules/concordium/index.js +77 -0
  24. package/dist/modules/erc7710/index.d.ts +26 -0
  25. package/dist/modules/erc7710/index.js +220 -0
  26. package/dist/modules/evm/forms.d.ts +74 -0
  27. package/dist/modules/evm/forms.js +182 -0
  28. package/dist/modules/evm/index.d.ts +40 -0
  29. package/dist/modules/evm/index.js +148 -0
  30. package/dist/modules/evm/node.d.ts +29 -0
  31. package/dist/modules/evm/node.js +222 -0
  32. package/dist/modules/hedera/executor.d.ts +63 -0
  33. package/dist/modules/hedera/executor.js +343 -0
  34. package/dist/modules/hedera/index.d.ts +23 -0
  35. package/dist/modules/hedera/index.js +136 -0
  36. package/dist/modules/hedera/mirror.d.ts +32 -0
  37. package/dist/modules/hedera/mirror.js +111 -0
  38. package/dist/modules/index.d.ts +23 -0
  39. package/dist/modules/index.js +24 -0
  40. package/dist/modules/lnbtc/index.d.ts +10 -0
  41. package/dist/modules/lnbtc/index.js +111 -0
  42. package/dist/modules/near/index.d.ts +18 -0
  43. package/dist/modules/near/index.js +246 -0
  44. package/dist/modules/polkadot/index.d.ts +12 -0
  45. package/dist/modules/polkadot/index.js +149 -0
  46. package/dist/modules/polkadot/rail.d.ts +40 -0
  47. package/dist/{polkadot.js → modules/polkadot/rail.js} +214 -288
  48. package/dist/modules/solana/index.d.ts +60 -0
  49. package/dist/modules/solana/index.js +304 -0
  50. package/dist/modules/solana/reader.d.ts +25 -0
  51. package/dist/modules/solana/reader.js +194 -0
  52. package/dist/modules/solana/state.d.ts +6 -0
  53. package/dist/modules/solana/state.js +103 -0
  54. package/dist/modules/starknet/index.d.ts +35 -0
  55. package/dist/modules/starknet/index.js +541 -0
  56. package/dist/modules/starknet/node.d.ts +78 -0
  57. package/dist/modules/starknet/node.js +339 -0
  58. package/dist/modules/stellar/index.d.ts +44 -0
  59. package/dist/modules/stellar/index.js +481 -0
  60. package/dist/modules/stellar/node.d.ts +57 -0
  61. package/dist/modules/stellar/node.js +151 -0
  62. package/dist/modules/sui/index.d.ts +16 -0
  63. package/dist/modules/sui/index.js +309 -0
  64. package/dist/modules/sui/node.d.ts +49 -0
  65. package/dist/modules/sui/node.js +197 -0
  66. package/dist/modules/ton/index.d.ts +16 -0
  67. package/dist/modules/ton/index.js +73 -0
  68. package/dist/modules/tron/index.d.ts +12 -0
  69. package/dist/modules/tron/index.js +120 -0
  70. package/dist/modules/tron/rail.d.ts +32 -0
  71. package/dist/{tron.js → modules/tron/rail.js} +206 -195
  72. package/dist/modules/xrpl/index.d.ts +28 -0
  73. package/dist/modules/xrpl/index.js +299 -0
  74. package/dist/modules/xrpl/node.d.ts +52 -0
  75. package/dist/modules/xrpl/node.js +231 -0
  76. package/dist/modules/xrpl/upto.d.ts +5 -0
  77. package/dist/modules/xrpl/upto.js +269 -0
  78. package/dist/record.d.ts +131 -0
  79. package/dist/record.js +330 -0
  80. package/dist/unexpected.d.ts +3 -2
  81. package/dist/unexpected.js +2 -1
  82. package/dist/wrapper.d.ts +68 -0
  83. package/dist/wrapper.js +126 -0
  84. package/package.json +47 -12
  85. package/dist/polkadot.d.ts +0 -21
  86. package/dist/store.d.ts +0 -59
  87. package/dist/store.js +0 -103
  88. package/dist/tron.d.ts +0 -12
  89. /package/dist/{base58check.d.ts → modules/tron/base58check.d.ts} +0 -0
  90. /package/dist/{base58check.js → modules/tron/base58check.js} +0 -0
@@ -0,0 +1,151 @@
1
+ import { Keypair, xdr } from "@stellar/stellar-sdk/base";
2
+ import { isObject } from "../../answers.js";
3
+ import { NodeError, postJson } from "../../http.js";
4
+ /** A JSON-RPC error the node answered: it read the request and refused it. */
5
+ export class RpcFault extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(`${code}: ${message}`);
9
+ this.code = code;
10
+ }
11
+ }
12
+ /** The events one `getEvents` page asks for: Stellar RPC's default page, which its documentation states as 100. */
13
+ const PAGE = 100;
14
+ const isLedger = (v) => Number.isInteger(v) && v >= 0 && v <= 0xffffffff;
15
+ export function stellarNode(url) {
16
+ let id = 0;
17
+ async function call(method, params, deadline) {
18
+ const answer = await postJson(url, { jsonrpc: "2.0", id: ++id, method, params }, deadline - performance.now());
19
+ if (!isObject(answer))
20
+ throw new NodeError("malformed", true, method);
21
+ const error = answer["error"];
22
+ if (isObject(error))
23
+ throw new RpcFault(Number(error["code"]), String(error["message"]));
24
+ const result = answer["result"];
25
+ if (!isObject(result))
26
+ throw new NodeError("malformed", true, method);
27
+ return result;
28
+ }
29
+ const malformed = (method) => {
30
+ throw new NodeError("malformed", true, method);
31
+ };
32
+ const node = {
33
+ async passphrase(deadline) {
34
+ const r = await call("getNetwork", {}, deadline);
35
+ return typeof r["passphrase"] === "string" ? r["passphrase"] : malformed("getNetwork");
36
+ },
37
+ async latestLedger(deadline) {
38
+ const r = await call("getLatestLedger", {}, deadline);
39
+ if (!isLedger(r["sequence"]))
40
+ return malformed("getLatestLedger");
41
+ const close = Number(r["closeTime"]);
42
+ return { sequence: r["sequence"], ...(Number.isSafeInteger(close) ? { closeTime: close } : {}) };
43
+ },
44
+ async sequence(account, deadline) {
45
+ const key = xdr.LedgerKey.fromXdrObject({ type: 0, account: { accountId: { type: 0, ed25519: Keypair.fromPublicKey(account).rawPublicKey() } } });
46
+ const r = await call("getLedgerEntries", { keys: [key.toXdr("base64")] }, deadline);
47
+ const entries = r["entries"];
48
+ if (entries === undefined || entries === null || (Array.isArray(entries) && entries.length === 0))
49
+ return null;
50
+ if (!Array.isArray(entries) || entries.length !== 1 || !isObject(entries[0]) || typeof entries[0]["xdr"] !== "string") {
51
+ return malformed("getLedgerEntries");
52
+ }
53
+ const data = xdr.LedgerEntryData.fromXdr(entries[0]["xdr"], "base64").toXdrObject();
54
+ return data.type === 0 ? data.account.seqNum : malformed("getLedgerEntries");
55
+ },
56
+ async simulate(transaction, deadline) {
57
+ const r = await call("simulateTransaction", { transaction }, deadline);
58
+ if (typeof r["error"] === "string")
59
+ return { ok: false, error: r["error"] };
60
+ // A transaction that needs archived entries restored first cannot land as it is.
61
+ if (r["restorePreamble"] !== undefined && r["restorePreamble"] !== null)
62
+ return { ok: false, error: "restore needed" };
63
+ const fee = r["minResourceFee"];
64
+ const data = r["transactionData"];
65
+ const events = r["events"] ?? [];
66
+ if (typeof fee !== "string" || !/^[0-9]{1,19}$/.test(fee) || typeof data !== "string" || !Array.isArray(events)) {
67
+ return malformed("simulateTransaction");
68
+ }
69
+ if (!events.every((e) => typeof e === "string"))
70
+ return malformed("simulateTransaction");
71
+ return { ok: true, minResourceFee: BigInt(fee), transactionData: data, events: events };
72
+ },
73
+ async send(transaction, deadline) {
74
+ const r = await call("sendTransaction", { transaction }, deadline);
75
+ const status = r["status"];
76
+ if (status !== "PENDING" && status !== "DUPLICATE" && status !== "TRY_AGAIN_LATER" && status !== "ERROR")
77
+ return malformed("sendTransaction");
78
+ if (typeof r["hash"] !== "string")
79
+ return malformed("sendTransaction");
80
+ return { status, hash: r["hash"].toLowerCase(), ...(typeof r["errorResultXdr"] === "string" ? { errorResultXdr: r["errorResultXdr"] } : {}) };
81
+ },
82
+ async transaction(hash, deadline) {
83
+ const r = await call("getTransaction", { hash }, deadline);
84
+ const status = r["status"];
85
+ if (status !== "SUCCESS" && status !== "FAILED" && status !== "NOT_FOUND")
86
+ return malformed("getTransaction");
87
+ if (!isLedger(r["oldestLedger"]) || !isLedger(r["latestLedger"]))
88
+ return malformed("getTransaction");
89
+ const out = { status, oldestLedger: r["oldestLedger"], latestLedger: r["latestLedger"] };
90
+ if (isLedger(r["ledger"]))
91
+ out.ledger = r["ledger"];
92
+ if (Number.isInteger(r["applicationOrder"]))
93
+ out.applicationOrder = r["applicationOrder"];
94
+ if (typeof r["envelopeXdr"] === "string")
95
+ out.envelopeXdr = r["envelopeXdr"];
96
+ if (typeof r["resultXdr"] === "string")
97
+ out.resultXdr = r["resultXdr"];
98
+ return out;
99
+ },
100
+ reader(deadline) {
101
+ return {
102
+ passphrase: () => node.passphrase(deadline),
103
+ latestLedger: () => node.latestLedger(deadline),
104
+ async transaction(hash) {
105
+ const t = await node.transaction(hash, deadline);
106
+ return {
107
+ status: t.status,
108
+ oldestLedger: t.oldestLedger,
109
+ latestLedger: t.latestLedger,
110
+ ...(t.envelopeXdr === undefined ? {} : { envelopeXdr: t.envelopeXdr }),
111
+ ...(t.ledger === undefined ? {} : { ledger: t.ledger }),
112
+ ...(t.applicationOrder === undefined ? {} : { applicationOrder: t.applicationOrder }),
113
+ };
114
+ },
115
+ // Stellar RPC's `getEvents` takes a ledger range or a cursor, never both, and its `endLedger` is exclusive (lcp's
116
+ // `StellarReader.events`); a page shorter than the page asked for is the last of the range.
117
+ async events(f) {
118
+ const filters = [{ type: "contract", topics: f.topics }];
119
+ const params = f.cursor === undefined
120
+ ? { startLedger: f.fromLedger, endLedger: f.toLedger + 1, filters, pagination: { limit: PAGE } }
121
+ : { filters, pagination: { cursor: f.cursor, limit: PAGE } };
122
+ const r = await call("getEvents", params, deadline);
123
+ const rows = r["events"];
124
+ if (!Array.isArray(rows) || !isLedger(r["oldestLedger"]) || !isLedger(r["latestLedger"]))
125
+ return malformed("getEvents");
126
+ const events = [];
127
+ let past = false;
128
+ for (const e of rows) {
129
+ if (!isObject(e) || !isLedger(e["ledger"]))
130
+ return malformed("getEvents");
131
+ if (e["ledger"] > f.toLedger) {
132
+ past = true;
133
+ continue;
134
+ }
135
+ events.push({
136
+ id: e["id"],
137
+ ledger: e["ledger"],
138
+ txHash: e["txHash"],
139
+ contractId: e["contractId"],
140
+ topic: e["topic"],
141
+ value: e["value"],
142
+ });
143
+ }
144
+ const more = rows.length === PAGE && !past && typeof r["cursor"] === "string";
145
+ return { events, oldestLedger: r["oldestLedger"], latestLedger: r["latestLedger"], ...(more ? { cursor: r["cursor"] } : {}) };
146
+ },
147
+ };
148
+ },
149
+ };
150
+ return node;
151
+ }
@@ -0,0 +1,16 @@
1
+ import { type SuiNetwork } from "@integraledger/lcp/sui";
2
+ import { type Core, type Module, type ModuleStarter } from "../../module.js";
3
+ /** The configuration's member `sui`: one entry per network the settler serves. */
4
+ export interface SuiConfig {
5
+ readonly networks: readonly SuiNetworkConfig[];
6
+ }
7
+ /** One Sui network. */
8
+ export interface SuiNetworkConfig {
9
+ network: SuiNetwork;
10
+ /** The seller's GraphQL endpoint. */
11
+ graphql: string;
12
+ }
13
+ /** Starts one module per configured network, each its own registration of `exact`. */
14
+ export declare const starter: ModuleStarter<SuiConfig>;
15
+ /** The module for one network. */
16
+ export declare function suiModule(c: SuiNetworkConfig, core: Core): Module;
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Sui: the settler's own facilitator for the pairing `x402/exact/sui`, written to x402's Sui scheme
3
+ * (`scheme_exact_sui.md`), which x402 specifies and publishes no code for, and to lcp's profile `x402-exact-sui.md`. The
4
+ * payer signs one programmable transaction carrying H as its one unused `Pure` input; the module checks it (the network,
5
+ * the signature, the gas path the option fixes, a simulation showing the payee's credit) and executes it unchanged.
6
+ * It serves the paths where the buyer pays gas and where none is paid (`extra.gasless`), and holds no key: x402's
7
+ * sponsored path needs a gas station, whose wire x402's scheme does not state and whose caller is the buyer's client,
8
+ * so an option naming one is refused. A transaction the buyer already executed is judged at `/verify` by its effects and not refused for having executed; its `/settle`
9
+ * answers a failure naming it. lcp decodes the payment (`bound`, `reference`, `decodeSuiTx`) and reads it (`status`).
10
+ */
11
+ import { canonicalJson, isRefusal } from "@integraledger/lcp";
12
+ import { decodeSuiTx, exactSui } from "@integraledger/lcp/sui";
13
+ import { bcs } from "@mysten/sui/bcs";
14
+ import { parseSerializedSignature } from "@mysten/sui/cryptography";
15
+ import { normalizeStructTag, normalizeSuiAddress, toBase64 } from "@mysten/sui/utils";
16
+ import { isValidTransactionSignature } from "@mysten/sui/verify";
17
+ import { isObject } from "../../answers.js";
18
+ import { NodeError, sleep } from "../../http.js";
19
+ import { outcomeOf } from "../../module.js";
20
+ import { settleReason as settleReasonOf, unexpectedSettle, unexpectedVerify } from "../../unexpected.js";
21
+ import { GraphqlFault, suiNode } from "./node.js";
22
+ const ID = exactSui.id;
23
+ const NETWORKS = ["sui:mainnet", "sui:testnet", "sui:devnet"];
24
+ const POLL_MS = 1_000;
25
+ const no = (reason, message) => (message === undefined ? { reason } : { reason, message });
26
+ const isNo = (v) => isObject(v) && typeof v["reason"] === "string" && Object.keys(v).every((k) => k === "reason" || k === "message");
27
+ /** lcp's refusals of the option's form: the requirements' fault where the payment echoes them unchanged. */
28
+ const OPTION_CODES = new Set(["x402/option-not-this-pairing", "x402/option-malformed", "sui/network-malformed"]);
29
+ function refusedBy(r, payload, requirements) {
30
+ if (OPTION_CODES.has(r.code) && canonicalJson(payload.accepted) === canonicalJson(requirements)) {
31
+ return no("invalid_payment_requirements", r.code);
32
+ }
33
+ return no("invalid_payload", r.code);
34
+ }
35
+ const address = (a) => normalizeSuiAddress(a);
36
+ function sameType(a, b) {
37
+ try {
38
+ return normalizeStructTag(a) === normalizeStructTag(b);
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
44
+ /** Starts one module per configured network, each its own registration of `exact`. */
45
+ export const starter = {
46
+ name: "sui",
47
+ async start(config, core) {
48
+ return { registrations: config.networks.map((c) => ({ network: c.network, module: suiModule(c, core), own: [] })) };
49
+ },
50
+ };
51
+ /** The module for one network. */
52
+ export function suiModule(c, core) {
53
+ if (!NETWORKS.includes(c.network))
54
+ throw new TypeError(`not a Sui network: ${c.network}`);
55
+ const network = c.network;
56
+ const { log, settleWaitMs } = core;
57
+ const node = suiNode(network, c.graphql.replace(/\/+$/, ""));
58
+ const about = (i) => ({ network, payer: i.sender, transaction: i.tx.digest });
59
+ /** Every check that reads neither the chain nor the clock: lcp's form, the gas path, the zero rule. */
60
+ async function inspect(payload, requirements) {
61
+ if (!isObject(payload) || !isObject(requirements) || !isObject(payload.payload))
62
+ return no("invalid_payload");
63
+ if (requirements.network !== network)
64
+ return no("invalid_network");
65
+ if (requirements.scheme !== "exact")
66
+ return no("unsupported_scheme");
67
+ const h = await exactSui.bound(payload);
68
+ if (isRefusal(h))
69
+ return refusedBy(h, payload, requirements);
70
+ const ref = await exactSui.reference(payload, requirements);
71
+ if (isRefusal(ref))
72
+ return refusedBy(ref, payload, requirements);
73
+ const tx = decodeSuiTx(payload.payload.transaction);
74
+ if (isRefusal(tx))
75
+ return refusedBy(tx, payload, requirements);
76
+ const parsed = bcs.TransactionData.parse(tx.bytes);
77
+ if (parsed.$kind !== "V1")
78
+ return no("invalid_payload", "sui/not-programmable");
79
+ const v1 = parsed.V1;
80
+ const extra = isObject(requirements.extra) ? requirements.extra : {};
81
+ // An option naming a gas station asks for a sponsorship the module does not give.
82
+ if (extra["gasStation"] !== undefined)
83
+ return no("invalid_payment_requirements", "sui/gas-station-not-ours");
84
+ const path = extra["gasless"] === true ? "gasless" : "buyer";
85
+ const sender = address(tx.sender);
86
+ const gas = v1.gasData;
87
+ if (path === "gasless") {
88
+ if ((gas.payment ?? []).length !== 0 || BigInt(gas.price ?? 0) !== 0n || BigInt(gas.budget ?? 0) !== 0n)
89
+ return no("invalid_payload", "sui/not-gasless");
90
+ }
91
+ else if (gas.owner === null || address(gas.owner) !== sender) {
92
+ // On the path where the buyer pays, a transaction whose gas another account owns needs that account's signature.
93
+ return no("invalid_payload", "sui/gas-owner-not-sender");
94
+ }
95
+ const payTo = address(requirements.payTo);
96
+ const amount = BigInt(requirements.amount);
97
+ // At "0", the signed transfer must name the option's payee (the profile, rule 8): a payee with no change at all
98
+ // would meet the check of the amount.
99
+ if (amount === 0n && !tx.transfers.some((t) => address(t.recipient) === payTo))
100
+ return no("invalid_payload", "sui/zero-names-no-payee");
101
+ const signature = payload.payload.signature;
102
+ return { tx, v1, h, path, sender, payTo, asset: requirements.asset, amount, signature };
103
+ }
104
+ /** The payee's net credit in the option's coin type equals the amount (x402's verification, its rule 4). */
105
+ function credited(i, e) {
106
+ const change = e.balanceChanges.find((b) => address(b.owner) === i.payTo && sameType(b.coinType, i.asset));
107
+ return (change?.amount ?? 0n) === i.amount;
108
+ }
109
+ /** The sender's signature over the transaction: locally, or by the node's `verifySignature` for zkLogin. */
110
+ async function signed(i, deadline) {
111
+ let scheme;
112
+ try {
113
+ scheme = parseSerializedSignature(i.signature).signatureScheme;
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ try {
119
+ if (scheme === "ZkLogin")
120
+ return await node.verifySignature(i.tx.bytes, i.signature, i.sender, deadline);
121
+ return await isValidTransactionSignature(i.tx.bytes, i.signature, { address: i.sender });
122
+ }
123
+ catch (e) {
124
+ return no(unexpectedVerify(log, { event: "node-call-failed", ...about(i), call: "verifySignature" }, e));
125
+ }
126
+ }
127
+ /**
128
+ * The checks that read the chain: the signature, then the transaction by its digest. One already executed is judged by its effects (status success, its bytes, the payee's
129
+ * credit); one not executed is simulated, and must succeed and credit the payee.
130
+ */
131
+ async function chainChecks(i, deadline) {
132
+ const sig = await signed(i, deadline);
133
+ if (isNo(sig))
134
+ return sig;
135
+ if (!sig)
136
+ return no("invalid_payload", "sui/signature-invalid");
137
+ let read;
138
+ try {
139
+ read = await node.transaction(i.tx.digest, deadline);
140
+ }
141
+ catch (e) {
142
+ return no(unexpectedVerify(log, { event: "node-call-failed", ...about(i), call: "transaction" }, e));
143
+ }
144
+ if (read.executed !== null) {
145
+ const { bytes, effects } = read.executed;
146
+ if (toBase64(bytes) !== toBase64(i.tx.bytes))
147
+ return no(unexpectedVerify(log, { event: "node-answer-differs", ...about(i), call: "transaction" }));
148
+ if (effects.status !== "SUCCESS")
149
+ return no("invalid_transaction_state", "sui/executed-failed");
150
+ if (!credited(i, effects))
151
+ return no("invalid_payload", "sui/payee-not-credited");
152
+ return { executed: effects, latest: read.latest };
153
+ }
154
+ let simulated;
155
+ try {
156
+ simulated = await node.simulate(i.tx.bytes, deadline);
157
+ }
158
+ catch (e) {
159
+ if (e instanceof GraphqlFault)
160
+ return no("invalid_transaction", "sui/simulation-refused");
161
+ return no(unexpectedVerify(log, { event: "node-call-failed", ...about(i), call: "simulateTransaction" }, e));
162
+ }
163
+ if (simulated.status !== "SUCCESS")
164
+ return no("invalid_transaction", "sui/simulation-failed");
165
+ if (!credited(i, simulated))
166
+ return no("invalid_payload", "sui/payee-not-credited");
167
+ return { executed: null, latest: read.latest };
168
+ }
169
+ async function verify(payload, requirements) {
170
+ const deadline = performance.now() + settleWaitMs;
171
+ const i = await inspect(payload, requirements);
172
+ if (isNo(i))
173
+ return refusedVerify(i);
174
+ const checked = await chainChecks(i, deadline);
175
+ if (isNo(checked))
176
+ return refusedVerify(checked);
177
+ // A transaction the buyer already executed is judged by its effects, and not refused for having executed.
178
+ return { isValid: true, payer: i.sender };
179
+ }
180
+ async function settle(payload, requirements) {
181
+ const deadline = performance.now() + settleWaitMs;
182
+ const i = await inspect(payload, requirements);
183
+ if (isNo(i))
184
+ return failed(settleReason(i.reason), "", i.message);
185
+ const checked = await chainChecks(i, deadline);
186
+ if (isNo(checked))
187
+ return failed(settleReason(checked.reason), "", checked.message);
188
+ // A transaction the buyer executed was not submitted here: a failure naming it, never a success.
189
+ if (checked.executed !== null)
190
+ return failed("invalid_transaction_state", i.tx.digest, "sui/executed-by-payer");
191
+ const signatures = [i.signature];
192
+ try {
193
+ const effects = await node.execute(i.tx.bytes, signatures, deadline);
194
+ if (effects.checkpoint !== null)
195
+ return landed(i, effects);
196
+ }
197
+ catch (e) {
198
+ const entry = { event: "node-call-failed", ...about(i), call: "executeTransaction" };
199
+ // A refused execution, or one that cannot have reached the node: nothing executed, and no transaction named.
200
+ if (e instanceof GraphqlFault || (e instanceof NodeError && !e.sent))
201
+ return unexpected(entry, e);
202
+ log(entry, e);
203
+ }
204
+ return watch(i, deadline);
205
+ }
206
+ /** The answer once the effects are in a checkpoint: a success only with status success and the payee's credit. */
207
+ async function landed(i, effects) {
208
+ if (effects.status === "SUCCESS" && credited(i, effects))
209
+ return { success: true, transaction: i.tx.digest, network: network, payer: i.sender };
210
+ log({ event: "settlement-failed", ...about(i), status: effects.status });
211
+ return failed("invalid_transaction_state", i.tx.digest);
212
+ }
213
+ /** Reads the transaction every second until its effects are in a checkpoint or `deadline` passes: `settlement_pending`. */
214
+ async function watch(i, deadline) {
215
+ for (;;) {
216
+ try {
217
+ const { executed } = await node.transaction(i.tx.digest, deadline);
218
+ if (executed !== null && executed.effects.checkpoint !== null)
219
+ return landed(i, executed.effects);
220
+ }
221
+ catch (e) {
222
+ if (!(e instanceof NodeError && e.code === "spent"))
223
+ log({ event: "node-call-failed", ...about(i), call: "transaction" }, e);
224
+ }
225
+ if (performance.now() + POLL_MS > deadline)
226
+ return failed("settlement_pending", i.tx.digest);
227
+ await sleep(POLL_MS);
228
+ }
229
+ }
230
+ /** `unexpected_settle_error` with no transaction, once its entry is in the operator log. */
231
+ function unexpected(entry, cause) {
232
+ const a = unexpectedSettle(log, { ...entry, network }, cause);
233
+ return { ...a, network: network };
234
+ }
235
+ function failed(errorReason, tx, errorMessage) {
236
+ return { success: false, errorReason, ...(errorMessage === undefined ? {} : { errorMessage }), transaction: tx, network: network };
237
+ }
238
+ const facilitator = {
239
+ scheme: "exact",
240
+ caipFamily: "sui:*",
241
+ getExtra: () => undefined,
242
+ getSigners: () => [],
243
+ verify,
244
+ settle,
245
+ };
246
+ const module = {
247
+ descriptor: {
248
+ name: "sui",
249
+ key: "none",
250
+ pairings: [ID],
251
+ // Zero through this module is not yet established by a run on any gas path.
252
+ acceptsZero: false,
253
+ verifiesLanded: true,
254
+ },
255
+ network: network,
256
+ facilitator,
257
+ record: {
258
+ async instrument(p) {
259
+ const i = await inspect(p.payload, p.requirements);
260
+ if (isNo(i))
261
+ return { refused: i.reason, ...(i.message === undefined ? {} : { message: i.message }) };
262
+ return {
263
+ pairing: ID,
264
+ // The digest is Blake2b-256 over the transaction data the buyer signed, its signatures apart: it executes once.
265
+ instrument: { by: "transaction", network: network, transaction: i.tx.digest },
266
+ nonce: exactSui.data.nonce,
267
+ // The lapse is an epoch, which names no time the payment alone gives: kept for the settler's life.
268
+ keep: { until: "settler" },
269
+ };
270
+ },
271
+ /** The newest checkpoint, read just before the claim: no execution of the payment can be in it or before it. */
272
+ async position(p, at) {
273
+ const i = await inspect(p.payload, p.requirements);
274
+ if (isNo(i))
275
+ return undefined;
276
+ return (await node.transaction(i.tx.digest, at.deadline)).latest.checkpoint;
277
+ },
278
+ async read(p, at) {
279
+ const i = await inspect(p.payload, p.requirements);
280
+ if (isNo(i))
281
+ return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
282
+ const ref = await exactSui.reference(p.payload, p.requirements);
283
+ if (isRefusal(ref))
284
+ return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
285
+ // The search starts at the checkpoint read just before the claim, where the record holds one.
286
+ const query = {
287
+ act: "payment",
288
+ finality: "final",
289
+ ...(typeof at.from === "bigint" ? { after: at.from } : {}),
290
+ ...(at.search === undefined ? {} : { search: at.search }),
291
+ };
292
+ return outcomeOf(await exactSui.status({ ...ref, h: i.h }, node.reader(at.deadline), query));
293
+ },
294
+ },
295
+ fees: {
296
+ // The buyer pays the gas, or no one does.
297
+ paysFee: () => false,
298
+ payerBroadcast: () => false,
299
+ },
300
+ };
301
+ return module;
302
+ }
303
+ function refusedVerify(r) {
304
+ return { isValid: false, invalidReason: r.reason, ...(r.message === undefined ? {} : { invalidMessage: r.message }) };
305
+ }
306
+ /** A verify reason as a settle answer's: a node or store that could not be read before submission is a settle error. */
307
+ function settleReason(reason) {
308
+ return settleReasonOf(reason);
309
+ }
@@ -0,0 +1,49 @@
1
+ import type { SuiNetwork, SuiReader } from "@integraledger/lcp/sui";
2
+ /** The node answered the request with GraphQL errors: it reached the node, which refused it. */
3
+ export declare class GraphqlFault extends Error {
4
+ readonly messages: readonly string[];
5
+ constructor(messages: readonly string[]);
6
+ }
7
+ /** One owner's net change in one coin type, as the effects' `balanceChangesJson` states it. */
8
+ export interface BalanceChange {
9
+ owner: string;
10
+ coinType: string;
11
+ amount: bigint;
12
+ }
13
+ /** A transaction's effects as the module reads them. */
14
+ export interface Effects {
15
+ status: "SUCCESS" | "FAILURE";
16
+ /** The checkpoint that holds them, or null for a transaction executed and not yet in one. */
17
+ checkpoint: bigint | null;
18
+ balanceChanges: BalanceChange[];
19
+ /** What the gas owner paid: computation and storage less the storage rebate, never below zero. */
20
+ fee: bigint;
21
+ }
22
+ /** An executed transaction: its bytes as the node holds them, and its effects. */
23
+ export interface Executed {
24
+ bytes: Uint8Array;
25
+ effects: Effects;
26
+ }
27
+ /** The newest checkpoint the node serves, its epoch and that epoch's reference gas price. */
28
+ export interface Latest {
29
+ checkpoint: bigint;
30
+ epoch: bigint;
31
+ referenceGasPrice: bigint;
32
+ }
33
+ export interface SuiNode {
34
+ readonly network: SuiNetwork;
35
+ /** The transaction with `digest`, or null where the node holds none, and the newest checkpoint. */
36
+ transaction(digest: string, deadline: number): Promise<{
37
+ executed: Executed | null;
38
+ latest: Latest;
39
+ }>;
40
+ /** Simulates the transaction with Sui's checks, its signatures apart. */
41
+ simulate(bytes: Uint8Array, deadline: number): Promise<Effects>;
42
+ /** Executes the transaction with its signatures; its effects, the checkpoint where the node states one. */
43
+ execute(bytes: Uint8Array, signatures: readonly string[], deadline: number): Promise<Effects>;
44
+ /** Whether the node's `verifySignature` accepts `signature` by `author` over the transaction bytes. */
45
+ verifySignature(bytes: Uint8Array, signature: string, author: string, deadline: number): Promise<boolean>;
46
+ /** lcp's reader over this node, its calls ending by `deadline`. */
47
+ reader(deadline: number): SuiReader;
48
+ }
49
+ export declare function suiNode(network: SuiNetwork, url: string): SuiNode;