@integraledger/profile-facilitator 0.2.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 +157 -69
- package/dist/answers.d.ts +23 -2
- package/dist/answers.js +43 -3
- package/dist/http.d.ts +22 -5
- package/dist/http.js +41 -20
- package/dist/index.d.ts +15 -1
- package/dist/index.js +25 -11
- package/dist/polkadot.d.ts +2 -2
- package/dist/polkadot.js +266 -103
- package/dist/store.d.ts +6 -4
- package/dist/store.js +17 -15
- package/dist/tron.d.ts +2 -2
- package/dist/tron.js +243 -106
- package/dist/unexpected.d.ts +21 -0
- package/dist/unexpected.js +27 -0
- package/package.json +9 -6
package/dist/tron.js
CHANGED
|
@@ -6,17 +6,15 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
8
8
|
import { keccak_256 } from "@noble/hashes/sha3.js";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
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";
|
|
12
13
|
import { base58check } from "./base58check.js";
|
|
13
|
-
import { NodeError, postJson, sleep } from "./http.js";
|
|
14
|
+
import { isSpent, NodeError, postJson, sleep } from "./http.js";
|
|
14
15
|
import { answerReserve, inTime } from "./store.js";
|
|
16
|
+
import { settleReason, unexpectedSettle, unexpectedVerify } from "./unexpected.js";
|
|
15
17
|
const POLL_MS = 1_000;
|
|
16
|
-
/** A verify reason as a settle answer's: a node that could not be read before submission is a settle error. */
|
|
17
|
-
function settleReason(r) {
|
|
18
|
-
return r === "unexpected_verify_error" ? "unexpected_settle_error" : r;
|
|
19
|
-
}
|
|
20
18
|
function hexOf(b) {
|
|
21
19
|
return Buffer.from(b).toString("hex");
|
|
22
20
|
}
|
|
@@ -24,6 +22,16 @@ function hexOf(b) {
|
|
|
24
22
|
function int64(v) {
|
|
25
23
|
return typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : undefined;
|
|
26
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
|
+
}
|
|
27
35
|
function sameBytes(a, b) {
|
|
28
36
|
return a.length === b.length && a.every((x, i) => x === b[i]);
|
|
29
37
|
}
|
|
@@ -56,17 +64,51 @@ function signerOf(signature, txid) {
|
|
|
56
64
|
return out;
|
|
57
65
|
}
|
|
58
66
|
catch {
|
|
67
|
+
// The payer's own signature bytes do not recover a key: refused `invalid_payload` to the client that sent them.
|
|
59
68
|
return undefined;
|
|
60
69
|
}
|
|
61
70
|
}
|
|
62
|
-
export function createTron(nodes, s, settleWaitMs) {
|
|
71
|
+
export function createTron(nodes, s, settleWaitMs, log) {
|
|
63
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
|
+
});
|
|
64
106
|
/** Every check of rule 5 that reads neither the clock nor the node. */
|
|
65
107
|
async function check(r) {
|
|
66
108
|
const req = r.paymentRequirements;
|
|
67
109
|
if (!byNetwork.has(req.network))
|
|
68
110
|
return "invalid_network";
|
|
69
|
-
if (pairingOf(req)
|
|
111
|
+
if (pairingOf(req) !== "x402/exact/tron/lcp-trc20-memo")
|
|
70
112
|
return "invalid_payment_requirements";
|
|
71
113
|
const hex = r.paymentPayload.payload["transaction"];
|
|
72
114
|
if (typeof hex !== "string")
|
|
@@ -100,13 +142,20 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
100
142
|
maxTimeoutSeconds: req.maxTimeoutSeconds,
|
|
101
143
|
};
|
|
102
144
|
}
|
|
103
|
-
/**
|
|
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
|
+
*/
|
|
104
150
|
async function ask(c, path, body, deadline) {
|
|
151
|
+
const url = `${byNetwork.get(c.network).fullNode}${path}`;
|
|
105
152
|
try {
|
|
106
|
-
return await postJson(
|
|
153
|
+
return { answer: await postJson(url, body, deadline - performance.now()) };
|
|
107
154
|
}
|
|
108
|
-
catch {
|
|
109
|
-
|
|
155
|
+
catch (e) {
|
|
156
|
+
if (isSpent(e))
|
|
157
|
+
return { spent: path };
|
|
158
|
+
return unexpectedVerify(log, { event: "node-call-failed", ...about(c), call: path }, e);
|
|
110
159
|
}
|
|
111
160
|
}
|
|
112
161
|
/**
|
|
@@ -115,25 +164,30 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
115
164
|
* permission: the address's own key, weight 1, threshold 1.
|
|
116
165
|
*/
|
|
117
166
|
async function permitted(c, deadline) {
|
|
118
|
-
const
|
|
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;
|
|
119
172
|
if (!isObject(account))
|
|
120
|
-
return "
|
|
173
|
+
return malformed(c, call, "the account");
|
|
121
174
|
const permission = account["owner_permission"];
|
|
122
175
|
if (permission === undefined)
|
|
123
176
|
return null;
|
|
124
177
|
if (!isObject(permission) || !Array.isArray(permission["keys"]))
|
|
125
|
-
return "
|
|
178
|
+
return malformed(c, call, "owner_permission.keys");
|
|
126
179
|
const threshold = int64(permission["threshold"]);
|
|
127
180
|
if (threshold === undefined)
|
|
128
|
-
return "
|
|
181
|
+
return malformed(c, call, "owner_permission.threshold");
|
|
129
182
|
const owner = hexOf(c.raw.owner);
|
|
130
183
|
let weight = 0n;
|
|
131
184
|
for (const key of permission["keys"]) {
|
|
132
|
-
if (!isObject(key) || typeof key["address"] !== "string")
|
|
133
|
-
return "
|
|
185
|
+
if (!isObject(key) || typeof key["address"] !== "string") {
|
|
186
|
+
return malformed(c, call, "owner_permission.keys[].address");
|
|
187
|
+
}
|
|
134
188
|
const w = int64(key["weight"]);
|
|
135
189
|
if (w === undefined)
|
|
136
|
-
return "
|
|
190
|
+
return malformed(c, call, "owner_permission.keys[].weight");
|
|
137
191
|
if (key["address"].toLowerCase() === owner)
|
|
138
192
|
weight = w;
|
|
139
193
|
}
|
|
@@ -149,23 +203,29 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
149
203
|
if (refBytes.length !== 2 || refHash.length !== 8)
|
|
150
204
|
return "invalid_transaction";
|
|
151
205
|
const now = await ask(c, "/wallet/getnowblock", {}, deadline);
|
|
152
|
-
|
|
206
|
+
if (typeof now === "string" || "spent" in now)
|
|
207
|
+
return now;
|
|
208
|
+
const header = isObject(now.answer) ? now.answer["block_header"] : undefined;
|
|
153
209
|
const raw = isObject(header) ? header["raw_data"] : undefined;
|
|
154
210
|
const head = isObject(raw) ? raw["number"] : undefined;
|
|
155
|
-
if (typeof head !== "number" || !Number.isSafeInteger(head) || head < 0)
|
|
156
|
-
return "
|
|
211
|
+
if (typeof head !== "number" || !Number.isSafeInteger(head) || head < 0) {
|
|
212
|
+
return malformed(c, "/wallet/getnowblock", "block_header.raw_data.number");
|
|
213
|
+
}
|
|
157
214
|
const low = (refBytes[0] << 8) | refBytes[1];
|
|
158
215
|
const number = head - ((head % 65_536) - low + 65_536) % 65_536;
|
|
159
216
|
if (number < 0)
|
|
160
217
|
return "invalid_transaction";
|
|
161
|
-
const
|
|
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;
|
|
162
222
|
if (!isObject(block))
|
|
163
|
-
return "
|
|
223
|
+
return malformed(c, "/wallet/getblock", "the block");
|
|
164
224
|
if (Object.keys(block).length === 0)
|
|
165
225
|
return "invalid_transaction";
|
|
166
226
|
const id = block["blockID"];
|
|
167
227
|
if (typeof id !== "string" || !/^[0-9a-f]{64}$/.test(id) || BigInt(`0x${id.slice(0, 16)}`) !== BigInt(number)) {
|
|
168
|
-
return "
|
|
228
|
+
return malformed(c, "/wallet/getblock", "blockID");
|
|
169
229
|
}
|
|
170
230
|
return id.slice(16, 32) === hexOf(refHash) ? null : "invalid_transaction";
|
|
171
231
|
}
|
|
@@ -174,21 +234,34 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
174
234
|
* `/wallet/gettransactionfrompending` for its pending pool. Each answers `{}` for an id it does not hold.
|
|
175
235
|
*/
|
|
176
236
|
async function unheld(c, path, deadline) {
|
|
177
|
-
const
|
|
178
|
-
if (
|
|
179
|
-
return
|
|
180
|
-
|
|
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
|
+
]);
|
|
181
250
|
}
|
|
182
251
|
/** The node's simulation of `transfer(payTo, amount)` from the owner on the asset. */
|
|
183
252
|
async function simulated(c, deadline) {
|
|
184
|
-
const
|
|
253
|
+
const call = "/wallet/triggerconstantcontract";
|
|
254
|
+
const read = await ask(c, call, {
|
|
185
255
|
owner_address: hexOf(c.raw.owner),
|
|
186
256
|
contract_address: hexOf(c.raw.contractAddress),
|
|
187
257
|
function_selector: "transfer(address,uint256)",
|
|
188
258
|
parameter: hexOf(c.raw.callData.subarray(4)),
|
|
189
259
|
}, deadline);
|
|
260
|
+
if (typeof read === "string" || "spent" in read)
|
|
261
|
+
return read;
|
|
262
|
+
const sim = read.answer;
|
|
190
263
|
if (!isObject(sim) || !isObject(sim["result"]))
|
|
191
|
-
return "
|
|
264
|
+
return malformed(c, call, "result");
|
|
192
265
|
if (sim["result"]["result"] !== true)
|
|
193
266
|
return "invalid_transaction";
|
|
194
267
|
const ret = isObject(sim["transaction"]) ? sim["transaction"]["ret"] : undefined;
|
|
@@ -197,25 +270,32 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
197
270
|
return null;
|
|
198
271
|
}
|
|
199
272
|
/**
|
|
200
|
-
* The
|
|
201
|
-
*
|
|
202
|
-
* by `deadline`.
|
|
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.
|
|
203
275
|
*/
|
|
204
|
-
|
|
276
|
+
function beforeReads(c, deadline) {
|
|
205
277
|
const now = BigInt(Date.now());
|
|
206
278
|
const expiration = c.raw.expiration;
|
|
207
279
|
if (expiration <= now || expiration > now + BigInt(c.maxTimeoutSeconds) * 1000n)
|
|
208
280
|
return "invalid_payload";
|
|
209
281
|
if (deadline - performance.now() <= 0)
|
|
210
|
-
return "
|
|
211
|
-
|
|
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([
|
|
212
293
|
permitted(c, deadline),
|
|
213
294
|
tapos(c, deadline),
|
|
214
|
-
|
|
215
|
-
unheld(c, "/wallet/gettransactionfrompending", deadline),
|
|
295
|
+
ids,
|
|
216
296
|
simulated(c, deadline),
|
|
217
297
|
]);
|
|
218
|
-
return
|
|
298
|
+
return [account, reference, inBlocks, inPool, simulation].find((r) => r !== null) ?? null;
|
|
219
299
|
}
|
|
220
300
|
/** Every check of `/verify`: the transaction, the store, which must not hold its id, and the node reads. */
|
|
221
301
|
async function verify(r) {
|
|
@@ -226,27 +306,48 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
226
306
|
try {
|
|
227
307
|
stored = await inTime(s.read(c.network, c.txid), Infinity);
|
|
228
308
|
}
|
|
229
|
-
catch {
|
|
230
|
-
return invalid("
|
|
309
|
+
catch (e) {
|
|
310
|
+
return invalid(unexpectedVerify(log, { event: "store-call-failed", ...about(c), call: "read" }, e), c.payer);
|
|
231
311
|
}
|
|
232
312
|
if (stored.state !== "none")
|
|
233
313
|
return invalid("invalid_transaction_state", c.payer);
|
|
234
|
-
const now = await
|
|
235
|
-
|
|
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);
|
|
236
318
|
}
|
|
237
|
-
/**
|
|
319
|
+
/**
|
|
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.
|
|
324
|
+
*/
|
|
238
325
|
function reader(c, deadline) {
|
|
239
326
|
const node = byNetwork.get(c.network);
|
|
240
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
|
+
}
|
|
241
340
|
return {
|
|
242
341
|
network: c.network,
|
|
243
342
|
async info(txid, level) {
|
|
244
|
-
const
|
|
245
|
-
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());
|
|
246
347
|
if (!isObject(o))
|
|
247
348
|
throw new NodeError("malformed", true, "gettransactioninfobyid");
|
|
248
349
|
if (Object.keys(o).length === 0)
|
|
249
|
-
return
|
|
350
|
+
return { notFound: true, timestamp: readTo };
|
|
250
351
|
const blockNumber = o["blockNumber"];
|
|
251
352
|
const result = isObject(o["receipt"]) ? o["receipt"]["result"] : undefined;
|
|
252
353
|
if (!Number.isSafeInteger(blockNumber) || typeof result !== "string") {
|
|
@@ -258,16 +359,8 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
258
359
|
transaction() {
|
|
259
360
|
return Promise.reject(new NodeError("malformed", false, "not read by this facilitator"));
|
|
260
361
|
},
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
const header = isObject(o) ? o["block_header"] : undefined;
|
|
264
|
-
const raw = isObject(header) ? header["raw_data"] : undefined;
|
|
265
|
-
const number = isObject(raw) ? raw["number"] : undefined;
|
|
266
|
-
const timestamp = isObject(raw) ? raw["timestamp"] : undefined;
|
|
267
|
-
if (!Number.isSafeInteger(number) || !Number.isSafeInteger(timestamp)) {
|
|
268
|
-
throw new NodeError("malformed", true, "getnowblock fields");
|
|
269
|
-
}
|
|
270
|
-
return { number: BigInt(number), timestamp: BigInt(timestamp) };
|
|
362
|
+
solidHead() {
|
|
363
|
+
return latest(`${node.solidityNode}/walletsolidity`);
|
|
271
364
|
},
|
|
272
365
|
};
|
|
273
366
|
}
|
|
@@ -275,9 +368,9 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
275
368
|
* One read of the transaction's status through the profile's `tronStatus`: settled, at the Solidity node or the
|
|
276
369
|
* FullNode, only with receipt result `SUCCESS` and a `Transfer` log from the asset, whatever the call returned (a
|
|
277
370
|
* TRC-20 token may return false from `transfer` and still transfer). A failed receipt, or one with no such log, is
|
|
278
|
-
* final only when the Solidity node, which serves solidified blocks alone, shows it. A transaction
|
|
279
|
-
* with the latest solidified block two slots past its expiration, can never be included
|
|
280
|
-
* undefined.
|
|
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.
|
|
281
374
|
*/
|
|
282
375
|
async function outcome(c, deadline) {
|
|
283
376
|
const reads = reader(c, deadline);
|
|
@@ -290,29 +383,25 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
290
383
|
}, {
|
|
291
384
|
...reads,
|
|
292
385
|
async info(txid, level) {
|
|
293
|
-
const
|
|
294
|
-
|
|
386
|
+
const api = level === "solid" ? "/walletsolidity" : "/wallet";
|
|
387
|
+
const info = await reported(c, `${api}/gettransactioninfobyid`, reads.info(txid, level));
|
|
388
|
+
if (!("notFound" in info))
|
|
295
389
|
found = level;
|
|
296
390
|
return info;
|
|
297
391
|
},
|
|
392
|
+
solidHead: () => reported(c, "/walletsolidity/getnowblock", reads.solidHead()),
|
|
298
393
|
});
|
|
299
394
|
if (st.state === "settled")
|
|
300
395
|
return { success: true, transaction: c.txid, network: c.network, payer: c.payer };
|
|
301
396
|
if (st.state === "pending")
|
|
302
397
|
return undefined;
|
|
303
398
|
if (st.why === "expired") {
|
|
304
|
-
|
|
399
|
+
log({ event: "settlement-expired", ...about(c) });
|
|
305
400
|
return failed("invalid_transaction_state", c.txid, c.network);
|
|
306
401
|
}
|
|
307
402
|
if (found !== "solid")
|
|
308
403
|
return undefined;
|
|
309
|
-
|
|
310
|
-
event: "settlement-failed",
|
|
311
|
-
network: c.network,
|
|
312
|
-
transaction: c.txid,
|
|
313
|
-
why: st.why,
|
|
314
|
-
result: st.result,
|
|
315
|
-
});
|
|
404
|
+
log({ event: "settlement-failed", ...about(c), why: st.why, result: st.result });
|
|
316
405
|
return failed("invalid_transaction_state", c.txid, c.network);
|
|
317
406
|
}
|
|
318
407
|
/** The answer to a `/settle` of a payment whose success has already been answered: a consumed payment fails. */
|
|
@@ -322,15 +411,20 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
322
411
|
/**
|
|
323
412
|
* Reads the transaction's status every second until `deadline`, and the stored answer too when `stored` is set,
|
|
324
413
|
* answering with the first final answer either gives. A stored success is another settle's, so it gives the consumed
|
|
325
|
-
* answer.
|
|
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.
|
|
326
416
|
*/
|
|
327
417
|
async function watch(c, deadline, stored) {
|
|
328
418
|
for (;;) {
|
|
419
|
+
if (deadline - performance.now() <= 0)
|
|
420
|
+
return pending(c.txid, c.network);
|
|
329
421
|
if (stored) {
|
|
330
|
-
const row = await
|
|
422
|
+
const row = await readStored(c, deadline);
|
|
331
423
|
if (row?.state === "answered" && !isPending(row.answer))
|
|
332
424
|
return row.answer.success ? consumed(c) : row.answer;
|
|
333
425
|
}
|
|
426
|
+
if (deadline - performance.now() <= 0)
|
|
427
|
+
return pending(c.txid, c.network);
|
|
334
428
|
const final = await outcome(c, deadline);
|
|
335
429
|
if (final !== undefined)
|
|
336
430
|
return final;
|
|
@@ -339,7 +433,12 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
339
433
|
await sleep(POLL_MS);
|
|
340
434
|
}
|
|
341
435
|
}
|
|
342
|
-
/**
|
|
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
|
+
*/
|
|
343
442
|
async function submit(c, deadline) {
|
|
344
443
|
const node = byNetwork.get(c.network);
|
|
345
444
|
let sent;
|
|
@@ -347,40 +446,67 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
347
446
|
sent = await postJson(`${node.fullNode}/wallet/broadcasthex`, { transaction: c.hex }, deadline - performance.now());
|
|
348
447
|
}
|
|
349
448
|
catch (e) {
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
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));
|
|
353
462
|
}
|
|
354
|
-
const accepted = isObject(sent) && (sent["result"] === true || sent["code"] === "DUP_TRANSACTION_ERROR");
|
|
355
|
-
if (!accepted)
|
|
356
|
-
return failed("unexpected_settle_error", "", c.network);
|
|
357
463
|
return watch(c, deadline, false);
|
|
358
464
|
}
|
|
359
465
|
/**
|
|
360
466
|
* Stores the answer unless the row holds a final one. A success is given only by the settle whose write stored it,
|
|
361
467
|
* so one payment is answered success once: a success another settle stored first gives the consumed answer, and a
|
|
362
|
-
* success whose write fails gives `settlement_pending` with the id.
|
|
363
|
-
*
|
|
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.
|
|
364
472
|
*/
|
|
365
473
|
async function keep(c, answer, deadline) {
|
|
366
474
|
let wrote;
|
|
367
475
|
try {
|
|
368
476
|
wrote = await inTime(s.answer(c.network, c.txid, answer), deadline);
|
|
369
477
|
}
|
|
370
|
-
catch {
|
|
371
|
-
|
|
372
|
-
return answer.success ? pending(c.txid, c.network) : answer;
|
|
478
|
+
catch (e) {
|
|
479
|
+
log({ event: "answer-not-stored", ...about(c) }, e);
|
|
480
|
+
return answer.success || answer.transaction === "" ? pending(c.txid, c.network) : answer;
|
|
373
481
|
}
|
|
374
|
-
|
|
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;
|
|
375
492
|
}
|
|
376
493
|
/**
|
|
377
494
|
* Answers within `settleWaitMs`. A stored success means the payment is consumed, and gives
|
|
378
495
|
* `invalid_transaction_state` with the id; any other stored final answer is given as it is. A claimed id, or a stored
|
|
379
|
-
* pending answer, is read again from the chain.
|
|
380
|
-
*
|
|
381
|
-
*
|
|
382
|
-
*
|
|
383
|
-
*
|
|
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.
|
|
384
510
|
*/
|
|
385
511
|
async function settle(r) {
|
|
386
512
|
const deadline = performance.now() + settleWaitMs;
|
|
@@ -393,7 +519,8 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
393
519
|
try {
|
|
394
520
|
stored = await inTime(s.read(c.network, c.txid), deadline);
|
|
395
521
|
}
|
|
396
|
-
catch {
|
|
522
|
+
catch (e) {
|
|
523
|
+
log({ event: "store-call-failed", ...about(c), call: "read" }, e);
|
|
397
524
|
return pending(c.txid, c.network);
|
|
398
525
|
}
|
|
399
526
|
if (stored.state === "answered" && !isPending(stored.answer)) {
|
|
@@ -402,27 +529,37 @@ export function createTron(nodes, s, settleWaitMs) {
|
|
|
402
529
|
const waitUntil = deadline - answerReserve(settleWaitMs);
|
|
403
530
|
if (stored.state !== "none")
|
|
404
531
|
return keep(c, await watch(c, waitUntil, true), deadline);
|
|
405
|
-
|
|
406
|
-
|
|
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"))
|
|
407
541
|
return consumed(c);
|
|
408
|
-
if (now !== null)
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
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"));
|
|
412
552
|
let won;
|
|
413
553
|
try {
|
|
414
554
|
won = await inTime(s.claim(c.network, c.txid, new Date(Number(c.raw.expiration))), deadline);
|
|
415
555
|
}
|
|
416
|
-
catch {
|
|
556
|
+
catch (e) {
|
|
557
|
+
log({ event: "store-call-failed", ...about(c), call: "claim" }, e);
|
|
417
558
|
return pending(c.txid, c.network);
|
|
418
559
|
}
|
|
419
560
|
if (!won)
|
|
420
561
|
return keep(c, await watch(c, waitUntil, true), deadline);
|
|
421
|
-
|
|
422
|
-
if (answer.success || answer.transaction !== "")
|
|
423
|
-
return keep(c, answer, deadline);
|
|
424
|
-
const released = await inTime(s.release(c.network, c.txid), deadline).catch(() => false);
|
|
425
|
-
return released ? answer : pending(c.txid, c.network);
|
|
562
|
+
return keep(c, await submit(c, waitUntil), deadline);
|
|
426
563
|
}
|
|
427
564
|
return { verify, settle, networks: nodes.map((n) => n.network) };
|
|
428
565
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* x402's `unexpected_verify_error` and `unexpected_settle_error`: a failure inside the facilitator, its node or its
|
|
3
|
+
* store stopped a check or a settlement, and the client gets nothing it can act on. Each is first given only here,
|
|
4
|
+
* once its entry is in the operator log; a repeated `/settle` gets the stored answer, whose entry is the one written
|
|
5
|
+
* then.
|
|
6
|
+
*/
|
|
7
|
+
import { type InvalidReason, type OperatorEntry, type OperatorLog, type SettleAnswer } from "./answers.js";
|
|
8
|
+
/** `unexpected_verify_error`, once `entry` is in the operator log, with `cause` when there is one. */
|
|
9
|
+
export declare function unexpectedVerify(log: OperatorLog, entry: OperatorEntry, cause?: unknown): InvalidReason;
|
|
10
|
+
/**
|
|
11
|
+
* `unexpected_settle_error` on `entry.network`, with no transaction, once `entry` is in the operator log, with `cause`
|
|
12
|
+
* when there is one.
|
|
13
|
+
*/
|
|
14
|
+
export declare function unexpectedSettle(log: OperatorLog, entry: OperatorEntry & {
|
|
15
|
+
network: string;
|
|
16
|
+
}, cause?: unknown): SettleAnswer;
|
|
17
|
+
/**
|
|
18
|
+
* A verify reason as a settle answer's: a node or store that could not be read before submission is a settle error.
|
|
19
|
+
* Its entry is the one written where the verify reason is given.
|
|
20
|
+
*/
|
|
21
|
+
export declare function settleReason(r: InvalidReason): string;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* x402's `unexpected_verify_error` and `unexpected_settle_error`: a failure inside the facilitator, its node or its
|
|
3
|
+
* store stopped a check or a settlement, and the client gets nothing it can act on. Each is first given only here,
|
|
4
|
+
* once its entry is in the operator log; a repeated `/settle` gets the stored answer, whose entry is the one written
|
|
5
|
+
* then.
|
|
6
|
+
*/
|
|
7
|
+
import { failed } from "./answers.js";
|
|
8
|
+
/** `unexpected_verify_error`, once `entry` is in the operator log, with `cause` when there is one. */
|
|
9
|
+
export function unexpectedVerify(log, entry, cause) {
|
|
10
|
+
log(entry, cause);
|
|
11
|
+
return "unexpected_verify_error";
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* `unexpected_settle_error` on `entry.network`, with no transaction, once `entry` is in the operator log, with `cause`
|
|
15
|
+
* when there is one.
|
|
16
|
+
*/
|
|
17
|
+
export function unexpectedSettle(log, entry, cause) {
|
|
18
|
+
log(entry, cause);
|
|
19
|
+
return failed("unexpected_settle_error", "", entry.network);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A verify reason as a settle answer's: a node or store that could not be read before submission is a settle error.
|
|
23
|
+
* Its entry is the one written where the verify reason is given.
|
|
24
|
+
*/
|
|
25
|
+
export function settleReason(r) {
|
|
26
|
+
return r === "unexpected_verify_error" ? "unexpected_settle_error" : r;
|
|
27
|
+
}
|