@integraledger/profile-facilitator 0.3.1 → 0.5.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 +642 -456
- package/dist/answers.d.ts +11 -4
- package/dist/answers.js +24 -0
- package/dist/core.d.ts +51 -0
- package/dist/core.js +758 -0
- package/dist/http.d.ts +20 -3
- package/dist/http.js +32 -7
- package/dist/index.d.ts +12 -36
- package/dist/index.js +9 -162
- package/dist/module.d.ts +372 -0
- package/dist/module.js +13 -0
- package/dist/modules/algorand/index.d.ts +22 -0
- package/dist/modules/algorand/index.js +247 -0
- package/dist/modules/algorand/own.d.ts +26 -0
- package/dist/modules/algorand/own.js +231 -0
- package/dist/modules/aptos/index.d.ts +23 -0
- package/dist/modules/aptos/index.js +232 -0
- package/dist/modules/cardano/index.d.ts +18 -0
- package/dist/modules/cardano/index.js +124 -0
- package/dist/modules/casper/index.d.ts +120 -0
- package/dist/modules/casper/index.js +442 -0
- package/dist/modules/concordium/index.d.ts +16 -0
- package/dist/modules/concordium/index.js +77 -0
- package/dist/modules/erc7710/index.d.ts +26 -0
- package/dist/modules/erc7710/index.js +220 -0
- package/dist/modules/evm/forms.d.ts +74 -0
- package/dist/modules/evm/forms.js +182 -0
- package/dist/modules/evm/index.d.ts +40 -0
- package/dist/modules/evm/index.js +148 -0
- package/dist/modules/evm/node.d.ts +29 -0
- package/dist/modules/evm/node.js +222 -0
- package/dist/modules/hedera/executor.d.ts +63 -0
- package/dist/modules/hedera/executor.js +343 -0
- package/dist/modules/hedera/index.d.ts +23 -0
- package/dist/modules/hedera/index.js +136 -0
- package/dist/modules/hedera/mirror.d.ts +32 -0
- package/dist/modules/hedera/mirror.js +111 -0
- package/dist/modules/index.d.ts +23 -0
- package/dist/modules/index.js +24 -0
- package/dist/modules/lnbtc/index.d.ts +10 -0
- package/dist/modules/lnbtc/index.js +111 -0
- package/dist/modules/near/index.d.ts +18 -0
- package/dist/modules/near/index.js +246 -0
- package/dist/modules/polkadot/index.d.ts +12 -0
- package/dist/modules/polkadot/index.js +149 -0
- package/dist/modules/polkadot/rail.d.ts +40 -0
- package/dist/{polkadot.js → modules/polkadot/rail.js} +214 -288
- package/dist/modules/solana/index.d.ts +60 -0
- package/dist/modules/solana/index.js +304 -0
- package/dist/modules/solana/reader.d.ts +25 -0
- package/dist/modules/solana/reader.js +194 -0
- package/dist/modules/solana/state.d.ts +6 -0
- package/dist/modules/solana/state.js +103 -0
- package/dist/modules/starknet/index.d.ts +35 -0
- package/dist/modules/starknet/index.js +541 -0
- package/dist/modules/starknet/node.d.ts +78 -0
- package/dist/modules/starknet/node.js +339 -0
- package/dist/modules/stellar/index.d.ts +44 -0
- package/dist/modules/stellar/index.js +481 -0
- package/dist/modules/stellar/node.d.ts +57 -0
- package/dist/modules/stellar/node.js +151 -0
- package/dist/modules/sui/index.d.ts +16 -0
- package/dist/modules/sui/index.js +309 -0
- package/dist/modules/sui/node.d.ts +49 -0
- package/dist/modules/sui/node.js +197 -0
- package/dist/modules/ton/index.d.ts +16 -0
- package/dist/modules/ton/index.js +73 -0
- package/dist/modules/tron/index.d.ts +12 -0
- package/dist/modules/tron/index.js +120 -0
- package/dist/modules/tron/rail.d.ts +32 -0
- package/dist/{tron.js → modules/tron/rail.js} +206 -195
- package/dist/modules/xrpl/index.d.ts +28 -0
- package/dist/modules/xrpl/index.js +299 -0
- package/dist/modules/xrpl/node.d.ts +52 -0
- package/dist/modules/xrpl/node.js +231 -0
- package/dist/modules/xrpl/upto.d.ts +5 -0
- package/dist/modules/xrpl/upto.js +269 -0
- package/dist/record.d.ts +131 -0
- package/dist/record.js +330 -0
- package/dist/unexpected.d.ts +3 -2
- package/dist/unexpected.js +2 -1
- package/dist/wrapper.d.ts +68 -0
- package/dist/wrapper.js +126 -0
- package/package.json +47 -12
- package/dist/polkadot.d.ts +0 -21
- package/dist/store.d.ts +0 -59
- package/dist/store.js +0 -103
- package/dist/tron.d.ts +0 -12
- /package/dist/{base58check.d.ts → modules/tron/base58check.d.ts} +0 -0
- /package/dist/{base58check.js → modules/tron/base58check.js} +0 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The XRPL module's own facilitator for `x402/upto/xrpl` on one network, x402's `upto` scheme on the XRP Ledger, which
|
|
3
|
+
* no published class implements. The payer opens a payment channel to `payTo` and signs one claim off the ledger over
|
|
4
|
+
* the channel and the maximum; `/verify` reads the channel at the validated ledger and makes the scheme's checks of it
|
|
5
|
+
* and of that claim, and refuses a payload carrying `settlementTransaction`. At `/settle` the resource server adds
|
|
6
|
+
* `settlementTransaction`, a `PaymentChannelClaim` its `payTo` key signed for the actual charge with `tfClose`; the
|
|
7
|
+
* module's checks before it submits (`phaseOf` the context: `settle`) and its settle check it against the payment and
|
|
8
|
+
* the channel, and the settle submits it unchanged and waits for it in a validated ledger. The module holds no key and
|
|
9
|
+
* pays no fee (`extra.key` `none`).
|
|
10
|
+
*
|
|
11
|
+
* The record names the payment by its channel, which one claim closes: one row per channel, as the scheme's
|
|
12
|
+
* duplicate-settlement rule keys it. Nothing the payer signs carries H, and lcp reads the channel's create, the
|
|
13
|
+
* payer's act, not the claim, so the module's read is of the claim the record holds: the transaction the settle
|
|
14
|
+
* submitted, by its hash.
|
|
15
|
+
*/
|
|
16
|
+
import { isRefusal } from "@integraledger/lcp";
|
|
17
|
+
import { uptoXrpl } from "@integraledger/lcp/x402-upto-xrpl";
|
|
18
|
+
import { decode, deriveAddress, encodeForSigning, encodeForSigningClaim, verifyKeypairSignature } from "xrpl";
|
|
19
|
+
import { isObject } from "../../answers.js";
|
|
20
|
+
import { outcomeOf, phaseOf } from "../../module.js";
|
|
21
|
+
/** The scheme's landing margin, in seconds: two ledger closes at a pessimistic 10-second rate. */
|
|
22
|
+
const MARGIN_S = 20;
|
|
23
|
+
/** The offset xrpl.js's autofill gives `LastLedgerSequence`, which the settlement window admits. */
|
|
24
|
+
const AUTOFILL_LEDGERS = 20;
|
|
25
|
+
/** Unix seconds at the Ripple epoch, 2000-01-01T00:00:00Z. */
|
|
26
|
+
const RIPPLE_EPOCH = 946_684_800;
|
|
27
|
+
const TF_CLOSE = 0x00020000;
|
|
28
|
+
const TF_RENEW = 0x00010000;
|
|
29
|
+
/** The largest network id that carries no `NetworkID` field. */
|
|
30
|
+
const LEGACY_NETWORK_ID = 1024;
|
|
31
|
+
/** The x402 reason for one of lcp's refusals: the version, the option, or else the payload. */
|
|
32
|
+
function reasonOf(r) {
|
|
33
|
+
if (r.code === "x402/not-v2")
|
|
34
|
+
return "invalid_x402_version";
|
|
35
|
+
if (r.code.startsWith("x402/option") || r.code === "xrpl/currency-not-xrp")
|
|
36
|
+
return "invalid_payment_requirements";
|
|
37
|
+
return "invalid_payload";
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The requirements the payment's `accepted` must equal: at `/verify` the requirements as given; with a settlement
|
|
41
|
+
* transaction, the settle-time requirements with `payload.maxAmount` for `amount`, as the scheme's re-verification
|
|
42
|
+
* makes them.
|
|
43
|
+
*/
|
|
44
|
+
function termsOf(payload, r) {
|
|
45
|
+
const settling = typeof payload.payload["settlementTransaction"] === "string";
|
|
46
|
+
const max = payload.payload["maxAmount"];
|
|
47
|
+
return settling && typeof max === "string" ? { ...r, amount: max } : r;
|
|
48
|
+
}
|
|
49
|
+
/** The checks that read neither the chain nor the clock: the network, then lcp's checks of the payment and its option. */
|
|
50
|
+
async function pure(network, payload, r) {
|
|
51
|
+
if (r.network !== network || payload.accepted?.network !== network)
|
|
52
|
+
return { reason: "invalid_network" };
|
|
53
|
+
const ref = await uptoXrpl.reference(payload, termsOf(payload, r));
|
|
54
|
+
if (isRefusal(ref))
|
|
55
|
+
return { reason: reasonOf(ref), code: ref.code };
|
|
56
|
+
const p = payload.payload;
|
|
57
|
+
for (const k of ["maxAmount", "signature", "publicKey"])
|
|
58
|
+
if (typeof p[k] !== "string")
|
|
59
|
+
return { reason: "invalid_payload" };
|
|
60
|
+
if (!/^[1-9][0-9]{0,16}$/.test(p["maxAmount"]))
|
|
61
|
+
return { reason: "invalid_payload" };
|
|
62
|
+
const settlement = p["settlementTransaction"];
|
|
63
|
+
if (settlement !== undefined && typeof settlement !== "string")
|
|
64
|
+
return { reason: "invalid_payload" };
|
|
65
|
+
return {
|
|
66
|
+
channelId: ref.channel,
|
|
67
|
+
maxAmount: p["maxAmount"],
|
|
68
|
+
signature: p["signature"],
|
|
69
|
+
publicKey: p["publicKey"],
|
|
70
|
+
payer: ref.payer,
|
|
71
|
+
...(typeof settlement === "string" ? { settlementTransaction: settlement } : {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const isPresented = (v) => !("reason" in v);
|
|
75
|
+
const same = (a, b) => typeof a === "string" && typeof b === "string" && a.toUpperCase() === b.toUpperCase();
|
|
76
|
+
const int = (v) => (typeof v === "number" && Number.isSafeInteger(v) ? v : undefined);
|
|
77
|
+
/**
|
|
78
|
+
* The scheme's checks of the channel and the claim (its rules 2 to 7 at `/verify`; at `/settle`, rules 3 to 5 in full
|
|
79
|
+
* against the maximum, and 6 and 7 as the settle-time table relaxes them). The channel and the ledger, or the refusal.
|
|
80
|
+
*/
|
|
81
|
+
async function channelChecks(node, p, r, settling) {
|
|
82
|
+
const channel = await node.payChannel(p.channelId);
|
|
83
|
+
if (channel === null)
|
|
84
|
+
return { reason: "invalid_upto_xrpl_payload_channel_not_found" };
|
|
85
|
+
if (channel["Destination"] !== r.payTo || channel["Account"] !== p.payer)
|
|
86
|
+
return { reason: "invalid_upto_xrpl_payload_recipient_mismatch" };
|
|
87
|
+
const amount = BigInt(String(channel["Amount"] ?? "0"));
|
|
88
|
+
const balance = BigInt(String(channel["Balance"] ?? "0"));
|
|
89
|
+
if (!settling && p.maxAmount !== r.amount)
|
|
90
|
+
return { reason: "invalid_upto_xrpl_payload_amount_mismatch" };
|
|
91
|
+
if (BigInt(p.maxAmount) > amount)
|
|
92
|
+
return { reason: "invalid_upto_xrpl_payload_amount_exceeds_channel" };
|
|
93
|
+
if (!same(p.publicKey, channel["PublicKey"]))
|
|
94
|
+
return { reason: "invalid_upto_xrpl_payload_public_key_mismatch" };
|
|
95
|
+
// xrpl's declaration names a PaymentChannelClaim; it passes ripple-binary-codec's claim, the channel and the drops.
|
|
96
|
+
const claim = encodeForSigningClaim({ channel: p.channelId, amount: p.maxAmount });
|
|
97
|
+
if (!verifyKeypairSignature(claim, p.signature, p.publicKey))
|
|
98
|
+
return { reason: "invalid_upto_xrpl_payload_signature" };
|
|
99
|
+
const { index, closeTime } = await node.validatedClose();
|
|
100
|
+
const cancelAfter = int(channel["CancelAfter"]);
|
|
101
|
+
const expiration = int(channel["Expiration"]);
|
|
102
|
+
const settleDelay = int(channel["SettleDelay"]) ?? 0;
|
|
103
|
+
if (!settling) {
|
|
104
|
+
if (balance !== 0n)
|
|
105
|
+
return { reason: "invalid_upto_xrpl_payload_channel_claimed" };
|
|
106
|
+
const headroom = r.maxTimeoutSeconds + MARGIN_S;
|
|
107
|
+
const minDelay = int(r.extra?.["minSettleDelay"]) ?? 0;
|
|
108
|
+
if (cancelAfter === undefined || cancelAfter < closeTime + headroom)
|
|
109
|
+
return { reason: "invalid_upto_xrpl_payload_channel_expiring" };
|
|
110
|
+
if (expiration !== undefined)
|
|
111
|
+
return { reason: "invalid_upto_xrpl_payload_channel_expiring" };
|
|
112
|
+
if (settleDelay < headroom || settleDelay < minDelay)
|
|
113
|
+
return { reason: "invalid_upto_xrpl_payload_settle_delay_too_short" };
|
|
114
|
+
const validAfter = int(r.extra?.["validAfter"]);
|
|
115
|
+
if (validAfter !== undefined && closeTime < validAfter - RIPPLE_EPOCH)
|
|
116
|
+
return { reason: "invalid_upto_xrpl_payload_not_yet_valid" };
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
if (cancelAfter !== undefined && cancelAfter < closeTime + MARGIN_S)
|
|
120
|
+
return { reason: "invalid_upto_xrpl_payload_channel_expiring" };
|
|
121
|
+
if (expiration !== undefined && expiration < closeTime + MARGIN_S)
|
|
122
|
+
return { reason: "invalid_upto_xrpl_payload_channel_expiring" };
|
|
123
|
+
}
|
|
124
|
+
return { channel, ledger: index };
|
|
125
|
+
}
|
|
126
|
+
/** The checks of the resource server's settlement transaction (the scheme's *Settlement Authorization*); the blob's hash-free form, or the refusal. */
|
|
127
|
+
async function settlementChecks(node, network, p, r, channel, ledger) {
|
|
128
|
+
const mismatch = { reason: "invalid_upto_xrpl_settlement_transaction_mismatch" };
|
|
129
|
+
if (p.settlementTransaction === undefined)
|
|
130
|
+
return { reason: "invalid_upto_xrpl_missing_settlement_transaction" };
|
|
131
|
+
let tx;
|
|
132
|
+
try {
|
|
133
|
+
tx = decode(p.settlementTransaction);
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return mismatch;
|
|
137
|
+
}
|
|
138
|
+
if (tx["TransactionType"] !== "PaymentChannelClaim" || tx["Account"] !== r.payTo)
|
|
139
|
+
return mismatch;
|
|
140
|
+
if (tx["Delegate"] !== undefined || tx["Signers"] !== undefined)
|
|
141
|
+
return mismatch;
|
|
142
|
+
const key = tx["SigningPubKey"];
|
|
143
|
+
const signature = tx["TxnSignature"];
|
|
144
|
+
if (typeof key !== "string" || key === "" || typeof signature !== "string")
|
|
145
|
+
return mismatch;
|
|
146
|
+
if (!verifyKeypairSignature(encodeForSigning(tx), signature, key))
|
|
147
|
+
return mismatch;
|
|
148
|
+
const signer = deriveAddress(key);
|
|
149
|
+
const auth = await node.authorization(r.payTo);
|
|
150
|
+
if (!(signer === r.payTo ? !auth.isMasterKeyDisabled : signer === auth.regularKey)) {
|
|
151
|
+
return { reason: "invalid_upto_xrpl_settlement_signer_not_authorized" };
|
|
152
|
+
}
|
|
153
|
+
if (!same(tx["Channel"], p.channelId))
|
|
154
|
+
return mismatch;
|
|
155
|
+
const flags = Number(tx["Flags"] ?? 0) >>> 0;
|
|
156
|
+
if ((flags & TF_CLOSE) === 0 || (flags & TF_RENEW) !== 0)
|
|
157
|
+
return mismatch;
|
|
158
|
+
const last = int(tx["LastLedgerSequence"]);
|
|
159
|
+
if (last === undefined || last <= ledger || last > ledger + AUTOFILL_LEDGERS + r.maxTimeoutSeconds)
|
|
160
|
+
return mismatch;
|
|
161
|
+
const id = Number(network.slice("xrpl:".length));
|
|
162
|
+
if (id <= LEGACY_NETWORK_ID ? tx["NetworkID"] !== undefined : tx["NetworkID"] !== id)
|
|
163
|
+
return mismatch;
|
|
164
|
+
if (BigInt(r.amount) > BigInt(p.maxAmount))
|
|
165
|
+
return { reason: "invalid_upto_xrpl_payload_settlement_exceeds_amount" };
|
|
166
|
+
const delivered = BigInt(String(channel["Balance"] ?? "0"));
|
|
167
|
+
const claims = ["Balance", "Amount", "Signature", "PublicKey"];
|
|
168
|
+
if (BigInt(r.amount) === 0n || delivered >= BigInt(r.amount)) {
|
|
169
|
+
// A zero charge, or one the channel already delivered: a bare close, carrying no claim.
|
|
170
|
+
if (claims.some((k) => tx[k] !== undefined))
|
|
171
|
+
return mismatch;
|
|
172
|
+
}
|
|
173
|
+
else if (tx["Balance"] !== r.amount ||
|
|
174
|
+
tx["Amount"] !== p.maxAmount ||
|
|
175
|
+
!same(tx["Signature"], p.signature) ||
|
|
176
|
+
!same(tx["PublicKey"], p.publicKey)) {
|
|
177
|
+
return mismatch;
|
|
178
|
+
}
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
function verifyFailure(f, payer) {
|
|
182
|
+
return { isValid: false, invalidReason: f.reason, ...(f.code ? { invalidMessage: f.code } : {}), ...(payer ? { payer } : {}) };
|
|
183
|
+
}
|
|
184
|
+
/** The settler's own `upto` facilitator over the seller's server. */
|
|
185
|
+
function uptoFacilitator(network, node) {
|
|
186
|
+
/** The scheme's checks at `/verify`, or at `/settle` (`settling`), where the settlement transaction is the server's. */
|
|
187
|
+
const checked = async (payload, r, settling) => {
|
|
188
|
+
const p = await pure(network, payload, r);
|
|
189
|
+
if (!isPresented(p))
|
|
190
|
+
return p;
|
|
191
|
+
if (!settling && p.settlementTransaction !== undefined) {
|
|
192
|
+
return { reason: "invalid_upto_xrpl_payload_unexpected_settlement_transaction", payer: p.payer };
|
|
193
|
+
}
|
|
194
|
+
if (settling && p.settlementTransaction === undefined) {
|
|
195
|
+
return { reason: "invalid_upto_xrpl_missing_settlement_transaction", payer: p.payer };
|
|
196
|
+
}
|
|
197
|
+
const c = await channelChecks(node, p, r, settling);
|
|
198
|
+
if ("reason" in c)
|
|
199
|
+
return { ...c, payer: p.payer };
|
|
200
|
+
if (settling) {
|
|
201
|
+
const s = await settlementChecks(node, network, p, r, c.channel, c.ledger);
|
|
202
|
+
if (s !== undefined)
|
|
203
|
+
return { ...s, payer: p.payer };
|
|
204
|
+
}
|
|
205
|
+
return p;
|
|
206
|
+
};
|
|
207
|
+
return {
|
|
208
|
+
scheme: "upto",
|
|
209
|
+
caipFamily: "xrpl:*",
|
|
210
|
+
getExtra: () => undefined,
|
|
211
|
+
getSigners: () => [],
|
|
212
|
+
async verify(payload, r, context) {
|
|
213
|
+
const p = await checked(payload, r, phaseOf(context) === "settle");
|
|
214
|
+
return isPresented(p) ? { isValid: true, payer: p.payer } : verifyFailure(p, p.payer);
|
|
215
|
+
},
|
|
216
|
+
async settle(payload, r) {
|
|
217
|
+
const n = r.network;
|
|
218
|
+
const p = await checked(payload, r, true);
|
|
219
|
+
if (!isPresented(p)) {
|
|
220
|
+
const payer = p.payer;
|
|
221
|
+
return { success: false, errorReason: p.reason, ...(p.code ? { errorMessage: p.code } : {}), transaction: "", network: n, ...(payer ? { payer } : {}) };
|
|
222
|
+
}
|
|
223
|
+
const sent = await node.submit(p.settlementTransaction);
|
|
224
|
+
if (sent.validated && sent.resultCode === "tesSUCCESS")
|
|
225
|
+
return { success: true, transaction: sent.hash, network: n, payer: p.payer, amount: r.amount };
|
|
226
|
+
if (!sent.validated)
|
|
227
|
+
return { success: false, errorReason: "settlement_pending", transaction: sent.hash, network: n, payer: p.payer };
|
|
228
|
+
return { success: false, errorReason: `transaction_failed: ${sent.resultCode}`, transaction: sent.hash, network: n, payer: p.payer };
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/** The module of `x402/upto/xrpl` on the configured network. */
|
|
233
|
+
export function uptoModule(network, node) {
|
|
234
|
+
const n = network;
|
|
235
|
+
return {
|
|
236
|
+
// The maximum a payment authorises is a positive number of drops (lcp's option filter); zero is not established.
|
|
237
|
+
descriptor: { name: "xrpl", key: "none", pairings: [uptoXrpl.id], acceptsZero: false },
|
|
238
|
+
network: n,
|
|
239
|
+
facilitator: uptoFacilitator(network, node),
|
|
240
|
+
record: {
|
|
241
|
+
async instrument(p) {
|
|
242
|
+
const r = await pure(network, p.payload, p.requirements);
|
|
243
|
+
if (!isPresented(r))
|
|
244
|
+
return { refused: r.reason };
|
|
245
|
+
return {
|
|
246
|
+
pairing: uptoXrpl.id,
|
|
247
|
+
// The channel, which one destination claim with tfClose closes: the scheme's settlement identity.
|
|
248
|
+
instrument: { by: "single-use", network: n, signer: r.payer, value: r.channelId, scope: "PayChannel" },
|
|
249
|
+
nonce: uptoXrpl.data.nonce,
|
|
250
|
+
keep: { until: "settler" },
|
|
251
|
+
};
|
|
252
|
+
},
|
|
253
|
+
async read(_p, at) {
|
|
254
|
+
// lcp reads the channel's create, the payer's act, and no claim; the claim the record holds is read by its hash.
|
|
255
|
+
if (at.transaction === undefined)
|
|
256
|
+
return outcomeOf({ state: "pending", reason: "not-found", foreign: [] });
|
|
257
|
+
const t = await node.transaction(at.transaction);
|
|
258
|
+
if (t === null || !t.validated)
|
|
259
|
+
return outcomeOf({ state: "pending", reason: "not-found", foreign: [] });
|
|
260
|
+
if (t.resultCode === "tesSUCCESS") {
|
|
261
|
+
return outcomeOf({ state: "settled", transaction: at.transaction, finality: "validated", presented: "yes", foreign: [] });
|
|
262
|
+
}
|
|
263
|
+
// A claim that failed in a validated ledger consumed nothing: the channel stays open to another claim.
|
|
264
|
+
return outcomeOf({ state: "pending", reason: "instrument-live", transaction: at.transaction, foreign: [] });
|
|
265
|
+
},
|
|
266
|
+
},
|
|
267
|
+
fees: { paysFee: () => false, payerBroadcast: () => false },
|
|
268
|
+
};
|
|
269
|
+
}
|
package/dist/record.d.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import pg from "pg";
|
|
2
|
+
import type { Network } from "@x402/core/types";
|
|
3
|
+
import { type OperatorLog } from "./answers.js";
|
|
4
|
+
import type { FeeMeter, Instrument, Keep, ModuleState } from "./module.js";
|
|
5
|
+
/** The bound on acquiring a connection, on each query as the client waits for it, and on each statement in the server. */
|
|
6
|
+
export declare const STORE_TIMEOUT_MS = 5000;
|
|
7
|
+
/** Opens the pool of the settler's database. `log` receives an error the pool reports for an idle connection. */
|
|
8
|
+
export declare function openPool(url: string, log?: OperatorLog): Promise<pg.Pool>;
|
|
9
|
+
/**
|
|
10
|
+
* The part of `settleWaitMs` kept for writing the answer once the wait for the chain ends: a second, or a quarter of a
|
|
11
|
+
* shorter wait. The node calls and the waits end that much before the deadline, so the answer is stored, then given.
|
|
12
|
+
*/
|
|
13
|
+
export declare function answerReserve(settleWaitMs: number): number;
|
|
14
|
+
/** A store call bounded by `STORE_TIMEOUT_MS` and by what is left before `deadline` (a `performance.now()` time). */
|
|
15
|
+
export declare function inTime<T>(p: Promise<T>, deadline: number): Promise<T>;
|
|
16
|
+
/** How long a final row is kept past its form's lapse or life: a day, as the settler has kept one since its first release. */
|
|
17
|
+
export declare const KEEP_AFTER_MS: number;
|
|
18
|
+
export declare const RECORD_SCHEMA = "CREATE TABLE IF NOT EXISTS instrument (\n network text NOT NULL,\n key text NOT NULL,\n pairing text NOT NULL,\n claimed bigint NOT NULL,\n held_until bigint NOT NULL,\n final boolean NOT NULL DEFAULT false,\n outcome text,\n answer jsonb,\n transaction text,\n sent text[] NOT NULL DEFAULT '{}',\n body text,\n payer text,\n search jsonb,\n since jsonb,\n keep_until bigint,\n PRIMARY KEY (network, key)\n);\nCREATE INDEX IF NOT EXISTS instrument_final_keep ON instrument (keep_until) WHERE final AND keep_until IS NOT NULL;\nCREATE TABLE IF NOT EXISTS fee (\n network text NOT NULL,\n transaction text NOT NULL,\n at bigint NOT NULL,\n fee numeric(78, 0) NOT NULL,\n included boolean NOT NULL,\n PRIMARY KEY (network, transaction)\n);\nCREATE INDEX IF NOT EXISTS fee_at ON fee (network, at);\nCREATE TABLE IF NOT EXISTS module_state (\n module text NOT NULL,\n key text NOT NULL,\n value jsonb NOT NULL,\n PRIMARY KEY (module, key)\n)";
|
|
19
|
+
/** A JSON value with each `bigint` written as `{"$bigint": "<decimal>"}`, so that it survives the store. */
|
|
20
|
+
export declare function toStored(value: unknown): unknown;
|
|
21
|
+
/** A stored JSON value, with each `{"$bigint": "<decimal>"}` read back as a `bigint`. */
|
|
22
|
+
export declare function fromStored(value: unknown): unknown;
|
|
23
|
+
/**
|
|
24
|
+
* The record's key for an instrument, within its network: its kind and its parts as a JSON array, so that no two
|
|
25
|
+
* instruments share one.
|
|
26
|
+
*/
|
|
27
|
+
export declare function keyOf(i: Instrument): string;
|
|
28
|
+
/**
|
|
29
|
+
* The earliest time, in Unix milliseconds, at which a final row may be dropped, before `KEEP_AFTER_MS`: the form's
|
|
30
|
+
* lapse, or its life counted from the claim; null for the settler's life, where the form has neither or its nonce is
|
|
31
|
+
* not single-use.
|
|
32
|
+
*/
|
|
33
|
+
export declare function keepUntil(keep: Keep, nonce: string, claimed: number): number | null;
|
|
34
|
+
/** A row of the record. Times are Unix milliseconds. */
|
|
35
|
+
export interface Row {
|
|
36
|
+
readonly pairing: string;
|
|
37
|
+
readonly claimed: number;
|
|
38
|
+
/** Until when the settle that holds the claim may send; a repeat sends nothing before it. 0 once that settle answered. */
|
|
39
|
+
readonly heldUntil: number;
|
|
40
|
+
readonly final: boolean;
|
|
41
|
+
/** For a final row: `settled`, or the reason of lcp's `failed` answer that made it final. */
|
|
42
|
+
readonly outcome?: string;
|
|
43
|
+
/** For a final row: the answer as first given. */
|
|
44
|
+
readonly answer?: Record<string, unknown>;
|
|
45
|
+
/** The transaction the row names: the last one the settler's submissions named, or the one a read found. */
|
|
46
|
+
readonly transaction?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Every transaction the settler's submissions for the claim named, first to last, the instrument's own id among them
|
|
49
|
+
* where it names one: any of them can be the one that lands.
|
|
50
|
+
*/
|
|
51
|
+
readonly sent: readonly string[];
|
|
52
|
+
/** The digest of the body that claimed the row, the only body a repeat sends again. */
|
|
53
|
+
readonly body?: string;
|
|
54
|
+
readonly payer?: string;
|
|
55
|
+
/** The search position of the last live read that gave one, which the next read resumes from. */
|
|
56
|
+
readonly search?: unknown;
|
|
57
|
+
/** The chain's position the module read just before the claim, from which its reads search. */
|
|
58
|
+
readonly since?: unknown;
|
|
59
|
+
}
|
|
60
|
+
/** What makes a row final. */
|
|
61
|
+
export interface Finish {
|
|
62
|
+
readonly pairing: string;
|
|
63
|
+
readonly outcome: string;
|
|
64
|
+
readonly answer: Record<string, unknown>;
|
|
65
|
+
readonly transaction?: string;
|
|
66
|
+
readonly payer?: string;
|
|
67
|
+
/** As `keepUntil` gives it. */
|
|
68
|
+
readonly keepUntil: number | null;
|
|
69
|
+
readonly now: number;
|
|
70
|
+
}
|
|
71
|
+
export interface InstrumentRecord {
|
|
72
|
+
read(network: string, key: string): Promise<Row | undefined>;
|
|
73
|
+
/** Inserts the claim, held by this call until `now + holdMs`. True where this call inserted it. */
|
|
74
|
+
claim(network: string, key: string, c: {
|
|
75
|
+
pairing: string;
|
|
76
|
+
payer?: string;
|
|
77
|
+
transaction?: string;
|
|
78
|
+
body: string;
|
|
79
|
+
since?: unknown;
|
|
80
|
+
now: number;
|
|
81
|
+
holdMs: number;
|
|
82
|
+
}): Promise<boolean>;
|
|
83
|
+
/**
|
|
84
|
+
* Takes a claim that is not final and whose hold has ended, until `now + holdMs`: the row as this call took it, or
|
|
85
|
+
* undefined where it did not take it.
|
|
86
|
+
*/
|
|
87
|
+
retake(network: string, key: string, now: number, holdMs: number): Promise<Row | undefined>;
|
|
88
|
+
/** Adds a transaction the settler's submission named to a claim that is not final, as the one the row names. */
|
|
89
|
+
sent(network: string, key: string, transaction: string): Promise<void>;
|
|
90
|
+
/** Ends this call's hold of a claim that is not final, keeping the search position of its read. */
|
|
91
|
+
release(network: string, key: string, learnt: {
|
|
92
|
+
search?: unknown;
|
|
93
|
+
}): Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* Makes the row final with `f.answer`, unless it is final already; a row the record does not hold is inserted final.
|
|
96
|
+
* True where this call made it final: the one call whose answer is the row's.
|
|
97
|
+
*/
|
|
98
|
+
finish(network: string, key: string, f: Finish): Promise<boolean>;
|
|
99
|
+
/** Drops the final rows kept past `KEEP_AFTER_MS` after their keep, and the fees older than `feesBefore`. */
|
|
100
|
+
sweep(now: number, feesBefore: number): Promise<void>;
|
|
101
|
+
}
|
|
102
|
+
/** The record over `pool`, its tables created. */
|
|
103
|
+
export declare function openRecord(pool: pg.Pool): Promise<InstrumentRecord>;
|
|
104
|
+
/** One network's fee budget: an amount of its fee asset, in its smallest unit, over a period of seconds. */
|
|
105
|
+
export interface FeeBudget {
|
|
106
|
+
readonly network: Network;
|
|
107
|
+
readonly amount: bigint;
|
|
108
|
+
readonly periodSeconds: number;
|
|
109
|
+
}
|
|
110
|
+
/** The fee count of the networks that have a budget. */
|
|
111
|
+
export interface Fees {
|
|
112
|
+
/** Whether `network` has a budget. */
|
|
113
|
+
budgeted(network: string): boolean;
|
|
114
|
+
/** Whether `network`'s budget is spent: its count over the last period has reached its amount. */
|
|
115
|
+
spent(network: string, now: number): Promise<boolean>;
|
|
116
|
+
/**
|
|
117
|
+
* Counts a transaction the settler submitted on `network`: `fee` is its bound until `included`, then what it paid. A
|
|
118
|
+
* paid fee is never replaced by a bound, and the transaction keeps the time it was first counted at.
|
|
119
|
+
*/
|
|
120
|
+
count(network: string, transaction: string, fee: bigint, included: boolean, now: number): Promise<void>;
|
|
121
|
+
/** The meter an own module whose key pays fees on `network` is given. */
|
|
122
|
+
meter(network: Network, now: () => number, log: OperatorLog): FeeMeter;
|
|
123
|
+
/** The oldest time any budget's period still counts. */
|
|
124
|
+
oldest(now: number): number;
|
|
125
|
+
}
|
|
126
|
+
/** The fee count over `pool`, for `budgets`, at most one per network. */
|
|
127
|
+
export declare function feesOn(pool: pg.Pool, budgets: readonly FeeBudget[]): Fees;
|
|
128
|
+
/** `module`'s durable state over `pool`. */
|
|
129
|
+
export declare function moduleState(pool: pg.Pool, module: string): ModuleState;
|
|
130
|
+
/** Runs `record.sweep` every minute until the returned function is called; a sweep that fails goes to `log`. */
|
|
131
|
+
export declare function sweeping(record: InstrumentRecord, fees: Fees, log?: OperatorLog): () => void;
|