@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,299 @@
1
+ /**
2
+ * The XRPL module for `x402/exact/xrpl` on one network: `@x402/xrpl` 2.31.0's facilitator class, registered unchanged
3
+ * behind lcp's checks of the pairing, for a payment signed with one key; and the settler's own path for a multisigned
4
+ * payment, which that class refuses (`invalid_exact_xrpl_payload_multisig_not_supported`), claimed by the transaction's
5
+ * own `Signers`. The buyer signs and pays the fee and the settler submits what the buyer signed, so the module holds no
6
+ * key (`extra.key` `none`).
7
+ *
8
+ * `x402/upto/xrpl`, which no class implements, is the module's own facilitator (`./upto.ts`).
9
+ *
10
+ * Both paths refuse, before anything moves, a payment that names a `Delegate` or carries `Memos`, as x402's scheme
11
+ * requires of every facilitator. Both name the record's instrument by the payer's account and the `Sequence` or
12
+ * `TicketSequence` it signed, never by the transaction's hash, which another quorum's copy of one payment changes.
13
+ */
14
+ import { isRefusal } from "@integraledger/lcp";
15
+ import { exactXrpl } from "@integraledger/lcp/x402-exact-xrpl";
16
+ import { ExactXrplScheme } from "@x402/xrpl/exact/facilitator";
17
+ import { decode, deriveAddress, encodeForMultiSigning, verifyKeypairSignature } from "xrpl";
18
+ import { isObject } from "../../answers.js";
19
+ import { outcomeOf, } from "../../module.js";
20
+ import { validatedLedger, xrplNode, xrplReader } from "./node.js";
21
+ import { uptoModule } from "./upto.js";
22
+ /** The class's default fee bound, `DEFAULT_MAX_FEE_DROPS` of `@x402/xrpl` 2.31.0. */
23
+ const DEFAULT_MAX_FEE_DROPS = "10000";
24
+ /** `tfPartialPayment`. */
25
+ const PARTIAL_PAYMENT = 0x00020000;
26
+ /** The x402 reason for an lcp refusal: the version, the option, or else the payload. */
27
+ function reasonOf(r) {
28
+ if (r.code === "x402/not-v2")
29
+ return "invalid_x402_version";
30
+ if (r.code.startsWith("x402/option"))
31
+ return "invalid_payment_requirements";
32
+ return "invalid_payload";
33
+ }
34
+ /** The signed transaction the payload carries, decoded, or undefined where it does not decode. */
35
+ function txOf(payload) {
36
+ const blob = isObject(payload.payload) ? payload.payload["signedTxBlob"] : undefined;
37
+ if (typeof blob !== "string")
38
+ return undefined;
39
+ try {
40
+ return decode(blob);
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ }
46
+ /**
47
+ * The module's checks that read neither the chain nor the clock: its network; no `Delegate` and no `Memos`; lcp's bound
48
+ * and reference of the pairing. The reference, or the refusal.
49
+ */
50
+ async function pure(network, payload, requirements) {
51
+ if (requirements.network !== network || payload.accepted?.network !== network)
52
+ return { reason: "invalid_network" };
53
+ const tx = txOf(payload);
54
+ if (tx !== undefined && tx["Delegate"] !== undefined)
55
+ return { reason: "invalid_exact_xrpl_payload_delegate_not_allowed" };
56
+ if (tx !== undefined && tx["Memos"] !== undefined)
57
+ return { reason: "invalid_exact_xrpl_payload_memos_not_allowed" };
58
+ const bound = await exactXrpl.bound(payload);
59
+ if (isRefusal(bound))
60
+ return { reason: reasonOf(bound), code: bound.code };
61
+ // The requirements arrive as JSON, which lcp's option type names.
62
+ const ref = await exactXrpl.reference(payload, requirements);
63
+ if (isRefusal(ref))
64
+ return { reason: reasonOf(ref), code: ref.code };
65
+ return ref;
66
+ }
67
+ const isRef = (v) => !("reason" in v);
68
+ /**
69
+ * The ledger from which lcp's read searches where the record holds no position for the payment, a read made before
70
+ * any claim: the first ledger, which reads more and misses nothing; a server that does not hold that range answers a
71
+ * gap, which leaves the payment live.
72
+ */
73
+ const FROM_LEDGER = 1;
74
+ function verifyFailure(f, payer) {
75
+ return { isValid: false, invalidReason: f.reason, ...(f.code ? { invalidMessage: f.code } : {}), ...(payer ? { payer } : {}) };
76
+ }
77
+ function settleFailure(f, network, payer) {
78
+ return {
79
+ success: false,
80
+ errorReason: f.reason,
81
+ ...(f.code ? { errorMessage: f.code } : {}),
82
+ transaction: "",
83
+ network,
84
+ ...(payer ? { payer } : {}),
85
+ };
86
+ }
87
+ /** The record's members, the same on both paths. */
88
+ function recordOf(c) {
89
+ return {
90
+ async instrument(p) {
91
+ const r = await pure(c.network, p.payload, p.requirements);
92
+ if (!isRef(r))
93
+ return { refused: r.reason };
94
+ const signed = r.signed;
95
+ if (signed === undefined)
96
+ return { refused: "invalid_payload" };
97
+ return {
98
+ pairing: exactXrpl.id,
99
+ // The account's Sequence, or the ticket it consumes, as signed: every quorum's copy of one payment names it.
100
+ instrument: signed.ticket === undefined
101
+ ? { by: "single-use", network: c.network, signer: signed.account, value: String(signed.sequence), scope: "Sequence" }
102
+ : { by: "single-use", network: c.network, signer: signed.account, value: String(signed.ticket), scope: "TicketSequence" },
103
+ nonce: exactXrpl.data.nonce,
104
+ // The lapse is a ledger index, LastLedgerSequence, which no clock bounds from above.
105
+ keep: { until: "settler" },
106
+ };
107
+ },
108
+ async read(p, at) {
109
+ const r = await pure(c.network, p.payload, p.requirements);
110
+ if (!isRef(r))
111
+ return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
112
+ const reader = xrplReader(c.network, c.node, at.deadline);
113
+ const search = at.search;
114
+ const fromLedger = at.from?.ledger ?? FROM_LEDGER;
115
+ return outcomeOf(await exactXrpl.status({ ...r, fromLedger }, reader, { act: "payment", finality: "validated", ...(search ? { search } : {}) }));
116
+ },
117
+ async position(_p, at) {
118
+ return { ledger: await validatedLedger(c.node, at.deadline) };
119
+ },
120
+ };
121
+ }
122
+ const NO_FEES = { paysFee: () => false, payerBroadcast: () => false };
123
+ /** The payer variant the published class refuses: a transaction that carries `Signers`. */
124
+ export function isMultisigned(payload) {
125
+ const tx = txOf(payload);
126
+ return tx !== undefined && Array.isArray(tx["Signers"]) && tx["Signers"].length > 0;
127
+ }
128
+ /** The amount the Payment signs equals the requirements' (drops for XRP, else the issued currency with its issuer). */
129
+ function amountMatches(tx, r) {
130
+ const amount = tx["Amount"];
131
+ if (r.asset === "XRP")
132
+ return typeof amount === "string" && amount === r.amount;
133
+ return (isObject(amount) &&
134
+ amount["currency"] === r.asset &&
135
+ amount["issuer"] === r.extra?.["issuer"] &&
136
+ amount["value"] === r.amount);
137
+ }
138
+ /**
139
+ * The checks of a multisigned payment that read the chain: the Payment's form against the requirements, as the class
140
+ * makes them for a payment signed with one key; each signer's signature over the transaction's multisigning data with
141
+ * its own key, a key that is its master key or its regular key; the payer's signer list met by those signers' weights;
142
+ * its Sequence or ticket unconsumed; and the server's simulation. The payer, or the refusal.
143
+ */
144
+ async function multisigChecks(c, node, payload, r) {
145
+ const ref = await pure(c.network, payload, r);
146
+ if (!isRef(ref))
147
+ return ref;
148
+ const tx = txOf(payload);
149
+ const account = String(tx["Account"]);
150
+ if (tx["TransactionType"] !== "Payment")
151
+ return { reason: "invalid_exact_xrpl_payload_transaction_type" };
152
+ if (tx["SigningPubKey"] !== "")
153
+ return { reason: "invalid_exact_xrpl_payload_signing_pub_key" };
154
+ if (tx["Destination"] !== r.payTo)
155
+ return { reason: "invalid_exact_xrpl_payload_destination_mismatch" };
156
+ if (!amountMatches(tx, r))
157
+ return { reason: "invalid_exact_xrpl_payload_amount_mismatch" };
158
+ if (((Number(tx["Flags"] ?? 0) >>> 0) & PARTIAL_PAYMENT) !== 0)
159
+ return { reason: "invalid_exact_xrpl_payload_partial_payment_not_allowed" };
160
+ if (tx["SendMax"] !== undefined || tx["Paths"] !== undefined || tx["DeliverMin"] !== undefined) {
161
+ return { reason: "invalid_exact_xrpl_payload_paths_not_allowed" };
162
+ }
163
+ if (typeof tx["Fee"] !== "string" || BigInt(tx["Fee"]) > BigInt(c.maxFeeDrops ?? DEFAULT_MAX_FEE_DROPS)) {
164
+ return { reason: "invalid_exact_xrpl_payload_fee_too_high" };
165
+ }
166
+ const last = tx["LastLedgerSequence"];
167
+ if (typeof last !== "number")
168
+ return { reason: "invalid_exact_xrpl_payload_lastledgersequence_missing" };
169
+ const signers = tx["Signers"];
170
+ const list = await node.signerList(account);
171
+ if (list === null)
172
+ return { reason: "invalid_exact_xrpl_payload_signer_not_authorized" };
173
+ let weight = 0;
174
+ const seen = new Set();
175
+ for (const s of signers) {
176
+ const signer = isObject(s) && isObject(s["Signer"]) ? s["Signer"] : undefined;
177
+ const who = signer?.["Account"];
178
+ const key = signer?.["SigningPubKey"];
179
+ const sig = signer?.["TxnSignature"];
180
+ if (typeof who !== "string" || typeof key !== "string" || typeof sig !== "string" || seen.has(who)) {
181
+ return { reason: "invalid_exact_xrpl_payload_signature" };
182
+ }
183
+ seen.add(who);
184
+ const data = encodeForMultiSigning(tx, who);
185
+ if (!verifyKeypairSignature(data, sig, key))
186
+ return { reason: "invalid_exact_xrpl_payload_signature" };
187
+ const derived = deriveAddress(key);
188
+ if (derived !== who) {
189
+ const auth = await node.authorization(who);
190
+ if (auth.regularKey !== derived)
191
+ return { reason: "invalid_exact_xrpl_payload_signer_not_authorized" };
192
+ }
193
+ else if ((await node.authorization(who)).isMasterKeyDisabled) {
194
+ return { reason: "invalid_exact_xrpl_payload_signer_not_authorized" };
195
+ }
196
+ weight += list.weights.get(who) ?? 0;
197
+ }
198
+ if (weight < list.quorum)
199
+ return { reason: "invalid_exact_xrpl_payload_signer_not_authorized" };
200
+ if ((await node.validatedLedger()) >= last)
201
+ return { reason: "invalid_exact_xrpl_payload_expired" };
202
+ const ticket = tx["TicketSequence"];
203
+ if (typeof ticket === "number") {
204
+ if (!(await node.ticket(account, ticket)))
205
+ return { reason: "invalid_exact_xrpl_payload_ticket_unavailable" };
206
+ }
207
+ else if ((await node.sequence(account)) !== tx["Sequence"]) {
208
+ return { reason: "invalid_exact_xrpl_payload_sequence_mismatch" };
209
+ }
210
+ const simulated = await node.simulate(String(payload.payload["signedTxBlob"]));
211
+ if (simulated.engineResult !== "tesSUCCESS")
212
+ return { reason: "invalid_exact_xrpl_payload_simulation_failed", code: simulated.engineResult };
213
+ return account;
214
+ }
215
+ /** The own path for a multisigned payer: the checks above, then the signed blob submitted unchanged. */
216
+ function multisignedModule(c, node) {
217
+ const network = c.network;
218
+ const facilitator = {
219
+ scheme: "exact",
220
+ caipFamily: "xrpl:*",
221
+ getExtra: () => undefined,
222
+ getSigners: () => [],
223
+ async verify(payload, requirements) {
224
+ const r = await multisigChecks(c, node, payload, requirements);
225
+ return typeof r === "string" ? { isValid: true, payer: r } : verifyFailure(r);
226
+ },
227
+ async settle(payload, requirements) {
228
+ const r = await multisigChecks(c, node, payload, requirements);
229
+ if (typeof r !== "string")
230
+ return settleFailure(r, network);
231
+ const sent = await node.submit(String(payload.payload["signedTxBlob"]));
232
+ if (sent.validated && sent.resultCode === "tesSUCCESS")
233
+ return { success: true, transaction: sent.hash, network, payer: r };
234
+ if (!sent.validated)
235
+ return { success: false, errorReason: "settlement_pending", transaction: sent.hash, network, payer: r };
236
+ return { success: false, errorReason: `transaction_failed: ${sent.resultCode}`, transaction: sent.hash, network, payer: r };
237
+ },
238
+ };
239
+ return { descriptor: descriptor(), network, facilitator, record: recordOf(c), fees: NO_FEES };
240
+ }
241
+ /** One kind for both paths: x402/exact/xrpl, no key; zero is no Payment (a Payment of zero is malformed). */
242
+ function descriptor() {
243
+ return { name: "xrpl", key: "none", pairings: [exactXrpl.id], acceptsZero: false };
244
+ }
245
+ /** The published class with the module's pure checks before it on both calls. */
246
+ function behind(cls, network) {
247
+ return {
248
+ scheme: cls.scheme,
249
+ caipFamily: cls.caipFamily,
250
+ getExtra: (n) => cls.getExtra(n),
251
+ getSigners: (n) => cls.getSigners(n),
252
+ async verify(payload, requirements, context) {
253
+ const r = await pure(network, payload, requirements);
254
+ return isRef(r) ? cls.verify(payload, requirements, context) : verifyFailure(r);
255
+ },
256
+ async settle(payload, requirements, context) {
257
+ const r = await pure(network, payload, requirements);
258
+ return isRef(r) ? cls.settle(payload, requirements, context) : settleFailure(r, requirements.network);
259
+ },
260
+ };
261
+ }
262
+ /** The registration of `x402/exact/xrpl` on the configured network, the multisigned payer handed to the own path. */
263
+ export function xrplRegistration(c, node = xrplNode(c.node, c.waitMs ?? 30_000)) {
264
+ const cls = new ExactXrplScheme({
265
+ maxFeeDrops: c.maxFeeDrops ?? DEFAULT_MAX_FEE_DROPS,
266
+ getCurrentLedgerIndex: () => node.validatedLedger(),
267
+ getAccountSequence: (account) => node.sequence(account),
268
+ getAccountAuthorization: (account) => node.authorization(account),
269
+ isTicketAvailable: (account, ticket) => node.ticket(account, ticket),
270
+ simulateSignedTransaction: (blob) => node.simulate(blob),
271
+ submitSignedTransaction: (blob) => node.submit(blob),
272
+ });
273
+ const network = c.network;
274
+ const module = { descriptor: descriptor(), network, facilitator: behind(cls, c.network), record: recordOf(c), fees: NO_FEES };
275
+ const multisigned = {
276
+ claim: { by: "payment", claims: (payload) => isMultisigned(payload) },
277
+ module: multisignedModule(c, node),
278
+ };
279
+ return { network, module, own: [multisigned] };
280
+ }
281
+ /** The registration of `x402/upto/xrpl` on the configured network: the module's own facilitator, x402 publishing none. */
282
+ export function uptoRegistration(c, node = xrplNode(c.node, c.waitMs ?? 30_000)) {
283
+ return { network: c.network, module: uptoModule(c.network, node), own: [] };
284
+ }
285
+ /**
286
+ * How the core starts the module: the configuration's `xrpl` member lists the networks, one entry each, and each is
287
+ * served `exact` and `upto` over its server.
288
+ */
289
+ export const starter = {
290
+ name: "xrpl",
291
+ async start(networks) {
292
+ return {
293
+ registrations: networks.flatMap((c) => {
294
+ const node = xrplNode(c.node, c.waitMs ?? 30_000);
295
+ return [xrplRegistration(c, node), uptoRegistration(c, node)];
296
+ }),
297
+ };
298
+ },
299
+ };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The seller's rippled or Clio server, over its JSON-RPC interface: lcp's XRPL reader, and the node calls
3
+ * `@x402/xrpl`'s facilitator class takes in its options, so the class reads and submits through the configured server
4
+ * over HTTP. Each call is bounded by the settler's node bounds and by its deadline, a `performance.now()` time; an
5
+ * answer whose status is `error` rejects, but for the errors that mean "not found", which the callers read.
6
+ */
7
+ import type { XrplNetwork, XrplReader } from "@integraledger/lcp/xrpl";
8
+ /** One call: its `result`, the server's error names kept (`error`) so a caller can read "not found". */
9
+ export declare function xrplRpc(url: string, method: string, params: Record<string, unknown>, deadline: number): Promise<Record<string, unknown>>;
10
+ /** lcp's reader over the server at `url`, its calls ending by `deadline`. */
11
+ export declare function xrplReader(network: XrplNetwork, url: string, deadline: number): XrplReader;
12
+ /** The index of the server's latest validated ledger, its call ending by `deadline`. */
13
+ export declare function validatedLedger(url: string, deadline: number): Promise<number>;
14
+ /** What the class and the own module read of the payer's account and the ledger, and how they submit. */
15
+ export interface XrplNode {
16
+ validatedLedger(): Promise<number>;
17
+ sequence(account: string): Promise<number>;
18
+ authorization(account: string): Promise<{
19
+ regularKey?: string;
20
+ isMasterKeyDisabled: boolean;
21
+ }>;
22
+ ticket(account: string, ticketSequence: number): Promise<boolean>;
23
+ /** The account's signer list at the validated ledger: its quorum and each signer's weight, or none. */
24
+ signerList(account: string): Promise<{
25
+ quorum: number;
26
+ weights: ReadonlyMap<string, number>;
27
+ } | null>;
28
+ simulate(blob: string): Promise<{
29
+ engineResult: string;
30
+ engineResultMessage?: string;
31
+ }>;
32
+ /** Submits the signed blob and waits up to `waitMs` for it in a validated ledger. */
33
+ submit(blob: string): Promise<{
34
+ hash: string;
35
+ validated: boolean;
36
+ resultCode: string;
37
+ }>;
38
+ /** The `PayChannel` ledger entry `id` names at the validated ledger, its fields as the server gives them, or none. */
39
+ payChannel(id: string): Promise<Record<string, unknown> | null>;
40
+ /** The validated ledger's index and its close time, in seconds since the Ripple epoch. */
41
+ validatedClose(): Promise<{
42
+ index: number;
43
+ closeTime: number;
44
+ }>;
45
+ /** A transaction by its hash: whether a validated ledger holds it, and its result; none where the server holds none. */
46
+ transaction(hash: string): Promise<{
47
+ validated: boolean;
48
+ resultCode: string;
49
+ } | null>;
50
+ }
51
+ /** The node calls over the server at `url`, each bounded by the node bounds; a submission waits up to `waitMs`. */
52
+ export declare function xrplNode(url: string, waitMs: number): XrplNode;
@@ -0,0 +1,231 @@
1
+ import { decode, hashes } from "xrpl";
2
+ import { isObject } from "../../answers.js";
3
+ import { NodeError, postJson, sleep } from "../../http.js";
4
+ /** One call: its `result`, the server's error names kept (`error`) so a caller can read "not found". */
5
+ export async function xrplRpc(url, method, params, deadline) {
6
+ const answer = await postJson(url, { method, params: [params] }, deadline - performance.now());
7
+ if (!isObject(answer) || !isObject(answer["result"]))
8
+ throw new NodeError("malformed", true, `${method}: no result`);
9
+ return answer["result"];
10
+ }
11
+ function failedOf(method, r) {
12
+ throw new NodeError("malformed", true, `${method}: ${String(r["error"] ?? "an answer without its members")}`);
13
+ }
14
+ const int = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : undefined);
15
+ /** A landed transaction from its binary `tx_blob` and `meta`. */
16
+ function landedOf(t, method) {
17
+ const blob = t["tx_blob"];
18
+ const metaHex = t["meta"];
19
+ if (typeof blob !== "string" || typeof metaHex !== "string")
20
+ return failedOf(method, t);
21
+ const meta = decode(metaHex);
22
+ const result = meta["TransactionResult"];
23
+ if (typeof result !== "string")
24
+ return failedOf(method, t);
25
+ const created = [];
26
+ const deleted = [];
27
+ for (const n of Array.isArray(meta["AffectedNodes"]) ? meta["AffectedNodes"] : []) {
28
+ if (!isObject(n))
29
+ continue;
30
+ for (const [kind, out] of [["CreatedNode", created], ["DeletedNode", deleted]]) {
31
+ const node = n[kind];
32
+ if (isObject(node) && node["LedgerEntryType"] === "PayChannel" && typeof node["LedgerIndex"] === "string")
33
+ out.push(node["LedgerIndex"]);
34
+ }
35
+ }
36
+ const delivered = meta["delivered_amount"] ?? meta["DeliveredAmount"];
37
+ const index = int(t["ledger_index"]);
38
+ const parent = meta["ParentBatchID"];
39
+ return {
40
+ hash: typeof t["hash"] === "string" ? t["hash"] : hashes.hashSignedTx(blob),
41
+ validated: t["validated"] === true,
42
+ ...(index === undefined ? {} : { ledgerIndex: index }),
43
+ result,
44
+ blob,
45
+ ...(delivered === undefined ? {} : { delivered: delivered }),
46
+ ...(created.length ? { createdChannels: created } : {}),
47
+ ...(deleted.length ? { deletedChannels: deleted } : {}),
48
+ ...(typeof parent === "string" ? { parent } : {}),
49
+ };
50
+ }
51
+ const ledgerOf = (r) => int(r["ledger_index"]) ?? int(r["ledger_current_index"]) ?? 0;
52
+ /** lcp's reader over the server at `url`, its calls ending by `deadline`. */
53
+ export function xrplReader(network, url, deadline) {
54
+ const call = (method, params) => xrplRpc(url, method, params, deadline);
55
+ return {
56
+ network,
57
+ async server() {
58
+ const r = await call("server_info", {});
59
+ const info = isObject(r["info"]) ? r["info"] : failedOf("server_info", r);
60
+ const validated = isObject(info["validated_ledger"]) ? int(info["validated_ledger"]["seq"]) : undefined;
61
+ const current = await call("ledger_current", {});
62
+ const latest = int(current["ledger_current_index"]);
63
+ if (validated === undefined || latest === undefined || typeof info["complete_ledgers"] !== "string")
64
+ return failedOf("server_info", r);
65
+ const id = int(info["network_id"]);
66
+ return { validated, latest, completeLedgers: info["complete_ledgers"], ...(id === undefined ? {} : { networkId: id }) };
67
+ },
68
+ async tx(hash, range) {
69
+ const r = await call("tx", { transaction: hash, binary: true, ...(range ? { min_ledger: range.min, max_ledger: range.max } : {}) });
70
+ if (r["error"] === "txnNotFound")
71
+ return { notFound: true, searchedAll: r["searched_all"] === true };
72
+ if (r["error"] !== undefined)
73
+ return failedOf("tx", r);
74
+ return landedOf({ ...r, hash: r["hash"] ?? hash }, "tx");
75
+ },
76
+ async accountTx(account, range, marker) {
77
+ const r = await call("account_tx", {
78
+ account,
79
+ ledger_index_min: range.min,
80
+ ledger_index_max: range.max,
81
+ binary: true,
82
+ forward: true,
83
+ ...(marker === undefined ? {} : { marker }),
84
+ });
85
+ const min = int(r["ledger_index_min"]);
86
+ const max = int(r["ledger_index_max"]);
87
+ if (r["error"] !== undefined || !Array.isArray(r["transactions"]) || min === undefined || max === undefined) {
88
+ return failedOf("account_tx", r);
89
+ }
90
+ const transactions = r["transactions"].map((t) => (isObject(t) ? landedOf(t, "account_tx") : failedOf("account_tx", r)));
91
+ return { transactions, min, max, ...(r["marker"] === undefined ? {} : { marker: r["marker"] }) };
92
+ },
93
+ async accountInfo(account, ledger) {
94
+ const r = await call("account_info", { account, ledger_index: ledger });
95
+ if (r["error"] === "actNotFound")
96
+ return { notFound: true, ledgerIndex: ledgerOf(r) };
97
+ const data = r["account_data"];
98
+ const sequence = isObject(data) ? int(data["Sequence"]) : undefined;
99
+ if (sequence === undefined)
100
+ return failedOf("account_info", r);
101
+ return { sequence, ledgerIndex: ledgerOf(r) };
102
+ },
103
+ async ticket(account, ticketSequence, ledger) {
104
+ const r = await call("ledger_entry", { ticket: { account, ticket_seq: ticketSequence }, ledger_index: ledger });
105
+ if (r["error"] === "entryNotFound")
106
+ return { present: false, ledgerIndex: ledgerOf(r) };
107
+ if (r["error"] !== undefined || !isObject(r["node"]))
108
+ return failedOf("ledger_entry", r);
109
+ return { present: true, ledgerIndex: ledgerOf(r) };
110
+ },
111
+ async channel(id, ledger) {
112
+ const r = await call("ledger_entry", { payment_channel: id, ledger_index: ledger });
113
+ if (r["error"] === "entryNotFound")
114
+ return { notFound: true, ledgerIndex: ledgerOf(r) };
115
+ const n = r["node"];
116
+ if (!isObject(n) || typeof n["Account"] !== "string" || typeof n["Destination"] !== "string" || typeof n["Amount"] !== "string") {
117
+ return failedOf("ledger_entry", r);
118
+ }
119
+ return { account: n["Account"], destination: n["Destination"], amount: n["Amount"] };
120
+ },
121
+ };
122
+ }
123
+ /** The index of the server's latest validated ledger, its call ending by `deadline`. */
124
+ export async function validatedLedger(url, deadline) {
125
+ const r = await xrplRpc(url, "ledger", { ledger_index: "validated" }, deadline);
126
+ return int(r["ledger_index"]) ?? failedOf("ledger", r);
127
+ }
128
+ /** The account's flag that disables its master key (`lsfDisableMaster`). */
129
+ const DISABLE_MASTER = 0x00100000;
130
+ /** The node calls over the server at `url`, each bounded by the node bounds; a submission waits up to `waitMs`. */
131
+ export function xrplNode(url, waitMs) {
132
+ const call = (method, params) => xrplRpc(url, method, params, performance.now() + 5_000);
133
+ const accountData = async (account, ledger) => {
134
+ const r = await call("account_info", { account, ledger_index: ledger });
135
+ return isObject(r["account_data"]) ? r["account_data"] : failedOf("account_info", r);
136
+ };
137
+ return {
138
+ async validatedLedger() {
139
+ const r = await call("ledger", { ledger_index: "validated" });
140
+ return int(r["ledger_index"]) ?? failedOf("ledger", r);
141
+ },
142
+ async sequence(account) {
143
+ return int((await accountData(account, "current"))["Sequence"]) ?? failedOf("account_info", {});
144
+ },
145
+ async authorization(account) {
146
+ const data = await accountData(account, "validated");
147
+ const flags = int(data["Flags"]) ?? 0;
148
+ return {
149
+ ...(typeof data["RegularKey"] === "string" ? { regularKey: data["RegularKey"] } : {}),
150
+ isMasterKeyDisabled: (flags & DISABLE_MASTER) !== 0,
151
+ };
152
+ },
153
+ async ticket(account, ticketSequence) {
154
+ const r = await call("ledger_entry", { ticket: { account, ticket_seq: ticketSequence }, ledger_index: "validated" });
155
+ if (r["error"] === "entryNotFound")
156
+ return false;
157
+ return isObject(r["node"]) ? true : failedOf("ledger_entry", r);
158
+ },
159
+ async signerList(account) {
160
+ const r = await call("account_objects", { account, type: "signer_list", ledger_index: "validated" });
161
+ if (!Array.isArray(r["account_objects"]))
162
+ return failedOf("account_objects", r);
163
+ const list = r["account_objects"].find((o) => isObject(o) && o["LedgerEntryType"] === "SignerList");
164
+ if (!isObject(list))
165
+ return null;
166
+ const quorum = int(list["SignerQuorum"]);
167
+ if (quorum === undefined || !Array.isArray(list["SignerEntries"]))
168
+ return failedOf("account_objects", r);
169
+ const weights = new Map();
170
+ for (const e of list["SignerEntries"]) {
171
+ const entry = isObject(e) ? e["SignerEntry"] : undefined;
172
+ if (isObject(entry) && typeof entry["Account"] === "string")
173
+ weights.set(entry["Account"], int(entry["SignerWeight"]) ?? 0);
174
+ }
175
+ return { quorum, weights };
176
+ },
177
+ async simulate(blob) {
178
+ // rippled simulates only an unsigned transaction and answers `transactionSigned` to a signed one, so the signing fields
179
+ // go before the call, as the published class's own default strips them (@x402/xrpl 2.31.0).
180
+ const { TxnSignature, SigningPubKey, Signers, ...unsigned } = decode(blob);
181
+ void TxnSignature;
182
+ void SigningPubKey;
183
+ void Signers;
184
+ const r = await call("simulate", { tx_json: unsigned });
185
+ if (typeof r["engine_result"] !== "string")
186
+ return failedOf("simulate", r);
187
+ return {
188
+ engineResult: r["engine_result"],
189
+ ...(typeof r["engine_result_message"] === "string" ? { engineResultMessage: r["engine_result_message"] } : {}),
190
+ };
191
+ },
192
+ async payChannel(id) {
193
+ const r = await call("ledger_entry", { payment_channel: id, ledger_index: "validated" });
194
+ if (r["error"] === "entryNotFound")
195
+ return null;
196
+ const n = r["node"];
197
+ return isObject(n) && n["LedgerEntryType"] === "PayChannel" ? n : failedOf("ledger_entry", r);
198
+ },
199
+ async validatedClose() {
200
+ const r = await call("ledger", { ledger_index: "validated" });
201
+ const ledger = isObject(r["ledger"]) ? r["ledger"] : {};
202
+ const index = int(r["ledger_index"]);
203
+ const closeTime = int(ledger["close_time"]);
204
+ return index === undefined || closeTime === undefined ? failedOf("ledger", r) : { index, closeTime };
205
+ },
206
+ async transaction(hash) {
207
+ const r = await call("tx", { transaction: hash });
208
+ if (r["error"] === "txnNotFound")
209
+ return null;
210
+ const meta = r["meta"];
211
+ if (!isObject(meta) || typeof meta["TransactionResult"] !== "string")
212
+ return { validated: false, resultCode: "" };
213
+ return { validated: r["validated"] === true, resultCode: meta["TransactionResult"] };
214
+ },
215
+ async submit(blob) {
216
+ const sent = await call("submit", { tx_blob: blob });
217
+ const hash = isObject(sent["tx_json"]) && typeof sent["tx_json"]["hash"] === "string" ? sent["tx_json"]["hash"] : hashes.hashSignedTx(blob);
218
+ const engine = typeof sent["engine_result"] === "string" ? sent["engine_result"] : "";
219
+ const until = performance.now() + waitMs;
220
+ for (;;) {
221
+ const r = await call("tx", { transaction: hash });
222
+ if (r["validated"] === true && isObject(r["meta"]) && typeof r["meta"]["TransactionResult"] === "string") {
223
+ return { hash, validated: true, resultCode: r["meta"]["TransactionResult"] };
224
+ }
225
+ if (performance.now() + 1_000 > until)
226
+ return { hash, validated: false, resultCode: engine };
227
+ await sleep(1_000);
228
+ }
229
+ },
230
+ };
231
+ }
@@ -0,0 +1,5 @@
1
+ import type { XrplNetwork } from "@integraledger/lcp/xrpl";
2
+ import { type Module } from "../../module.js";
3
+ import type { XrplNode } from "./node.js";
4
+ /** The module of `x402/upto/xrpl` on the configured network. */
5
+ export declare function uptoModule(network: XrplNetwork, node: XrplNode): Module;