@redditech/x402-solana 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -0
- package/LICENSE +21 -0
- package/README.md +301 -2
- package/dist/budget-policy.d.ts +68 -0
- package/dist/budget-policy.js +234 -0
- package/dist/buyer.d.ts +54 -0
- package/dist/buyer.js +147 -0
- package/dist/client.d.ts +80 -0
- package/dist/client.js +225 -0
- package/dist/direct-auth.d.ts +94 -0
- package/dist/direct-auth.js +120 -0
- package/dist/direct-payment.d.ts +33 -0
- package/dist/direct-payment.js +65 -0
- package/dist/ed25519.d.ts +6 -0
- package/dist/ed25519.js +42 -0
- package/dist/escrow-http.d.ts +125 -0
- package/dist/escrow-http.js +192 -0
- package/dist/escrow-readiness.d.ts +132 -0
- package/dist/escrow-readiness.js +171 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +42 -0
- package/dist/jupiter.d.ts +36 -0
- package/dist/jupiter.js +120 -0
- package/dist/metered.d.ts +58 -0
- package/dist/metered.js +82 -0
- package/dist/middleware.d.ts +9 -0
- package/dist/middleware.js +71 -0
- package/dist/nonce.d.ts +57 -0
- package/dist/nonce.js +123 -0
- package/dist/payment.d.ts +202 -0
- package/dist/payment.js +967 -0
- package/dist/provider.d.ts +371 -0
- package/dist/provider.js +492 -0
- package/dist/rating.d.ts +552 -0
- package/dist/rating.js +829 -0
- package/dist/session-auth.d.ts +168 -0
- package/dist/session-auth.js +341 -0
- package/dist/session.d.ts +220 -0
- package/dist/session.js +297 -0
- package/dist/spl-token-observer.d.ts +70 -0
- package/dist/spl-token-observer.js +319 -0
- package/dist/token-escrow.d.ts +125 -0
- package/dist/token-escrow.js +163 -0
- package/dist/types.d.ts +148 -0
- package/dist/types.js +2 -0
- package/package.json +109 -4
package/dist/provider.js
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_MAX_CHARGE_MULTIPLE = exports.DEFAULT_MAX_OUTPUT_TOKENS = void 0;
|
|
4
|
+
exports.providerMeteredTerms = providerMeteredTerms;
|
|
5
|
+
exports.estimateInputTokens = estimateInputTokens;
|
|
6
|
+
exports.outputLimit = outputLimit;
|
|
7
|
+
exports.meteredEstimate = meteredEstimate;
|
|
8
|
+
exports.meteredOffer = meteredOffer;
|
|
9
|
+
exports.readMeteredPaymentHeader = readMeteredPaymentHeader;
|
|
10
|
+
exports.meteredPaymentHeaderValue = meteredPaymentHeaderValue;
|
|
11
|
+
exports.checkProviderCluster = checkProviderCluster;
|
|
12
|
+
exports.checkMeteredPayout = checkMeteredPayout;
|
|
13
|
+
exports.verifyMeteredLock = verifyMeteredLock;
|
|
14
|
+
exports.meteredEscrowReplayKey = meteredEscrowReplayKey;
|
|
15
|
+
exports.usageFrom = usageFrom;
|
|
16
|
+
exports.meteredSettlement = meteredSettlement;
|
|
17
|
+
exports.recordedInstruction = recordedInstruction;
|
|
18
|
+
exports.transactionHasOnlyInstruction = transactionHasOnlyInstruction;
|
|
19
|
+
exports.confirmMeteredSettlement = confirmMeteredSettlement;
|
|
20
|
+
exports.meteredDecline = meteredDecline;
|
|
21
|
+
exports.meteredRatingAccount = meteredRatingAccount;
|
|
22
|
+
/**
|
|
23
|
+
* The seller side of a per-token (metered) call.
|
|
24
|
+
*
|
|
25
|
+
* A buyer locks the most it will pay in a metered token escrow payable to the
|
|
26
|
+
* provider. The provider reads the lock back from the chain, serves the call,
|
|
27
|
+
* counts the tokens the model reports and settles the actual cost. The escrow
|
|
28
|
+
* program pays the protocol fee (2.5% until 1 April 2027, then 5%) of that to the protocol treasury, the rest to the
|
|
29
|
+
* provider, and returns the unused maximum to the buyer.
|
|
30
|
+
*
|
|
31
|
+
* Nothing here reads a key or sends a transaction. `meteredSettlement` returns
|
|
32
|
+
* instructions; the operator signs and sends them.
|
|
33
|
+
*/
|
|
34
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
35
|
+
const spl_token_1 = require("@solana/spl-token");
|
|
36
|
+
const escrow_readiness_1 = require("./escrow-readiness");
|
|
37
|
+
const metered_1 = require("./metered");
|
|
38
|
+
const payment_1 = require("./payment");
|
|
39
|
+
const rating_1 = require("./rating");
|
|
40
|
+
const token_escrow_1 = require("./token-escrow");
|
|
41
|
+
/** Output tokens assumed when the request sets no limit and the operator sets none. */
|
|
42
|
+
exports.DEFAULT_MAX_OUTPUT_TOKENS = 1000;
|
|
43
|
+
/** The buyer's default maximum, as a multiple of the estimate. The buyer may raise it, never below the estimate. */
|
|
44
|
+
exports.DEFAULT_MAX_CHARGE_MULTIPLE = 2;
|
|
45
|
+
/**
|
|
46
|
+
* A provider's metered terms. Throws when the currency is not a token
|
|
47
|
+
* currency, a price does not parse, or an address is malformed.
|
|
48
|
+
*/
|
|
49
|
+
function providerMeteredTerms(input) {
|
|
50
|
+
const currency = (0, payment_1.directPaymentCurrency)(input.currency);
|
|
51
|
+
if (!currency)
|
|
52
|
+
throw new Error(`unsupported currency: ${input.currency}`);
|
|
53
|
+
// SOL settles through the SOL escrow, which has no metered seller path here.
|
|
54
|
+
if (!currency.tokenProgram)
|
|
55
|
+
throw new Error(`${input.currency} is not a token currency: metered calls are priced in USDC, AUDD, PYUSD or USDG`);
|
|
56
|
+
const price = { currency: input.currency, inputPerMillion: input.inputPerMillion, outputPerMillion: input.outputPerMillion };
|
|
57
|
+
if ((0, metered_1.tokenCostBaseUnits)(price, { inputTokens: 1000000, outputTokens: 1000000 }) <= BigInt(0))
|
|
58
|
+
throw new Error('a metered price must be above zero');
|
|
59
|
+
const maxOutputTokens = input.maxOutputTokens ?? exports.DEFAULT_MAX_OUTPUT_TOKENS;
|
|
60
|
+
if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0)
|
|
61
|
+
throw new Error('maxOutputTokens must be a positive whole number');
|
|
62
|
+
return {
|
|
63
|
+
price,
|
|
64
|
+
programId: new web3_js_1.PublicKey(input.programId),
|
|
65
|
+
mint: new web3_js_1.PublicKey(input.mint),
|
|
66
|
+
tokenProgram: new web3_js_1.PublicKey(currency.tokenProgram),
|
|
67
|
+
payee: new web3_js_1.PublicKey(input.payee),
|
|
68
|
+
maxOutputTokens,
|
|
69
|
+
...(input.payoutAccount ? { payoutAccount: new web3_js_1.PublicKey(input.payoutAccount) } : {}),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** About four characters a token, over every message. */
|
|
73
|
+
function estimateInputTokens(messages) {
|
|
74
|
+
return messages.reduce((total, message) => total + Math.ceil((typeof message.content === 'string' ? message.content : '').length / 4), 0);
|
|
75
|
+
}
|
|
76
|
+
/** Output limit for this call: the request's own, held to the provider's. */
|
|
77
|
+
function outputLimit(terms, requested) {
|
|
78
|
+
return requested !== undefined && Number.isSafeInteger(requested) && requested > 0 ? Math.min(requested, terms.maxOutputTokens) : terms.maxOutputTokens;
|
|
79
|
+
}
|
|
80
|
+
/** The estimate a call is quoted on: the input estimate plus the full output limit. */
|
|
81
|
+
function meteredEstimate(terms, messages, requestedMaxTokens) {
|
|
82
|
+
return { inputTokens: estimateInputTokens(messages), outputTokens: outputLimit(terms, requestedMaxTokens) };
|
|
83
|
+
}
|
|
84
|
+
/** What a 402 tells a buyer about metered payment. The buyer's lock must cover `minimumLockBaseUnits`. */
|
|
85
|
+
function meteredOffer(terms, messages, requestedMaxTokens, network) {
|
|
86
|
+
const estimate = meteredEstimate(terms, messages, requestedMaxTokens);
|
|
87
|
+
const decimals = (0, payment_1.directPaymentCurrency)(terms.price.currency).decimals;
|
|
88
|
+
const minimum = (0, metered_1.tokenCostBaseUnits)(terms.price, estimate);
|
|
89
|
+
const suggested = minimum * BigInt(exports.DEFAULT_MAX_CHARGE_MULTIPLE);
|
|
90
|
+
const quote = suggested > BigInt(0) ? (0, metered_1.quoteMeteredCall)(terms.price, estimate, (0, payment_1.baseUnitsToDecimal)(suggested, decimals)) : undefined;
|
|
91
|
+
return {
|
|
92
|
+
settlement: 'metered-escrow',
|
|
93
|
+
...(network ? { network } : {}),
|
|
94
|
+
currency: terms.price.currency,
|
|
95
|
+
inputPerMillion: terms.price.inputPerMillion,
|
|
96
|
+
outputPerMillion: terms.price.outputPerMillion,
|
|
97
|
+
maxOutputTokens: terms.maxOutputTokens,
|
|
98
|
+
estimate,
|
|
99
|
+
estimatedCost: quote?.estimatedCost ?? '0',
|
|
100
|
+
suggestedMaxCharge: quote?.maxCharge ?? '0',
|
|
101
|
+
suggestedMaxChargeBaseUnits: suggested.toString(),
|
|
102
|
+
estimatedFee: quote?.estimatedFee ?? '0',
|
|
103
|
+
minimumLockBaseUnits: minimum.toString(),
|
|
104
|
+
escrowProgramId: terms.programId.toBase58(),
|
|
105
|
+
mint: terms.mint.toBase58(),
|
|
106
|
+
payTo: terms.payee.toBase58(),
|
|
107
|
+
nonce: '32 lowercase hex characters you choose; the escrow is [token-escrow, payer, nonce]',
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
const NONCE_HEX = /^[0-9a-f]{32}$/;
|
|
111
|
+
/** The metered receipt a buyer presents, or undefined when the header is not one. */
|
|
112
|
+
function readMeteredPaymentHeader(headers) {
|
|
113
|
+
const value = headers.get('x402-payment') ?? headers.get('x-payment');
|
|
114
|
+
if (!value)
|
|
115
|
+
return undefined;
|
|
116
|
+
const parsed = (0, payment_1.parseX402PaymentHeader)(value);
|
|
117
|
+
if (!parsed || typeof parsed !== 'object' || parsed.settlement !== 'metered-escrow')
|
|
118
|
+
return undefined;
|
|
119
|
+
const record = parsed;
|
|
120
|
+
const nonce = typeof record.nonce === 'string' ? record.nonce.replace(/-/g, '').toLowerCase() : '';
|
|
121
|
+
if (!NONCE_HEX.test(nonce))
|
|
122
|
+
return { error: 'A metered payment names the 16-byte escrow nonce as 32 hex characters.' };
|
|
123
|
+
try {
|
|
124
|
+
return { escrow: new web3_js_1.PublicKey(String(record.escrow)), payer: new web3_js_1.PublicKey(String(record.payer)), nonce: Uint8Array.from(Buffer.from(nonce, 'hex')) };
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return { error: 'A metered payment must name the payer and the escrow address.' };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** The value a buyer sends in `x402-payment` once its metered lock is confirmed. */
|
|
131
|
+
function meteredPaymentHeaderValue(input) {
|
|
132
|
+
if (input.nonce.length !== 16)
|
|
133
|
+
throw new Error('nonce must be 16 bytes');
|
|
134
|
+
const { escrow } = (0, token_escrow_1.tokenEscrowAddresses)({ programId: input.programId, payer: input.payer, nonce: input.nonce });
|
|
135
|
+
return JSON.stringify({ settlement: 'metered-escrow', escrow: escrow.toBase58(), payer: input.payer.toBase58(), nonce: Buffer.from(input.nonce).toString('hex') });
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Confirms the RPC endpoint serves the network the provider is configured
|
|
139
|
+
* for, so a lock on another cluster is never taken as payment. Run it before
|
|
140
|
+
* trusting any account the endpoint returns.
|
|
141
|
+
*/
|
|
142
|
+
async function checkProviderCluster(readGenesisHash, network, expectedGenesisHash) {
|
|
143
|
+
const publicHash = payment_1.SOLANA_GENESIS_HASHES[network];
|
|
144
|
+
if (!publicHash)
|
|
145
|
+
return { ok: false, reason: 'wrong_cluster', message: `Unknown network ${String(network)}.` };
|
|
146
|
+
// A public cluster's hash cannot be replaced. Only a local validator has its own.
|
|
147
|
+
if (expectedGenesisHash !== undefined && network === 'solana-mainnet-beta' && expectedGenesisHash !== publicHash) {
|
|
148
|
+
return { ok: false, reason: 'wrong_cluster', message: 'The mainnet genesis hash cannot be replaced.' };
|
|
149
|
+
}
|
|
150
|
+
let actual;
|
|
151
|
+
try {
|
|
152
|
+
actual = await readGenesisHash();
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return { ok: false, reason: 'payment_check_unavailable', message: 'The chain could not be read. Nothing was accepted.' };
|
|
156
|
+
}
|
|
157
|
+
const expected = expectedGenesisHash ?? publicHash;
|
|
158
|
+
return actual === expected ? { ok: true } : { ok: false, reason: 'wrong_cluster', message: `The RPC endpoint is not ${network}.` };
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Reads every account a settle of this escrow would pay into and says whether
|
|
162
|
+
* the payout can land: the provider's token account (or its recovery
|
|
163
|
+
* account), the treasury's, and the buyer's account for the unused part. Each
|
|
164
|
+
* must exist under the mint's token program, be initialised, not frozen, hold
|
|
165
|
+
* the mint, have the right owner and not require a memo.
|
|
166
|
+
*
|
|
167
|
+
* Nothing is created by default. `allowPayerAssociatedAccount` lets the
|
|
168
|
+
* unused part go to the payer's associated token account when the recorded
|
|
169
|
+
* source no longer works; `createRefundAccount` lets the provider pay to
|
|
170
|
+
* create that account when it does not exist at all.
|
|
171
|
+
*/
|
|
172
|
+
async function checkMeteredPayout(input) {
|
|
173
|
+
const { terms, escrow } = input;
|
|
174
|
+
const token = { mint: terms.mint, tokenProgram: terms.tokenProgram };
|
|
175
|
+
const treasury = input.treasury ?? token_escrow_1.ESCROW_PROTOCOL_TREASURY;
|
|
176
|
+
const treasuryToken = (0, token_escrow_1.treasuryTokenAccount)(token, treasury);
|
|
177
|
+
const notReady = (message) => ({ ok: false, reason: 'provider_not_ready', message });
|
|
178
|
+
try {
|
|
179
|
+
let payTo;
|
|
180
|
+
if (!(0, escrow_readiness_1.checkTokenAccount)(escrow.recipient, await input.readAccount(escrow.recipient), { ...token, owner: terms.payee }).ok) {
|
|
181
|
+
const recovery = terms.payoutAccount;
|
|
182
|
+
if (!recovery || recovery.equals(escrow.recipient) || !(0, escrow_readiness_1.checkTokenAccount)(recovery, await input.readAccount(recovery), { ...token, owner: terms.payee }).ok) {
|
|
183
|
+
return notReady(`This provider's ${terms.price.currency} account cannot receive payment right now. Nothing was accepted; your lock is untouched.`);
|
|
184
|
+
}
|
|
185
|
+
payTo = recovery;
|
|
186
|
+
}
|
|
187
|
+
if (!(0, escrow_readiness_1.checkTokenAccount)(treasuryToken, await input.readAccount(treasuryToken), { ...token, owner: treasury }).ok) {
|
|
188
|
+
return notReady(`The protocol treasury cannot receive ${terms.price.currency} right now, so this provider is not taking payment in it. Nothing was accepted; your lock is untouched.`);
|
|
189
|
+
}
|
|
190
|
+
let harvestWithheldFees = false;
|
|
191
|
+
if (terms.tokenProgram.equals(spl_token_1.TOKEN_2022_PROGRAM_ID)) {
|
|
192
|
+
const mint = await input.readAccount(terms.mint);
|
|
193
|
+
if (!mint || !mint.owner.equals(spl_token_1.TOKEN_2022_PROGRAM_ID))
|
|
194
|
+
return notReady(`The ${terms.price.currency} mint could not be read. Nothing was accepted; your lock is untouched.`);
|
|
195
|
+
try {
|
|
196
|
+
harvestWithheldFees = (0, spl_token_1.getTransferFeeConfig)((0, spl_token_1.unpackMint)(terms.mint, { data: Buffer.from(mint.data), owner: mint.owner, lamports: 0, executable: false }, spl_token_1.TOKEN_2022_PROGRAM_ID)) !== null;
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
return notReady(`The ${terms.price.currency} mint could not be read. Nothing was accepted; your lock is untouched.`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const base = { ...(payTo ? { payTo } : {}), treasuryToken, harvestWithheldFees };
|
|
203
|
+
const refundTarget = { ...token, owner: escrow.payer };
|
|
204
|
+
const source = await input.readAccount(escrow.source);
|
|
205
|
+
if ((0, escrow_readiness_1.checkTokenAccount)(escrow.source, source, refundTarget).ok)
|
|
206
|
+
return { ok: true, payout: { ...base, refundTo: escrow.source } };
|
|
207
|
+
if (input.allowPayerAssociatedAccount || input.createRefundAccount) {
|
|
208
|
+
const associated = (0, spl_token_1.getAssociatedTokenAddressSync)(terms.mint, escrow.payer, true, terms.tokenProgram);
|
|
209
|
+
const held = associated.equals(escrow.source) ? source : await input.readAccount(associated);
|
|
210
|
+
if ((0, escrow_readiness_1.checkTokenAccount)(associated, held, refundTarget).ok)
|
|
211
|
+
return { ok: true, payout: { ...base, refundTo: associated } };
|
|
212
|
+
// Only an account that does not exist can be created. A frozen or memo-requiring one stays as it is.
|
|
213
|
+
if (input.createRefundAccount && held === null)
|
|
214
|
+
return { ok: true, payout: { ...base, refundTo: associated, createRefundAccount: true } };
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
ok: false,
|
|
218
|
+
reason: 'refund_account_unusable',
|
|
219
|
+
message: `The ${terms.price.currency} account that funded this lock is closed, frozen or requires a memo, so the unused part could not be returned to you. Nothing was accepted. Restore that account and present the same lock again, or refund the lock once its refund window opens.`,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return { ok: false, reason: 'payment_check_unavailable', message: 'The chain could not be read. Nothing was accepted; present the same receipt again.' };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Checks the lock on chain against this provider's terms: the escrow program,
|
|
228
|
+
* the address the payer and nonce give, still locked, metered, payable to this
|
|
229
|
+
* provider's token account in the accepted mint, and at least `minimum`. Then
|
|
230
|
+
* checks that the payout can land (`checkMeteredPayout`), using the source
|
|
231
|
+
* account the lock recorded for the unused part, so a call is refused before
|
|
232
|
+
* any work is done rather than left unpaid after it.
|
|
233
|
+
* The escrow is then remembered, so one lock pays for one call.
|
|
234
|
+
*
|
|
235
|
+
* An escrow the buyer opted in to rating is refused (`rated_escrow_declined`)
|
|
236
|
+
* before anything is served or remembered, unless `acceptRatedEscrows` is
|
|
237
|
+
* true. `readAccount` must read at `confirmed` commitment or better for that
|
|
238
|
+
* answer to be final (see `AccountReader`).
|
|
239
|
+
*/
|
|
240
|
+
async function verifyMeteredLock(input) {
|
|
241
|
+
const purpose = input.purpose ?? 'call';
|
|
242
|
+
const { header, terms } = input;
|
|
243
|
+
const expected = (0, token_escrow_1.tokenEscrowAddresses)({ programId: terms.programId, payer: header.payer, nonce: header.nonce }).escrow;
|
|
244
|
+
if (!expected.equals(header.escrow))
|
|
245
|
+
return { ok: false, reason: 'invalid_receipt', message: 'The escrow address is not the one this payer and nonce give.' };
|
|
246
|
+
let account;
|
|
247
|
+
try {
|
|
248
|
+
account = await input.readAccount(header.escrow);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
return { ok: false, reason: 'payment_check_unavailable', message: 'The chain could not be read. Nothing was accepted; present the same receipt again.' };
|
|
252
|
+
}
|
|
253
|
+
if (!account)
|
|
254
|
+
return { ok: false, reason: 'invalid_receipt', message: 'No escrow is locked at that address yet.' };
|
|
255
|
+
if (!account.owner.equals(terms.programId))
|
|
256
|
+
return { ok: false, reason: 'invalid_receipt', message: 'That account is not held by the escrow program.' };
|
|
257
|
+
let escrow;
|
|
258
|
+
try {
|
|
259
|
+
escrow = (0, token_escrow_1.decodeTokenEscrowAccount)(Buffer.from(account.data));
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
return { ok: false, reason: 'invalid_receipt', message: 'That account is not a token escrow.' };
|
|
263
|
+
}
|
|
264
|
+
if (escrow.status !== 0)
|
|
265
|
+
return { ok: false, reason: 'duplicate_nonce', message: 'This escrow has already been settled or cancelled.' };
|
|
266
|
+
if (!escrow.metered)
|
|
267
|
+
return { ok: false, reason: 'invalid_receipt', message: 'This escrow was not locked as a metered escrow.' };
|
|
268
|
+
if (escrow.rated && input.acceptRatedEscrows !== true) {
|
|
269
|
+
return { ok: false, reason: 'rated_escrow_declined', message: 'This escrow was opted in to rating, and this provider does not take rated jobs. Nothing was accepted or served. Lock a new escrow without rating, and refund this one once its refund window opens.' };
|
|
270
|
+
}
|
|
271
|
+
// The payer may refund once its window has elapsed, so the settlement has to
|
|
272
|
+
// land before then. The time left now is what counts, not the window named
|
|
273
|
+
// at lock: a buyer could lock, wait out most of the window, then make the
|
|
274
|
+
// call. An escrow that states no window, or a slot that cannot be read, is
|
|
275
|
+
// refused.
|
|
276
|
+
if (escrow.cancelWindowSlots === undefined) {
|
|
277
|
+
return { ok: false, reason: 'invalid_receipt', message: 'This escrow states no refund window. Lock a new one with the current program.' };
|
|
278
|
+
}
|
|
279
|
+
if (purpose !== 'session-settle') {
|
|
280
|
+
let currentSlot;
|
|
281
|
+
try {
|
|
282
|
+
currentSlot = BigInt(await input.readSlot());
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
return { ok: false, reason: 'payment_check_unavailable', message: 'The chain could not be read. Nothing was accepted; present the same receipt again.' };
|
|
286
|
+
}
|
|
287
|
+
const elapsed = currentSlot > escrow.createdSlot ? currentSlot - escrow.createdSlot : BigInt(0);
|
|
288
|
+
if (escrow.cancelWindowSlots < elapsed + token_escrow_1.SELLER_MIN_CANCEL_WINDOW_SLOTS) {
|
|
289
|
+
return purpose === 'session-call'
|
|
290
|
+
? { ok: false, reason: 'session_window_closing', message: "This session's refund window has less than 10 minutes left, so it takes no more calls and is settled now. Lock a new escrow to go on." }
|
|
291
|
+
: { ok: false, reason: 'invalid_receipt', message: "This escrow's refund window has less than 10 minutes left. Lock a new one with a longer refund window, then make the call straight away." };
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (!escrow.payer.equals(header.payer))
|
|
295
|
+
return { ok: false, reason: 'invalid_receipt', message: 'The escrow was locked by a different wallet.' };
|
|
296
|
+
if (!escrow.payee.equals(terms.payee))
|
|
297
|
+
return { ok: false, reason: 'wrong_payee', message: 'The escrow pays a different provider.' };
|
|
298
|
+
if (!escrow.mint.equals(terms.mint))
|
|
299
|
+
return { ok: false, reason: 'wrong_currency', message: `The escrow holds a different mint than this provider's ${terms.price.currency}.` };
|
|
300
|
+
// The provider's associated token account for the mint (the helper derives any owner's).
|
|
301
|
+
if (!escrow.recipient.equals((0, token_escrow_1.treasuryTokenAccount)({ mint: terms.mint, tokenProgram: terms.tokenProgram }, terms.payee))) {
|
|
302
|
+
return { ok: false, reason: 'wrong_payee', message: 'The escrow pays a token account this provider does not use.' };
|
|
303
|
+
}
|
|
304
|
+
if (escrow.amount < input.minimum) {
|
|
305
|
+
return { ok: false, reason: 'wrong_amount', message: `The locked maximum is below this request's estimate of ${input.minimum.toString()} base units.` };
|
|
306
|
+
}
|
|
307
|
+
// A rated job is named by its rating's opened slot: read it now, with the
|
|
308
|
+
// lock this provider is about to serve, and keep it for the settle.
|
|
309
|
+
let openedSlot;
|
|
310
|
+
if (escrow.rated) {
|
|
311
|
+
let ratingAccount;
|
|
312
|
+
try {
|
|
313
|
+
ratingAccount = await input.readAccount((0, rating_1.ratingPda)(header.escrow, terms.programId));
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return { ok: false, reason: 'payment_check_unavailable', message: 'The chain could not be read. Nothing was accepted; present the same receipt again.' };
|
|
317
|
+
}
|
|
318
|
+
let rating;
|
|
319
|
+
try {
|
|
320
|
+
rating = ratingAccount && ratingAccount.owner.equals(terms.programId) ? (0, rating_1.decodeRatingAccount)(Buffer.from(ratingAccount.data)) : undefined;
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
rating = undefined;
|
|
324
|
+
}
|
|
325
|
+
// A rating opens in its escrow's lock slot, so a rating whose opened slot
|
|
326
|
+
// is not this escrow's lock slot belongs to another job at this address.
|
|
327
|
+
if (!rating || !rating.escrow.equals(header.escrow) || rating.state !== 'awaiting_settlement' || rating.openedSlot !== escrow.createdSlot) {
|
|
328
|
+
return { ok: false, reason: 'invalid_receipt', message: "This escrow is opted in to rating, but its rating account could not be read as this job's. Nothing was accepted." };
|
|
329
|
+
}
|
|
330
|
+
openedSlot = rating.openedSlot;
|
|
331
|
+
}
|
|
332
|
+
// Reading a lock back to settle calls already served: if the account that
|
|
333
|
+
// funded it is gone, the unused part goes to the payer's associated token
|
|
334
|
+
// account, created by the settle at the provider's cost when it does not
|
|
335
|
+
// exist and the provider allowed that.
|
|
336
|
+
const payout = await checkMeteredPayout({
|
|
337
|
+
terms,
|
|
338
|
+
escrow,
|
|
339
|
+
readAccount: input.readAccount,
|
|
340
|
+
...(input.treasury ? { treasury: input.treasury } : {}),
|
|
341
|
+
...(purpose === 'session-settle' ? { allowPayerAssociatedAccount: true, createRefundAccount: input.createRefundAccount === true } : {}),
|
|
342
|
+
});
|
|
343
|
+
if (!payout.ok)
|
|
344
|
+
return payout;
|
|
345
|
+
if (purpose === 'call' && !(await input.replayStore.checkAndStore(meteredEscrowReplayKey(header.escrow)))) {
|
|
346
|
+
return { ok: false, reason: 'duplicate_nonce', message: 'This escrow has already paid for a call.' };
|
|
347
|
+
}
|
|
348
|
+
return {
|
|
349
|
+
ok: true,
|
|
350
|
+
payer: escrow.payer,
|
|
351
|
+
payout: payout.payout,
|
|
352
|
+
rated: escrow.rated,
|
|
353
|
+
createdSlot: escrow.createdSlot,
|
|
354
|
+
...(openedSlot !== undefined ? { openedSlot } : {}),
|
|
355
|
+
maxBaseUnits: escrow.amount,
|
|
356
|
+
terms: {
|
|
357
|
+
programId: terms.programId,
|
|
358
|
+
tokenProgram: terms.tokenProgram,
|
|
359
|
+
payer: escrow.payer,
|
|
360
|
+
payee: escrow.payee,
|
|
361
|
+
mint: escrow.mint,
|
|
362
|
+
source: escrow.source,
|
|
363
|
+
recipient: escrow.recipient,
|
|
364
|
+
amount: escrow.amount,
|
|
365
|
+
nonce: Uint8Array.from(escrow.nonce),
|
|
366
|
+
metered: true,
|
|
367
|
+
...(escrow.claimWindowSlots !== undefined && escrow.cancelWindowSlots !== undefined
|
|
368
|
+
? { claimWindowSlots: escrow.claimWindowSlots, cancelWindowSlots: escrow.cancelWindowSlots }
|
|
369
|
+
: {}),
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/** The replay-store key that marks an escrow as taken, by a single call or by a session's first call. */
|
|
374
|
+
function meteredEscrowReplayKey(escrow) {
|
|
375
|
+
return `metered-escrow:${escrow.toBase58()}`;
|
|
376
|
+
}
|
|
377
|
+
/** Token counts from an OpenAI-style usage report, or the estimate from the text when it reports none. */
|
|
378
|
+
function usageFrom(upstream, inputEstimate) {
|
|
379
|
+
const usage = upstream.usage;
|
|
380
|
+
const whole = (value) => (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
|
|
381
|
+
const input = whole(usage?.prompt_tokens);
|
|
382
|
+
const output = whole(usage?.completion_tokens);
|
|
383
|
+
if (input !== undefined && output !== undefined)
|
|
384
|
+
return { inputTokens: input, outputTokens: output };
|
|
385
|
+
const choices = upstream.choices;
|
|
386
|
+
const text = typeof choices?.[0]?.message?.content === 'string' ? choices[0].message.content : '';
|
|
387
|
+
return { inputTokens: input ?? inputEstimate, outputTokens: output ?? Math.ceil(text.length / 4) };
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* The settle for the tokens used, never above the locked maximum. It pays
|
|
391
|
+
* into the accounts checked with the lock (`lock.payout`), or into `payout`
|
|
392
|
+
* when the caller has checked them again. Nothing is created unless that
|
|
393
|
+
* check chose to create the buyer's token account. The settle names the
|
|
394
|
+
* escrow by its lock slot (`lock.createdSlot`) after its data, and a rated
|
|
395
|
+
* lock's settle carries the escrow's rating account after the usual accounts.
|
|
396
|
+
*/
|
|
397
|
+
function meteredSettlement(terms, lock, usage, payout = lock.payout) {
|
|
398
|
+
const decimals = (0, payment_1.directPaymentCurrency)(terms.price.currency).decimals;
|
|
399
|
+
const settlement = (0, metered_1.settleMeteredCall)(terms.price, usage, (0, payment_1.baseUnitsToDecimal)(lock.maxBaseUnits, decimals));
|
|
400
|
+
if (settlement.chargedBaseUnits <= BigInt(0))
|
|
401
|
+
throw new Error('nothing to settle');
|
|
402
|
+
const prep = (0, escrow_readiness_1.prepareTokenPayout)(lock.terms, terms.payee, undefined, { refundTo: payout.refundTo, createRefundAccount: payout.createRefundAccount === true });
|
|
403
|
+
const instruction = (0, rating_1.withRatingAccount)((0, token_escrow_1.buildSettleTokenEscrowInstruction)(lock.terms, false, terms.payee, {
|
|
404
|
+
actual: settlement.chargedBaseUnits,
|
|
405
|
+
treasuryToken: payout.treasuryToken,
|
|
406
|
+
refundTo: payout.refundTo,
|
|
407
|
+
...(payout.payTo ? { payTo: payout.payTo } : {}),
|
|
408
|
+
...(payout.harvestWithheldFees ? { harvestWithheldFees: true } : {}),
|
|
409
|
+
}), lock.rated === true, lock.createdSlot);
|
|
410
|
+
return { settlement, instruction, instructions: [...prep.instructions, instruction] };
|
|
411
|
+
}
|
|
412
|
+
/** The form a settle instruction is recorded and compared in. */
|
|
413
|
+
function recordedInstruction(instruction) {
|
|
414
|
+
return {
|
|
415
|
+
programId: instruction.programId.toBase58(),
|
|
416
|
+
accounts: instruction.keys.map((key) => key.pubkey.toBase58()),
|
|
417
|
+
data: Buffer.from(instruction.data).toString('base64'),
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* True when the transaction calls the escrow program exactly once, with
|
|
422
|
+
* exactly `expected`: the same accounts in the same order and the same data.
|
|
423
|
+
* So the credits read from its balances are this settle's, not another
|
|
424
|
+
* instruction's.
|
|
425
|
+
*/
|
|
426
|
+
function transactionHasOnlyInstruction(record, expected) {
|
|
427
|
+
if (!record.instructions)
|
|
428
|
+
return false;
|
|
429
|
+
const calls = record.instructions.filter((ix) => ix.programId === expected.programId);
|
|
430
|
+
if (calls.length !== 1)
|
|
431
|
+
return false;
|
|
432
|
+
const [call] = calls;
|
|
433
|
+
return call.data === expected.data
|
|
434
|
+
&& call.accounts.length === expected.accounts.length
|
|
435
|
+
&& call.accounts.every((account, index) => account === expected.accounts[index]);
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* The amounts a settle actually moved, from the confirmed transaction: it
|
|
439
|
+
* must have succeeded, called the escrow program and named this escrow (and,
|
|
440
|
+
* when `expected.rating` is given, that rating account: pass
|
|
441
|
+
* `meteredRatingAccount(lock)` for a rated lock). Accounts the transaction
|
|
442
|
+
* names beyond those are not held against it. The
|
|
443
|
+
* provider's credit and the treasury's fee are read from the balance changes,
|
|
444
|
+
* not from what the provider intended. Refused when the buyer got back less
|
|
445
|
+
* than the maximum less the amount billed, or more was billed than was
|
|
446
|
+
* locked: a receipt cannot state that honestly. A mint that charges a
|
|
447
|
+
* non-zero transfer fee would land here on every settle, since each transfer
|
|
448
|
+
* arrives short; the accepted Token-2022 mints are watched to stay at zero.
|
|
449
|
+
*/
|
|
450
|
+
function confirmMeteredSettlement(record, expected) {
|
|
451
|
+
if (!record)
|
|
452
|
+
return { ok: false, reason: 'not_found' };
|
|
453
|
+
if (record.failed)
|
|
454
|
+
return { ok: false, reason: 'failed' };
|
|
455
|
+
if (!record.programIds.includes(expected.programId.toBase58()) || !record.accounts.includes(expected.escrow.toBase58()))
|
|
456
|
+
return { ok: false, reason: 'wrong_transaction' };
|
|
457
|
+
if (expected.instruction && (expected.instruction.programId !== expected.programId.toBase58() || !transactionHasOnlyInstruction(record, expected.instruction)))
|
|
458
|
+
return { ok: false, reason: 'wrong_transaction' };
|
|
459
|
+
if (expected.rating && !record.accounts.includes(expected.rating.toBase58()))
|
|
460
|
+
return { ok: false, reason: 'wrong_transaction' };
|
|
461
|
+
const mint = expected.mint.toBase58();
|
|
462
|
+
const change = (account) => {
|
|
463
|
+
const row = record.tokenBalances.find((b) => b.account === account.toBase58() && b.mint === mint);
|
|
464
|
+
return row ? row.after - row.before : BigInt(0);
|
|
465
|
+
};
|
|
466
|
+
const providerBaseUnits = change(expected.destination);
|
|
467
|
+
const feeBaseUnits = change(expected.treasuryToken);
|
|
468
|
+
const returned = change(expected.refundTo);
|
|
469
|
+
const paidBaseUnits = providerBaseUnits + feeBaseUnits;
|
|
470
|
+
if (providerBaseUnits <= BigInt(0) || feeBaseUnits < BigInt(0) || returned < BigInt(0) || paidBaseUnits > expected.maxBaseUnits)
|
|
471
|
+
return { ok: false, reason: 'amounts_do_not_add_up' };
|
|
472
|
+
const refundedBaseUnits = expected.maxBaseUnits - paidBaseUnits;
|
|
473
|
+
if (returned < refundedBaseUnits)
|
|
474
|
+
return { ok: false, reason: 'amounts_do_not_add_up' };
|
|
475
|
+
return { ok: true, paidBaseUnits, feeBaseUnits, providerBaseUnits, refundedBaseUnits, surplusBaseUnits: returned - refundedBaseUnits };
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Declines a verified lock the provider will not serve, for example when the
|
|
479
|
+
* model failed before any work was done: the payee may refund the whole
|
|
480
|
+
* amount to the payer at any time. The program sends a decline to the source
|
|
481
|
+
* account the lock recorded, which the lock check found usable. Returns the
|
|
482
|
+
* instruction for the operator to sign with the provider wallet. The decline
|
|
483
|
+
* of a rated lock carries the rating account, which the program closes: a
|
|
484
|
+
* job that was not paid is not rated.
|
|
485
|
+
*/
|
|
486
|
+
function meteredDecline(terms, lock) {
|
|
487
|
+
return (0, rating_1.withRatingAccount)((0, token_escrow_1.buildSettleTokenEscrowInstruction)(lock.terms, true, terms.payee, lock.payout.harvestWithheldFees ? { harvestWithheldFees: true } : {}), lock.rated === true, lock.createdSlot);
|
|
488
|
+
}
|
|
489
|
+
/** The rating account a rated lock's settle and decline carry, or undefined for a lock that is not rated. */
|
|
490
|
+
function meteredRatingAccount(lock) {
|
|
491
|
+
return lock.rated === true ? (0, rating_1.ratingPda)((0, token_escrow_1.tokenEscrowAddresses)(lock.terms).escrow, lock.terms.programId) : undefined;
|
|
492
|
+
}
|