@integraledger/profile-facilitator 0.1.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.
package/dist/tron.js ADDED
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Rule 5 of `x402/exact/tron/lcp-trc20-memo` against one network's FullNode: `/verify` checks the signed transaction
3
+ * against the requirements and simulates it; `/settle` repeats that, claims the transaction id, broadcasts, and polls
4
+ * for the receipt.
5
+ */
6
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
7
+ import { keccak_256 } from "@noble/hashes/sha3.js";
8
+ import { decodeTronTx, pairingOf, tronAddress, tronCarrier, tronStatus, } from "@integraledger/lcp/tron";
9
+ import { failed, invalid, isObject, isPending, operatorLog, pending, } from "./answers.js";
10
+ import { base58check } from "./base58check.js";
11
+ import { NODE_TIMEOUT_MS, NodeError, postJson, sleep } from "./http.js";
12
+ import { answerReserve, inTime } from "./store.js";
13
+ const POLL_MS = 1_000;
14
+ /** A verify reason as a settle answer's: a node that could not be read before submission is a settle error. */
15
+ function settleReason(r) {
16
+ return r === "unexpected_verify_error" ? "unexpected_settle_error" : r;
17
+ }
18
+ function refused(v) {
19
+ return isObject(v) && v["refused"] === true;
20
+ }
21
+ function hexOf(b) {
22
+ return Buffer.from(b).toString("hex");
23
+ }
24
+ function sameBytes(a, b) {
25
+ return a.length === b.length && a.every((x, i) => x === b[i]);
26
+ }
27
+ /** `transfer(payTo, amount)` call data: the selector, payTo's 20 bytes as a word, amount as a 32-byte word. */
28
+ function transferCall(payTo, amount) {
29
+ const out = new Uint8Array(68);
30
+ out.set([0xa9, 0x05, 0x9c, 0xbb], 0);
31
+ out.set(payTo.subarray(1), 16);
32
+ let v = amount;
33
+ for (let i = 67; i >= 36; i--) {
34
+ out[i] = Number(v & 0xffn);
35
+ v >>= 8n;
36
+ }
37
+ return out;
38
+ }
39
+ /** The Tron address (0x41 ‖ 20 bytes) whose key made the 65-byte signature over the transaction id. */
40
+ function signerOf(signature, txid) {
41
+ const v = signature[64];
42
+ const bit = v >= 27 ? v - 27 : v;
43
+ if (bit !== 0 && bit !== 1)
44
+ return undefined;
45
+ try {
46
+ const point = secp256k1.Signature.fromBytes(signature.subarray(0, 64), "compact")
47
+ .addRecoveryBit(bit)
48
+ .recoverPublicKey(txid);
49
+ const key = point.toBytes(false);
50
+ const out = new Uint8Array(21);
51
+ out[0] = 0x41;
52
+ out.set(keccak_256(key.subarray(1)).subarray(12), 1);
53
+ return out;
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
59
+ export function createTron(nodes, s, settleWaitMs) {
60
+ const byNetwork = new Map(nodes.map((n) => [n.network, n]));
61
+ /** Every check of rule 5 that reads neither the clock nor the node. */
62
+ async function check(r) {
63
+ const req = r.paymentRequirements;
64
+ if (!byNetwork.has(req.network))
65
+ return "invalid_network";
66
+ if (pairingOf(req) === undefined)
67
+ return "invalid_payment_requirements";
68
+ const hex = r.paymentPayload.payload["transaction"];
69
+ if (typeof hex !== "string")
70
+ return "invalid_payload";
71
+ const tx = decodeTronTx(hex);
72
+ if (refused(tx))
73
+ return "invalid_payload";
74
+ const carried = await tronCarrier(tx);
75
+ if (refused(carried))
76
+ return "invalid_payload";
77
+ const asset = await tronAddress(req.asset);
78
+ const payTo = await tronAddress(req.payTo);
79
+ if (refused(asset) || refused(payTo))
80
+ return "invalid_payment_requirements";
81
+ if (!sameBytes(tx.raw.contractAddress, asset))
82
+ return "invalid_payload";
83
+ if (!sameBytes(tx.raw.callData, transferCall(payTo, BigInt(req.amount))))
84
+ return "invalid_payload";
85
+ if (tx.signatures.length !== 1)
86
+ return "unsupported_permission";
87
+ const txid = carried.txid.slice(2);
88
+ const signer = signerOf(tx.signatures[0], Buffer.from(txid, "hex"));
89
+ if (signer === undefined || !sameBytes(signer, tx.raw.owner))
90
+ return "invalid_payload";
91
+ return {
92
+ network: req.network,
93
+ hex,
94
+ raw: tx.raw,
95
+ txid,
96
+ payer: base58check(tx.raw.owner),
97
+ maxTimeoutSeconds: req.maxTimeoutSeconds,
98
+ };
99
+ }
100
+ /** The expiration window, then the node's simulation of the call, within `timeoutMs`. */
101
+ async function checkNow(c, timeoutMs = NODE_TIMEOUT_MS) {
102
+ const now = BigInt(Date.now());
103
+ const expiration = c.raw.expiration;
104
+ if (expiration <= now || expiration > now + BigInt(c.maxTimeoutSeconds) * 1000n)
105
+ return "invalid_payload";
106
+ if (timeoutMs <= 0)
107
+ return "unexpected_verify_error";
108
+ let sim;
109
+ try {
110
+ sim = await postJson(`${byNetwork.get(c.network).fullNode}/wallet/triggerconstantcontract`, {
111
+ owner_address: hexOf(c.raw.owner),
112
+ contract_address: hexOf(c.raw.contractAddress),
113
+ function_selector: "transfer(address,uint256)",
114
+ parameter: hexOf(c.raw.callData.subarray(4)),
115
+ }, timeoutMs);
116
+ }
117
+ catch {
118
+ return "unexpected_verify_error";
119
+ }
120
+ if (!isObject(sim) || !isObject(sim["result"]))
121
+ return "unexpected_verify_error";
122
+ if (sim["result"]["result"] !== true)
123
+ return "invalid_transaction";
124
+ const ret = isObject(sim["transaction"]) ? sim["transaction"]["ret"] : undefined;
125
+ if (Array.isArray(ret) && ret.some((x) => isObject(x) && x["ret"] === "FAILED"))
126
+ return "invalid_transaction";
127
+ return null;
128
+ }
129
+ async function verify(r) {
130
+ const c = await check(r);
131
+ if (typeof c === "string")
132
+ return invalid(c);
133
+ const now = await checkNow(c);
134
+ return now === null ? { isValid: true, payer: c.payer } : invalid(now, c.payer);
135
+ }
136
+ /** A receipt's block and result from `gettransactioninfobyid` at `url`; undefined when there is none or it is unreadable. */
137
+ async function infoAt(url, c, deadline) {
138
+ let info;
139
+ try {
140
+ info = await postJson(`${url}/gettransactioninfobyid`, { value: c.txid }, deadline - performance.now());
141
+ }
142
+ catch {
143
+ return undefined;
144
+ }
145
+ if (!isObject(info) || typeof info["blockNumber"] !== "number")
146
+ return undefined;
147
+ const result = isObject(info["receipt"]) ? info["receipt"]["result"] : undefined;
148
+ return typeof result === "string" ? { result } : undefined;
149
+ }
150
+ /**
151
+ * One read of the transaction's receipt: success once the FullNode shows it in a block with `SUCCESS`; a failure only
152
+ * once the Solidity node, which serves solidified blocks alone, shows it with another result; else undefined.
153
+ */
154
+ async function receipt(c, deadline) {
155
+ const node = byNetwork.get(c.network);
156
+ const head = await infoAt(`${node.fullNode}/wallet`, c, deadline);
157
+ if (head === undefined)
158
+ return undefined;
159
+ const success = { success: true, transaction: c.txid, network: c.network, payer: c.payer };
160
+ if (head.result === "SUCCESS")
161
+ return success;
162
+ const solid = await infoAt(`${node.solidityNode}/walletsolidity`, c, deadline);
163
+ if (solid === undefined)
164
+ return undefined;
165
+ if (solid.result === "SUCCESS")
166
+ return success;
167
+ operatorLog({ event: "settlement-failed", network: c.network, transaction: c.txid, result: solid.result });
168
+ return failed("invalid_transaction_state", c.txid, c.network);
169
+ }
170
+ /** The profile's reads at the Solidity node and the FullNode, each bounded by `deadline`. */
171
+ function reader(c, deadline) {
172
+ const node = byNetwork.get(c.network);
173
+ const left = () => deadline - performance.now();
174
+ return {
175
+ network: c.network,
176
+ async info(txid, level) {
177
+ const url = level === "solid" ? `${node.solidityNode}/walletsolidity` : `${node.fullNode}/wallet`;
178
+ const o = await postJson(`${url}/gettransactioninfobyid`, { value: txid.replace(/^0x/, "") }, left());
179
+ if (!isObject(o))
180
+ throw new NodeError("malformed", true, "gettransactioninfobyid");
181
+ if (Object.keys(o).length === 0)
182
+ return null;
183
+ const blockNumber = o["blockNumber"];
184
+ const result = isObject(o["receipt"]) ? o["receipt"]["result"] : undefined;
185
+ if (!Number.isSafeInteger(blockNumber) || typeof result !== "string") {
186
+ throw new NodeError("malformed", true, "gettransactioninfobyid fields");
187
+ }
188
+ const logs = (Array.isArray(o["log"]) ? o["log"] : []).filter((l) => isObject(l) && typeof l["address"] === "string" && Array.isArray(l["topics"]));
189
+ return { blockNumber: BigInt(blockNumber), result, logs };
190
+ },
191
+ transaction() {
192
+ return Promise.reject(new NodeError("malformed", false, "not read by this facilitator"));
193
+ },
194
+ async solidHead() {
195
+ const o = await postJson(`${node.solidityNode}/walletsolidity/getnowblock`, {}, left());
196
+ const header = isObject(o) ? o["block_header"] : undefined;
197
+ const raw = isObject(header) ? header["raw_data"] : undefined;
198
+ const number = isObject(raw) ? raw["number"] : undefined;
199
+ const timestamp = isObject(raw) ? raw["timestamp"] : undefined;
200
+ if (!Number.isSafeInteger(number) || !Number.isSafeInteger(timestamp)) {
201
+ throw new NodeError("malformed", true, "getnowblock fields");
202
+ }
203
+ return { number: BigInt(number), timestamp: BigInt(timestamp) };
204
+ },
205
+ };
206
+ }
207
+ /**
208
+ * True once the reads prove the transaction can never be included: the profile's status finds it at no node, with the
209
+ * latest solidified block two slots past its expiration. Reads nothing while the local clock is before the expiration.
210
+ */
211
+ async function expired(c, deadline) {
212
+ if (BigInt(Date.now()) < c.raw.expiration)
213
+ return false;
214
+ const ref = {
215
+ network: c.network,
216
+ txid: `0x${c.txid}`,
217
+ asset: `0x${hexOf(c.raw.contractAddress)}`,
218
+ expiration: c.raw.expiration.toString(),
219
+ };
220
+ const st = await tronStatus(ref, reader(c, deadline));
221
+ return st.state === "failed" && st.why === "expired";
222
+ }
223
+ /**
224
+ * Reads the receipt every second until `deadline`, and the stored answer too when `stored` is set, answering with the
225
+ * first final answer either gives, or with `invalid_transaction_state` once the transaction can never be included.
226
+ * Broadcasts nothing.
227
+ */
228
+ async function watch(c, deadline, stored) {
229
+ for (;;) {
230
+ if (stored) {
231
+ const row = await inTime(s.read(c.network, c.txid), deadline).catch(() => undefined);
232
+ if (row?.state === "answered" && !isPending(row.answer))
233
+ return row.answer;
234
+ }
235
+ const final = await receipt(c, deadline);
236
+ if (final !== undefined)
237
+ return final;
238
+ if (await expired(c, deadline)) {
239
+ operatorLog({ event: "settlement-expired", network: c.network, transaction: c.txid });
240
+ return failed("invalid_transaction_state", c.txid, c.network);
241
+ }
242
+ if (performance.now() + POLL_MS > deadline)
243
+ return pending(c.txid, c.network);
244
+ await sleep(POLL_MS);
245
+ }
246
+ }
247
+ /** Broadcasts, then reads the receipt until `deadline`. */
248
+ async function submit(c, deadline) {
249
+ const node = byNetwork.get(c.network);
250
+ let sent;
251
+ try {
252
+ sent = await postJson(`${node.fullNode}/wallet/broadcasthex`, { transaction: c.hex }, deadline - performance.now());
253
+ }
254
+ catch (e) {
255
+ return e instanceof NodeError && !e.sent
256
+ ? failed("unexpected_settle_error", "", c.network)
257
+ : pending(c.txid, c.network);
258
+ }
259
+ const accepted = isObject(sent) && (sent["result"] === true || sent["code"] === "DUP_TRANSACTION_ERROR");
260
+ if (!accepted)
261
+ return failed("unexpected_settle_error", "", c.network);
262
+ return watch(c, deadline, false);
263
+ }
264
+ /** Stores the answer, unless the row holds a final one; a failed write leaves the row for a later read of the chain. */
265
+ async function keep(c, answer, deadline) {
266
+ await inTime(s.answer(c.network, c.txid, answer), deadline).catch(() => {
267
+ operatorLog({ event: "answer-not-stored", network: c.network, transaction: c.txid });
268
+ });
269
+ return answer;
270
+ }
271
+ /**
272
+ * Answers within `settleWaitMs`. A stored final answer is given as it is. A claimed id, or a stored pending answer, is
273
+ * read again from the chain. An answer with no transaction says nothing was broadcast, so it is given only for an id
274
+ * the store does not hold: a broadcast the node refused releases the claim, and when nothing is released the answer
275
+ * is pending with its id. A refusal as a duplicate is read as broadcast. When the store cannot be read, the
276
+ * facilitator cannot know whether the transaction was broadcast, so the answer is pending with its id.
277
+ */
278
+ async function settle(r) {
279
+ const deadline = performance.now() + settleWaitMs;
280
+ const left = () => deadline - performance.now();
281
+ const network = r.paymentRequirements.network;
282
+ const c = await check(r);
283
+ if (typeof c === "string")
284
+ return failed(settleReason(c), "", network);
285
+ let stored;
286
+ try {
287
+ stored = await inTime(s.read(c.network, c.txid), deadline);
288
+ }
289
+ catch {
290
+ return pending(c.txid, c.network);
291
+ }
292
+ if (stored.state === "answered" && !isPending(stored.answer))
293
+ return stored.answer;
294
+ const waitUntil = deadline - answerReserve(settleWaitMs);
295
+ if (stored.state !== "none")
296
+ return keep(c, await watch(c, waitUntil, true), deadline);
297
+ const now = await checkNow(c, left());
298
+ if (now !== null)
299
+ return failed(settleReason(now), "", network);
300
+ if (left() <= 0)
301
+ return failed("unexpected_settle_error", "", network);
302
+ let won;
303
+ try {
304
+ won = await inTime(s.claim(c.network, c.txid, new Date(Number(c.raw.expiration))), deadline);
305
+ }
306
+ catch {
307
+ return pending(c.txid, c.network);
308
+ }
309
+ if (!won)
310
+ return keep(c, await watch(c, waitUntil, true), deadline);
311
+ const answer = await submit(c, waitUntil);
312
+ if (answer.success || answer.transaction !== "")
313
+ return keep(c, answer, deadline);
314
+ const released = await inTime(s.release(c.network, c.txid), deadline).catch(() => false);
315
+ return released ? answer : pending(c.txid, c.network);
316
+ }
317
+ return { verify, settle, networks: nodes.map((n) => n.network) };
318
+ }
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@integraledger/profile-facilitator",
3
+ "version": "0.1.0",
4
+ "description": "An x402 facilitator for the LCP profiles x402/exact/tron/lcp-trc20-memo and x402/exact/polkadot/lcp-assets-remark: verifies and settles payments whose signed transaction carries the ATR hash.",
5
+ "license": "Apache-2.0",
6
+ "engines": {
7
+ "node": ">=26.10.0"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/IntegraLedger/integra-agentic-connectors.git",
12
+ "directory": "profile-facilitator"
13
+ },
14
+ "homepage": "https://github.com/IntegraLedger/integra-agentic-connectors/tree/main/profile-facilitator#readme",
15
+ "bugs": "https://github.com/IntegraLedger/integra-agentic-connectors/issues",
16
+ "keywords": [
17
+ "lcp",
18
+ "legal-context-protocol",
19
+ "x402",
20
+ "facilitator",
21
+ "tron",
22
+ "trc20",
23
+ "polkadot",
24
+ "asset-hub"
25
+ ],
26
+ "type": "module",
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ }
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "dependencies": {
42
+ "@integraledger/lcp": "0.1.0",
43
+ "@noble/curves": "2.4.0",
44
+ "@noble/hashes": "2.4.0",
45
+ "@polkadot/api": "17.0.1",
46
+ "pg": "8.23.0"
47
+ },
48
+ "devDependencies": {
49
+ "vitest": "5.0.1"
50
+ },
51
+ "scripts": {
52
+ "build": "tsc -p tsconfig.json",
53
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json",
54
+ "test": "vitest run"
55
+ }
56
+ }