@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
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sessions: one metered escrow lock pays for many calls, settled once.
|
|
3
|
+
*
|
|
4
|
+
* The escrow program lets the payee settle any amount up to the locked
|
|
5
|
+
* maximum, once, paying the protocol fee and returning the rest in the same
|
|
6
|
+
* instruction. A session is an off-chain rule on top of that. The buyer sends
|
|
7
|
+
* the same lock with every call and numbers the calls 1, 2, 3. The provider
|
|
8
|
+
* keeps a ledger per escrow: calls served, total tokens, total cost. A call is
|
|
9
|
+
* served only when the total so far plus that call's worst case (its input
|
|
10
|
+
* plus its output limit) still fits under the lock, and only one call of a
|
|
11
|
+
* session runs at a time. The provider settles the total once: when the buyer
|
|
12
|
+
* closes the session, when it has been idle for a while, or before the
|
|
13
|
+
* buyer's refund window opens.
|
|
14
|
+
*
|
|
15
|
+
* Money order: a call's tokens are added to the ledger, and the ledger saved,
|
|
16
|
+
* before its answer is sent. A call that fails before that adds nothing. The
|
|
17
|
+
* ledger's total cost is exactly what `meteredSettlement` charges for the
|
|
18
|
+
* total tokens, so the settle equals the last receipt's cumulative cost.
|
|
19
|
+
*
|
|
20
|
+
* Nothing here reads a key or sends a transaction.
|
|
21
|
+
*/
|
|
22
|
+
import { PublicKey } from '@solana/web3.js';
|
|
23
|
+
import { type TokenCounts } from './metered';
|
|
24
|
+
import type { HeaderReader, MeteredTerms, VerifiedLock } from './provider';
|
|
25
|
+
import type { NonceReplayStore } from './types';
|
|
26
|
+
import { meteredSettlement } from './provider';
|
|
27
|
+
/** Settle a session after this long without a call. */
|
|
28
|
+
export declare const DEFAULT_SESSION_IDLE_SECONDS = 600;
|
|
29
|
+
/** The highest call number a session takes. */
|
|
30
|
+
export declare const MAX_SESSION_SEQUENCE = 1000000;
|
|
31
|
+
export declare const SESSION_SEQUENCE_HEADER = "x402-session-sequence";
|
|
32
|
+
export declare const SESSION_HEADER = "x402-session";
|
|
33
|
+
export type SessionHeaders = {
|
|
34
|
+
sequence: number;
|
|
35
|
+
close: boolean;
|
|
36
|
+
} | {
|
|
37
|
+
error: string;
|
|
38
|
+
} | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* The session headers of a request: `x402-session-sequence: <n>` makes the
|
|
41
|
+
* call number n of the session its lock pays for, and `x402-session: close`
|
|
42
|
+
* asks the provider to settle after answering. Undefined when the request is
|
|
43
|
+
* not a session call.
|
|
44
|
+
*/
|
|
45
|
+
export declare function readSessionHeaders(headers: HeaderReader): SessionHeaders;
|
|
46
|
+
/** One escrow's session, as the ledger keeps and saves it. Amounts in base units as decimal strings, so it serialises as JSON. */
|
|
47
|
+
export interface SessionState {
|
|
48
|
+
escrow: string;
|
|
49
|
+
payer: string;
|
|
50
|
+
/** The lock's 16-byte nonce, hex: with the payer it names the escrow, so the lock can be read back to settle. */
|
|
51
|
+
nonce: string;
|
|
52
|
+
maxBaseUnits: string;
|
|
53
|
+
/** The session key the payer delegated to at call 1 (see `session-auth`). Later calls, the close and reads must be signed by it. */
|
|
54
|
+
sessionKey: string;
|
|
55
|
+
/** The slot the lock was made in and its refund window: the session is settled before the buyer may refund. */
|
|
56
|
+
createdSlot: string;
|
|
57
|
+
cancelWindowSlots: string;
|
|
58
|
+
/** The lock's funding account and claim window, kept so a later lock at the same address is not taken for this one. Absent on sessions saved before they were kept. */
|
|
59
|
+
source?: string;
|
|
60
|
+
claimWindowSlots?: string;
|
|
61
|
+
/** The last call served and recorded. 0 before the first. */
|
|
62
|
+
sequence: number;
|
|
63
|
+
inputTokens: number;
|
|
64
|
+
outputTokens: number;
|
|
65
|
+
/** What the totals cost at the provider's price, capped at the lock: what the settle charges. */
|
|
66
|
+
costBaseUnits: string;
|
|
67
|
+
/** Hash of the last call's receipt, which the next call's receipt names. */
|
|
68
|
+
lastReceiptHash?: string;
|
|
69
|
+
/** `closing`: no more calls; the settle (or, with nothing to charge, the decline) is due. */
|
|
70
|
+
status: 'open' | 'closing' | 'settled' | 'declined' | 'refunded_unpaid';
|
|
71
|
+
/** When the last call was recorded, in milliseconds since the epoch. */
|
|
72
|
+
lastActivityMs: number;
|
|
73
|
+
settleSignature?: string;
|
|
74
|
+
/** The signed receipt of the settle, kept for a buyer who asks after the session closed. */
|
|
75
|
+
closingReceipt?: unknown;
|
|
76
|
+
/**
|
|
77
|
+
* A settle signed and saved before it was sent. Until it is known to have
|
|
78
|
+
* landed or to be unable to land, it is the only transaction that can count
|
|
79
|
+
* as this session's settle.
|
|
80
|
+
*/
|
|
81
|
+
pendingSettle?: PendingSettle;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* A settle transaction recorded before it is sent: its signature, the signed
|
|
85
|
+
* transaction (base64) so it can be sent again unchanged, the last block height
|
|
86
|
+
* it can land at, and the settle instruction it carries.
|
|
87
|
+
*/
|
|
88
|
+
export interface PendingSettle {
|
|
89
|
+
signature: string;
|
|
90
|
+
transaction: string;
|
|
91
|
+
lastValidBlockHeight: number;
|
|
92
|
+
instruction: {
|
|
93
|
+
programId: string;
|
|
94
|
+
accounts: string[];
|
|
95
|
+
data: string;
|
|
96
|
+
};
|
|
97
|
+
/** Where the settle pays: the provider's account, the treasury's, and the buyer's for the unused part. */
|
|
98
|
+
destination: string;
|
|
99
|
+
treasuryToken: string;
|
|
100
|
+
refundTo: string;
|
|
101
|
+
requestId?: string;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* True when a lock read back is the same lock a session was opened on: same
|
|
105
|
+
* payer, maximum, creation slot and refund window, and (when the session kept
|
|
106
|
+
* them) the same funding account and claim window. A lock closed and made again
|
|
107
|
+
* at the same address is a different lock, and a session's calls are never
|
|
108
|
+
* charged to it.
|
|
109
|
+
*/
|
|
110
|
+
export declare function lockMatchesSession(lock: Extract<VerifiedLock, {
|
|
111
|
+
ok: true;
|
|
112
|
+
}>, state: SessionState): boolean;
|
|
113
|
+
/** Where the ledger saves sessions so a restart can go on or settle them. `save` must be durable before it resolves. */
|
|
114
|
+
export interface SessionStore {
|
|
115
|
+
load(): SessionState[] | Promise<SessionState[]>;
|
|
116
|
+
save(state: SessionState): void | Promise<void>;
|
|
117
|
+
}
|
|
118
|
+
export type SessionRefusal = {
|
|
119
|
+
ok: false;
|
|
120
|
+
reason: 'session_sequence_invalid' | 'session_call_in_progress' | 'session_closed' | 'session_max_reached' | 'session_lock_mismatch' | 'session_key_mismatch' | 'duplicate_nonce';
|
|
121
|
+
message: string;
|
|
122
|
+
};
|
|
123
|
+
export interface SessionReservation {
|
|
124
|
+
escrow: string;
|
|
125
|
+
sequence: number;
|
|
126
|
+
/** The state before this call, as the receipt's previous totals. */
|
|
127
|
+
before: SessionState;
|
|
128
|
+
}
|
|
129
|
+
/** A session's state after one more call: what the receipt states. */
|
|
130
|
+
export interface SessionCall {
|
|
131
|
+
state: SessionState;
|
|
132
|
+
usage: TokenCounts;
|
|
133
|
+
/** The lock is used up: no further call can fit, so the session settles now. */
|
|
134
|
+
full: boolean;
|
|
135
|
+
}
|
|
136
|
+
export declare class MeteredSessionLedger {
|
|
137
|
+
private readonly terms;
|
|
138
|
+
private readonly store?;
|
|
139
|
+
private readonly sessions;
|
|
140
|
+
private readonly inFlight;
|
|
141
|
+
constructor(terms: MeteredTerms, store?: SessionStore | undefined);
|
|
142
|
+
/** Loads saved sessions. Call once at start, before serving. */
|
|
143
|
+
restore(): Promise<number>;
|
|
144
|
+
get(escrow: PublicKey | string): SessionState | undefined;
|
|
145
|
+
/** What the totals so far plus `more` would cost, uncapped. */
|
|
146
|
+
private costOf;
|
|
147
|
+
/**
|
|
148
|
+
* Reserves call `sequence` of the session `lock` pays for, after the lock
|
|
149
|
+
* was verified with `purpose: 'session-call'`. Call 1 claims the escrow in
|
|
150
|
+
* the replay store, so a lock that paid for a single call cannot start a
|
|
151
|
+
* session and a session's lock cannot pay for a single call. Refused when
|
|
152
|
+
* the number is not the next one, a call of the session is still running,
|
|
153
|
+
* the session is closed, or the total so far plus `worstCase` would not fit
|
|
154
|
+
* under the lock. Release the reservation if the call fails before its
|
|
155
|
+
* tokens are known; record them with `record` otherwise.
|
|
156
|
+
*/
|
|
157
|
+
begin(input: {
|
|
158
|
+
lock: Extract<VerifiedLock, {
|
|
159
|
+
ok: true;
|
|
160
|
+
}>;
|
|
161
|
+
escrow: PublicKey;
|
|
162
|
+
sequence: number;
|
|
163
|
+
sessionKey: string;
|
|
164
|
+
worstCase: TokenCounts;
|
|
165
|
+
replayStore: NonceReplayStore;
|
|
166
|
+
nowMs: number;
|
|
167
|
+
}): Promise<{
|
|
168
|
+
ok: true;
|
|
169
|
+
reservation: SessionReservation;
|
|
170
|
+
} | SessionRefusal>;
|
|
171
|
+
/** Gives up a reserved call that produced nothing to charge. The next call reuses its number. */
|
|
172
|
+
release(reservation: SessionReservation): void;
|
|
173
|
+
/**
|
|
174
|
+
* Records a served call's tokens and saves the session before the answer is
|
|
175
|
+
* sent. `receiptHash` is the hash of the receipt this call is answered with.
|
|
176
|
+
* When the model used more than the worst case allowed and the total would
|
|
177
|
+
* pass the lock, the cost is capped at the lock and the session is full.
|
|
178
|
+
*/
|
|
179
|
+
record(reservation: SessionReservation, usage: TokenCounts, receiptHash: string | undefined, nowMs: number): Promise<SessionCall>;
|
|
180
|
+
/** The cumulative state this call's receipt would state, before it is recorded. */
|
|
181
|
+
preview(reservation: SessionReservation, usage: TokenCounts): SessionState;
|
|
182
|
+
/** Stops new calls on a session, so it can be settled. Refused while a call of it is running. */
|
|
183
|
+
close(escrow: PublicKey | string): Promise<SessionState | undefined>;
|
|
184
|
+
/**
|
|
185
|
+
* Saves the settle about to be sent, or clears it (`undefined`) once it is
|
|
186
|
+
* known that it cannot land. Durable before it resolves, so a settle is never
|
|
187
|
+
* sent without a record of it.
|
|
188
|
+
*/
|
|
189
|
+
markSettling(escrow: string, pending: PendingSettle | undefined): Promise<void>;
|
|
190
|
+
/** Records the settle (or, for a session with nothing to charge, the decline) that ended a session. */
|
|
191
|
+
finish(escrow: string, outcome: {
|
|
192
|
+
status: 'settled' | 'declined' | 'refunded_unpaid';
|
|
193
|
+
signature?: string;
|
|
194
|
+
closingReceipt?: unknown;
|
|
195
|
+
}): Promise<void>;
|
|
196
|
+
/**
|
|
197
|
+
* Sessions to settle now: closing ones, open ones idle for `idleMs`, and open
|
|
198
|
+
* ones whose refund window has less than the seller's minimum left (no new
|
|
199
|
+
* call is taken then, so the settle has that long to land). A session with a
|
|
200
|
+
* call running is never due.
|
|
201
|
+
*/
|
|
202
|
+
due(nowMs: number, currentSlot: bigint, idleMs: number): SessionState[];
|
|
203
|
+
}
|
|
204
|
+
/** The token totals a session's settle charges for. */
|
|
205
|
+
export declare function sessionUsage(state: SessionState): TokenCounts;
|
|
206
|
+
/**
|
|
207
|
+
* The settle of a session: one `meteredSettlement` for the session's total
|
|
208
|
+
* tokens, which charges exactly the ledger's cumulative cost. Pass the lock
|
|
209
|
+
* as read back with `purpose: 'session-settle'`. Throws when the two
|
|
210
|
+
* disagree, which would mean the receipts and the settle differ.
|
|
211
|
+
*/
|
|
212
|
+
export declare function sessionSettlement(terms: MeteredTerms, lock: Extract<VerifiedLock, {
|
|
213
|
+
ok: true;
|
|
214
|
+
}>, state: SessionState, payout?: Parameters<typeof meteredSettlement>[3]): ReturnType<typeof meteredSettlement>;
|
|
215
|
+
/** The payment header a session's lock was presented with, rebuilt from the saved state, for reading the lock back to settle. */
|
|
216
|
+
export declare function sessionPaymentHeader(state: SessionState): {
|
|
217
|
+
escrow: PublicKey;
|
|
218
|
+
payer: PublicKey;
|
|
219
|
+
nonce: Uint8Array;
|
|
220
|
+
};
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MeteredSessionLedger = exports.SESSION_HEADER = exports.SESSION_SEQUENCE_HEADER = exports.MAX_SESSION_SEQUENCE = exports.DEFAULT_SESSION_IDLE_SECONDS = void 0;
|
|
4
|
+
exports.readSessionHeaders = readSessionHeaders;
|
|
5
|
+
exports.lockMatchesSession = lockMatchesSession;
|
|
6
|
+
exports.sessionUsage = sessionUsage;
|
|
7
|
+
exports.sessionSettlement = sessionSettlement;
|
|
8
|
+
exports.sessionPaymentHeader = sessionPaymentHeader;
|
|
9
|
+
/**
|
|
10
|
+
* Sessions: one metered escrow lock pays for many calls, settled once.
|
|
11
|
+
*
|
|
12
|
+
* The escrow program lets the payee settle any amount up to the locked
|
|
13
|
+
* maximum, once, paying the protocol fee and returning the rest in the same
|
|
14
|
+
* instruction. A session is an off-chain rule on top of that. The buyer sends
|
|
15
|
+
* the same lock with every call and numbers the calls 1, 2, 3. The provider
|
|
16
|
+
* keeps a ledger per escrow: calls served, total tokens, total cost. A call is
|
|
17
|
+
* served only when the total so far plus that call's worst case (its input
|
|
18
|
+
* plus its output limit) still fits under the lock, and only one call of a
|
|
19
|
+
* session runs at a time. The provider settles the total once: when the buyer
|
|
20
|
+
* closes the session, when it has been idle for a while, or before the
|
|
21
|
+
* buyer's refund window opens.
|
|
22
|
+
*
|
|
23
|
+
* Money order: a call's tokens are added to the ledger, and the ledger saved,
|
|
24
|
+
* before its answer is sent. A call that fails before that adds nothing. The
|
|
25
|
+
* ledger's total cost is exactly what `meteredSettlement` charges for the
|
|
26
|
+
* total tokens, so the settle equals the last receipt's cumulative cost.
|
|
27
|
+
*
|
|
28
|
+
* Nothing here reads a key or sends a transaction.
|
|
29
|
+
*/
|
|
30
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
31
|
+
const metered_1 = require("./metered");
|
|
32
|
+
const token_escrow_1 = require("./token-escrow");
|
|
33
|
+
const provider_1 = require("./provider");
|
|
34
|
+
/** Settle a session after this long without a call. */
|
|
35
|
+
exports.DEFAULT_SESSION_IDLE_SECONDS = 600;
|
|
36
|
+
/** The highest call number a session takes. */
|
|
37
|
+
exports.MAX_SESSION_SEQUENCE = 1000000;
|
|
38
|
+
exports.SESSION_SEQUENCE_HEADER = 'x402-session-sequence';
|
|
39
|
+
exports.SESSION_HEADER = 'x402-session';
|
|
40
|
+
/**
|
|
41
|
+
* The session headers of a request: `x402-session-sequence: <n>` makes the
|
|
42
|
+
* call number n of the session its lock pays for, and `x402-session: close`
|
|
43
|
+
* asks the provider to settle after answering. Undefined when the request is
|
|
44
|
+
* not a session call.
|
|
45
|
+
*/
|
|
46
|
+
function readSessionHeaders(headers) {
|
|
47
|
+
const raw = headers.get(exports.SESSION_SEQUENCE_HEADER);
|
|
48
|
+
const close = headers.get(exports.SESSION_HEADER);
|
|
49
|
+
if (raw === null)
|
|
50
|
+
return close === null ? undefined : { error: `${exports.SESSION_HEADER} needs ${exports.SESSION_SEQUENCE_HEADER}.` };
|
|
51
|
+
if (close !== null && close.trim().toLowerCase() !== 'close')
|
|
52
|
+
return { error: `${exports.SESSION_HEADER} takes only "close".` };
|
|
53
|
+
const text = raw.trim();
|
|
54
|
+
if (!/^[1-9]\d{0,6}$/.test(text) || Number(text) > exports.MAX_SESSION_SEQUENCE)
|
|
55
|
+
return { error: `${exports.SESSION_SEQUENCE_HEADER} must be a whole number from 1 to ${exports.MAX_SESSION_SEQUENCE}.` };
|
|
56
|
+
return { sequence: Number(text), close: close !== null };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* True when a lock read back is the same lock a session was opened on: same
|
|
60
|
+
* payer, maximum, creation slot and refund window, and (when the session kept
|
|
61
|
+
* them) the same funding account and claim window. A lock closed and made again
|
|
62
|
+
* at the same address is a different lock, and a session's calls are never
|
|
63
|
+
* charged to it.
|
|
64
|
+
*/
|
|
65
|
+
function lockMatchesSession(lock, state) {
|
|
66
|
+
if (lock.payer.toBase58() !== state.payer || lock.maxBaseUnits.toString() !== state.maxBaseUnits)
|
|
67
|
+
return false;
|
|
68
|
+
if (lock.createdSlot.toString() !== state.createdSlot)
|
|
69
|
+
return false;
|
|
70
|
+
if ((lock.terms.cancelWindowSlots ?? 0n).toString() !== state.cancelWindowSlots)
|
|
71
|
+
return false;
|
|
72
|
+
if (state.source !== undefined && lock.terms.source.toBase58() !== state.source)
|
|
73
|
+
return false;
|
|
74
|
+
if (state.claimWindowSlots !== undefined && (lock.terms.claimWindowSlots ?? 0n).toString() !== state.claimWindowSlots)
|
|
75
|
+
return false;
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
const clone = (state) => ({ ...state });
|
|
79
|
+
class MeteredSessionLedger {
|
|
80
|
+
constructor(terms, store) {
|
|
81
|
+
this.terms = terms;
|
|
82
|
+
this.store = store;
|
|
83
|
+
this.sessions = new Map();
|
|
84
|
+
this.inFlight = new Set();
|
|
85
|
+
}
|
|
86
|
+
/** Loads saved sessions. Call once at start, before serving. */
|
|
87
|
+
async restore() {
|
|
88
|
+
const saved = this.store ? await this.store.load() : [];
|
|
89
|
+
for (const state of saved)
|
|
90
|
+
this.sessions.set(state.escrow, clone(state));
|
|
91
|
+
return saved.length;
|
|
92
|
+
}
|
|
93
|
+
get(escrow) {
|
|
94
|
+
const state = this.sessions.get(typeof escrow === 'string' ? escrow : escrow.toBase58());
|
|
95
|
+
return state ? clone(state) : undefined;
|
|
96
|
+
}
|
|
97
|
+
/** What the totals so far plus `more` would cost, uncapped. */
|
|
98
|
+
costOf(state, more) {
|
|
99
|
+
return (0, metered_1.tokenCostBaseUnits)(this.terms.price, { inputTokens: state.inputTokens + more.inputTokens, outputTokens: state.outputTokens + more.outputTokens });
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Reserves call `sequence` of the session `lock` pays for, after the lock
|
|
103
|
+
* was verified with `purpose: 'session-call'`. Call 1 claims the escrow in
|
|
104
|
+
* the replay store, so a lock that paid for a single call cannot start a
|
|
105
|
+
* session and a session's lock cannot pay for a single call. Refused when
|
|
106
|
+
* the number is not the next one, a call of the session is still running,
|
|
107
|
+
* the session is closed, or the total so far plus `worstCase` would not fit
|
|
108
|
+
* under the lock. Release the reservation if the call fails before its
|
|
109
|
+
* tokens are known; record them with `record` otherwise.
|
|
110
|
+
*/
|
|
111
|
+
async begin(input) {
|
|
112
|
+
const key = input.escrow.toBase58();
|
|
113
|
+
if (this.inFlight.has(key))
|
|
114
|
+
return { ok: false, reason: 'session_call_in_progress', message: 'The previous call of this session is still being served. Send the next call when it has answered.' };
|
|
115
|
+
let state = this.sessions.get(key);
|
|
116
|
+
if (!state) {
|
|
117
|
+
if (input.sequence !== 1)
|
|
118
|
+
return { ok: false, reason: 'session_sequence_invalid', message: 'No session is open on this lock. Start at call 1.' };
|
|
119
|
+
this.inFlight.add(key);
|
|
120
|
+
try {
|
|
121
|
+
if (!(await input.replayStore.checkAndStore((0, provider_1.meteredEscrowReplayKey)(input.escrow)))) {
|
|
122
|
+
return { ok: false, reason: 'duplicate_nonce', message: 'This escrow has already paid for a call. A session needs a lock of its own.' };
|
|
123
|
+
}
|
|
124
|
+
state = {
|
|
125
|
+
escrow: key,
|
|
126
|
+
payer: input.lock.payer.toBase58(),
|
|
127
|
+
nonce: Buffer.from(input.lock.terms.nonce).toString('hex'),
|
|
128
|
+
maxBaseUnits: input.lock.maxBaseUnits.toString(),
|
|
129
|
+
sessionKey: input.sessionKey,
|
|
130
|
+
createdSlot: input.lock.createdSlot.toString(),
|
|
131
|
+
cancelWindowSlots: (input.lock.terms.cancelWindowSlots ?? 0n).toString(),
|
|
132
|
+
source: input.lock.terms.source.toBase58(),
|
|
133
|
+
claimWindowSlots: (input.lock.terms.claimWindowSlots ?? 0n).toString(),
|
|
134
|
+
sequence: 0,
|
|
135
|
+
inputTokens: 0,
|
|
136
|
+
outputTokens: 0,
|
|
137
|
+
costBaseUnits: '0',
|
|
138
|
+
status: 'open',
|
|
139
|
+
lastActivityMs: input.nowMs,
|
|
140
|
+
};
|
|
141
|
+
// Saved before any work, so a restart knows this lock belongs to a session even if no call was recorded.
|
|
142
|
+
await this.store?.save(state);
|
|
143
|
+
this.sessions.set(key, state);
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
this.inFlight.delete(key);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (state.sessionKey !== input.sessionKey)
|
|
150
|
+
return { ok: false, reason: 'session_key_mismatch', message: 'This session was started with another session key. Sign with the key it was started with.' };
|
|
151
|
+
if (state.status !== 'open')
|
|
152
|
+
return { ok: false, reason: 'session_closed', message: state.status === 'settled' ? 'This session has been settled. Lock a new escrow to go on.' : 'This session is closed and being settled. Lock a new escrow to go on.' };
|
|
153
|
+
if (!lockMatchesSession(input.lock, state)) {
|
|
154
|
+
return { ok: false, reason: 'session_lock_mismatch', message: 'This lock no longer matches the session opened on it.' };
|
|
155
|
+
}
|
|
156
|
+
if (input.sequence !== state.sequence + 1) {
|
|
157
|
+
return { ok: false, reason: 'session_sequence_invalid', message: input.sequence <= state.sequence ? `Call ${input.sequence} of this session was already served. The next is ${state.sequence + 1}.` : `The next call of this session is ${state.sequence + 1}; calls cannot be skipped.` };
|
|
158
|
+
}
|
|
159
|
+
if (this.costOf(state, input.worstCase) > BigInt(state.maxBaseUnits)) {
|
|
160
|
+
return { ok: false, reason: 'session_max_reached', message: `This call could take the session past the ${state.maxBaseUnits} base units locked, so it was not served and nothing more was charged. Close the session, or send a shorter call or a lower max_tokens.` };
|
|
161
|
+
}
|
|
162
|
+
this.inFlight.add(key);
|
|
163
|
+
return { ok: true, reservation: { escrow: key, sequence: input.sequence, before: clone(state) } };
|
|
164
|
+
}
|
|
165
|
+
/** Gives up a reserved call that produced nothing to charge. The next call reuses its number. */
|
|
166
|
+
release(reservation) {
|
|
167
|
+
this.inFlight.delete(reservation.escrow);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Records a served call's tokens and saves the session before the answer is
|
|
171
|
+
* sent. `receiptHash` is the hash of the receipt this call is answered with.
|
|
172
|
+
* When the model used more than the worst case allowed and the total would
|
|
173
|
+
* pass the lock, the cost is capped at the lock and the session is full.
|
|
174
|
+
*/
|
|
175
|
+
async record(reservation, usage, receiptHash, nowMs) {
|
|
176
|
+
const current = this.sessions.get(reservation.escrow);
|
|
177
|
+
if (!current || current.sequence !== reservation.sequence - 1 || !this.inFlight.has(reservation.escrow))
|
|
178
|
+
throw new Error('session reservation is stale');
|
|
179
|
+
const max = BigInt(current.maxBaseUnits);
|
|
180
|
+
const cost = this.costOf(current, usage);
|
|
181
|
+
const next = {
|
|
182
|
+
...current,
|
|
183
|
+
sequence: reservation.sequence,
|
|
184
|
+
inputTokens: current.inputTokens + usage.inputTokens,
|
|
185
|
+
outputTokens: current.outputTokens + usage.outputTokens,
|
|
186
|
+
costBaseUnits: (cost > max ? max : cost).toString(),
|
|
187
|
+
...(receiptHash ? { lastReceiptHash: receiptHash } : {}),
|
|
188
|
+
lastActivityMs: nowMs,
|
|
189
|
+
};
|
|
190
|
+
const full = cost >= max;
|
|
191
|
+
if (full)
|
|
192
|
+
next.status = 'closing';
|
|
193
|
+
try {
|
|
194
|
+
await this.store?.save(next);
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
// Not saved means not recorded: the call stays reserved no longer, and the caller must not answer.
|
|
198
|
+
this.inFlight.delete(reservation.escrow);
|
|
199
|
+
}
|
|
200
|
+
this.sessions.set(reservation.escrow, next);
|
|
201
|
+
return { state: clone(next), usage, full };
|
|
202
|
+
}
|
|
203
|
+
/** The cumulative state this call's receipt would state, before it is recorded. */
|
|
204
|
+
preview(reservation, usage) {
|
|
205
|
+
const max = BigInt(reservation.before.maxBaseUnits);
|
|
206
|
+
const cost = this.costOf(reservation.before, usage);
|
|
207
|
+
return {
|
|
208
|
+
...reservation.before,
|
|
209
|
+
sequence: reservation.sequence,
|
|
210
|
+
inputTokens: reservation.before.inputTokens + usage.inputTokens,
|
|
211
|
+
outputTokens: reservation.before.outputTokens + usage.outputTokens,
|
|
212
|
+
costBaseUnits: (cost > max ? max : cost).toString(),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
/** Stops new calls on a session, so it can be settled. Refused while a call of it is running. */
|
|
216
|
+
async close(escrow) {
|
|
217
|
+
const key = typeof escrow === 'string' ? escrow : escrow.toBase58();
|
|
218
|
+
const state = this.sessions.get(key);
|
|
219
|
+
if (!state || this.inFlight.has(key))
|
|
220
|
+
return undefined;
|
|
221
|
+
if (state.status === 'open') {
|
|
222
|
+
const next = { ...state, status: 'closing' };
|
|
223
|
+
await this.store?.save(next);
|
|
224
|
+
this.sessions.set(key, next);
|
|
225
|
+
return clone(next);
|
|
226
|
+
}
|
|
227
|
+
return clone(state);
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Saves the settle about to be sent, or clears it (`undefined`) once it is
|
|
231
|
+
* known that it cannot land. Durable before it resolves, so a settle is never
|
|
232
|
+
* sent without a record of it.
|
|
233
|
+
*/
|
|
234
|
+
async markSettling(escrow, pending) {
|
|
235
|
+
const state = this.sessions.get(escrow);
|
|
236
|
+
if (!state)
|
|
237
|
+
throw new Error('no session on that escrow');
|
|
238
|
+
const { pendingSettle: _previous, ...rest } = state;
|
|
239
|
+
const next = pending ? { ...rest, pendingSettle: pending } : rest;
|
|
240
|
+
await this.store?.save(next);
|
|
241
|
+
this.sessions.set(escrow, next);
|
|
242
|
+
}
|
|
243
|
+
/** Records the settle (or, for a session with nothing to charge, the decline) that ended a session. */
|
|
244
|
+
async finish(escrow, outcome) {
|
|
245
|
+
const state = this.sessions.get(escrow);
|
|
246
|
+
if (!state)
|
|
247
|
+
return;
|
|
248
|
+
const { pendingSettle: _pending, ...rest } = state;
|
|
249
|
+
const next = { ...rest, status: outcome.status, ...(outcome.signature ? { settleSignature: outcome.signature } : {}), ...(outcome.closingReceipt !== undefined ? { closingReceipt: outcome.closingReceipt } : {}) };
|
|
250
|
+
await this.store?.save(next);
|
|
251
|
+
this.sessions.set(escrow, next);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Sessions to settle now: closing ones, open ones idle for `idleMs`, and open
|
|
255
|
+
* ones whose refund window has less than the seller's minimum left (no new
|
|
256
|
+
* call is taken then, so the settle has that long to land). A session with a
|
|
257
|
+
* call running is never due.
|
|
258
|
+
*/
|
|
259
|
+
due(nowMs, currentSlot, idleMs) {
|
|
260
|
+
const out = [];
|
|
261
|
+
for (const state of this.sessions.values()) {
|
|
262
|
+
if (this.inFlight.has(state.escrow))
|
|
263
|
+
continue;
|
|
264
|
+
if (state.status === 'closing')
|
|
265
|
+
out.push(clone(state));
|
|
266
|
+
else if (state.status === 'open') {
|
|
267
|
+
const refundOpens = BigInt(state.createdSlot) + BigInt(state.cancelWindowSlots);
|
|
268
|
+
if (nowMs - state.lastActivityMs >= idleMs || currentSlot + token_escrow_1.SELLER_MIN_CANCEL_WINDOW_SLOTS >= refundOpens)
|
|
269
|
+
out.push(clone(state));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
exports.MeteredSessionLedger = MeteredSessionLedger;
|
|
276
|
+
/** The token totals a session's settle charges for. */
|
|
277
|
+
function sessionUsage(state) {
|
|
278
|
+
return { inputTokens: state.inputTokens, outputTokens: state.outputTokens };
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The settle of a session: one `meteredSettlement` for the session's total
|
|
282
|
+
* tokens, which charges exactly the ledger's cumulative cost. Pass the lock
|
|
283
|
+
* as read back with `purpose: 'session-settle'`. Throws when the two
|
|
284
|
+
* disagree, which would mean the receipts and the settle differ.
|
|
285
|
+
*/
|
|
286
|
+
function sessionSettlement(terms, lock, state, payout) {
|
|
287
|
+
if (!lockMatchesSession(lock, state))
|
|
288
|
+
throw new Error('the lock does not match the session');
|
|
289
|
+
const settled = (0, provider_1.meteredSettlement)(terms, lock, sessionUsage(state), payout);
|
|
290
|
+
if (settled.settlement.chargedBaseUnits.toString() !== state.costBaseUnits)
|
|
291
|
+
throw new Error('the settle would charge a different amount than the session recorded');
|
|
292
|
+
return settled;
|
|
293
|
+
}
|
|
294
|
+
/** The payment header a session's lock was presented with, rebuilt from the saved state, for reading the lock back to settle. */
|
|
295
|
+
function sessionPaymentHeader(state) {
|
|
296
|
+
return { escrow: new web3_js_1.PublicKey(state.escrow), payer: new web3_js_1.PublicKey(state.payer), nonce: Uint8Array.from(Buffer.from(state.nonce, 'hex')) };
|
|
297
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
export declare const SPL_TRANSFER_CHECKED_OBSERVATION_SCHEMA_VERSION: "reddi.svm-spl-transfer-checked-observation.v1";
|
|
2
|
+
export declare const SPL_TRANSFER_CHECKED_OBSERVER_VERSION: "reddi.x402-solana.spl-transfer-checked-observer.v1";
|
|
3
|
+
export declare const SPL_TOKEN_PROGRAM_ID: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
4
|
+
export declare const TOKEN_2022_PROGRAM_ID: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
|
|
5
|
+
export declare const SPL_MEMO_PROGRAM_ID: "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
|
|
6
|
+
export type SplTransferCheckedCommitment = 'confirmed' | 'finalized';
|
|
7
|
+
export type SplTransferCheckedObservationFailureReason = 'malformed_expected_payment' | 'missing_transaction' | 'failed_transaction' | 'missing_confirmation_metadata' | 'wrong_signature' | 'no_transfer_checked' | 'wrong_token_program' | 'wrong_mint' | 'wrong_amount' | 'wrong_payee' | 'wrong_destination' | 'wrong_decimals' | 'wrong_authority' | 'duplicate_matching_transfer' | 'missing_memo' | 'memo_mismatch' | 'replay_detected';
|
|
8
|
+
export type SplTransferCheckedExpectedPayment = {
|
|
9
|
+
network: string;
|
|
10
|
+
signature: string;
|
|
11
|
+
mint: string;
|
|
12
|
+
tokenProgram: string;
|
|
13
|
+
payTo: string;
|
|
14
|
+
amountBaseUnits: string;
|
|
15
|
+
destinationTokenAccount?: string;
|
|
16
|
+
authority?: string;
|
|
17
|
+
decimals?: number;
|
|
18
|
+
memo?: string;
|
|
19
|
+
memoRequired?: boolean;
|
|
20
|
+
paymentIntentId?: string;
|
|
21
|
+
};
|
|
22
|
+
export type SplTransferCheckedObservation = {
|
|
23
|
+
schemaVersion: typeof SPL_TRANSFER_CHECKED_OBSERVATION_SCHEMA_VERSION;
|
|
24
|
+
verifierVersion: typeof SPL_TRANSFER_CHECKED_OBSERVER_VERSION | string;
|
|
25
|
+
network: string;
|
|
26
|
+
signature: string;
|
|
27
|
+
slot: number;
|
|
28
|
+
/** Optional: Solana nodes legitimately report a null blockTime for a confirmed slot. */
|
|
29
|
+
blockTime?: number;
|
|
30
|
+
commitment: SplTransferCheckedCommitment;
|
|
31
|
+
instructionIndex: string;
|
|
32
|
+
innerInstruction: boolean;
|
|
33
|
+
sourceTokenAccount?: string;
|
|
34
|
+
destinationTokenAccount: string;
|
|
35
|
+
destinationOwner: string;
|
|
36
|
+
authority?: string;
|
|
37
|
+
mint: string;
|
|
38
|
+
tokenProgram: string;
|
|
39
|
+
amountBaseUnits: string;
|
|
40
|
+
decimals?: number;
|
|
41
|
+
memo?: string;
|
|
42
|
+
paymentIntentId?: string;
|
|
43
|
+
evidence: {
|
|
44
|
+
source: 'parsed-transaction-fixture' | 'parsed-rpc-transaction';
|
|
45
|
+
grantEligible: false | 'pending_partner_acceptance' | true;
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
export type SplTransferReplayStore = {
|
|
49
|
+
checkAndStore(key: string): boolean | Promise<boolean>;
|
|
50
|
+
};
|
|
51
|
+
export type VerifySplTransferCheckedObservationInput = {
|
|
52
|
+
parsedTransaction: unknown;
|
|
53
|
+
expected: SplTransferCheckedExpectedPayment;
|
|
54
|
+
commitment: SplTransferCheckedCommitment;
|
|
55
|
+
replayStore?: SplTransferReplayStore;
|
|
56
|
+
evidenceSource?: SplTransferCheckedObservation['evidence']['source'];
|
|
57
|
+
grantEligible?: SplTransferCheckedObservation['evidence']['grantEligible'];
|
|
58
|
+
verifierVersion?: string;
|
|
59
|
+
};
|
|
60
|
+
export type VerifySplTransferCheckedObservationResult = {
|
|
61
|
+
ok: true;
|
|
62
|
+
observation: SplTransferCheckedObservation;
|
|
63
|
+
} | {
|
|
64
|
+
ok: false;
|
|
65
|
+
reason: SplTransferCheckedObservationFailureReason;
|
|
66
|
+
message: string;
|
|
67
|
+
expected?: unknown;
|
|
68
|
+
actual?: unknown;
|
|
69
|
+
};
|
|
70
|
+
export declare function verifySplTransferCheckedObservation(input: VerifySplTransferCheckedObservationInput): Promise<VerifySplTransferCheckedObservationResult>;
|