@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,343 @@
1
+ /**
2
+ * `x402/exact/hedera/transfer-executor`: the settler's own module for x402's `transferExecutor` method of the `exact`
3
+ * scheme on Hedera (x402's `specs/schemes/exact/scheme_exact_hedera.md`, *Executor interface*, *Executor admission*,
4
+ * Phase 3 and Phase 4). The payer signs no Hedera transaction: it gives an executor contract and an authorization that
5
+ * contract validates. The module admits only the executors it is given, builds
6
+ * `executeTransfer(from = payer, asset, to = payTo, amount, authorization)` from the requirements and the payload alone,
7
+ * simulates it through the Mirror Node from the account it submits from, at the gas limit it submits with, wraps it in
8
+ * a `ContractExecuteTransaction` that its fee payer signs and pays for, and judges the outcome by the transaction's
9
+ * record merged with its child records and by the contract's logs.
10
+ *
11
+ * The settler's configuration names no executor, so no settler started from configuration admits one: this module is
12
+ * built by whoever gives it its executors and is not started by the Hedera module's `starter`. Its key signs and pays
13
+ * for a transaction of its own that carries the payer's authorization (`extra.key` `relayer`).
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ import { AccountId, ContractExecuteTransaction, ContractId, Hbar, TransactionId } from "@hiero-ledger/sdk";
17
+ import { isRefusal } from "@integraledger/lcp";
18
+ import { exactHederaExecutor } from "@integraledger/lcp/hedera";
19
+ import { isObject } from "../../answers.js";
20
+ import { sleep } from "../../http.js";
21
+ import { outcomeOf } from "../../module.js";
22
+ import { mirrorOf, reasonOf } from "./index.js";
23
+ import { mirrorCall, mirrorId, mirrorReader, spelledAsSent } from "./mirror.js";
24
+ /** `executeTransfer(address,address,address,uint256,bytes)`, as x402's specification states its selector. */
25
+ export const EXECUTE_TRANSFER = "ea8f19fd";
26
+ /** The ERC-20 `Transfer(address,address,uint256)` event's topic. */
27
+ const TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
28
+ /** HIP-406's staking reward account, which pays the rewards a record lists in `staking_reward_transfers`. */
29
+ const STAKING_REWARD_ACCOUNT = "0.0.800";
30
+ /** How often `settle` asks the Mirror Node for the record while it waits. */
31
+ const RECORD_POLL_MS = 1_000;
32
+ const ENTITY = /^(0|[1-9]\d{0,18})\.(0|[1-9]\d{0,18})\.(0|[1-9]\d{0,18})$/;
33
+ /** An entity's long-zero EVM address: shard in 4 bytes, realm and number in 8 each, as Hedera addresses a contract. */
34
+ export function longZero(entity) {
35
+ const m = ENTITY.exec(entity);
36
+ if (m === null)
37
+ throw new TypeError(`not an entity id: ${entity}`);
38
+ const hex = (v, bytes) => BigInt(v).toString(16).padStart(bytes * 2, "0");
39
+ return `0x${hex(m[1], 4)}${hex(m[2], 8)}${hex(m[3], 8)}`;
40
+ }
41
+ const word = (hex) => hex.replace(/^0x/, "").padStart(64, "0");
42
+ /** The call data of `executeTransfer(from, asset, to, amount, authorization)`, ABI-encoded. */
43
+ export function executeTransferData(a) {
44
+ const bytes = a.authorization.replace(/^0x/, "");
45
+ const padded = bytes.padEnd(Math.ceil(bytes.length / 64) * 64, "0");
46
+ return (EXECUTE_TRANSFER +
47
+ word(a.from) +
48
+ word(a.asset) +
49
+ word(a.to) +
50
+ word(a.amount.toString(16)) +
51
+ word((5 * 32).toString(16)) +
52
+ word((bytes.length / 2).toString(16)) +
53
+ padded);
54
+ }
55
+ function callOf(payload) {
56
+ const p = payload.payload;
57
+ if (!isObject(p))
58
+ return undefined;
59
+ const { payer, executor, authorization } = p;
60
+ if (typeof payer !== "string" || typeof executor !== "string" || typeof authorization !== "string")
61
+ return undefined;
62
+ return { payer, executor, authorization };
63
+ }
64
+ const fail = (requirements, reason, payer = "", transaction = "") => ({
65
+ success: false,
66
+ errorReason: reason,
67
+ network: requirements.network,
68
+ transaction,
69
+ payer,
70
+ });
71
+ function add(nets, asset, account, amount) {
72
+ const m = nets.get(asset) ?? new Map();
73
+ m.set(account, (m.get(account) ?? 0n) + amount);
74
+ nets.set(asset, m);
75
+ }
76
+ function int(v) {
77
+ return typeof v === "number" && Number.isSafeInteger(v) ? BigInt(v) : typeof v === "string" && /^-?\d+$/.test(v) ? BigInt(v) : undefined;
78
+ }
79
+ /**
80
+ * Phase 4, rule 3, over the record merged with its child records: the payee credited exactly `amount` in the asset; the
81
+ * payer debited `amount`, the fee payer the fee, and no other account; nothing else moved but the fee's distribution
82
+ * in HBAR; no NFT changed owner; and no log records an ERC-20 transfer out of the fee payer's address. A staking reward
83
+ * the record lists (HIP-406) is taken out of the account it credits and out of the reward account's debit. The reason
84
+ * of the first rule that fails, or the fee the record charged.
85
+ */
86
+ export function judgeRecord(entries, logs, t) {
87
+ const parent = entries.find((e) => e["nonce"] === 0 && e["scheduled"] === false);
88
+ if (parent === undefined)
89
+ return { reason: "settlement_check_failed" };
90
+ if (parent["result"] !== "SUCCESS")
91
+ return { reason: "settlement_status_not_success" };
92
+ const fee = int(parent["charged_tx_fee"]);
93
+ if (fee === undefined)
94
+ return { reason: "settlement_check_failed" };
95
+ const nets = new Map();
96
+ for (const e of entries) {
97
+ if (e !== parent && (e["scheduled"] !== false || typeof e["nonce"] !== "number" || e["nonce"] === 0))
98
+ continue;
99
+ if (e !== parent && e["result"] !== "SUCCESS")
100
+ continue;
101
+ for (const r of Array.isArray(e["transfers"]) ? e["transfers"] : []) {
102
+ const amount = isObject(r) ? int(r["amount"]) : undefined;
103
+ if (amount === undefined || typeof r["account"] !== "string")
104
+ return { reason: "settlement_check_failed" };
105
+ add(nets, "0.0.0", r["account"], amount);
106
+ }
107
+ for (const r of Array.isArray(e["staking_reward_transfers"]) ? e["staking_reward_transfers"] : []) {
108
+ const amount = isObject(r) ? int(r["amount"]) : undefined;
109
+ if (amount === undefined || typeof r["account"] !== "string")
110
+ return { reason: "settlement_check_failed" };
111
+ add(nets, "0.0.0", r["account"], -amount);
112
+ add(nets, "0.0.0", STAKING_REWARD_ACCOUNT, amount);
113
+ }
114
+ for (const r of Array.isArray(e["token_transfers"]) ? e["token_transfers"] : []) {
115
+ const amount = isObject(r) ? int(r["amount"]) : undefined;
116
+ if (amount === undefined || typeof r["account"] !== "string" || typeof r["token_id"] !== "string") {
117
+ return { reason: "settlement_check_failed" };
118
+ }
119
+ add(nets, r["token_id"], r["account"], amount);
120
+ }
121
+ if (Array.isArray(e["nft_transfers"]) && e["nft_transfers"].length > 0)
122
+ return { reason: "settlement_unexpected_transfer" };
123
+ }
124
+ for (const [asset, m] of nets) {
125
+ if (asset !== "0.0.0" && asset !== t.asset && [...m.values()].some((v) => v !== 0n)) {
126
+ return { reason: "settlement_unexpected_transfer" };
127
+ }
128
+ }
129
+ const of = (asset, account) => nets.get(asset)?.get(account) ?? 0n;
130
+ const hbar = t.asset === "0.0.0";
131
+ if (of(t.asset, t.payTo) !== t.amount)
132
+ return { reason: "settlement_payee_credit_mismatch" };
133
+ // Debits: in HBAR the payer's amount (where HBAR is the asset) and the fee payer's fee; in a token the payer's amount.
134
+ if (t.payer === t.feePayer && hbar) {
135
+ if (of("0.0.0", t.payer) !== -(t.amount + fee))
136
+ return { reason: "settlement_payer_debit_mismatch" };
137
+ }
138
+ else {
139
+ if (of(t.asset, t.payer) !== -t.amount)
140
+ return { reason: "settlement_payer_debit_mismatch" };
141
+ if (of("0.0.0", t.feePayer) !== -fee)
142
+ return { reason: "settlement_fee_payer_debit_mismatch" };
143
+ }
144
+ for (const [asset, m] of nets) {
145
+ for (const [account, v] of m) {
146
+ if (v < 0n && !(account === t.payer && asset === t.asset) && !(account === t.feePayer && asset === "0.0.0")) {
147
+ return { reason: "settlement_unexpected_debit" };
148
+ }
149
+ }
150
+ }
151
+ // Credits beside the payee's: in HBAR, the fee's distribution, which sums to the fee; in a token, none.
152
+ const others = (asset) => [...(nets.get(asset) ?? new Map())].filter(([a, v]) => v > 0n && !(asset === t.asset && a === t.payTo));
153
+ if (others("0.0.0").reduce((s, [, v]) => s + v, 0n) !== fee)
154
+ return { reason: "settlement_check_failed" };
155
+ if (!hbar && others(t.asset).length > 0)
156
+ return { reason: "settlement_check_failed" };
157
+ const feePayerTopic = `0x${word(t.feePayerEvm)}`.toLowerCase();
158
+ for (const l of logs) {
159
+ const topics = Array.isArray(l["topics"]) ? l["topics"].map((x) => String(x).toLowerCase()) : [];
160
+ if (topics[0] === TRANSFER_TOPIC && topics[1] === feePayerTopic)
161
+ return { reason: "settlement_unexpected_transfer" };
162
+ }
163
+ return { fee };
164
+ }
165
+ /** The transfer-executor module on the Hedera module's network, admitting `offering.executors` alone. */
166
+ export function transferExecutorModule(c, offering) {
167
+ const network = c.network;
168
+ const mirror = mirrorOf(c);
169
+ const feePayer = offering.signer.accountId;
170
+ /** An account's EVM address as the Mirror Node gives it (its alias, or its long-zero form); undefined if unknown. */
171
+ async function evmOf(account, deadline) {
172
+ const a = await mirrorCall(`${mirror.base.replace(/\/+$/, "")}/api/v1/accounts/${encodeURIComponent(account)}`, deadline);
173
+ const evm = isObject(a) ? a["evm_address"] : undefined;
174
+ return typeof evm === "string" && /^0x[0-9a-fA-F]{40}$/.test(evm) ? evm.toLowerCase() : undefined;
175
+ }
176
+ /** Whether the HTS token holds a custom fee schedule, under which `exact` cannot hold. */
177
+ async function customFees(token, deadline) {
178
+ const a = await mirrorCall(`${mirror.base.replace(/\/+$/, "")}/api/v1/tokens/${encodeURIComponent(token)}`, deadline);
179
+ const fees = isObject(a) ? a["custom_fees"] : undefined;
180
+ if (!isObject(fees))
181
+ return false;
182
+ return ["fixed_fees", "fractional_fees", "royalty_fees"].some((k) => Array.isArray(fees[k]) && fees[k].length > 0);
183
+ }
184
+ /** Phase 3: admission, the asset, the addresses, then the call built and simulated; the call's data where it passes. */
185
+ async function phase3(payload, requirements, deadline) {
186
+ const call = callOf(payload);
187
+ if (call === undefined || requirements.extra?.["assetTransferMethod"] !== "transferExecutor") {
188
+ return { invalid: "invalid_payload", payer: "" };
189
+ }
190
+ if (!offering.executors.includes(call.executor))
191
+ return { invalid: "invalid_exact_hedera_executor_not_admitted", payer: call.payer };
192
+ if (requirements.asset !== "0.0.0" && (await customFees(requirements.asset, deadline))) {
193
+ return { invalid: "invalid_exact_hedera_custom_fee_asset", payer: call.payer };
194
+ }
195
+ const [from, to, feePayerEvm] = await Promise.all([
196
+ evmOf(call.payer, deadline),
197
+ evmOf(requirements.payTo, deadline),
198
+ evmOf(feePayer, deadline),
199
+ ]);
200
+ if (from === undefined || to === undefined || feePayerEvm === undefined)
201
+ return { invalid: "address_resolution_failed", payer: call.payer };
202
+ const asset = requirements.asset === "0.0.0" ? `0x${"0".repeat(40)}` : longZero(requirements.asset);
203
+ const data = executeTransferData({ from, asset, to, amount: BigInt(requirements.amount), authorization: call.authorization });
204
+ const simulated = await mirrorCall(`${mirror.base.replace(/\/+$/, "")}/api/v1/contracts/call`, deadline, {
205
+ block: "latest",
206
+ data: `0x${data}`,
207
+ estimate: false,
208
+ from: feePayerEvm,
209
+ gas: offering.gas,
210
+ to: longZero(call.executor),
211
+ });
212
+ if (!isObject(simulated) || "reverted" in simulated)
213
+ return { invalid: "simulation_reverted", payer: call.payer };
214
+ return { call, data, feePayerEvm };
215
+ }
216
+ const facilitator = {
217
+ scheme: "exact",
218
+ caipFamily: "hedera:*",
219
+ getExtra: () => ({ assetTransferMethod: "transferExecutor", executors: [...offering.executors] }),
220
+ getSigners: () => [feePayer],
221
+ async verify(payload, requirements) {
222
+ const v = await phase3(payload, requirements, performance.now() + offering.settleWaitMs);
223
+ if ("invalid" in v)
224
+ return { isValid: false, invalidReason: v.invalid, payer: v.payer };
225
+ return { isValid: true, payer: v.call.payer };
226
+ },
227
+ async settle(payload, requirements) {
228
+ const deadline = performance.now() + offering.settleWaitMs;
229
+ // Phase 3 again, admission among it, before anything is submitted.
230
+ const v = await phase3(payload, requirements, deadline);
231
+ if ("invalid" in v)
232
+ return fail(requirements, v.invalid, v.payer);
233
+ const id = TransactionId.generate(AccountId.fromString(feePayer));
234
+ const tx = new ContractExecuteTransaction()
235
+ .setTransactionId(id)
236
+ .setContractId(ContractId.fromString(v.call.executor))
237
+ .setGas(offering.gas)
238
+ .setFunctionParameters(Buffer.from(v.data, "hex"))
239
+ .setMaxTransactionFee(Hbar.fromTinybars(offering.maxFee.toString()));
240
+ const named = id.toString();
241
+ const mirrored = mirrorId(named);
242
+ if (!(await offering.meter.sending({ network, transaction: mirrored, bound: offering.maxFee }))) {
243
+ return fail(requirements, "fee_budget_spent", v.call.payer);
244
+ }
245
+ try {
246
+ await offering.signer.execute(tx, network);
247
+ }
248
+ catch {
249
+ // Whether it reached a node is not known: the transaction it would be is named, and the read decides.
250
+ return fail(requirements, "settlement_pending", v.call.payer, named);
251
+ }
252
+ // Phase 4: the record with its child records, merged, and the contract's logs, nested calls' included.
253
+ const reader = mirrorReader(mirror, deadline);
254
+ for (;;) {
255
+ let entries = null;
256
+ let logs = null;
257
+ try {
258
+ entries = (await reader.transactions(mirrored));
259
+ if (entries !== null)
260
+ logs = await mirrorCall(`${mirror.base.replace(/\/+$/, "")}/api/v1/contracts/results/${encodeURIComponent(mirrored)}`, deadline);
261
+ }
262
+ catch {
263
+ entries = null;
264
+ }
265
+ if (entries !== null && isObject(logs) && Array.isArray(logs["logs"])) {
266
+ const judged = judgeRecord(entries, logs["logs"].filter(isObject), {
267
+ asset: requirements.asset,
268
+ payTo: requirements.payTo,
269
+ amount: BigInt(requirements.amount),
270
+ payer: v.call.payer,
271
+ feePayer,
272
+ feePayerEvm: v.feePayerEvm,
273
+ });
274
+ const fee = (entries.find((e) => e["nonce"] === 0 && e["scheduled"] === false) ?? {})["charged_tx_fee"];
275
+ if (typeof fee === "number")
276
+ offering.meter.included({ network, transaction: mirrored, fee: BigInt(fee) });
277
+ if ("reason" in judged)
278
+ return fail(requirements, judged.reason, v.call.payer, named);
279
+ return { success: true, transaction: named, network: requirements.network, payer: v.call.payer };
280
+ }
281
+ if (performance.now() + RECORD_POLL_MS > deadline)
282
+ return fail(requirements, "settlement_pending", v.call.payer, named);
283
+ await sleep(RECORD_POLL_MS);
284
+ }
285
+ },
286
+ };
287
+ return {
288
+ descriptor: { name: "hedera", key: "relayer", pairings: [exactHederaExecutor.id], acceptsZero: [] },
289
+ network,
290
+ facilitator,
291
+ record: {
292
+ async instrument(p) {
293
+ const ref = await exactHederaExecutor.reference(p.payload, p.requirements);
294
+ if (isRefusal(ref))
295
+ return { refused: reasonOf(ref), message: ref.code };
296
+ const call = callOf(p.payload);
297
+ // x402's specification keys a payment in flight by the hash of (network, executor, payer, authorization); the
298
+ // executor, not the transaction id, holds the authorization single-use.
299
+ const digest = createHash("sha256")
300
+ .update(JSON.stringify([network, call.executor, call.payer, call.authorization.toLowerCase()]))
301
+ .digest("hex");
302
+ return { pairing: exactHederaExecutor.id, instrument: { by: "digest", network, digest: `0x${digest}` }, nonce: exactHederaExecutor.data.nonce, keep: { until: "settler" } };
303
+ },
304
+ async read(p, at) {
305
+ // The act is the transaction the module named; with none named there is nothing to read.
306
+ if (at.transaction === undefined)
307
+ return outcomeOf({ state: "pending", reason: "not-found", foreign: [] });
308
+ const ref = await exactHederaExecutor.reference(p.payload, p.requirements);
309
+ if (isRefusal(ref))
310
+ return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
311
+ const transaction = mirrorId(at.transaction) ?? at.transaction;
312
+ const reader = mirrorReader(mirror, at.deadline);
313
+ const answer = spelledAsSent(await exactHederaExecutor.status({ ...ref, transaction }, reader, { act: "payment", finality: "consensus" }));
314
+ if (answer.state !== "settled")
315
+ return outcomeOf(answer);
316
+ // lcp's read judges no amount; x402's Phase 4 does. A record that fails it consumed the authorization and paid
317
+ // otherwise than the option: final, and failed.
318
+ const call = callOf(p.payload);
319
+ const [entries, logs, feePayerEvm] = await Promise.all([
320
+ reader.transactions(transaction),
321
+ mirrorCall(`${mirror.base.replace(/\/+$/, "")}/api/v1/contracts/results/${encodeURIComponent(transaction)}`, at.deadline),
322
+ evmOf(feePayer, at.deadline),
323
+ ]);
324
+ const judged = judgeRecord((entries ?? []), isObject(logs) && Array.isArray(logs["logs"]) ? logs["logs"].filter(isObject) : [], {
325
+ asset: p.requirements.asset,
326
+ payTo: p.requirements.payTo,
327
+ amount: BigInt(p.requirements.amount),
328
+ payer: call.payer,
329
+ feePayer,
330
+ feePayerEvm: feePayerEvm ?? "",
331
+ });
332
+ if ("reason" in judged)
333
+ return outcomeOf({ state: "failed", reason: "transaction-failed", transaction: answer.transaction, foreign: [] });
334
+ return outcomeOf(answer);
335
+ },
336
+ },
337
+ fees: {
338
+ // An own module: it asks the meter before it submits, and tells it the fee the record shows.
339
+ paysFee: () => true,
340
+ payerBroadcast: () => false,
341
+ },
342
+ };
343
+ }
@@ -0,0 +1,23 @@
1
+ import { type Refusal } from "@integraledger/lcp";
2
+ import { type HederaNetwork } from "@integraledger/lcp/hedera";
3
+ import type { FacilitatorHederaSigner } from "@x402/hedera";
4
+ import { type Module, type ModuleStarter, type Registration } from "../../module.js";
5
+ import { type Mirror } from "./mirror.js";
6
+ export interface HederaConfig {
7
+ /** The network, exactly one. */
8
+ readonly network: HederaNetwork;
9
+ /** The seller's fee-payer account and its key, as `@x402/hedera`'s facilitator class takes them. */
10
+ readonly signer: FacilitatorHederaSigner;
11
+ /** The seller's Mirror Node, its REST interface's base URL, which lcp's read and the fee count use. */
12
+ readonly mirror: string;
13
+ /** Whether that Mirror Node holds every record since the network began. */
14
+ readonly archival?: boolean;
15
+ }
16
+ /** The x402 reason for one of lcp's refusals: the version, the option, or else the payload. */
17
+ export declare function reasonOf(r: Refusal): string;
18
+ export declare function mirrorOf(c: HederaConfig): Mirror;
19
+ /** The module of `x402/exact/hedera` on the configured network. */
20
+ export declare function hederaModule(c: HederaConfig): Module;
21
+ export declare function hederaRegistration(c: HederaConfig): Registration;
22
+ /** The module's start: one registration of `exact` per configured network. */
23
+ export declare const starter: ModuleStarter<readonly HederaConfig[]>;
@@ -0,0 +1,136 @@
1
+ /**
2
+ * The Hedera module for `x402/exact/hedera` on each configured network: `@x402/hedera` 2.31.0's facilitator class,
3
+ * registered unchanged. The class takes only a payment whose transaction id names an account the facilitator manages
4
+ * as `extra.feePayer`, so the key is always the seller's fee-payer account's (`extra.key` `fee-payer`): it signs the
5
+ * buyer's transfer as the account that pays its fee. It reaches the module as the `FacilitatorHederaSigner` the class
6
+ * takes, and its account is in `signers` and the class's `extra.feePayer`. lcp's checks of the pairing come first and
7
+ * name the instrument; lcp's read goes through the seller's Mirror Node.
8
+ *
9
+ * The transfer-executor form, `x402/exact/hedera/transfer-executor`, is built in `./executor.ts` and is not started
10
+ * from configuration: no member of this configuration names an executor, and x402's specification of the method
11
+ * admits none by default.
12
+ */
13
+ import { setTimeout as sleep } from "node:timers/promises";
14
+ import { isRefusal } from "@integraledger/lcp";
15
+ import { exactHedera } from "@integraledger/lcp/hedera";
16
+ import { ExactHederaScheme } from "@x402/hedera/exact/facilitator";
17
+ import { outcomeOf, } from "../../module.js";
18
+ import { chargedFee, mirrorId, mirrorReader, sdkId, spelledAsSent } from "./mirror.js";
19
+ /** The x402 reason for one of lcp's refusals: the version, the option, or else the payload. */
20
+ export function reasonOf(r) {
21
+ if (r.code === "x402/not-v2")
22
+ return "invalid_x402_version";
23
+ if (r.code.startsWith("x402/option") || r.code === "hedera/option-malformed")
24
+ return "invalid_payment_requirements";
25
+ return "invalid_payload";
26
+ }
27
+ export function mirrorOf(c) {
28
+ return { network: c.network, base: c.mirror, archival: c.archival === true };
29
+ }
30
+ /** lcp's checks of the payment, which read neither the chain nor the clock, and its read keys; or the refusal. */
31
+ async function checked(p) {
32
+ const bound = await exactHedera.bound(p.payload);
33
+ if (isRefusal(bound))
34
+ return bound;
35
+ // The requirements arrive as JSON, which lcp's option type names.
36
+ return exactHedera.reference(p.payload, p.requirements);
37
+ }
38
+ /** How long `charged` waits before it asks the mirror again for a transaction it does not hold yet. */
39
+ const MIRROR_POLL_MS = 250;
40
+ /** The time after which a body can no longer land: its valid start plus its valid duration, in Unix milliseconds. */
41
+ function lapseOf(ref) {
42
+ const [seconds, nanos] = ref.validStart.split(".");
43
+ return { until: "lapse", at: (Number(seconds) + ref.validDuration) * 1000 + Math.ceil(Number(nanos ?? "0") / 1e6) };
44
+ }
45
+ /**
46
+ * The class, its settle naming the payment's own transaction id where it answers `transaction_failed` naming none: the
47
+ * class answers so a submission that threw, which a node may have taken, and the id, the payer's, is known before the
48
+ * send, so the record holds it, lcp's read reads it and the fee budget counts it.
49
+ */
50
+ function naming(cls) {
51
+ return {
52
+ scheme: cls.scheme,
53
+ caipFamily: cls.caipFamily,
54
+ getExtra: (n) => cls.getExtra(n),
55
+ getSigners: (n) => cls.getSigners(n),
56
+ verify: (payload, requirements, context) => cls.verify(payload, requirements, context),
57
+ async settle(payload, requirements, context) {
58
+ const s = await cls.settle(payload, requirements, context);
59
+ if (s.success || s.transaction !== "" || s.errorReason !== "transaction_failed")
60
+ return s;
61
+ const ref = await checked({ payload, requirements });
62
+ return isRefusal(ref) ? s : { ...s, transaction: sdkId(ref.transactionId) ?? ref.transactionId };
63
+ },
64
+ };
65
+ }
66
+ /** The module of `x402/exact/hedera` on the configured network. */
67
+ export function hederaModule(c) {
68
+ const network = c.network;
69
+ const mirror = mirrorOf(c);
70
+ return {
71
+ // A zero transfer is not established on Hedera, so the kind does not take zero.
72
+ descriptor: { name: "hedera", key: "fee-payer", pairings: [exactHedera.id], acceptsZero: [] },
73
+ network,
74
+ facilitator: naming(new ExactHederaScheme(c.signer)),
75
+ record: {
76
+ async instrument(p) {
77
+ const ref = await checked(p);
78
+ if (isRefusal(ref))
79
+ return { refused: reasonOf(ref), message: ref.code };
80
+ return {
81
+ pairing: exactHedera.id,
82
+ // The transaction id, the payment's single-use value (profile rule 9), and its payer: every body of a list is
83
+ // the same payment (rule 6), so a list reordered or trimmed is the same instrument, and the chain takes one
84
+ // transaction under the id.
85
+ instrument: { by: "single-use", network, signer: ref.payer, value: ref.transactionId },
86
+ nonce: exactHedera.data.nonce,
87
+ keep: lapseOf(ref),
88
+ };
89
+ },
90
+ async read(p, at) {
91
+ const ref = await checked(p);
92
+ if (isRefusal(ref))
93
+ return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
94
+ const search = at.search;
95
+ const answer = await exactHedera.status(ref, mirrorReader(mirror, at.deadline), {
96
+ act: "payment",
97
+ finality: "consensus",
98
+ ...(search === undefined ? {} : { search }),
99
+ });
100
+ return outcomeOf(spelledAsSent(answer));
101
+ },
102
+ },
103
+ fees: {
104
+ // The class makes the configured fee payer the account of the transaction id, which pays the fee.
105
+ paysFee: () => true,
106
+ payerBroadcast: () => false,
107
+ // The mirror holds a transaction seconds after consensus, so it is asked until the deadline; only then is the
108
+ // transaction counted at its bound, the maxFee the payer signed, which a failed read also leaves.
109
+ async charged(p, sent) {
110
+ const id = mirrorId(sent.transaction) ?? sent.transaction;
111
+ for (;;) {
112
+ const fee = await chargedFee(mirror, id, sent.deadline).catch(() => undefined);
113
+ if (fee !== undefined)
114
+ return { fee, included: true };
115
+ if (performance.now() + MIRROR_POLL_MS >= sent.deadline)
116
+ break;
117
+ await sleep(MIRROR_POLL_MS);
118
+ }
119
+ const ref = await checked(p);
120
+ if (isRefusal(ref))
121
+ throw new TypeError(`a payment lcp refuses was sent: ${ref.code}`);
122
+ return { fee: BigInt(ref.presented.maxFee), included: false };
123
+ },
124
+ },
125
+ };
126
+ }
127
+ export function hederaRegistration(c) {
128
+ return { network: c.network, module: hederaModule(c), own: [] };
129
+ }
130
+ /** The module's start: one registration of `exact` per configured network. */
131
+ export const starter = {
132
+ name: "hedera",
133
+ async start(config) {
134
+ return { registrations: config.map(hederaRegistration) };
135
+ },
136
+ };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The Hedera Mirror Node's REST interface, bounded: lcp's `HederaReader` over it, and the reads the modules make beside
3
+ * lcp's read (a transaction's charged fee, an account's EVM address, a contract call simulated). Every call ends by the
4
+ * deadline it is given, a `performance.now()` time, and every failure rejects.
5
+ */
6
+ import type { HederaNetwork, HederaReader } from "@integraledger/lcp/hedera";
7
+ /** One bounded HTTP call of the mirror: the JSON answer, or `null` for a 404, the mirror's answer for what it does not hold. */
8
+ export declare function mirrorCall(url: string, deadline: number, body?: unknown): Promise<unknown>;
9
+ /** The mirror at `base` for `network`, its calls ending by `deadline`. */
10
+ export interface Mirror {
11
+ readonly network: HederaNetwork;
12
+ readonly base: string;
13
+ readonly archival: boolean;
14
+ }
15
+ /** lcp's reader over the mirror, as `HederaReader` names each call. */
16
+ export declare function mirrorReader(m: Mirror, deadline: number): HederaReader;
17
+ /** A transaction id as the SDK writes it, `0.0.n@seconds.nanos`, in the mirror's form `0.0.n-seconds-nanos`. */
18
+ export declare function mirrorId(sdkId: string): string | undefined;
19
+ /**
20
+ * The fee the mirror shows the transaction `id` (mirror form) charged its fee payer: the `charged_tx_fee` of its own
21
+ * entry, the one that is no child (`nonce` 0) and not scheduled; undefined where the mirror holds none yet.
22
+ */
23
+ export declare function chargedFee(m: Mirror, id: string, deadline: number): Promise<bigint | undefined>;
24
+ /** A transaction id in the mirror's form, `0.0.n-seconds-nanos`, as the SDK writes it, `0.0.n@seconds.nanos`. */
25
+ export declare function sdkId(mirror: string): string | undefined;
26
+ /**
27
+ * lcp's answer with the transaction it names spelled as the module's settle names it, the SDK's form, so that the
28
+ * settler tells the transaction it sent from another by its id alone.
29
+ */
30
+ export declare function spelledAsSent<A extends {
31
+ readonly state: string;
32
+ }>(answer: A): A;
@@ -0,0 +1,111 @@
1
+ import { isObject } from "../../answers.js";
2
+ import { NODE_MAX_BYTES, NODE_TIMEOUT_MS, NodeError, site } from "../../http.js";
3
+ /** One bounded HTTP call of the mirror: the JSON answer, or `null` for a 404, the mirror's answer for what it does not hold. */
4
+ export async function mirrorCall(url, deadline, body) {
5
+ const ms = Math.min(NODE_TIMEOUT_MS, deadline - performance.now());
6
+ if (ms <= 0)
7
+ throw new NodeError("spent", false, site(url));
8
+ let res;
9
+ try {
10
+ res = await fetch(url, {
11
+ method: body === undefined ? "GET" : "POST",
12
+ headers: { accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }) },
13
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
14
+ signal: AbortSignal.timeout(Math.ceil(ms)),
15
+ });
16
+ }
17
+ catch (e) {
18
+ throw new NodeError("transport", true, e instanceof Error ? e.message : String(e), { cause: e });
19
+ }
20
+ const text = await res.text();
21
+ if (text.length > NODE_MAX_BYTES)
22
+ throw new NodeError("too-large", true, site(url));
23
+ if (res.status === 404)
24
+ return null;
25
+ let json;
26
+ try {
27
+ json = JSON.parse(text);
28
+ }
29
+ catch (e) {
30
+ throw new NodeError("malformed", true, "the answer is not JSON", { cause: e });
31
+ }
32
+ // A contract call the EVM reverted is answered 400 with the revert's messages: the caller reads them.
33
+ if (res.status === 400 && body !== undefined)
34
+ return { reverted: json };
35
+ if (res.status < 200 || res.status > 299)
36
+ throw new NodeError("http-status", true, `status ${res.status}`);
37
+ return json;
38
+ }
39
+ function blockEdge(answer, edge) {
40
+ const blocks = isObject(answer) ? answer["blocks"] : undefined;
41
+ const first = Array.isArray(blocks) ? blocks[0] : undefined;
42
+ const timestamp = isObject(first) ? first["timestamp"] : undefined;
43
+ const t = isObject(timestamp) ? timestamp[edge] : undefined;
44
+ if (typeof t !== "string")
45
+ throw new NodeError("malformed", true, "a block's timestamp");
46
+ return t;
47
+ }
48
+ /** lcp's reader over the mirror, as `HederaReader` names each call. */
49
+ export function mirrorReader(m, deadline) {
50
+ const base = m.base.replace(/\/+$/, "");
51
+ const get = (path) => mirrorCall(`${base}${path}`, deadline);
52
+ return {
53
+ network: m.network,
54
+ async transactions(mirrorId) {
55
+ const a = await get(`/api/v1/transactions/${encodeURIComponent(mirrorId)}`);
56
+ if (a === null)
57
+ return null;
58
+ if (!isObject(a) || !Array.isArray(a["transactions"]))
59
+ throw new NodeError("malformed", true, "a transaction lookup");
60
+ return a["transactions"];
61
+ },
62
+ async latest() {
63
+ return blockEdge(await get("/api/v1/blocks?order=desc&limit=1"), "to");
64
+ },
65
+ async oldest() {
66
+ if (m.archival)
67
+ return "archival";
68
+ return blockEdge(await get("/api/v1/blocks?order=asc&limit=1"), "from");
69
+ },
70
+ async accountTransactions(q) {
71
+ const query = new URLSearchParams({ "account.id": q.account, order: "asc", limit: "100" });
72
+ query.append("timestamp", `gt:${q.after}`);
73
+ query.append("timestamp", `lte:${q.until}`);
74
+ const a = await get(`/api/v1/transactions?${query}`);
75
+ if (!isObject(a) || !Array.isArray(a["transactions"]))
76
+ throw new NodeError("malformed", true, "an account page");
77
+ const links = a["links"];
78
+ const next = isObject(links) && typeof links["next"] === "string" ? links["next"] : null;
79
+ return { transactions: a["transactions"], next };
80
+ },
81
+ };
82
+ }
83
+ /** A transaction id as the SDK writes it, `0.0.n@seconds.nanos`, in the mirror's form `0.0.n-seconds-nanos`. */
84
+ export function mirrorId(sdkId) {
85
+ const m = /^(\d+\.\d+\.\d+)@(\d+)\.(\d+)$/.exec(sdkId);
86
+ return m === null ? undefined : `${m[1]}-${m[2]}-${m[3]}`;
87
+ }
88
+ /**
89
+ * The fee the mirror shows the transaction `id` (mirror form) charged its fee payer: the `charged_tx_fee` of its own
90
+ * entry, the one that is no child (`nonce` 0) and not scheduled; undefined where the mirror holds none yet.
91
+ */
92
+ export async function chargedFee(m, id, deadline) {
93
+ const entries = await mirrorReader(m, deadline).transactions(id);
94
+ const own = entries?.find((e) => e.nonce === 0 && e.scheduled === false);
95
+ const fee = own?.charged_tx_fee;
96
+ return typeof fee === "number" && Number.isSafeInteger(fee) && fee >= 0 ? BigInt(fee) : undefined;
97
+ }
98
+ /** A transaction id in the mirror's form, `0.0.n-seconds-nanos`, as the SDK writes it, `0.0.n@seconds.nanos`. */
99
+ export function sdkId(mirror) {
100
+ const m = /^(\d+\.\d+\.\d+)-(\d+)-(\d+)$/.exec(mirror);
101
+ return m === null ? undefined : `${m[1]}@${m[2]}.${m[3].padStart(9, "0")}`;
102
+ }
103
+ /**
104
+ * lcp's answer with the transaction it names spelled as the module's settle names it, the SDK's form, so that the
105
+ * settler tells the transaction it sent from another by its id alone.
106
+ */
107
+ export function spelledAsSent(answer) {
108
+ const named = answer.transaction;
109
+ const sdk = typeof named === "string" ? sdkId(named) : undefined;
110
+ return sdk === undefined ? answer : { ...answer, transaction: sdk };
111
+ }