@integraledger/profile-facilitator 0.1.0 → 0.3.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/README.md +256 -76
- package/dist/answers.d.ts +28 -6
- package/dist/answers.js +43 -3
- package/dist/http.d.ts +33 -6
- package/dist/http.js +93 -26
- package/dist/index.d.ts +15 -1
- package/dist/index.js +25 -11
- package/dist/polkadot.d.ts +10 -2
- package/dist/polkadot.js +429 -133
- package/dist/store.d.ts +29 -14
- package/dist/store.js +40 -23
- package/dist/tron.d.ts +2 -2
- package/dist/tron.js +378 -131
- package/dist/unexpected.d.ts +21 -0
- package/dist/unexpected.js +27 -0
- package/package.json +9 -6
package/dist/tron.js
CHANGED
|
@@ -1,26 +1,37 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Rule 5 of `x402/exact/tron/lcp-trc20-memo` against one network's FullNode: `/verify` checks the
|
|
3
|
-
* against the requirements
|
|
4
|
-
*
|
|
2
|
+
* Rule 5 of `x402/exact/tron/lcp-trc20-memo` against one network's FullNode and Solidity node: `/verify` checks the
|
|
3
|
+
* signed transaction against the requirements, the owner's permission, its reference block and the ids already held,
|
|
4
|
+
* and simulates it; `/settle` repeats that, claims the transaction id, broadcasts, and reads the transaction's status
|
|
5
|
+
* until it is final.
|
|
5
6
|
*/
|
|
6
7
|
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
7
8
|
import { keccak_256 } from "@noble/hashes/sha3.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
9
|
+
import { pairingOf } from "@integraledger/lcp";
|
|
10
|
+
import { isRefusal } from "@integraledger/lcp/core";
|
|
11
|
+
import { decodeTronTx, tronAddress, tronCarrier, tronStatus, } from "@integraledger/lcp/tron";
|
|
12
|
+
import { failed, invalid, isObject, isPending, pending, } from "./answers.js";
|
|
10
13
|
import { base58check } from "./base58check.js";
|
|
11
|
-
import {
|
|
14
|
+
import { isSpent, NodeError, postJson, sleep } from "./http.js";
|
|
12
15
|
import { answerReserve, inTime } from "./store.js";
|
|
16
|
+
import { settleReason, unexpectedSettle, unexpectedVerify } from "./unexpected.js";
|
|
13
17
|
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
18
|
function hexOf(b) {
|
|
22
19
|
return Buffer.from(b).toString("hex");
|
|
23
20
|
}
|
|
21
|
+
/** A permission's threshold or a key's weight: java-tron prints an int64 as a JSON number, read as a safe one ≥ 0. */
|
|
22
|
+
function int64(v) {
|
|
23
|
+
return typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : undefined;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Why the FullNode did not accept a broadcast: java-tron's `code` and `message`, or a `malformed` NodeError for an
|
|
27
|
+
* answer that has no `code`.
|
|
28
|
+
*/
|
|
29
|
+
function refusalOf(sent) {
|
|
30
|
+
if (!isObject(sent) || typeof sent["code"] !== "string") {
|
|
31
|
+
return new NodeError("malformed", true, "/wallet/broadcasthex: code");
|
|
32
|
+
}
|
|
33
|
+
return new Error(`${sent["code"]}: ${typeof sent["message"] === "string" ? sent["message"] : ""}`);
|
|
34
|
+
}
|
|
24
35
|
function sameBytes(a, b) {
|
|
25
36
|
return a.length === b.length && a.every((x, i) => x === b[i]);
|
|
26
37
|
}
|
|
@@ -53,30 +64,64 @@ function signerOf(signature, txid) {
|
|
|
53
64
|
return out;
|
|
54
65
|
}
|
|
55
66
|
catch {
|
|
67
|
+
// The payer's own signature bytes do not recover a key: refused `invalid_payload` to the client that sent them.
|
|
56
68
|
return undefined;
|
|
57
69
|
}
|
|
58
70
|
}
|
|
59
|
-
export function createTron(nodes, s, settleWaitMs) {
|
|
71
|
+
export function createTron(nodes, s, settleWaitMs, log) {
|
|
60
72
|
const byNetwork = new Map(nodes.map((n) => [n.network, n]));
|
|
73
|
+
/** The fields that name a payment in an operator entry. */
|
|
74
|
+
const about = (c) => ({ network: c.network, payer: c.payer, transaction: c.txid });
|
|
75
|
+
/**
|
|
76
|
+
* `p`, rejecting as it does, after its rejection is given to the operator log as a failed call to `call`. A call its
|
|
77
|
+
* deadline left no time for was not sent, and writes no entry.
|
|
78
|
+
*/
|
|
79
|
+
const reported = (c, call, p) => p.catch((e) => {
|
|
80
|
+
if (!isSpent(e))
|
|
81
|
+
log({ event: "node-call-failed", ...about(c), call }, e);
|
|
82
|
+
throw e;
|
|
83
|
+
});
|
|
84
|
+
/**
|
|
85
|
+
* `unexpected_verify_error` for an answer to `call` this facilitator cannot read: a `node-call-failed` entry whose
|
|
86
|
+
* cause is a `malformed` NodeError naming the part it cannot read.
|
|
87
|
+
*/
|
|
88
|
+
const malformed = (c, call, part) => unexpectedVerify(log, { event: "node-call-failed", ...about(c), call }, new NodeError("malformed", true, `${call}: ${part}`));
|
|
89
|
+
/** The entry for a settle whose deadline, `settleWaitMs` after its request, passed before `before`. */
|
|
90
|
+
const deadlinePassed = (c, before) => ({
|
|
91
|
+
event: "settle-deadline-passed",
|
|
92
|
+
...about(c),
|
|
93
|
+
before,
|
|
94
|
+
settleWaitMs,
|
|
95
|
+
});
|
|
96
|
+
/**
|
|
97
|
+
* `unexpected_verify_error` for a `/verify` read its bound left no time for: the call `call` was not sent, and the
|
|
98
|
+
* entry is a failed call's, its cause a `spent` NodeError.
|
|
99
|
+
*/
|
|
100
|
+
const notSent = (c, call) => unexpectedVerify(log, { event: "node-call-failed", ...about(c), call }, new NodeError("spent", false, call));
|
|
101
|
+
/** The stored row, or undefined when the store does not answer by `deadline`; the failure goes to the operator log. */
|
|
102
|
+
const readStored = (c, deadline) => inTime(s.read(c.network, c.txid), deadline).catch((e) => {
|
|
103
|
+
log({ event: "store-call-failed", ...about(c), call: "read" }, e);
|
|
104
|
+
return undefined;
|
|
105
|
+
});
|
|
61
106
|
/** Every check of rule 5 that reads neither the clock nor the node. */
|
|
62
107
|
async function check(r) {
|
|
63
108
|
const req = r.paymentRequirements;
|
|
64
109
|
if (!byNetwork.has(req.network))
|
|
65
110
|
return "invalid_network";
|
|
66
|
-
if (pairingOf(req)
|
|
111
|
+
if (pairingOf(req) !== "x402/exact/tron/lcp-trc20-memo")
|
|
67
112
|
return "invalid_payment_requirements";
|
|
68
113
|
const hex = r.paymentPayload.payload["transaction"];
|
|
69
114
|
if (typeof hex !== "string")
|
|
70
115
|
return "invalid_payload";
|
|
71
116
|
const tx = decodeTronTx(hex);
|
|
72
|
-
if (
|
|
117
|
+
if (isRefusal(tx))
|
|
73
118
|
return "invalid_payload";
|
|
74
119
|
const carried = await tronCarrier(tx);
|
|
75
|
-
if (
|
|
120
|
+
if (isRefusal(carried))
|
|
76
121
|
return "invalid_payload";
|
|
77
122
|
const asset = await tronAddress(req.asset);
|
|
78
123
|
const payTo = await tronAddress(req.payTo);
|
|
79
|
-
if (
|
|
124
|
+
if (isRefusal(asset) || isRefusal(payTo))
|
|
80
125
|
return "invalid_payment_requirements";
|
|
81
126
|
if (!sameBytes(tx.raw.contractAddress, asset))
|
|
82
127
|
return "invalid_payload";
|
|
@@ -97,28 +142,126 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
97
142
|
maxTimeoutSeconds: req.maxTimeoutSeconds,
|
|
98
143
|
};
|
|
99
144
|
}
|
|
100
|
-
/**
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
return "unexpected_verify_error";
|
|
108
|
-
let sim;
|
|
145
|
+
/**
|
|
146
|
+
* A FullNode call's JSON answer, as `answer`, bounded by `deadline` (a `performance.now()` time) and by the node call
|
|
147
|
+
* bound; a call that fails gives `unexpected_verify_error`. A call `deadline` leaves no time for is not sent: the
|
|
148
|
+
* answer names it, with no entry, and the caller answers for it.
|
|
149
|
+
*/
|
|
150
|
+
async function ask(c, path, body, deadline) {
|
|
151
|
+
const url = `${byNetwork.get(c.network).fullNode}${path}`;
|
|
109
152
|
try {
|
|
110
|
-
|
|
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);
|
|
153
|
+
return { answer: await postJson(url, body, deadline - performance.now()) };
|
|
116
154
|
}
|
|
117
|
-
catch {
|
|
118
|
-
|
|
155
|
+
catch (e) {
|
|
156
|
+
if (isSpent(e))
|
|
157
|
+
return { spent: path };
|
|
158
|
+
return unexpectedVerify(log, { event: "node-call-failed", ...about(c), call: path }, e);
|
|
119
159
|
}
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The owner's permission accepts the one signature: the weight it gives the owner's own key is at least its
|
|
163
|
+
* threshold. An account the node does not hold, or one with no owner permission set, has java-tron's default owner
|
|
164
|
+
* permission: the address's own key, weight 1, threshold 1.
|
|
165
|
+
*/
|
|
166
|
+
async function permitted(c, deadline) {
|
|
167
|
+
const call = "/wallet/getaccount";
|
|
168
|
+
const read = await ask(c, call, { address: hexOf(c.raw.owner) }, deadline);
|
|
169
|
+
if (typeof read === "string" || "spent" in read)
|
|
170
|
+
return read;
|
|
171
|
+
const account = read.answer;
|
|
172
|
+
if (!isObject(account))
|
|
173
|
+
return malformed(c, call, "the account");
|
|
174
|
+
const permission = account["owner_permission"];
|
|
175
|
+
if (permission === undefined)
|
|
176
|
+
return null;
|
|
177
|
+
if (!isObject(permission) || !Array.isArray(permission["keys"]))
|
|
178
|
+
return malformed(c, call, "owner_permission.keys");
|
|
179
|
+
const threshold = int64(permission["threshold"]);
|
|
180
|
+
if (threshold === undefined)
|
|
181
|
+
return malformed(c, call, "owner_permission.threshold");
|
|
182
|
+
const owner = hexOf(c.raw.owner);
|
|
183
|
+
let weight = 0n;
|
|
184
|
+
for (const key of permission["keys"]) {
|
|
185
|
+
if (!isObject(key) || typeof key["address"] !== "string") {
|
|
186
|
+
return malformed(c, call, "owner_permission.keys[].address");
|
|
187
|
+
}
|
|
188
|
+
const w = int64(key["weight"]);
|
|
189
|
+
if (w === undefined)
|
|
190
|
+
return malformed(c, call, "owner_permission.keys[].weight");
|
|
191
|
+
if (key["address"].toLowerCase() === owner)
|
|
192
|
+
weight = w;
|
|
193
|
+
}
|
|
194
|
+
return weight >= threshold ? null : "unsupported_permission";
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* TaPoS as the node checks it: `ref_block_bytes` are bytes 6–7 of a block number, and `ref_block_hash` must equal
|
|
198
|
+
* bytes 8–15 of the id of the latest block at or below the FullNode's head whose number ends in those two bytes.
|
|
199
|
+
*/
|
|
200
|
+
async function tapos(c, deadline) {
|
|
201
|
+
const refBytes = c.raw.refBlockBytes;
|
|
202
|
+
const refHash = c.raw.refBlockHash;
|
|
203
|
+
if (refBytes.length !== 2 || refHash.length !== 8)
|
|
204
|
+
return "invalid_transaction";
|
|
205
|
+
const now = await ask(c, "/wallet/getnowblock", {}, deadline);
|
|
206
|
+
if (typeof now === "string" || "spent" in now)
|
|
207
|
+
return now;
|
|
208
|
+
const header = isObject(now.answer) ? now.answer["block_header"] : undefined;
|
|
209
|
+
const raw = isObject(header) ? header["raw_data"] : undefined;
|
|
210
|
+
const head = isObject(raw) ? raw["number"] : undefined;
|
|
211
|
+
if (typeof head !== "number" || !Number.isSafeInteger(head) || head < 0) {
|
|
212
|
+
return malformed(c, "/wallet/getnowblock", "block_header.raw_data.number");
|
|
213
|
+
}
|
|
214
|
+
const low = (refBytes[0] << 8) | refBytes[1];
|
|
215
|
+
const number = head - ((head % 65_536) - low + 65_536) % 65_536;
|
|
216
|
+
if (number < 0)
|
|
217
|
+
return "invalid_transaction";
|
|
218
|
+
const read = await ask(c, "/wallet/getblock", { id_or_num: String(number), detail: false }, deadline);
|
|
219
|
+
if (typeof read === "string" || "spent" in read)
|
|
220
|
+
return read;
|
|
221
|
+
const block = read.answer;
|
|
222
|
+
if (!isObject(block))
|
|
223
|
+
return malformed(c, "/wallet/getblock", "the block");
|
|
224
|
+
if (Object.keys(block).length === 0)
|
|
225
|
+
return "invalid_transaction";
|
|
226
|
+
const id = block["blockID"];
|
|
227
|
+
if (typeof id !== "string" || !/^[0-9a-f]{64}$/.test(id) || BigInt(`0x${id.slice(0, 16)}`) !== BigInt(number)) {
|
|
228
|
+
return malformed(c, "/wallet/getblock", "blockID");
|
|
229
|
+
}
|
|
230
|
+
return id.slice(16, 32) === hexOf(refHash) ? null : "invalid_transaction";
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* The FullNode does not hold the transaction id at `path`: `/wallet/gettransactionbyid` for its blocks, or
|
|
234
|
+
* `/wallet/gettransactionfrompending` for its pending pool. Each answers `{}` for an id it does not hold.
|
|
235
|
+
*/
|
|
236
|
+
async function unheld(c, path, deadline) {
|
|
237
|
+
const read = await ask(c, path, { value: c.txid }, deadline);
|
|
238
|
+
if (typeof read === "string" || "spent" in read)
|
|
239
|
+
return read;
|
|
240
|
+
if (!isObject(read.answer))
|
|
241
|
+
return malformed(c, path, "the transaction");
|
|
242
|
+
return Object.keys(read.answer).length === 0 ? null : "invalid_transaction_state";
|
|
243
|
+
}
|
|
244
|
+
/** The two id reads, made together: the FullNode's blocks, then its pending pool. */
|
|
245
|
+
function idReads(c, deadline) {
|
|
246
|
+
return Promise.all([
|
|
247
|
+
unheld(c, "/wallet/gettransactionbyid", deadline),
|
|
248
|
+
unheld(c, "/wallet/gettransactionfrompending", deadline),
|
|
249
|
+
]);
|
|
250
|
+
}
|
|
251
|
+
/** The node's simulation of `transfer(payTo, amount)` from the owner on the asset. */
|
|
252
|
+
async function simulated(c, deadline) {
|
|
253
|
+
const call = "/wallet/triggerconstantcontract";
|
|
254
|
+
const read = await ask(c, call, {
|
|
255
|
+
owner_address: hexOf(c.raw.owner),
|
|
256
|
+
contract_address: hexOf(c.raw.contractAddress),
|
|
257
|
+
function_selector: "transfer(address,uint256)",
|
|
258
|
+
parameter: hexOf(c.raw.callData.subarray(4)),
|
|
259
|
+
}, deadline);
|
|
260
|
+
if (typeof read === "string" || "spent" in read)
|
|
261
|
+
return read;
|
|
262
|
+
const sim = read.answer;
|
|
120
263
|
if (!isObject(sim) || !isObject(sim["result"]))
|
|
121
|
-
return "
|
|
264
|
+
return malformed(c, call, "result");
|
|
122
265
|
if (sim["result"]["result"] !== true)
|
|
123
266
|
return "invalid_transaction";
|
|
124
267
|
const ret = isObject(sim["transaction"]) ? sim["transaction"]["ret"] : undefined;
|
|
@@ -126,60 +269,85 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
126
269
|
return "invalid_transaction";
|
|
127
270
|
return null;
|
|
128
271
|
}
|
|
272
|
+
/**
|
|
273
|
+
* The checks made before any node call, in this order: the expiration window, then `deadline`. The first refusal is
|
|
274
|
+
* the answer. A deadline spent here sends no node call.
|
|
275
|
+
*/
|
|
276
|
+
function beforeReads(c, deadline) {
|
|
277
|
+
const now = BigInt(Date.now());
|
|
278
|
+
const expiration = c.raw.expiration;
|
|
279
|
+
if (expiration <= now || expiration > now + BigInt(c.maxTimeoutSeconds) * 1000n)
|
|
280
|
+
return "invalid_payload";
|
|
281
|
+
if (deadline - performance.now() <= 0)
|
|
282
|
+
return unexpectedVerify(log, deadlinePassed(c, "node reads"));
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* The node reads, made together: the owner's permission, TaPoS, the ids the node holds in its blocks and in its
|
|
287
|
+
* pending pool (`ids`), and the simulation. The first refusal in that order is the answer. Each call is bounded by
|
|
288
|
+
* the node call bound and by `deadline`, and one that `deadline` leaves no time for is not sent and is named in its
|
|
289
|
+
* place in that order.
|
|
290
|
+
*/
|
|
291
|
+
async function nodeReads(c, deadline, ids) {
|
|
292
|
+
const [account, reference, [inBlocks, inPool], simulation] = await Promise.all([
|
|
293
|
+
permitted(c, deadline),
|
|
294
|
+
tapos(c, deadline),
|
|
295
|
+
ids,
|
|
296
|
+
simulated(c, deadline),
|
|
297
|
+
]);
|
|
298
|
+
return [account, reference, inBlocks, inPool, simulation].find((r) => r !== null) ?? null;
|
|
299
|
+
}
|
|
300
|
+
/** Every check of `/verify`: the transaction, the store, which must not hold its id, and the node reads. */
|
|
129
301
|
async function verify(r) {
|
|
130
302
|
const c = await check(r);
|
|
131
303
|
if (typeof c === "string")
|
|
132
304
|
return invalid(c);
|
|
133
|
-
|
|
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;
|
|
305
|
+
let stored;
|
|
139
306
|
try {
|
|
140
|
-
|
|
307
|
+
stored = await inTime(s.read(c.network, c.txid), Infinity);
|
|
141
308
|
}
|
|
142
|
-
catch {
|
|
143
|
-
return
|
|
309
|
+
catch (e) {
|
|
310
|
+
return invalid(unexpectedVerify(log, { event: "store-call-failed", ...about(c), call: "read" }, e), c.payer);
|
|
144
311
|
}
|
|
145
|
-
if (
|
|
146
|
-
return
|
|
147
|
-
const
|
|
148
|
-
|
|
312
|
+
if (stored.state !== "none")
|
|
313
|
+
return invalid("invalid_transaction_state", c.payer);
|
|
314
|
+
const now = beforeReads(c, Infinity) ?? (await nodeReads(c, Infinity, idReads(c, Infinity)));
|
|
315
|
+
if (now === null)
|
|
316
|
+
return { isValid: true, payer: c.payer };
|
|
317
|
+
return invalid(typeof now === "string" ? now : notSent(c, now.spent), c.payer);
|
|
149
318
|
}
|
|
150
319
|
/**
|
|
151
|
-
*
|
|
152
|
-
*
|
|
320
|
+
* The profile's reads at the Solidity node's `/walletsolidity` API and the FullNode's `/wallet` API, each bounded by
|
|
321
|
+
* `deadline`. A receipt lookup that finds nothing names the time of the latest block at its level, read from the same
|
|
322
|
+
* node before the lookup, or null when that read fails or its answer lacks the time. A read that fails is given to the
|
|
323
|
+
* operator log; one `deadline` leaves no time for is not sent, and writes no entry.
|
|
153
324
|
*/
|
|
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
325
|
function reader(c, deadline) {
|
|
172
326
|
const node = byNetwork.get(c.network);
|
|
173
327
|
const left = () => deadline - performance.now();
|
|
328
|
+
/** `getnowblock` at `api`: the latest block's number and time in milliseconds. */
|
|
329
|
+
async function latest(api) {
|
|
330
|
+
const o = await postJson(`${api}/getnowblock`, {}, left());
|
|
331
|
+
const header = isObject(o) ? o["block_header"] : undefined;
|
|
332
|
+
const raw = isObject(header) ? header["raw_data"] : undefined;
|
|
333
|
+
const number = isObject(raw) ? raw["number"] : undefined;
|
|
334
|
+
const timestamp = isObject(raw) ? raw["timestamp"] : undefined;
|
|
335
|
+
if (!Number.isSafeInteger(number) || !Number.isSafeInteger(timestamp)) {
|
|
336
|
+
throw new NodeError("malformed", true, "getnowblock fields");
|
|
337
|
+
}
|
|
338
|
+
return { number: BigInt(number), timestamp: BigInt(timestamp) };
|
|
339
|
+
}
|
|
174
340
|
return {
|
|
175
341
|
network: c.network,
|
|
176
342
|
async info(txid, level) {
|
|
177
|
-
const
|
|
178
|
-
const
|
|
343
|
+
const path = level === "solid" ? "/walletsolidity" : "/wallet";
|
|
344
|
+
const api = `${level === "solid" ? node.solidityNode : node.fullNode}${path}`;
|
|
345
|
+
const readTo = await reported(c, `${path}/getnowblock`, latest(api)).then((block) => block.timestamp, () => null);
|
|
346
|
+
const o = await postJson(`${api}/gettransactioninfobyid`, { value: txid.replace(/^0x/, "") }, left());
|
|
179
347
|
if (!isObject(o))
|
|
180
348
|
throw new NodeError("malformed", true, "gettransactioninfobyid");
|
|
181
349
|
if (Object.keys(o).length === 0)
|
|
182
|
-
return
|
|
350
|
+
return { notFound: true, timestamp: readTo };
|
|
183
351
|
const blockNumber = o["blockNumber"];
|
|
184
352
|
const result = isObject(o["receipt"]) ? o["receipt"]["result"] : undefined;
|
|
185
353
|
if (!Number.isSafeInteger(blockNumber) || typeof result !== "string") {
|
|
@@ -191,60 +359,86 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
191
359
|
transaction() {
|
|
192
360
|
return Promise.reject(new NodeError("malformed", false, "not read by this facilitator"));
|
|
193
361
|
},
|
|
194
|
-
|
|
195
|
-
|
|
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) };
|
|
362
|
+
solidHead() {
|
|
363
|
+
return latest(`${node.solidityNode}/walletsolidity`);
|
|
204
364
|
},
|
|
205
365
|
};
|
|
206
366
|
}
|
|
207
367
|
/**
|
|
208
|
-
*
|
|
209
|
-
*
|
|
368
|
+
* One read of the transaction's status through the profile's `tronStatus`: settled, at the Solidity node or the
|
|
369
|
+
* FullNode, only with receipt result `SUCCESS` and a `Transfer` log from the asset, whatever the call returned (a
|
|
370
|
+
* TRC-20 token may return false from `transfer` and still transfer). A failed receipt, or one with no such log, is
|
|
371
|
+
* final only when the Solidity node, which serves solidified blocks alone, shows it. A transaction that neither
|
|
372
|
+
* lookup finds, with the latest solidified block, read first, two slots past its expiration, can never be included
|
|
373
|
+
* once each lookup names a latest block at or past that block's time. Anything else gives undefined.
|
|
210
374
|
*/
|
|
211
|
-
async function
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
const
|
|
375
|
+
async function outcome(c, deadline) {
|
|
376
|
+
const reads = reader(c, deadline);
|
|
377
|
+
let found;
|
|
378
|
+
const st = await tronStatus({
|
|
215
379
|
network: c.network,
|
|
216
380
|
txid: `0x${c.txid}`,
|
|
217
381
|
asset: `0x${hexOf(c.raw.contractAddress)}`,
|
|
218
382
|
expiration: c.raw.expiration.toString(),
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
|
|
383
|
+
}, {
|
|
384
|
+
...reads,
|
|
385
|
+
async info(txid, level) {
|
|
386
|
+
const api = level === "solid" ? "/walletsolidity" : "/wallet";
|
|
387
|
+
const info = await reported(c, `${api}/gettransactioninfobyid`, reads.info(txid, level));
|
|
388
|
+
if (!("notFound" in info))
|
|
389
|
+
found = level;
|
|
390
|
+
return info;
|
|
391
|
+
},
|
|
392
|
+
solidHead: () => reported(c, "/walletsolidity/getnowblock", reads.solidHead()),
|
|
393
|
+
});
|
|
394
|
+
if (st.state === "settled")
|
|
395
|
+
return { success: true, transaction: c.txid, network: c.network, payer: c.payer };
|
|
396
|
+
if (st.state === "pending")
|
|
397
|
+
return undefined;
|
|
398
|
+
if (st.why === "expired") {
|
|
399
|
+
log({ event: "settlement-expired", ...about(c) });
|
|
400
|
+
return failed("invalid_transaction_state", c.txid, c.network);
|
|
401
|
+
}
|
|
402
|
+
if (found !== "solid")
|
|
403
|
+
return undefined;
|
|
404
|
+
log({ event: "settlement-failed", ...about(c), why: st.why, result: st.result });
|
|
405
|
+
return failed("invalid_transaction_state", c.txid, c.network);
|
|
406
|
+
}
|
|
407
|
+
/** The answer to a `/settle` of a payment whose success has already been answered: a consumed payment fails. */
|
|
408
|
+
function consumed(c) {
|
|
409
|
+
return failed("invalid_transaction_state", c.txid, c.network);
|
|
222
410
|
}
|
|
223
411
|
/**
|
|
224
|
-
* Reads the
|
|
225
|
-
* first final answer either gives
|
|
226
|
-
*
|
|
412
|
+
* Reads the transaction's status every second until `deadline`, and the stored answer too when `stored` is set,
|
|
413
|
+
* answering with the first final answer either gives. A stored success is another settle's, so it gives the consumed
|
|
414
|
+
* answer. Once `deadline` has passed, neither the store nor the status is read: the answer is the one the wait's end
|
|
415
|
+
* gives. Broadcasts nothing.
|
|
227
416
|
*/
|
|
228
417
|
async function watch(c, deadline, stored) {
|
|
229
418
|
for (;;) {
|
|
419
|
+
if (deadline - performance.now() <= 0)
|
|
420
|
+
return pending(c.txid, c.network);
|
|
230
421
|
if (stored) {
|
|
231
|
-
const row = await
|
|
422
|
+
const row = await readStored(c, deadline);
|
|
232
423
|
if (row?.state === "answered" && !isPending(row.answer))
|
|
233
|
-
return row.answer;
|
|
424
|
+
return row.answer.success ? consumed(c) : row.answer;
|
|
234
425
|
}
|
|
235
|
-
|
|
426
|
+
if (deadline - performance.now() <= 0)
|
|
427
|
+
return pending(c.txid, c.network);
|
|
428
|
+
const final = await outcome(c, deadline);
|
|
236
429
|
if (final !== undefined)
|
|
237
430
|
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
431
|
if (performance.now() + POLL_MS > deadline)
|
|
243
432
|
return pending(c.txid, c.network);
|
|
244
433
|
await sleep(POLL_MS);
|
|
245
434
|
}
|
|
246
435
|
}
|
|
247
|
-
/**
|
|
436
|
+
/**
|
|
437
|
+
* Broadcasts, then reads the transaction's status until `deadline`. A `DUP_TRANSACTION_ERROR` says the node already
|
|
438
|
+
* holds the transaction id, so the payment is consumed. Any other refusal, or a request that cannot have reached the
|
|
439
|
+
* node, gives `unexpected_settle_error` with no transaction: nothing was broadcast. So does a broadcast `deadline`
|
|
440
|
+
* leaves no time for, as after a claim that answers late: it is not sent, and its entry is `settle-deadline-passed`.
|
|
441
|
+
*/
|
|
248
442
|
async function submit(c, deadline) {
|
|
249
443
|
const node = byNetwork.get(c.network);
|
|
250
444
|
let sent;
|
|
@@ -252,28 +446,67 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
252
446
|
sent = await postJson(`${node.fullNode}/wallet/broadcasthex`, { transaction: c.hex }, deadline - performance.now());
|
|
253
447
|
}
|
|
254
448
|
catch (e) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
449
|
+
if (isSpent(e))
|
|
450
|
+
return unexpectedSettle(log, deadlinePassed(c, "/wallet/broadcasthex"));
|
|
451
|
+
const entry = { event: "node-call-failed", ...about(c), call: "/wallet/broadcasthex" };
|
|
452
|
+
if (e instanceof NodeError && !e.sent)
|
|
453
|
+
return unexpectedSettle(log, entry, e);
|
|
454
|
+
log(entry, e);
|
|
455
|
+
return pending(c.txid, c.network);
|
|
456
|
+
}
|
|
457
|
+
if (isObject(sent) && sent["code"] === "DUP_TRANSACTION_ERROR")
|
|
458
|
+
return consumed(c);
|
|
459
|
+
if (!isObject(sent) || sent["result"] !== true) {
|
|
460
|
+
const entry = { event: "node-call-failed", ...about(c), call: "/wallet/broadcasthex" };
|
|
461
|
+
return unexpectedSettle(log, entry, refusalOf(sent));
|
|
258
462
|
}
|
|
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
463
|
return watch(c, deadline, false);
|
|
263
464
|
}
|
|
264
|
-
/**
|
|
465
|
+
/**
|
|
466
|
+
* Stores the answer unless the row holds a final one. A success is given only by the settle whose write stored it,
|
|
467
|
+
* so one payment is answered success once: a success another settle stored first gives the consumed answer, and a
|
|
468
|
+
* success whose write fails gives `settlement_pending` with the id. An answer with no transaction, a refused
|
|
469
|
+
* broadcast or one that cannot have reached the node, is given only once it is the stored answer: when the row holds
|
|
470
|
+
* another final answer, the answer is what a repeat gets for it, and when the write fails, `settlement_pending` with
|
|
471
|
+
* the id. A failed write of any other answer leaves the row for a later read of the chain.
|
|
472
|
+
*/
|
|
265
473
|
async function keep(c, answer, deadline) {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
474
|
+
let wrote;
|
|
475
|
+
try {
|
|
476
|
+
wrote = await inTime(s.answer(c.network, c.txid, answer), deadline);
|
|
477
|
+
}
|
|
478
|
+
catch (e) {
|
|
479
|
+
log({ event: "answer-not-stored", ...about(c) }, e);
|
|
480
|
+
return answer.success || answer.transaction === "" ? pending(c.txid, c.network) : answer;
|
|
481
|
+
}
|
|
482
|
+
if (wrote)
|
|
483
|
+
return answer;
|
|
484
|
+
if (answer.success)
|
|
485
|
+
return consumed(c);
|
|
486
|
+
if (answer.transaction !== "")
|
|
487
|
+
return answer;
|
|
488
|
+
const row = await readStored(c, deadline);
|
|
489
|
+
if (row?.state !== "answered" || isPending(row.answer))
|
|
490
|
+
return pending(c.txid, c.network);
|
|
491
|
+
return row.answer.success ? consumed(c) : row.answer;
|
|
270
492
|
}
|
|
271
493
|
/**
|
|
272
|
-
* Answers within `settleWaitMs`. A stored
|
|
273
|
-
*
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
494
|
+
* Answers within `settleWaitMs`. A stored success means the payment is consumed, and gives
|
|
495
|
+
* `invalid_transaction_state` with the id; any other stored final answer is given as it is. A claimed id, or a stored
|
|
496
|
+
* pending answer, is read again from the chain. For an id the store does not hold, the expiration window and then
|
|
497
|
+
* the deadline are checked before any node call: a deadline spent there sends none, and gives
|
|
498
|
+
* `unexpected_settle_error`, or `invalid_payload` for an expiration outside the window. A node read the deadline
|
|
499
|
+
* leaves no time for once the reads have started is not sent either, and in its place among the refusals gives
|
|
500
|
+
* `unexpected_settle_error`, with one entry naming the call; for an expiration outside the window, an id read not
|
|
501
|
+
* sent finds nothing, and the answer is `invalid_payload`, with no entry. The node's id reads answer first: an id
|
|
502
|
+
* the node holds, in a block or its pending pool, is consumed too, whatever else the checks refuse, the expiration
|
|
503
|
+
* window among them, and a node that does not answer them gives `unexpected_settle_error`.
|
|
504
|
+
* No id is claimed once the wait for the chain has ended: its broadcast would have no time left.
|
|
505
|
+
* A claimed id is never released: a broadcast the node refused as a duplicate is a consumed payment, and any other
|
|
506
|
+
* refused broadcast, or a broadcast request that cannot have reached the node, gives `unexpected_settle_error` with
|
|
507
|
+
* no transaction, which says nothing was broadcast. Each is stored final, and every repeat gets the stored answer.
|
|
508
|
+
* When the store cannot be read, the facilitator cannot know whether the transaction was broadcast, so the answer is
|
|
509
|
+
* pending with its id.
|
|
277
510
|
*/
|
|
278
511
|
async function settle(r) {
|
|
279
512
|
const deadline = performance.now() + settleWaitMs;
|
|
@@ -286,33 +519,47 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
286
519
|
try {
|
|
287
520
|
stored = await inTime(s.read(c.network, c.txid), deadline);
|
|
288
521
|
}
|
|
289
|
-
catch {
|
|
522
|
+
catch (e) {
|
|
523
|
+
log({ event: "store-call-failed", ...about(c), call: "read" }, e);
|
|
290
524
|
return pending(c.txid, c.network);
|
|
291
525
|
}
|
|
292
|
-
if (stored.state === "answered" && !isPending(stored.answer))
|
|
293
|
-
return stored.answer;
|
|
526
|
+
if (stored.state === "answered" && !isPending(stored.answer)) {
|
|
527
|
+
return stored.answer.success ? consumed(c) : stored.answer;
|
|
528
|
+
}
|
|
294
529
|
const waitUntil = deadline - answerReserve(settleWaitMs);
|
|
295
530
|
if (stored.state !== "none")
|
|
296
531
|
return keep(c, await watch(c, waitUntil, true), deadline);
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
532
|
+
// An expiration outside the window waits for the id reads while the deadline leaves time for them.
|
|
533
|
+
const before = beforeReads(c, deadline);
|
|
534
|
+
if (before !== null && (before !== "invalid_payload" || left() <= 0)) {
|
|
535
|
+
return failed(settleReason(before), "", network);
|
|
536
|
+
}
|
|
537
|
+
const ids = idReads(c, deadline);
|
|
538
|
+
const now = before ?? (await nodeReads(c, deadline, ids));
|
|
539
|
+
const held = await ids;
|
|
540
|
+
if (held.includes("invalid_transaction_state"))
|
|
541
|
+
return consumed(c);
|
|
542
|
+
if (now !== null) {
|
|
543
|
+
// An expired transaction's id reads look only for a held id: one the deadline leaves no time for leaves the
|
|
544
|
+
// expiration's refusal, as the deadline check before the reads gives it.
|
|
545
|
+
const refused = held.find((r) => r !== null && (before === null || typeof r === "string")) ?? now;
|
|
546
|
+
if (typeof refused === "object")
|
|
547
|
+
return unexpectedSettle(log, deadlinePassed(c, refused.spent));
|
|
548
|
+
return failed(settleReason(refused), "", network);
|
|
549
|
+
}
|
|
550
|
+
if (waitUntil - performance.now() <= 0)
|
|
551
|
+
return unexpectedSettle(log, deadlinePassed(c, "claim"));
|
|
302
552
|
let won;
|
|
303
553
|
try {
|
|
304
554
|
won = await inTime(s.claim(c.network, c.txid, new Date(Number(c.raw.expiration))), deadline);
|
|
305
555
|
}
|
|
306
|
-
catch {
|
|
556
|
+
catch (e) {
|
|
557
|
+
log({ event: "store-call-failed", ...about(c), call: "claim" }, e);
|
|
307
558
|
return pending(c.txid, c.network);
|
|
308
559
|
}
|
|
309
560
|
if (!won)
|
|
310
561
|
return keep(c, await watch(c, waitUntil, true), deadline);
|
|
311
|
-
|
|
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);
|
|
562
|
+
return keep(c, await submit(c, waitUntil), deadline);
|
|
316
563
|
}
|
|
317
564
|
return { verify, settle, networks: nodes.map((n) => n.network) };
|
|
318
565
|
}
|