@agent402-dev/pay-mcp 0.3.0 → 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/dist/bond.d.ts ADDED
@@ -0,0 +1,188 @@
1
+ import { type RuleDeal } from '@agent402-dev/bond-client/rules';
2
+ import type { AccountsFetcher } from './locks.js';
3
+ export declare const BOND_PROGRAM = "9hiCZZ6ddFG9oJBR1Su43Pj4JRFHeHC5cGiCgXtTuAaK";
4
+ /** sha256("account:Deal")[..8] */
5
+ export declare const DEAL_DISCRIMINATOR: number[];
6
+ declare const OUTCOMES: readonly ["open", "delivered", "buyer_default", "disputed", "seller_default", "cancelled"];
7
+ /** Mints the program accepts on mainnet (symbol, decimals). */
8
+ export declare const BOND_MINTS: Record<string, {
9
+ symbol: string;
10
+ decimals: number;
11
+ }>;
12
+ export interface DealAccount extends RuleDeal {
13
+ seller: string;
14
+ buyer: string;
15
+ mint: string;
16
+ nonce: bigint;
17
+ outcome: (typeof OUTCOMES)[number];
18
+ owedSeller: bigint;
19
+ }
20
+ /** Decodes a Deal account (Anchor layout). Null if the bytes are not a Deal. */
21
+ export declare function decodeDealAccount(data: Uint8Array): DealAccount | null;
22
+ /** Solana clock via the RPC: the Clock sysvar (what the program uses), falling back to getSlot + getBlockTime. */
23
+ export declare function rpcClock(rpcUrl: string, f?: typeof fetch): () => Promise<bigint>;
24
+ export interface BondStatusDeps {
25
+ accounts: AccountsFetcher;
26
+ clock: () => Promise<bigint>;
27
+ wallet?: string | null;
28
+ }
29
+ /** bond_deal_status: facts about one deal account, with amounts in units and times in ISO (Solana clock). */
30
+ export declare function bondDealStatus(d: BondStatusDeps, deal: string): Promise<{
31
+ result: "not_found";
32
+ message: string;
33
+ } | {
34
+ result: "not_a_deal";
35
+ message: string;
36
+ } | {
37
+ outcome: "cancelled" | "delivered" | "buyer_default" | "disputed" | "seller_default";
38
+ owedToSeller: {
39
+ atomic: string;
40
+ display: string;
41
+ };
42
+ note: string;
43
+ asset: {
44
+ mint: string;
45
+ symbol: string;
46
+ decimals: number;
47
+ };
48
+ price: {
49
+ atomic: string;
50
+ display: string;
51
+ };
52
+ sellerBond: {
53
+ atomic: string;
54
+ display: string;
55
+ };
56
+ buyerDeposit: {
57
+ atomic: string;
58
+ display: string;
59
+ };
60
+ balanceToPay: {
61
+ atomic: string;
62
+ display: string;
63
+ };
64
+ openedAt: {
65
+ unix: string;
66
+ iso: string;
67
+ } | null;
68
+ deliverBy: {
69
+ unix: string;
70
+ iso: string;
71
+ } | null;
72
+ sellerMarkedAt: {
73
+ unix: string;
74
+ iso: string;
75
+ } | null;
76
+ buyerConfirmedAt: {
77
+ unix: string;
78
+ iso: string;
79
+ } | null;
80
+ balancePaid: boolean;
81
+ clock: {
82
+ unix: string;
83
+ iso: string;
84
+ } | null;
85
+ yourRole?: string | undefined;
86
+ deal: string;
87
+ program: string;
88
+ seller: string;
89
+ buyer: string;
90
+ result: "settled";
91
+ message?: undefined;
92
+ } | {
93
+ deadlines: {
94
+ lateUntil: {
95
+ unix: string;
96
+ iso: string;
97
+ } | null;
98
+ buyerConfirmOrPayUntil: {
99
+ unix: string;
100
+ iso: string;
101
+ } | null;
102
+ settleableBy: {
103
+ unix: string;
104
+ iso: string;
105
+ } | null;
106
+ };
107
+ lateDeductionIfConfirmed: {
108
+ atomic: string;
109
+ display: string;
110
+ };
111
+ possibleActions: {
112
+ until?: string | undefined;
113
+ action: string;
114
+ who: "seller" | "buyer" | "both" | "anyone";
115
+ }[];
116
+ settlement: {
117
+ now: boolean;
118
+ outcome: import("@agent402-dev/bond-client/rules").Outcome;
119
+ toSeller: {
120
+ atomic: string;
121
+ display: string;
122
+ };
123
+ toBuyer: {
124
+ atomic: string;
125
+ display: string;
126
+ };
127
+ earliest?: undefined;
128
+ note?: undefined;
129
+ } | {
130
+ now: boolean;
131
+ earliest: string | null;
132
+ note: string;
133
+ outcome?: undefined;
134
+ toSeller?: undefined;
135
+ toBuyer?: undefined;
136
+ };
137
+ notes: string[];
138
+ asset: {
139
+ mint: string;
140
+ symbol: string;
141
+ decimals: number;
142
+ };
143
+ price: {
144
+ atomic: string;
145
+ display: string;
146
+ };
147
+ sellerBond: {
148
+ atomic: string;
149
+ display: string;
150
+ };
151
+ buyerDeposit: {
152
+ atomic: string;
153
+ display: string;
154
+ };
155
+ balanceToPay: {
156
+ atomic: string;
157
+ display: string;
158
+ };
159
+ openedAt: {
160
+ unix: string;
161
+ iso: string;
162
+ } | null;
163
+ deliverBy: {
164
+ unix: string;
165
+ iso: string;
166
+ } | null;
167
+ sellerMarkedAt: {
168
+ unix: string;
169
+ iso: string;
170
+ } | null;
171
+ buyerConfirmedAt: {
172
+ unix: string;
173
+ iso: string;
174
+ } | null;
175
+ balancePaid: boolean;
176
+ clock: {
177
+ unix: string;
178
+ iso: string;
179
+ } | null;
180
+ yourRole?: string | undefined;
181
+ deal: string;
182
+ program: string;
183
+ seller: string;
184
+ buyer: string;
185
+ result: "open";
186
+ message?: undefined;
187
+ }>;
188
+ export {};
package/dist/bond.js ADDED
@@ -0,0 +1,114 @@
1
+ // Agent402 Bond, read-only: decode a deal account and explain its deadlines, possible actions and settlement.
2
+ // Never signs. Deadlines and settlement come from the program's rules (ported in @agent402-dev/bond-client/rules);
3
+ // the program on chain is the source of truth.
4
+ import { getBase58Decoder } from '@solana/kit';
5
+ import { buyerDeadline, lateDeduction, possibleActions, settleBy, settleableFrom, settlePreview, t2 } from '@agent402-dev/bond-client/rules';
6
+ import { formatUnits } from './units.js';
7
+ export const BOND_PROGRAM = '9hiCZZ6ddFG9oJBR1Su43Pj4JRFHeHC5cGiCgXtTuAaK';
8
+ /** sha256("account:Deal")[..8] */
9
+ export const DEAL_DISCRIMINATOR = [125, 223, 160, 234, 71, 162, 182, 219];
10
+ const DEAL_SIZE = 8 + 32 * 3 + 8 * 4 + 8 * 6 + 1 + 2 + 1 + 8;
11
+ const OUTCOMES = ['open', 'delivered', 'buyer_default', 'disputed', 'seller_default', 'cancelled'];
12
+ /** Mints the program accepts on mainnet (symbol, decimals). */
13
+ export const BOND_MINTS = {
14
+ EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: { symbol: 'USDC', decimals: 6 },
15
+ So11111111111111111111111111111111111111112: { symbol: 'wSOL', decimals: 9 },
16
+ aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX: { symbol: 'PREQ', decimals: 6 },
17
+ // devnet USDC (Circle)
18
+ '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU': { symbol: 'USDC', decimals: 6 },
19
+ };
20
+ /** Decodes a Deal account (Anchor layout). Null if the bytes are not a Deal. */
21
+ export function decodeDealAccount(data) {
22
+ if (data.length < DEAL_SIZE || DEAL_DISCRIMINATOR.some((b, i) => data[i] !== b))
23
+ return null;
24
+ const v = new DataView(data.buffer, data.byteOffset, data.byteLength);
25
+ const b58 = getBase58Decoder();
26
+ let o = 8;
27
+ const key = () => b58.decode(data.subarray(o, (o += 32)));
28
+ const u64 = () => { const x = v.getBigUint64(o, true); o += 8; return x; };
29
+ const i64 = () => { const x = v.getBigInt64(o, true); o += 8; return x; };
30
+ const seller = key(), buyer = key(), mint = key();
31
+ const nonce = u64(), price = u64(), sellerBond = u64(), buyerDeposit = u64();
32
+ const deliverBy = i64(), lateWindow = i64(), payWindow = i64(), openedAt = i64(), mark = i64(), confirm = i64();
33
+ const balancePaid = data[o++] === 1;
34
+ o += 2; // bump, vault_bump
35
+ const outcome = OUTCOMES[data[o++]] ?? 'open';
36
+ const owedSeller = u64();
37
+ return {
38
+ seller, buyer, mint, nonce, outcome, owedSeller, openedAt, balancePaid,
39
+ terms: { price, sellerBond, buyerDeposit, deliverBy, lateWindow, payWindow },
40
+ sellerMark: mark === 0n ? null : mark,
41
+ buyerConfirm: confirm === 0n ? null : confirm,
42
+ };
43
+ }
44
+ /** Solana clock via the RPC: the Clock sysvar (what the program uses), falling back to getSlot + getBlockTime. */
45
+ export function rpcClock(rpcUrl, f = fetch) {
46
+ const call = async (method, params) => {
47
+ const r = await f(rpcUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) });
48
+ const j = (await r.json());
49
+ if (j.result === undefined || j.result === null)
50
+ throw new Error(`rpc ${method}: ${j.error?.message ?? r.status}`);
51
+ return j.result;
52
+ };
53
+ return async () => {
54
+ try {
55
+ const v = (await call('getAccountInfo', ['SysvarC1ock11111111111111111111111111111111', { encoding: 'base64', commitment: 'confirmed' }]));
56
+ if (v.value) {
57
+ const b = Uint8Array.from(atob(v.value.data[0]), (c) => c.charCodeAt(0));
58
+ if (b.length >= 40)
59
+ return new DataView(b.buffer).getBigInt64(32, true);
60
+ }
61
+ }
62
+ catch { /* fall back */ }
63
+ return BigInt((await call('getBlockTime', [await call('getSlot', [{ commitment: 'confirmed' }])])));
64
+ };
65
+ }
66
+ const iso = (t) => new Date(Number(t) * 1000).toISOString();
67
+ /** bond_deal_status: facts about one deal account, with amounts in units and times in ISO (Solana clock). */
68
+ export async function bondDealStatus(d, deal) {
69
+ const [acc] = await d.accounts([deal]);
70
+ if (!acc)
71
+ return { result: 'not_found', message: 'No account at this address. A settled deal is closed once both sides have claimed.' };
72
+ if (acc.owner !== BOND_PROGRAM)
73
+ return { result: 'not_a_deal', message: `This account is not owned by the Agent402 Bond program (${BOND_PROGRAM}).` };
74
+ const a = decodeDealAccount(acc.data);
75
+ if (!a)
76
+ return { result: 'not_a_deal', message: 'This account is not an Agent402 Bond deal.' };
77
+ const now = await d.clock();
78
+ const m = BOND_MINTS[a.mint] ?? { symbol: 'tokens', decimals: 0 };
79
+ const amt = (v) => ({ atomic: v.toString(), display: formatUnits(v, m.symbol, m.decimals) });
80
+ const time = (t) => (t === null ? null : { unix: t.toString(), iso: iso(t) });
81
+ const role = d.wallet === a.buyer ? 'buyer' : d.wallet === a.seller ? 'seller' : null;
82
+ const base = {
83
+ deal, program: BOND_PROGRAM, seller: a.seller, buyer: a.buyer, ...(role ? { yourRole: role } : {}),
84
+ asset: { mint: a.mint, symbol: m.symbol, decimals: m.decimals },
85
+ price: amt(a.terms.price), sellerBond: amt(a.terms.sellerBond), buyerDeposit: amt(a.terms.buyerDeposit),
86
+ balanceToPay: amt(a.terms.price - a.terms.buyerDeposit),
87
+ openedAt: time(a.openedAt), deliverBy: time(a.terms.deliverBy),
88
+ sellerMarkedAt: time(a.sellerMark), buyerConfirmedAt: time(a.buyerConfirm), balancePaid: a.balancePaid,
89
+ clock: time(now),
90
+ };
91
+ if (a.outcome !== 'open') {
92
+ return {
93
+ result: 'settled', ...base, outcome: a.outcome,
94
+ owedToSeller: amt(a.owedSeller),
95
+ note: 'Settled. Each side claims its own share (claim_buyer, then claim_seller); anyone may send the claims.',
96
+ };
97
+ }
98
+ const preview = settlePreview(a, now);
99
+ const from = settleableFrom(a, now);
100
+ return {
101
+ result: 'open', ...base,
102
+ deadlines: { lateUntil: time(t2(a.terms)), buyerConfirmOrPayUntil: time(buyerDeadline(a)), settleableBy: time(settleBy(a)) },
103
+ // What the bond loses to lateness if the buyer confirmed now (delivery time = the seller mark, or now)
104
+ lateDeductionIfConfirmed: amt(lateDeduction({ ...a, buyerConfirm: a.buyerConfirm ?? now })),
105
+ possibleActions: possibleActions(a, now).map((x) => ({ action: x.action, who: x.who, ...(x.until !== undefined ? { until: iso(x.until) } : {}) })),
106
+ settlement: preview
107
+ ? { now: true, outcome: preview.outcome, toSeller: amt(preview.toSeller), toBuyer: amt(preview.toBuyer) }
108
+ : { now: false, earliest: from === null ? null : iso(from), note: 'Not settleable yet. If nobody acts, settlement opens at "earliest".' },
109
+ notes: [
110
+ 'Predicted from the program rules; the program on chain decides. The program does not judge quality; quality disputes are resolved between the parties.',
111
+ 'Never send tokens directly to a deal vault: anything beyond the locked amount is paid to the buyer.',
112
+ ],
113
+ };
114
+ }
@@ -0,0 +1,32 @@
1
+ import { type AccountsFetcher, type LockProtocol } from './locks.js';
2
+ import { type LockAsset, type PayPolicy } from './policy.js';
3
+ export interface LockFact {
4
+ account: string;
5
+ protocol: LockProtocol;
6
+ asset: LockAsset | null;
7
+ /** Counted toward the requirement */
8
+ counted: boolean;
9
+ /** Why it is not counted */
10
+ reason?: string;
11
+ lockedNow?: string;
12
+ lockedAtDeadline?: string;
13
+ }
14
+ export interface CommitmentResult {
15
+ ok: boolean;
16
+ reasons: string[];
17
+ /** Facts shown to the user whatever the result */
18
+ facts: {
19
+ registration: string;
20
+ deadline: string;
21
+ locks: LockFact[];
22
+ totalsAtDeadline: Partial<Record<LockAsset, string>>;
23
+ };
24
+ }
25
+ export declare function checkCommitment(o: {
26
+ origin: string;
27
+ payTo: string;
28
+ policy: PayPolicy;
29
+ fetch: typeof fetch;
30
+ accounts?: AccountsFetcher;
31
+ now: Date;
32
+ }): Promise<CommitmentResult>;
@@ -0,0 +1,90 @@
1
+ // Seller lock check before paying (asset-neutral): reads the seller's registration, verifies signatures, reads each lock on-chain
2
+ // and checks how much is still locked minDays from now. Only irrevocable locks signed by their recipient count.
3
+ import { readLock } from './locks.js';
4
+ import { WSOL_MINT } from './policy.js';
5
+ import { REGISTRATION_PATH, verifyRegistration } from './registration.js';
6
+ import { formatUnits as fmt } from './units.js';
7
+ /** SOL (wrapped) has 9 decimals; USDC and PREQ have 6 */
8
+ const formatUnits = (v, unit) => fmt(v, unit, unit === 'SOL' ? 9 : 6);
9
+ export async function checkCommitment(o) {
10
+ const deadlineSec = BigInt(Math.floor(o.now.getTime() / 1000)) + BigInt(Math.round(o.policy.lock.minDays * 86_400));
11
+ const deadline = new Date(Number(deadlineSec) * 1000).toISOString();
12
+ const facts = { registration: 'not_checked', deadline, locks: [], totalsAtDeadline: {} };
13
+ const fail = (reason) => ({ ok: false, reasons: [reason], facts });
14
+ const host = new URL(o.origin).host;
15
+ let doc;
16
+ try {
17
+ const res = await o.fetch(`${o.origin}${REGISTRATION_PATH}`, { redirect: 'manual' });
18
+ if (res.status !== 200) {
19
+ facts.registration = `missing (http ${res.status})`;
20
+ return fail(`lock_registration_missing: ${host}${REGISTRATION_PATH}`);
21
+ }
22
+ const text = (await res.text()).slice(0, 65_536);
23
+ doc = JSON.parse(text);
24
+ }
25
+ catch {
26
+ facts.registration = 'unreadable';
27
+ return fail(`lock_registration_unreadable: ${host}${REGISTRATION_PATH}`);
28
+ }
29
+ const v = await verifyRegistration(doc, host, o.now);
30
+ if (!v.ok) {
31
+ facts.registration = v.reason;
32
+ return fail(`lock_${v.reason}`);
33
+ }
34
+ facts.registration = 'ok';
35
+ if (!v.payload.payTo.includes(o.payTo))
36
+ return fail(`lock_registration_pay_to_not_listed: ${o.payTo}`);
37
+ if (!o.accounts)
38
+ return fail('lock_check_unavailable: no RPC to read locks');
39
+ const locks = v.payload.locks.filter((l) => (l?.protocol === 'jupiter-lock' || l?.protocol === 'streamflow') && typeof l.account === 'string').slice(0, 20);
40
+ let accounts;
41
+ try {
42
+ accounts = await o.accounts(locks.map((l) => l.account));
43
+ }
44
+ catch (e) {
45
+ return fail(`lock_check_unavailable: ${e.message}`);
46
+ }
47
+ const mints = { PREQ: o.policy.mints.PREQ, USDC: o.policy.mints.USDC, SOL: WSOL_MINT };
48
+ const totals = {};
49
+ const nowSec = BigInt(Math.floor(o.now.getTime() / 1000));
50
+ const seen = new Set();
51
+ for (const [i, l] of locks.entries()) {
52
+ const fact = { account: l.account, protocol: l.protocol, asset: null, counted: false };
53
+ facts.locks.push(fact);
54
+ if (seen.has(l.account)) {
55
+ fact.reason = 'duplicate';
56
+ continue;
57
+ }
58
+ seen.add(l.account);
59
+ const j = await readLock(l.protocol, l.account, accounts[i]);
60
+ if (typeof j === 'string') {
61
+ fact.reason = j;
62
+ continue;
63
+ }
64
+ fact.asset = Object.keys(mints).find((k) => mints[k] && mints[k] === j.mint) ?? null;
65
+ const unit = fact.asset ?? 'tokens';
66
+ fact.lockedNow = formatUnits(j.lockedAt(nowSec), unit);
67
+ fact.lockedAtDeadline = formatUnits(j.lockedAt(deadlineSec), unit);
68
+ if (!fact.asset) {
69
+ fact.reason = `asset_not_counted: ${j.mint}`;
70
+ continue;
71
+ }
72
+ if (j.notFixed) {
73
+ fact.reason = `revocable_lock: ${j.notFixed}`;
74
+ continue;
75
+ }
76
+ if (!v.signers.has(j.recipient)) {
77
+ fact.reason = `recipient_did_not_sign: ${j.recipient}`;
78
+ continue;
79
+ }
80
+ fact.counted = true;
81
+ totals[fact.asset] = (totals[fact.asset] ?? 0n) + j.lockedAt(deadlineSec);
82
+ }
83
+ for (const [k, t] of Object.entries(totals))
84
+ facts.totalsAtDeadline[k] = formatUnits(t, k);
85
+ const met = Object.entries(o.policy.lock.min).find(([k, min]) => (totals[k] ?? 0n) >= min);
86
+ if (met)
87
+ return { ok: true, reasons: [], facts };
88
+ const need = Object.entries(o.policy.lock.min).map(([k, min]) => `${formatUnits(totals[k] ?? 0n, k)} of ${formatUnits(min, k)}`).join(' or ');
89
+ return { ok: false, reasons: [`lock_requirement_not_met: locked until ${deadline}: ${need}`], facts };
90
+ }
package/dist/history.js CHANGED
@@ -17,7 +17,8 @@ export function jsonlHistory(path, mints) {
17
17
  // A signed payment counts as spent regardless of result (succeeded, rejected, unknown), to be conservative
18
18
  const signedOn = (now) => {
19
19
  const day = now.toISOString().slice(0, 10);
20
- return read().filter((e) => e.signed && e.at.slice(0, 10) === day);
20
+ // Fee-only signatures (amount "0", e.g. settling a bond deal) move no tokens and do not count as payments
21
+ return read().filter((e) => e.signed && e.at.slice(0, 10) === day && e.amount !== '0');
21
22
  };
22
23
  const usdOf = (xs, usdc) => xs.filter((e) => e.mint === usdc && e.amount).reduce((s, e) => s + Number(e.amount) / 1e6, 0);
23
24
  const sumOf = (xs, mint) => (mint ? xs.filter((e) => e.mint === mint && e.amount && /^\d+$/.test(e.amount)).reduce((s, e) => s + BigInt(e.amount), 0n) : 0n);
@@ -0,0 +1,58 @@
1
+ export declare const JUPITER_LOCK_PROGRAM = "LocpQgucEQHbqNABEYvBvwoxCPsSbG91A1QaQhQQqjn";
2
+ export interface AccountData {
3
+ owner: string;
4
+ data: Uint8Array;
5
+ }
6
+ /** getMultipleAccounts: one entry per address, null if missing */
7
+ export type AccountsFetcher = (addresses: string[]) => Promise<(AccountData | null)[]>;
8
+ export interface JupiterLockInfo {
9
+ recipient: string;
10
+ mint: string;
11
+ cancel: string;
12
+ updateRecipient: string;
13
+ cliffTime: bigint;
14
+ frequency: bigint;
15
+ cliffUnlockAmount: bigint;
16
+ amountPerPeriod: bigint;
17
+ numberOfPeriod: bigint;
18
+ cancelledAt: bigint;
19
+ }
20
+ export declare function decodeJupiterLock(data: Uint8Array): JupiterLockInfo | null;
21
+ /** Amount still locked at Unix time t (not yet released); 0 if cancelled */
22
+ export declare function lockedAt(l: JupiterLockInfo, t: bigint): bigint;
23
+ export declare const isIrrevocable: (l: JupiterLockInfo) => boolean;
24
+ /** getMultipleAccounts over JSON-RPC (read-only) */
25
+ export declare function rpcAccounts(rpcUrl: string, f?: typeof fetch): AccountsFetcher;
26
+ export declare const STREAMFLOW_PROGRAM = "strmRqUCoQUgGUan5YhzUZa6KqdzwX5L6FpUxfmKg5m";
27
+ export interface StreamflowInfo {
28
+ recipient: string;
29
+ mint: string;
30
+ escrowTokens: string;
31
+ canceledAt: bigint;
32
+ startTime: bigint;
33
+ netAmountDeposited: bigint;
34
+ period: bigint;
35
+ amountPerPeriod: bigint;
36
+ cliff: bigint;
37
+ cliffAmount: bigint;
38
+ cancelableBySender: boolean;
39
+ cancelableByRecipient: boolean;
40
+ transferableBySender: boolean;
41
+ transferableByRecipient: boolean;
42
+ canUpdateRate: boolean;
43
+ closed: boolean;
44
+ }
45
+ export declare function decodeStreamflow(data: Uint8Array): StreamflowInfo | null;
46
+ /** Amount still locked at Unix time t: nothing released before the cliff, then the cliff amount plus one amount per period (capped at the deposit) */
47
+ export declare function streamflowLockedAt(s: StreamflowInfo, t: bigint): bigint;
48
+ /** Why a Streamflow contract is not a fixed lock (null = fixed) */
49
+ export declare function streamflowNotFixed(s: StreamflowInfo): string | null;
50
+ export type LockProtocol = 'jupiter-lock' | 'streamflow';
51
+ export interface LockView {
52
+ recipient: string;
53
+ mint: string;
54
+ notFixed: string | null;
55
+ lockedAt(t: bigint): bigint;
56
+ }
57
+ /** Decodes a lock account of the given protocol; returns the reason as a string if it is not one */
58
+ export declare function readLock(protocol: LockProtocol, address: string, a: AccountData | null): Promise<LockView | string>;
package/dist/locks.js ADDED
@@ -0,0 +1,105 @@
1
+ // Reads seller lock accounts on Solana (read-only): Jupiter Lock escrows (program "locker" 0.4.0) and Streamflow contracts.
2
+ // Layout: the program's on-chain Anchor IDL (8-byte discriminator + 288-byte struct, little-endian), checked against real mainnet escrows on 2026-11-22.
3
+ import { address as address_, getAddressEncoder, getBase58Decoder, getProgramDerivedAddress } from '@solana/kit';
4
+ export const JUPITER_LOCK_PROGRAM = 'LocpQgucEQHbqNABEYvBvwoxCPsSbG91A1QaQhQQqjn';
5
+ const DISCRIMINATOR = [244, 119, 183, 4, 73, 116, 135, 195];
6
+ const SIZE = 296;
7
+ const PERMISSION = ['none', 'creator', 'recipient', 'either'];
8
+ export function decodeJupiterLock(data) {
9
+ if (data.length < SIZE || DISCRIMINATOR.some((b, i) => data[i] !== b))
10
+ return null;
11
+ const v = new DataView(data.buffer, data.byteOffset, data.byteLength);
12
+ const b58 = getBase58Decoder();
13
+ const key = (o) => b58.decode(data.subarray(o, o + 32));
14
+ const u64 = (o) => v.getBigUint64(o, true);
15
+ return {
16
+ recipient: key(8), mint: key(40),
17
+ updateRecipient: PERMISSION[data[137]] ?? 'unknown', cancel: PERMISSION[data[138]] ?? 'unknown',
18
+ cliffTime: u64(144), frequency: u64(152), cliffUnlockAmount: u64(160), amountPerPeriod: u64(168), numberOfPeriod: u64(176),
19
+ cancelledAt: u64(200),
20
+ };
21
+ }
22
+ /** Amount still locked at Unix time t (not yet released); 0 if cancelled */
23
+ export function lockedAt(l, t) {
24
+ if (l.cancelledAt !== 0n)
25
+ return 0n;
26
+ const total = l.cliffUnlockAmount + l.amountPerPeriod * l.numberOfPeriod;
27
+ if (t < l.cliffTime)
28
+ return total;
29
+ const periods = l.frequency > 0n ? (t - l.cliffTime) / l.frequency : l.numberOfPeriod;
30
+ return total - (l.cliffUnlockAmount + (periods < l.numberOfPeriod ? periods : l.numberOfPeriod) * l.amountPerPeriod);
31
+ }
32
+ export const isIrrevocable = (l) => l.cancel === 'none' && l.updateRecipient === 'none' && l.cancelledAt === 0n;
33
+ /** getMultipleAccounts over JSON-RPC (read-only) */
34
+ export function rpcAccounts(rpcUrl, f = fetch) {
35
+ return async (addresses) => {
36
+ if (!addresses.length)
37
+ return [];
38
+ const r = await f(rpcUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getMultipleAccounts', params: [addresses, { encoding: 'base64' }] }) });
39
+ const j = (await r.json());
40
+ if (!j.result)
41
+ throw new Error(`rpc getMultipleAccounts: ${j.error?.message ?? r.status}`);
42
+ return j.result.value.map((a) => (a ? { owner: a.owner, data: new Uint8Array(Buffer.from(a.data[0], 'base64')) } : null));
43
+ };
44
+ }
45
+ // ---- Streamflow (program strmRqUCoQUgGUan5YhzUZa6KqdzwX5L6FpUxfmKg5m): same offsets as the check-engine decoder (@streamflow/stream 13.4.0 layout)
46
+ export const STREAMFLOW_PROGRAM = 'strmRqUCoQUgGUan5YhzUZa6KqdzwX5L6FpUxfmKg5m';
47
+ const STREAMFLOW_MIN_SIZE = 819;
48
+ export function decodeStreamflow(data) {
49
+ if (data.length < STREAMFLOW_MIN_SIZE)
50
+ return null;
51
+ const v = new DataView(data.buffer, data.byteOffset, data.byteLength);
52
+ const b58 = getBase58Decoder();
53
+ const key = (o) => b58.decode(data.subarray(o, o + 32));
54
+ const u64 = (o) => v.getBigUint64(o, true);
55
+ const bool = (o) => data[o] !== 0;
56
+ return {
57
+ canceledAt: u64(25), recipient: key(113), mint: key(177), escrowTokens: key(209),
58
+ startTime: u64(409), netAmountDeposited: u64(417), period: u64(425), amountPerPeriod: u64(433), cliff: u64(441), cliffAmount: u64(449),
59
+ cancelableBySender: bool(457), cancelableByRecipient: bool(458), transferableBySender: bool(460), transferableByRecipient: bool(461),
60
+ canUpdateRate: bool(540), closed: bool(671),
61
+ };
62
+ }
63
+ /** Amount still locked at Unix time t: nothing released before the cliff, then the cliff amount plus one amount per period (capped at the deposit) */
64
+ export function streamflowLockedAt(s, t) {
65
+ if (s.canceledAt !== 0n || s.closed)
66
+ return 0n;
67
+ if (t < s.cliff)
68
+ return s.netAmountDeposited;
69
+ const periods = s.period > 0n ? (t - s.cliff) / s.period : 0n;
70
+ const released = s.cliffAmount + periods * s.amountPerPeriod;
71
+ return released >= s.netAmountDeposited ? 0n : s.netAmountDeposited - released;
72
+ }
73
+ /** Why a Streamflow contract is not a fixed lock (null = fixed) */
74
+ export function streamflowNotFixed(s) {
75
+ const why = [
76
+ s.cancelableBySender && 'cancelable by sender', s.cancelableByRecipient && 'cancelable by recipient',
77
+ s.transferableBySender && 'transferable by sender', s.transferableByRecipient && 'transferable by recipient',
78
+ s.canUpdateRate && 'rate can be updated', s.canceledAt !== 0n && 'cancelled', s.closed && 'closed',
79
+ ].filter(Boolean);
80
+ return why.length ? why.join(', ') : null;
81
+ }
82
+ /** Decodes a lock account of the given protocol; returns the reason as a string if it is not one */
83
+ export async function readLock(protocol, address, a) {
84
+ if (!a)
85
+ return 'account_not_found';
86
+ if (protocol === 'jupiter-lock') {
87
+ if (a.owner !== JUPITER_LOCK_PROGRAM)
88
+ return 'not_a_jupiter_lock_account';
89
+ const j = decodeJupiterLock(a.data);
90
+ if (!j)
91
+ return 'not_a_jupiter_lock_escrow';
92
+ const notFixed = isIrrevocable(j) ? null : `cancel=${j.cancel}, updateRecipient=${j.updateRecipient}${j.cancelledAt ? ', cancelled' : ''}`;
93
+ return { recipient: j.recipient, mint: j.mint, notFixed, lockedAt: (t) => lockedAt(j, t) };
94
+ }
95
+ if (a.owner !== STREAMFLOW_PROGRAM)
96
+ return 'not_a_streamflow_account';
97
+ const s = decodeStreamflow(a.data);
98
+ if (!s)
99
+ return 'not_a_streamflow_contract';
100
+ // A real contract's escrow is PDA(["strm", contract], program)
101
+ const [escrow] = await getProgramDerivedAddress({ programAddress: address_(STREAMFLOW_PROGRAM), seeds: [new TextEncoder().encode('strm'), getAddressEncoder().encode(address_(address))] });
102
+ if (escrow !== s.escrowTokens)
103
+ return 'streamflow_escrow_mismatch';
104
+ return { recipient: s.recipient, mint: s.mint, notFixed: streamflowNotFixed(s), lockedAt: (t) => streamflowLockedAt(s, t) };
105
+ }
package/dist/policy.d.ts CHANGED
@@ -41,6 +41,8 @@ export interface PayPolicy {
41
41
  maxUsdPerRecipientPerDay: number | null;
42
42
  /** Daily PREQ cap per recipient (smallest units). null = only the overall PREQ daily cap applies */
43
43
  maxPreqPerRecipientPerDay: bigint | null;
44
+ /** Seller lock (commitment) requirement: 'always', USDC payments at or above aboveUsd, or off */
45
+ lock: LockPolicy;
44
46
  /** USDC payments at or above this amount (USD) need human confirmation. null = never ask */
45
47
  confirmAboveUsd: number | null;
46
48
  /** Per-token limits (base units). No defaults: both per-payment and daily must be set to pay in that token */
@@ -59,6 +61,15 @@ export interface PolicyEnv {
59
61
  X402_MAX_USD_PER_DAY?: string;
60
62
  X402_MAX_USD_PER_RECIPIENT_PER_DAY?: string;
61
63
  X402_MAX_PREQ_PER_RECIPIENT_PER_DAY_ATOMIC?: string;
64
+ /** yes = pay only sellers whose registered lock meets the minimums */
65
+ X402_REQUIRE_LOCK?: string;
66
+ /** Require the lock only for USDC payments at or above this amount (USD) */
67
+ X402_REQUIRE_LOCK_ABOVE_USD?: string;
68
+ /** The lock must still hold the minimum this many days from now (default 90) */
69
+ X402_MIN_LOCK_DAYS?: string;
70
+ X402_MIN_LOCK_PREQ_ATOMIC?: string;
71
+ X402_MIN_LOCK_USDC_ATOMIC?: string;
72
+ X402_MIN_LOCK_SOL_ATOMIC?: string;
62
73
  X402_CONFIRM_ABOVE_USD?: string;
63
74
  X402_MAX_PREQ_ATOMIC?: string;
64
75
  X402_MAX_PREQ_PER_DAY_ATOMIC?: string;
@@ -96,6 +107,21 @@ export interface DayUsage {
96
107
  /** Total A402 (v1) signed today (base units) */
97
108
  a402: bigint;
98
109
  }
110
+ /** Lock assets are read the same way (asset-neutral): a seller passes if any configured asset meets its minimum */
111
+ export type LockAsset = 'PREQ' | 'USDC' | 'SOL';
112
+ export interface LockPolicy {
113
+ always: boolean;
114
+ aboveUsd: number | null;
115
+ minDays: number;
116
+ /** Minimum still locked at now + minDays, per asset (smallest units). Only assets listed here count */
117
+ min: Partial<Record<LockAsset, bigint>>;
118
+ }
119
+ export declare const WSOL_MINT = "So11111111111111111111111111111111111111112";
120
+ /** Whether this payment option needs a seller lock check */
121
+ export declare function needsLock(p: PayPolicy, e: {
122
+ asset: AssetSymbol | null;
123
+ usd: number | null;
124
+ }): boolean;
99
125
  /** Today's signed payments to one recipient (payTo) */
100
126
  export interface RecipientUsage {
101
127
  count: number;