@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,60 @@
1
+ /**
2
+ * The Solana module: `@x402/svm` 2.31.0's facilitator classes for `x402/exact/solana`, `x402/upto/solana` and
3
+ * `x402/batch-settlement/solana`, each registered unchanged for one network, behind lcp's checks of the pairing.
4
+ *
5
+ * The seller's fee-payer key co-signs every transaction the payer signed as its fee payer (and, on the channel forms,
6
+ * pays the channel's rent), so `extra.key` is `fee-payer` and the key's address is in `signers` and in the class's own
7
+ * `extra.feePayer`. The key reaches the module as the signer object the classes take, `FacilitatorSvmSigner`, which
8
+ * the operator's code makes (for example with `toFacilitatorSvmSigner` over the same node), so the settler reads no key
9
+ * material. The channel forms need the payment-channels program, which is deployed on devnet and testnet and not on
10
+ * mainnet, and durable channel storage, which the settler's database gives: on mainnet only `exact` is made.
11
+ */
12
+ import { type Refusal } from "@integraledger/lcp";
13
+ import type { SolanaNetwork } from "@integraledger/lcp/svm";
14
+ import type { FacilitatorSvmSigner } from "@x402/svm";
15
+ import { type BatchPendingSettlementStore, type PaymentChannelStorage } from "@x402/svm/batch-settlement/facilitator";
16
+ import type { PendingSettlementStore } from "@x402/core/facilitator";
17
+ import { type FeeMeter, type Module, type ModuleStarter, type X402Payment } from "../../module.js";
18
+ /** Solana mainnet, where the payment-channels program the `upto` and batch-settlement forms call is not deployed. */
19
+ export declare const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
20
+ /** The durable state the channel forms' classes keep, from the settler's database. */
21
+ export interface SolanaChannelState {
22
+ /** The channels the `upto` and batch-settlement classes open, read back at a claim and by rent cleanup. */
23
+ readonly channels: PaymentChannelStorage;
24
+ /** The signatures `upto` and `exact` broadcast and have not yet seen confirmed, so a retried settle reconciles. */
25
+ readonly pending: PendingSettlementStore;
26
+ /** The batch-settlement class's own pending signatures. */
27
+ readonly batchPending: BatchPendingSettlementStore;
28
+ }
29
+ export interface SolanaConfig {
30
+ /** The network, exactly one. */
31
+ readonly network: SolanaNetwork;
32
+ /**
33
+ * The seller's Solana JSON-RPC endpoint, which lcp's read uses: one whose `getFirstAvailableBlock` is at or below the
34
+ * slot at which each payment was issued.
35
+ */
36
+ readonly node: string;
37
+ /** The seller's fee-payer key, as `@x402/svm`'s facilitator classes take it. */
38
+ readonly signer: FacilitatorSvmSigner;
39
+ /** The message versions the classes accept and state in `extra.transactionVersions`; their default is `[0, 1]`. */
40
+ readonly transactionVersions?: readonly (0 | 1)[];
41
+ }
42
+ /** The x402 reason for an lcp refusal: the version, the option, or else the payload. */
43
+ export declare function reasonOf(r: Refusal): string;
44
+ /**
45
+ * The digest that names a settle which carries no H, a claim against a channel or a batch's voucher, refund or top-up:
46
+ * SHA-256 over the network, the amount the resource server asks for and the payload as presented, so each signed
47
+ * settle is its own row.
48
+ */
49
+ export declare function collectionDigest(network: string, p: X402Payment): string;
50
+ /**
51
+ * The Solana modules for one network: `exact` always; `upto` and batch settlement where the network is not mainnet and
52
+ * durable channel state is given. With `meter`, the network's fee meter, every transaction the classes send is counted.
53
+ */
54
+ export declare function solanaModules(config: SolanaConfig, state?: SolanaChannelState, meter?: FeeMeter): Module[];
55
+ /**
56
+ * How the core starts the module: the configuration's `solana` member lists the networks, one entry each, and each
57
+ * form made on a network is one registration of x402's class. The channels, and every class's pending signatures, are
58
+ * kept in the settler's database, and each network's fee meter counts every transaction the classes send.
59
+ */
60
+ export declare const starter: ModuleStarter<readonly SolanaConfig[]>;
@@ -0,0 +1,326 @@
1
+ /**
2
+ * The Solana module: `@x402/svm` 2.31.0's facilitator classes for `x402/exact/solana`, `x402/upto/solana` and
3
+ * `x402/batch-settlement/solana`, each registered unchanged for one network, behind lcp's checks of the pairing.
4
+ *
5
+ * The seller's fee-payer key co-signs every transaction the payer signed as its fee payer (and, on the channel forms,
6
+ * pays the channel's rent), so `extra.key` is `fee-payer` and the key's address is in `signers` and in the class's own
7
+ * `extra.feePayer`. The key reaches the module as the signer object the classes take, `FacilitatorSvmSigner`, which
8
+ * the operator's code makes (for example with `toFacilitatorSvmSigner` over the same node), so the settler reads no key
9
+ * material. The channel forms need the payment-channels program, which is deployed on devnet and testnet and not on
10
+ * mainnet, and durable channel storage, which the settler's database gives: on mainnet only `exact` is made.
11
+ */
12
+ import { isRefusal } from "@integraledger/lcp";
13
+ import { batchSvm } from "@integraledger/lcp/x402-batch-settlement";
14
+ import { exactSvm } from "@integraledger/lcp/x402-exact-solana";
15
+ import { uptoSvm } from "@integraledger/lcp/x402-upto-solana";
16
+ import { BatchSvmScheme } from "@x402/svm/batch-settlement/facilitator";
17
+ import { ExactSvmScheme } from "@x402/svm/exact/facilitator";
18
+ import { UptoSvmScheme } from "@x402/svm/upto/facilitator";
19
+ import { getBase58Decoder, getTransactionDecoder } from "@solana/kit";
20
+ import { createHash } from "node:crypto";
21
+ import { isObject } from "../../answers.js";
22
+ import { NODE_TIMEOUT_MS } from "../../http.js";
23
+ import { outcomeOf, phaseOf, } from "../../module.js";
24
+ import { chargedOn, svmReader } from "./reader.js";
25
+ import { batchPendingStore, channelStorage } from "./state.js";
26
+ /** Solana mainnet, where the payment-channels program the `upto` and batch-settlement forms call is not deployed. */
27
+ export const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
28
+ /** The x402 reason for an lcp refusal: the version, the option, or else the payload. */
29
+ export function reasonOf(r) {
30
+ if (r.code === "x402/not-v2")
31
+ return "invalid_x402_version";
32
+ if (r.code.startsWith("x402/option") || r.code === "x402/flow-missing")
33
+ return "invalid_payment_requirements";
34
+ return "invalid_payload";
35
+ }
36
+ /** The payment as lcp reads it: the payload as presented, which holds the option it accepted. */
37
+ function presented(payload) {
38
+ return payload;
39
+ }
40
+ /**
41
+ * The published class, unchanged, with the module's checks before it on both calls: a payment they refuse is answered
42
+ * by x402's failure shape with lcp's code as its message, and the class never sees it. At `/settle`, the class's check
43
+ * is `atSettle` where given, else its `verify`.
44
+ */
45
+ function behind(cls, check, atSettle) {
46
+ return {
47
+ scheme: cls.scheme,
48
+ caipFamily: cls.caipFamily,
49
+ getExtra: (network) => cls.getExtra(network),
50
+ getSigners: (network) => cls.getSigners(network),
51
+ async verify(payload, requirements, context) {
52
+ const refused = await check(payload, requirements);
53
+ if (refused !== null) {
54
+ return { isValid: false, invalidReason: refused.reason, ...(refused.code ? { invalidMessage: refused.code } : {}) };
55
+ }
56
+ if (atSettle !== undefined && phaseOf(context) === "settle")
57
+ return atSettle(cls, payload, requirements, context);
58
+ return cls.verify(payload, requirements, context);
59
+ },
60
+ async settle(payload, requirements, context) {
61
+ const refused = await check(payload, requirements);
62
+ if (refused !== null) {
63
+ return {
64
+ success: false,
65
+ errorReason: refused.reason,
66
+ ...(refused.code ? { errorMessage: refused.code } : {}),
67
+ transaction: "",
68
+ network: requirements.network,
69
+ };
70
+ }
71
+ return cls.settle(payload, requirements, context);
72
+ },
73
+ };
74
+ }
75
+ /** JSON with every object's keys in order, so one value has one spelling. */
76
+ function canonical(v) {
77
+ if (Array.isArray(v))
78
+ return `[${v.map(canonical).join(",")}]`;
79
+ if (isObject(v)) {
80
+ return `{${Object.keys(v)
81
+ .sort()
82
+ .map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`)
83
+ .join(",")}}`;
84
+ }
85
+ return JSON.stringify(v) ?? "null";
86
+ }
87
+ /**
88
+ * The digest that names a settle which carries no H, a claim against a channel or a batch's voucher, refund or top-up:
89
+ * SHA-256 over the network, the amount the resource server asks for and the payload as presented, so each signed
90
+ * settle is its own row.
91
+ */
92
+ export function collectionDigest(network, p) {
93
+ const body = canonical({ network, amount: p.requirements.amount, payload: p.payload.payload });
94
+ return `0x${createHash("sha256").update(body).digest("hex")}`;
95
+ }
96
+ /** A wire's transaction id: its first signature, the fee payer's, base58; undefined where the wire does not decode. */
97
+ function txidOf(wireBase64) {
98
+ try {
99
+ const first = Object.values(getTransactionDecoder().decode(Buffer.from(wireBase64, "base64")).signatures)[0];
100
+ return first ? getBase58Decoder().decode(first) : undefined;
101
+ }
102
+ catch {
103
+ return undefined;
104
+ }
105
+ }
106
+ /**
107
+ * The fee payer's signer object as the classes take it, each transaction it sends given to the network's fee meter
108
+ * once the send ends, every other member unchanged. x402's classes send every transaction through `sendTransaction`,
109
+ * and answer one whose send threw naming no transaction, though the node may have taken it; its id is in the wire, so
110
+ * the meter counts it at the wire's own bound until the node shows its fee.
111
+ */
112
+ function counted(signer, meter, node) {
113
+ return new Proxy(signer, {
114
+ get(inner, member) {
115
+ const value = Reflect.get(inner, member);
116
+ if (typeof value !== "function")
117
+ return value;
118
+ if (member === "sendTransaction") {
119
+ return async (wire, network) => {
120
+ try {
121
+ return await value.call(inner, wire, network);
122
+ }
123
+ finally {
124
+ const transaction = txidOf(wire);
125
+ if (transaction !== undefined) {
126
+ meter.sent(transaction, () => chargedOn(node, transaction, wire, performance.now() + NODE_TIMEOUT_MS));
127
+ }
128
+ }
129
+ };
130
+ }
131
+ return value.bind(inner);
132
+ },
133
+ });
134
+ }
135
+ /** lcp's checks of a payment of `pairing`, and its reference; the refusal where the module's network differs. */
136
+ async function checked(network, pairing, payload, requirements) {
137
+ if (requirements.network !== network || payload.accepted?.network !== network)
138
+ return { reason: "invalid_network" };
139
+ const bound = await pairing.bound(presented(payload));
140
+ if (isRefusal(bound))
141
+ return { reason: reasonOf(bound), code: bound.code };
142
+ // The requirements arrive as JSON, which lcp's option type names.
143
+ const ref = await pairing.reference(presented(payload), requirements);
144
+ if (isRefusal(ref))
145
+ return { reason: reasonOf(ref), code: ref.code };
146
+ return ref;
147
+ }
148
+ const isRef = (v) => !("reason" in v);
149
+ /**
150
+ * lcp's read of the payment act `ref` names, at the one mark, `finalized`, resuming `search`, after the slot the claim
151
+ * read (`from`), where the core holds one: a node that holds the blocks from that slot on then serves the read.
152
+ */
153
+ async function readOf(pairing, node, ref, at) {
154
+ const reader = svmReader(ref.network, node, at.deadline);
155
+ const search = at.search;
156
+ const after = at.from?.slot;
157
+ return outcomeOf(await pairing.status(ref, reader, {
158
+ act: "payment",
159
+ finality: "finalized",
160
+ ...(search ? { search } : {}),
161
+ ...(typeof after === "bigint" ? { after } : {}),
162
+ }));
163
+ }
164
+ /** The transaction the payer gave, base64, where the payload carries one: `exact`'s, or an `upto` opening's. */
165
+ function givenWire(p) {
166
+ const body = p.payload.payload;
167
+ const wire = body["transaction"] ?? body["openTransaction"];
168
+ return typeof wire === "string" ? wire : undefined;
169
+ }
170
+ /**
171
+ * The instrument of a payment lcp's checks accept: the message the payer signed, by its digest, which holds every
172
+ * byte the payer signed and no signature, so a copy signed again is the same instrument; `single-use` where the
173
+ * pairing's single-use value is that signed message, else named by that digest alone. A blockhash bounds its life in
174
+ * blocks, which no clock bounds from above, and a durable nonce does not bound it: the row is kept for the settler's
175
+ * life.
176
+ */
177
+ function instrumentOf(pairing, nonce, ref) {
178
+ const digest = ref.digest ?? "";
179
+ return {
180
+ pairing: pairing.id,
181
+ instrument: nonce === "single-use"
182
+ ? { by: "single-use", network: ref.network, signer: ref.payer, value: digest }
183
+ : { by: "digest", network: ref.network, digest },
184
+ nonce,
185
+ keep: { until: "settler" },
186
+ };
187
+ }
188
+ /**
189
+ * The module for one pairing whose every settle carries H in the signed message (`exact`), or whose opening does and
190
+ * whose later settles are collection (`isOpening` false: an `upto` claim, a batch's voucher, top-up or refund), which
191
+ * lcp does not read: those go to the class with the network checked, and each is its own row.
192
+ */
193
+ function moduleOf(c, pairing, cls, acceptsZero, isOpening, atSettle) {
194
+ const network = c.network;
195
+ const check = async (payload, requirements) => {
196
+ if (!isOpening({ payload, requirements })) {
197
+ return requirements.network === network && payload.accepted?.network === network ? null : { reason: "invalid_network" };
198
+ }
199
+ const r = await checked(c.network, pairing, payload, requirements);
200
+ return isRef(r) ? null : r;
201
+ };
202
+ return {
203
+ descriptor: { name: "solana", key: "fee-payer", pairings: [pairing.id], acceptsZero },
204
+ network,
205
+ facilitator: behind(cls, check, atSettle),
206
+ record: {
207
+ async instrument(p) {
208
+ if (!isOpening(p)) {
209
+ if (p.requirements.network !== network || p.payload.accepted?.network !== network)
210
+ return { refused: "invalid_network" };
211
+ return {
212
+ pairing: pairing.id,
213
+ instrument: { by: "digest", network, digest: collectionDigest(network, p) },
214
+ nonce: "unshown",
215
+ keep: { until: "settler" },
216
+ };
217
+ }
218
+ const r = await checked(c.network, pairing, p.payload, p.requirements);
219
+ return isRef(r) ? instrumentOf(pairing, pairing.data.nonce, r) : { refused: r.reason, ...(r.code === undefined ? {} : { message: r.code }) };
220
+ },
221
+ async read(p, at) {
222
+ if (!isOpening(p)) {
223
+ // A collection settle carries no H and lcp has no read of it: the read finds nothing it can test.
224
+ return outcomeOf({ state: "pending", reason: "not-found", foreign: [] });
225
+ }
226
+ const r = await checked(c.network, pairing, p.payload, p.requirements);
227
+ if (!isRef(r))
228
+ return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
229
+ return readOf(pairing, c.node, r, at);
230
+ },
231
+ async position(_p, at) {
232
+ return { slot: await svmReader(c.network, c.node, at.deadline).slot("finalized") };
233
+ },
234
+ },
235
+ fees: {
236
+ // The key co-signs as fee payer every transaction this module sends, the claims and closes among them.
237
+ paysFee: () => true,
238
+ payerBroadcast: () => false,
239
+ charged: (p, sent) => chargedOn(c.node, sent.transaction, givenWire(p), sent.deadline),
240
+ },
241
+ };
242
+ }
243
+ /**
244
+ * Whether an `upto` payload goes through lcp's checks as an opening: every payload but one `UptoSvmScheme.settle`
245
+ * positively reads as a claim against an open channel, `type` `claim` or a `voucherSignature` with no `type`. The class
246
+ * takes a payload with neither for a deposit where the amount equals `maxAmount` as numbers, however `maxAmount` is
247
+ * spelt, so the module never tells a deposit by the spelling.
248
+ */
249
+ function uptoOpening(p) {
250
+ const body = p.payload.payload;
251
+ const type = body["type"];
252
+ if (type === "claim")
253
+ return false;
254
+ return !(type === undefined && typeof body["voucherSignature"] === "string");
255
+ }
256
+ /**
257
+ * The `upto` class's check at `/settle`. The resource server stamps `type` on each settle it sends (x402's `upto`
258
+ * server: `deposit` before its handler runs, `claim` after it), and the class's `verify`, the check of the buyer's
259
+ * opening, refuses a payload that carries one. A deposit is checked by that `verify` as the buyer sent it, without
260
+ * the stamp. A claim, which that `verify` never takes, is checked by the class's `settle` before it sends anything (the
261
+ * channel it opened, the receiver authorizer, the validity window, the voucher): here it is valid, naming the
262
+ * payload's payer.
263
+ */
264
+ const uptoAtSettle = async (cls, payload, requirements, context) => {
265
+ const body = payload.payload;
266
+ if (!uptoOpening({ payload, requirements })) {
267
+ const from = body["from"];
268
+ return { isValid: true, ...(typeof from === "string" ? { payer: from } : {}) };
269
+ }
270
+ if (body["type"] !== "deposit")
271
+ return cls.verify(payload, requirements, context);
272
+ const { type: _stamp, ...signed } = body;
273
+ return cls.verify({ ...payload, payload: signed }, requirements, context);
274
+ };
275
+ /**
276
+ * Whether a batch-settlement payload goes through lcp's checks as an opening: a deposit that lcp's channel read does not
277
+ * place within an open channel (a top-up), that is its `open`, and a deposit lcp cannot read, which its checks refuse.
278
+ * Every other type is a voucher or a call on the channel the resource server makes, which lcp does not read.
279
+ */
280
+ function batchOpening(p) {
281
+ if (p.payload.payload["type"] !== "deposit")
282
+ return false;
283
+ return batchSvm.channel.kind(p.payload) !== "within";
284
+ }
285
+ /**
286
+ * The Solana modules for one network: `exact` always; `upto` and batch settlement where the network is not mainnet and
287
+ * durable channel state is given. With `meter`, the network's fee meter, every transaction the classes send is counted.
288
+ */
289
+ export function solanaModules(config, state, meter) {
290
+ const c = meter === undefined ? config : { ...config, signer: counted(config.signer, meter, config.node) };
291
+ const versions = c.transactionVersions === undefined ? {} : { transactionVersions: c.transactionVersions };
292
+ const pending = state === undefined ? {} : { pendingSettlementStore: state.pending };
293
+ const exact = new ExactSvmScheme(c.signer, undefined, { ...versions, ...pending });
294
+ // lcp's floor on x402/exact/solana is 0: a zero TransferChecked lands, and the class compares amounts by equality.
295
+ const modules = [moduleOf(c, exactSvm, exact, [exactSvm.id], () => true)];
296
+ if (c.network === SOLANA_MAINNET || state === undefined)
297
+ return modules;
298
+ const upto = new UptoSvmScheme(c.signer, { ...versions, channelStorage: state.channels, pendingSettlementStore: state.pending });
299
+ const batch = new BatchSvmScheme(c.signer, {
300
+ ...versions,
301
+ channelStorage: state.channels,
302
+ pendingSettlementStore: state.batchPending,
303
+ });
304
+ // upto: lcp's filter admits a positive amount only. Batch settlement: zero through it has not been read.
305
+ modules.push(moduleOf(c, uptoSvm, upto, [], uptoOpening, uptoAtSettle));
306
+ modules.push(moduleOf(c, batchSvm, batch, [], batchOpening));
307
+ return modules;
308
+ }
309
+ /**
310
+ * How the core starts the module: the configuration's `solana` member lists the networks, one entry each, and each
311
+ * form made on a network is one registration of x402's class. The channels, and every class's pending signatures, are
312
+ * kept in the settler's database, and each network's fee meter counts every transaction the classes send.
313
+ */
314
+ export const starter = {
315
+ name: "solana",
316
+ async start(networks, core) {
317
+ const state = {
318
+ channels: channelStorage(core.state),
319
+ pending: core.state.pendingSettlements(),
320
+ batchPending: batchPendingStore(core.state),
321
+ };
322
+ return {
323
+ registrations: networks.flatMap((c) => solanaModules(c, state, core.meter(c.network)).map((module) => ({ network: module.network, module, own: [] }))),
324
+ };
325
+ },
326
+ };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * lcp's Solana reader over one Solana JSON-RPC endpoint: the calls `SvmReader` names, each a POST of one JSON-RPC
3
+ * request bounded by the settler's node bounds and by the read's deadline, a `performance.now()` time. Every failure
4
+ * rejects, an error answer of the node among them, so lcp reads it as `unreadable`.
5
+ */
6
+ import type { SolanaNetwork, SvmLanded, SvmReader } from "@integraledger/lcp/svm";
7
+ /** One JSON-RPC call: its `result`, or a rejection where the node answers an error or no result. */
8
+ export declare function solanaRpc(url: string, method: string, params: unknown[], deadline: number): Promise<unknown>;
9
+ /** A landed transaction as `getTransaction` gives it with encoding `base64`. */
10
+ export declare function landedOf(result: unknown): SvmLanded;
11
+ /** lcp's reader for `network` over the JSON-RPC endpoint at `url`, its calls ending by `deadline`. */
12
+ export declare function svmReader(network: SolanaNetwork, url: string, deadline: number): SvmReader;
13
+ /**
14
+ * The most a transaction's own fields let it pay, in lamports: its base fee, one per signature its message requires,
15
+ * and its priority fee, its compute-unit limit times its price in micro-lamports, rounded up.
16
+ */
17
+ export declare function feeBound(wireBase64: string): bigint;
18
+ /**
19
+ * The fee a transaction a class sent paid, as the node shows it once included (`meta.fee`); until then the bound of the
20
+ * transaction the payer gave, where the payment carries one; a transaction neither shown nor given rejects.
21
+ */
22
+ export declare function chargedOn(url: string, signature: string, given: string | undefined, deadline: number): Promise<{
23
+ fee: bigint;
24
+ included: boolean;
25
+ }>;
@@ -0,0 +1,194 @@
1
+ import { getBase58Encoder, getCompiledTransactionMessageDecoder, getTransactionDecoder } from "@solana/kit";
2
+ import { isObject } from "../../answers.js";
3
+ import { NodeError, postJson } from "../../http.js";
4
+ /** One JSON-RPC call: its `result`, or a rejection where the node answers an error or no result. */
5
+ export async function solanaRpc(url, method, params, deadline) {
6
+ const answer = await postJson(url, { jsonrpc: "2.0", id: 1, method, params }, deadline - performance.now());
7
+ if (!isObject(answer))
8
+ throw new NodeError("malformed", true, `${method}: the answer is not an object`);
9
+ if (answer["error"] !== undefined)
10
+ throw new NodeError("malformed", true, `${method}: ${JSON.stringify(answer["error"])}`);
11
+ if (!("result" in answer))
12
+ throw new NodeError("malformed", true, `${method}: no result`);
13
+ return answer["result"];
14
+ }
15
+ function malformed(what) {
16
+ throw new NodeError("malformed", true, what);
17
+ }
18
+ function int(v, what) {
19
+ if (typeof v === "number" && Number.isSafeInteger(v) && v >= 0)
20
+ return BigInt(v);
21
+ return malformed(`${what} is not a slot`);
22
+ }
23
+ const base58 = getBase58Encoder();
24
+ function keyBytes(v, what) {
25
+ if (typeof v !== "string")
26
+ return malformed(`${what} is not base58`);
27
+ try {
28
+ return new Uint8Array(base58.encode(v));
29
+ }
30
+ catch {
31
+ return malformed(`${what} is not base58`);
32
+ }
33
+ }
34
+ function base64Of(v, what) {
35
+ if (!Array.isArray(v) || typeof v[0] !== "string" || v[1] !== "base64")
36
+ return malformed(`${what} is not base64 data`);
37
+ return new Uint8Array(Buffer.from(v[0], "base64"));
38
+ }
39
+ function balances(v) {
40
+ if (v === undefined || v === null)
41
+ return undefined;
42
+ if (!Array.isArray(v))
43
+ return malformed("token balances are not a list");
44
+ return v.map((b) => {
45
+ if (!isObject(b) || typeof b["accountIndex"] !== "number" || typeof b["mint"] !== "string") {
46
+ return malformed("a token balance");
47
+ }
48
+ return {
49
+ account: b["accountIndex"],
50
+ mint: b["mint"],
51
+ ...(typeof b["owner"] === "string" ? { owner: b["owner"] } : {}),
52
+ };
53
+ });
54
+ }
55
+ function inner(v) {
56
+ if (v === undefined || v === null)
57
+ return [];
58
+ if (!Array.isArray(v))
59
+ return malformed("inner instructions are not a list");
60
+ const out = [];
61
+ for (const group of v) {
62
+ if (!isObject(group) || typeof group["index"] !== "number" || !Array.isArray(group["instructions"])) {
63
+ return malformed("an inner instruction group");
64
+ }
65
+ for (const ix of group["instructions"]) {
66
+ if (!isObject(ix) || typeof ix["programIdIndex"] !== "number" || !Array.isArray(ix["accounts"])) {
67
+ return malformed("an inner instruction");
68
+ }
69
+ out.push({
70
+ index: group["index"],
71
+ program: ix["programIdIndex"],
72
+ accounts: ix["accounts"].map((a) => (typeof a === "number" ? a : malformed("an inner instruction account"))),
73
+ data: keyBytes(ix["data"], "an inner instruction's data"),
74
+ });
75
+ }
76
+ }
77
+ return out;
78
+ }
79
+ /** A landed transaction as `getTransaction` gives it with encoding `base64`. */
80
+ export function landedOf(result) {
81
+ if (!isObject(result) || !isObject(result["meta"]))
82
+ return malformed("a transaction without meta");
83
+ const meta = result["meta"];
84
+ const loaded = isObject(meta["loadedAddresses"]) ? meta["loadedAddresses"] : {};
85
+ const keys = (v) => (Array.isArray(v) ? v.map((k) => keyBytes(k, "a loaded address")) : []);
86
+ const pre = balances(meta["preTokenBalances"]);
87
+ const post = balances(meta["postTokenBalances"]);
88
+ return {
89
+ wire: base64Of(result["transaction"], "the transaction"),
90
+ err: meta["err"] ?? null,
91
+ ...(result["slot"] === undefined ? {} : { slot: int(result["slot"], "the slot") }),
92
+ loaded: { writable: keys(loaded["writable"]), readonly: keys(loaded["readonly"]) },
93
+ inner: inner(meta["innerInstructions"]),
94
+ ...(pre === undefined ? {} : { pre }),
95
+ ...(post === undefined ? {} : { post }),
96
+ };
97
+ }
98
+ /** lcp's reader for `network` over the JSON-RPC endpoint at `url`, its calls ending by `deadline`. */
99
+ export function svmReader(network, url, deadline) {
100
+ const call = (method, params) => solanaRpc(url, method, params, deadline);
101
+ const slot = async (commitment) => int(await call("getSlot", [{ commitment }]), "getSlot");
102
+ return {
103
+ network,
104
+ slot,
105
+ async transaction(signature, commitment) {
106
+ const at = await slot(commitment);
107
+ const result = await call("getTransaction", [
108
+ signature,
109
+ { encoding: "base64", commitment, maxSupportedTransactionVersion: 1 },
110
+ ]);
111
+ return result === null ? { notFound: true, slot: at } : landedOf(result);
112
+ },
113
+ async signatures(address, page) {
114
+ const result = await call("getSignaturesForAddress", [address, page]);
115
+ if (!Array.isArray(result))
116
+ return malformed("getSignaturesForAddress is not a list");
117
+ return result.map((s) => {
118
+ if (!isObject(s) || typeof s["signature"] !== "string")
119
+ return malformed("a signature entry");
120
+ const memo = s["memo"];
121
+ return { signature: s["signature"], slot: int(s["slot"], "a signature's slot"), memo: typeof memo === "string" ? memo : null };
122
+ });
123
+ },
124
+ async blockhashValid(blockhash, commitment) {
125
+ const result = await call("isBlockhashValid", [blockhash, { commitment }]);
126
+ if (!isObject(result) || !isObject(result["context"]) || typeof result["value"] !== "boolean") {
127
+ return malformed("isBlockhashValid");
128
+ }
129
+ return { valid: result["value"], slot: int(result["context"]["slot"], "the context slot") };
130
+ },
131
+ async firstAvailableBlock() {
132
+ return int(await call("getFirstAvailableBlock", []), "getFirstAvailableBlock");
133
+ },
134
+ async account(address, commitment) {
135
+ const result = await call("getAccountInfo", [address, { encoding: "base64", commitment }]);
136
+ if (!isObject(result) || !isObject(result["context"]))
137
+ return malformed("getAccountInfo");
138
+ const at = int(result["context"]["slot"], "the context slot");
139
+ const value = result["value"];
140
+ if (value === null)
141
+ return { slot: at, value: null };
142
+ if (!isObject(value) || typeof value["owner"] !== "string")
143
+ return malformed("an account");
144
+ return { slot: at, value: { owner: value["owner"], data: base64Of(value["data"], "the account's data") } };
145
+ },
146
+ };
147
+ }
148
+ /** The Compute Budget program, whose instructions set a transaction's compute-unit limit (2) and price (3). */
149
+ const COMPUTE_BUDGET = "ComputeBudget111111111111111111111111111111";
150
+ /** Solana's base fee per signature, in lamports. */
151
+ const LAMPORTS_PER_SIGNATURE = 5000n;
152
+ /** The most compute units one transaction may request, the bound where none is set. */
153
+ const MAX_COMPUTE_UNITS = 1400000n;
154
+ /**
155
+ * The most a transaction's own fields let it pay, in lamports: its base fee, one per signature its message requires,
156
+ * and its priority fee, its compute-unit limit times its price in micro-lamports, rounded up.
157
+ */
158
+ export function feeBound(wireBase64) {
159
+ const tx = getTransactionDecoder().decode(Buffer.from(wireBase64, "base64"));
160
+ const message = getCompiledTransactionMessageDecoder().decode(tx.messageBytes);
161
+ const base = BigInt(message.header.numSignerAccounts) * LAMPORTS_PER_SIGNATURE;
162
+ if (!("instructions" in message)) {
163
+ // A version-1 message states its priority fee in lamports among its configuration values, the first when its mask
164
+ // sets both bits of it (TRANSACTION_CONFIG_PRIORITY_FEE_LAMPORTS_BIT_MASK, 3).
165
+ const first = (message.configMask & 3) === 3 ? message.configValues[0] : undefined;
166
+ return base + (first?.kind === "u64" ? first.value : 0n);
167
+ }
168
+ let limit = MAX_COMPUTE_UNITS;
169
+ let price = 0n;
170
+ for (const ix of message.instructions) {
171
+ if (message.staticAccounts[ix.programAddressIndex] !== COMPUTE_BUDGET || ix.data === undefined)
172
+ continue;
173
+ const data = Buffer.from(ix.data);
174
+ if (data[0] === 2 && data.length >= 5)
175
+ limit = BigInt(data.readUInt32LE(1));
176
+ if (data[0] === 3 && data.length >= 9)
177
+ price = data.readBigUInt64LE(1);
178
+ }
179
+ return base + (limit * price + 999999n) / 1000000n;
180
+ }
181
+ /**
182
+ * The fee a transaction a class sent paid, as the node shows it once included (`meta.fee`); until then the bound of the
183
+ * transaction the payer gave, where the payment carries one; a transaction neither shown nor given rejects.
184
+ */
185
+ export async function chargedOn(url, signature, given, deadline) {
186
+ const result = await solanaRpc(url, "getTransaction", [signature, { encoding: "base64", commitment: "confirmed", maxSupportedTransactionVersion: 1 }], deadline);
187
+ if (result !== null) {
188
+ const meta = isObject(result) ? result["meta"] : undefined;
189
+ return { fee: int(isObject(meta) ? meta["fee"] : undefined, "the fee"), included: true };
190
+ }
191
+ if (given === undefined)
192
+ throw new NodeError("malformed", true, `the node holds no transaction ${signature}`);
193
+ return { fee: feeBound(given), included: false };
194
+ }
@@ -0,0 +1,6 @@
1
+ import type { BatchPendingSettlementStore, PaymentChannelStorage } from "@x402/svm/batch-settlement/facilitator";
2
+ import type { ModuleState } from "../../module.js";
3
+ /** x402's `PaymentChannelStorage` over the module's state, with the semantics of its in-memory reference store. */
4
+ export declare function channelStorage(state: ModuleState): PaymentChannelStorage;
5
+ /** The batch-settlement class's pending signatures over the module's state, its reserve and release each one swap. */
6
+ export declare function batchPendingStore(state: ModuleState): BatchPendingSettlementStore;