@agent402-dev/pay-mcp 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,6 +43,23 @@ Nothing is signed unless every rule passes. **With no configuration, every payme
43
43
 
44
44
  Other settings: `X402_KEYPAIR_PATH` (wallet key file, Solana CLI JSON; without it nothing is paid), `X402_NETWORK` (`mainnet` | `devnet`), `X402_RPC_URL`, `X402_PAY_WITH` (`USDC` | `PREQ`), `X402_HISTORY_PATH` (default `~/.agent402/payments.jsonl`).
45
45
 
46
+ ## Require a seller lock (optional)
47
+ For larger payments you can pay only sellers that have locked funds on-chain for a fixed time. A lock is a commitment signal: nobody can confiscate it, so it does not cover losses.
48
+
49
+ | Rule | Variable | Default |
50
+ |---|---|---|
51
+ | Require a lock for every payment | `X402_REQUIRE_LOCK=yes` | off |
52
+ | Require a lock only for USDC payments at or above this amount (USD) | `X402_REQUIRE_LOCK_ABOVE_USD` | off |
53
+ | The minimum must still be locked this many days from now | `X402_MIN_LOCK_DAYS` | `90` |
54
+ | Minimum PREQ locked (PREQ smallest units; 1 PREQ = 1,000,000) | `X402_MIN_LOCK_PREQ_ATOMIC` | not set |
55
+ | Minimum USDC locked (USDC smallest units; 1 USDC = 1,000,000) | `X402_MIN_LOCK_USDC_ATOMIC` | not set |
56
+ | Minimum SOL locked as wrapped SOL (smallest units, lamports; 1 SOL = 1,000,000,000) | `X402_MIN_LOCK_SOL_ATOMIC` | not set |
57
+
58
+ - Assets are treated the same way: the seller passes if any asset you set meets its minimum. Turning the requirement on without any minimum stops the server at start.
59
+ - Before signing, pay-mcp reads `https://<seller host>/.well-known/agent402.json` (made with `signRegistration` from `@agent402-dev/pay-server`), checks the signatures, then reads each listed Jupiter Lock escrow on-chain (read-only, through `X402_RPC_URL` or the public RPC).
60
+ - A lock counts only if nobody can cancel it or change its recipient, it was not cancelled, and its recipient key signed the seller's registration.
61
+ - Results show the facts: each lock, how much is locked now and at the deadline, and why a lock did not count.
62
+
46
63
  ## Create a payment wallet
47
64
  ```bash
48
65
  npx -y @agent402-dev/pay-mcp init
package/dist/agent.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { History, PaymentResult } from './history.js';
2
+ import { type CommitmentResult } from './commitment.js';
3
+ import type { AccountsFetcher } from './locks.js';
2
4
  import { type PayPolicy } from './policy.js';
3
5
  import type { Wallet } from './wallet.js';
4
6
  export type ConfirmAnswer = 'accept' | 'decline' | 'unsupported';
@@ -11,6 +13,8 @@ export interface AgentDeps {
11
13
  confirm: (message: string) => Promise<ConfirmAnswer>;
12
14
  now?: () => Date;
13
15
  maxRedirects?: number;
16
+ /** Read-only account reader for seller lock checks (getMultipleAccounts) */
17
+ accounts?: AccountsFetcher;
14
18
  }
15
19
  export interface RequestSpec {
16
20
  url: string;
@@ -42,6 +46,10 @@ export interface FetchOutcome {
42
46
  }[];
43
47
  /** Warnings (e.g. the deprecation notice when trying to pay with A402 (v1)) */
44
48
  warnings?: string[];
49
+ /** Seller lock check, when the policy required one */
50
+ lock?: CommitmentResult['facts'] & {
51
+ ok: boolean;
52
+ };
45
53
  /** Seller's signed receipt, if the server sent one (X-Agent402-Receipt) */
46
54
  receipt?: {
47
55
  signer: string | null;
package/dist/agent.js CHANGED
@@ -2,7 +2,8 @@
2
2
  // Order: domain check → request (follows redirects itself, checking the domain each time) → on 402, evaluate the policy → (confirm the quote is unchanged) → (human confirmation) → sign once → re-request
3
3
  // At most one signature per request. If another 402 comes after paying, it does not sign again
4
4
  import { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';
5
- import { A402_DEPRECATION_WARNING, choose, domainCheck, evaluate, nearLimits } from './policy.js';
5
+ import { checkCommitment } from './commitment.js';
6
+ import { A402_DEPRECATION_WARNING, choose, domainCheck, evaluate, nearLimits, needsLock } from './policy.js';
6
7
  import { checkReceipt, RECEIPT_HEADER } from './receipt.js';
7
8
  import { withSmallest } from './units.js';
8
9
  const REDIRECTS = new Set([301, 302, 303, 307, 308]);
@@ -12,6 +13,17 @@ export function createAgent(d) {
12
13
  const now = d.now ?? (() => new Date());
13
14
  const quotes = new Map();
14
15
  const QUOTE_TTL_MS = 5 * 60_000;
16
+ const lockCache = new Map();
17
+ const LOCK_TTL_MS = 10 * 60_000;
18
+ async function commitmentFor(origin, payTo) {
19
+ const key = `${origin}|${payTo}`;
20
+ const hit = lockCache.get(key);
21
+ if (hit && now().getTime() - hit.at < LOCK_TTL_MS)
22
+ return hit.r;
23
+ const r = await checkCommitment({ origin, payTo, policy: d.policy, fetch: d.fetch, accounts: d.accounts, now: now() });
24
+ lockCache.set(key, { at: now().getTime(), r });
25
+ return r;
26
+ }
15
27
  /** Follows redirects itself and checks the domain at each step */
16
28
  async function send(spec, extraHeaders = {}, follow = true) {
17
29
  let url = spec.url;
@@ -71,7 +83,19 @@ export function createAgent(d) {
71
83
  }
72
84
  const usage = d.history.today(now());
73
85
  const evs = pr.accepts.map((r) => evaluate(d.policy, r, usage, d.history.recipientToday(r.payTo, now())));
74
- return { kind: '402', pr, evs, chosen: choose(d.policy, evs), finalUrl };
86
+ // Seller lock check, only for options that need it and passed every other rule (before signing)
87
+ let lock;
88
+ for (const e of evs) {
89
+ if (!e.ok || !needsLock(d.policy, e))
90
+ continue;
91
+ const c = await commitmentFor(new URL(finalUrl).origin, e.requirement.payTo);
92
+ lock = { ok: c.ok, ...c.facts };
93
+ if (!c.ok) {
94
+ e.ok = false;
95
+ e.reasons.push(...c.reasons);
96
+ }
97
+ }
98
+ return { kind: '402', pr, evs, chosen: choose(d.policy, evs), finalUrl, ...(lock ? { lock } : {}) };
75
99
  }
76
100
  async function quote(spec) {
77
101
  const a = await assess(spec);
@@ -81,11 +105,11 @@ export function createAgent(d) {
81
105
  return { result: 'not_required', httpStatus: a.res.status };
82
106
  const options = a.evs.map(describe);
83
107
  if (!a.chosen)
84
- return { result: 'refused', reasons: ['no_option_passes_policy'], options };
108
+ return { result: 'refused', reasons: ['no_option_passes_policy'], options, ...(a.lock ? { lock: a.lock } : {}) };
85
109
  const quoteId = crypto.randomUUID();
86
110
  const r = a.chosen.requirement;
87
111
  quotes.set(quoteId, { url: spec.url, asset: r.asset, amount: r.amount, payTo: r.payTo, network: r.network, at: now().getTime() });
88
- return { result: 'not_required', quoteId, options, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network }, reasons: a.chosen.needsConfirmation ? ['will_ask_for_confirmation'] : [] };
112
+ return { result: 'not_required', quoteId, options, ...(a.lock ? { lock: a.lock } : {}), payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network }, reasons: a.chosen.needsConfirmation ? ['will_ask_for_confirmation'] : [] };
89
113
  }
90
114
  async function payAndFetch(spec) {
91
115
  const base = { url: spec.url, host: host(spec.url) };
@@ -100,7 +124,7 @@ export function createAgent(d) {
100
124
  if (!a.chosen) {
101
125
  const reasons = ['no_option_passes_policy', ...a.evs.flatMap((e) => e.reasons)];
102
126
  record({ ...base, result: 'refused', reasons, signed: false });
103
- return { result: 'refused', reasons, options };
127
+ return { result: 'refused', reasons, options, ...(a.lock ? { lock: a.lock } : {}) };
104
128
  }
105
129
  const r = a.chosen.requirement;
106
130
  const pay = { network: r.network, asset: a.chosen.asset ?? undefined, mint: r.asset, amount: r.amount, payTo: r.payTo };
@@ -153,7 +177,7 @@ export function createAgent(d) {
153
177
  const receipt = rc ? { signer: rc.signer, verified: rc.verified, reasons: rc.reasons } : undefined;
154
178
  record({ ...base, ...pay, result: 'paid', httpStatus: res.status, settlementTx: tx, signed: true, ...(rc ? { receipt: { ...receipt, token: rc.token } } : {}) });
155
179
  const near = nearLimits(d.policy, d.history.today(now()));
156
- return { result: 'paid', httpStatus: res.status, body, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network, settlementTx: tx }, ...(receipt ? { receipt } : {}), ...(near.length ? { warnings: near } : {}) };
180
+ return { result: 'paid', httpStatus: res.status, body, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network, settlementTx: tx }, ...(a.lock ? { lock: a.lock } : {}), ...(receipt ? { receipt } : {}), ...(near.length ? { warnings: near } : {}) };
157
181
  }
158
182
  const reason = typeof body === 'object' && body && 'reason' in body ? String(body.reason) : `http_${res.status}`;
159
183
  const result = res.status === 402 ? 'rejected_by_server' : res.headers.get('x-payment-status') === 'not-settled' || res.status === 409 ? 'failed' : 'unknown';
@@ -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
+ }
@@ -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;
package/dist/policy.js CHANGED
@@ -57,6 +57,7 @@ export function policyFromEnv(env) {
57
57
  maxUsdPerDay: num(env.X402_MAX_USD_PER_DAY, 1),
58
58
  maxUsdPerRecipientPerDay: Number(env.X402_MAX_USD_PER_RECIPIENT_PER_DAY) > 0 ? Number(env.X402_MAX_USD_PER_RECIPIENT_PER_DAY) : null,
59
59
  maxPreqPerRecipientPerDay: atomic(env.X402_MAX_PREQ_PER_RECIPIENT_PER_DAY_ATOMIC),
60
+ lock: lockPolicyFromEnv(env),
60
61
  confirmAboveUsd: env.X402_CONFIRM_ABOVE_USD ? Number(env.X402_CONFIRM_ABOVE_USD) : null,
61
62
  tokenLimits: { PREQ: limitsFor('PREQ'), A402: limitsFor('A402') },
62
63
  prefer,
@@ -82,6 +83,28 @@ export function domainCheck(p, url) {
82
83
  return { ok: false, reason: `domain_not_allowed: ${host}` };
83
84
  return { ok: true, host };
84
85
  }
86
+ export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
87
+ function lockPolicyFromEnv(env) {
88
+ const always = env.X402_REQUIRE_LOCK === 'yes';
89
+ const aboveUsd = Number(env.X402_REQUIRE_LOCK_ABOVE_USD) > 0 ? Number(env.X402_REQUIRE_LOCK_ABOVE_USD) : null;
90
+ const min = {};
91
+ for (const [a, v] of [['PREQ', env.X402_MIN_LOCK_PREQ_ATOMIC], ['USDC', env.X402_MIN_LOCK_USDC_ATOMIC], ['SOL', env.X402_MIN_LOCK_SOL_ATOMIC]]) {
92
+ const x = atomic(v);
93
+ if (x !== null)
94
+ min[a] = x;
95
+ }
96
+ if ((always || aboveUsd !== null) && !Object.keys(min).length) {
97
+ throw new Error('Lock requirement is on but no minimum is set: set at least one of X402_MIN_LOCK_PREQ_ATOMIC, X402_MIN_LOCK_USDC_ATOMIC, X402_MIN_LOCK_SOL_ATOMIC (smallest units).');
98
+ }
99
+ const days = Number(env.X402_MIN_LOCK_DAYS);
100
+ return { always, aboveUsd, minDays: Number.isFinite(days) && days >= 0 && env.X402_MIN_LOCK_DAYS ? days : 90, min };
101
+ }
102
+ /** Whether this payment option needs a seller lock check */
103
+ export function needsLock(p, e) {
104
+ if (p.lock.always)
105
+ return true;
106
+ return p.lock.aboveUsd !== null && e.asset === 'USDC' && e.usd !== null && e.usd >= p.lock.aboveUsd;
107
+ }
85
108
  const NO_RECIPIENT_USAGE = { count: 0, usd: 0, preq: 0n };
86
109
  export function symbolOf(p, mint) {
87
110
  if (!mint)
@@ -0,0 +1,24 @@
1
+ export declare const REGISTRATION_PATH = "/.well-known/agent402.json";
2
+ export declare const REGISTRATION_KIND = "agent402.seller-registration";
3
+ export interface RegistrationPayload {
4
+ v: 1;
5
+ kind: typeof REGISTRATION_KIND;
6
+ host: string;
7
+ payTo: string[];
8
+ locks: {
9
+ protocol: 'jupiter-lock' | 'streamflow';
10
+ account: string;
11
+ }[];
12
+ receiptSigners?: string[];
13
+ issuedAt: string;
14
+ expiresAt?: string;
15
+ }
16
+ export type VerifiedRegistration = {
17
+ ok: true;
18
+ payload: RegistrationPayload;
19
+ signers: Set<string>;
20
+ } | {
21
+ ok: false;
22
+ reason: string;
23
+ };
24
+ export declare function verifyRegistration(doc: unknown, host: string, now: Date): Promise<VerifiedRegistration>;
@@ -0,0 +1,39 @@
1
+ // Seller registration (Agent402 standard, asset-neutral): https://<seller host>/.well-known/agent402.json
2
+ // { "v": 1, "payload": "<base64url JSON>", "signatures": [{ "signer": "<base58 key>", "sig": "<base64url Ed25519 signature over the payload bytes>" }] }
3
+ // Payload: { v: 1, kind: "agent402.seller-registration", host, payTo: [...], locks: [{ protocol: "jupiter-lock" | "streamflow", account }], receiptSigners?: [...], issuedAt, expiresAt? }
4
+ // Each lock counts only if its recipient key signed the payload, so nobody can claim someone else's lock.
5
+ import { getBase58Encoder } from '@solana/kit';
6
+ export const REGISTRATION_PATH = '/.well-known/agent402.json';
7
+ export const REGISTRATION_KIND = 'agent402.seller-registration';
8
+ const b64 = (s) => new Uint8Array(Buffer.from(s, 'base64url'));
9
+ export async function verifyRegistration(doc, host, now) {
10
+ const d = doc;
11
+ if (!d || d.v !== 1 || typeof d.payload !== 'string' || !Array.isArray(d.signatures))
12
+ return { ok: false, reason: 'registration_malformed' };
13
+ const bytes = b64(d.payload);
14
+ let p;
15
+ try {
16
+ p = JSON.parse(new TextDecoder().decode(bytes));
17
+ }
18
+ catch {
19
+ return { ok: false, reason: 'registration_malformed' };
20
+ }
21
+ if (p.v !== 1 || p.kind !== REGISTRATION_KIND || !Array.isArray(p.payTo) || !Array.isArray(p.locks))
22
+ return { ok: false, reason: 'registration_unknown_format' };
23
+ if (String(p.host).toLowerCase() !== host.toLowerCase())
24
+ return { ok: false, reason: `registration_host_mismatch: ${p.host}` };
25
+ if (p.expiresAt && Date.parse(p.expiresAt) <= now.getTime())
26
+ return { ok: false, reason: 'registration_expired' };
27
+ const signers = new Set();
28
+ for (const s of d.signatures.slice(0, 16)) {
29
+ if (typeof s?.signer !== 'string' || typeof s.sig !== 'string')
30
+ continue;
31
+ try {
32
+ const key = await crypto.subtle.importKey('raw', getBase58Encoder().encode(s.signer), { name: 'Ed25519' }, false, ['verify']);
33
+ if (await crypto.subtle.verify('Ed25519', key, b64(s.sig), bytes))
34
+ signers.add(s.signer);
35
+ }
36
+ catch { /* invalid key or signature: ignored */ }
37
+ }
38
+ return { ok: true, payload: p, signers };
39
+ }
package/dist/server.js CHANGED
@@ -11,6 +11,7 @@ import { join } from 'node:path';
11
11
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
12
12
  import { historyToCsv } from './csv.js';
13
13
  import { jsonlHistory } from './history.js';
14
+ import { rpcAccounts } from './locks.js';
14
15
  import { initWallet } from './init.js';
15
16
  import { policyFromEnv } from './policy.js';
16
17
  import { createPayServer } from './tools.js';
@@ -74,5 +75,6 @@ else {
74
75
  })
75
76
  : null;
76
77
  const history = jsonlHistory(process.env.X402_HISTORY_PATH ?? DEFAULT_HISTORY, () => policy.mints);
77
- await createPayServer({ policy, wallet, history, fetch }).connect(new StdioServerTransport());
78
+ const rpc = process.env.X402_RPC_URL ?? (policy.network.includes('EtWTRAB') ? 'https://api.devnet.solana.com' : 'https://api.mainnet-beta.solana.com');
79
+ await createPayServer({ policy, wallet, history, fetch, accounts: rpcAccounts(rpc) }).connect(new StdioServerTransport());
78
80
  }
package/dist/tools.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import type { History } from './history.js';
3
+ import type { AccountsFetcher } from './locks.js';
3
4
  import { type PayPolicy } from './policy.js';
4
5
  import type { Wallet } from './wallet.js';
5
6
  export interface PayServerDeps {
@@ -8,5 +9,7 @@ export interface PayServerDeps {
8
9
  history: History;
9
10
  fetch: typeof fetch;
10
11
  now?: () => Date;
12
+ /** Read-only account reader for seller lock checks */
13
+ accounts?: AccountsFetcher;
11
14
  }
12
15
  export declare function createPayServer(d: PayServerDeps): McpServer;
package/dist/tools.js CHANGED
@@ -37,7 +37,7 @@ function tokenLimitFields(p, t) {
37
37
  };
38
38
  }
39
39
  export function createPayServer(d) {
40
- const server = new McpServer({ name: 'a402-pay', version: '0.3.0' });
40
+ const server = new McpServer({ name: 'a402-pay', version: '0.4.0' });
41
41
  const confirm = async (message) => {
42
42
  if (!server.server.getClientCapabilities()?.elicitation)
43
43
  return 'unsupported';
@@ -73,6 +73,9 @@ export function createPayServer(d) {
73
73
  maxUsdPerPayment: d.policy.maxUsdPerPayment, maxUsdPerDay: d.policy.maxUsdPerDay, maxPaymentsPerDay: d.policy.maxPaymentsPerDay,
74
74
  confirmAboveUsd: d.policy.confirmAboveUsd,
75
75
  maxUsdPerRecipientPerDay: d.policy.maxUsdPerRecipientPerDay,
76
+ sellerLock: d.policy.lock.always || d.policy.lock.aboveUsd !== null
77
+ ? { required: d.policy.lock.always ? 'always' : `USDC payments of ${d.policy.lock.aboveUsd} USD or more`, minDays: d.policy.lock.minDays, minimums: d.policy.lock.min }
78
+ : 'off',
76
79
  maxPreqPerRecipientPerDayAtomic: d.policy.maxPreqPerRecipientPerDay,
77
80
  ...tokenLimitFields(d.policy, 'PREQ'),
78
81
  ...(showA402 ? tokenLimitFields(d.policy, 'A402') : {}),
package/dist/units.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export declare const DECIMALS = 6;
2
2
  /** Base-unit integer → "140,000 PREQ" */
3
- export declare function formatUnits(atomic: string | bigint, symbol: string): string;
3
+ export declare function formatUnits(atomic: string | bigint, symbol: string, decimals?: number): string;
4
4
  /** "140,000 PREQ (140000000000 smallest units)" */
5
5
  export declare const withSmallest: (atomic: string | bigint, symbol: string) => string;
package/dist/units.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // Amount display: USDC and PREQ (and the deprecated A402) all have 6 decimals. Token amounts are always shown with units
2
2
  export const DECIMALS = 6;
3
3
  /** Base-unit integer → "140,000 PREQ" */
4
- export function formatUnits(atomic, symbol) {
5
- const s = atomic.toString().padStart(DECIMALS + 1, '0');
6
- const int = s.slice(0, -DECIMALS).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
7
- const frac = s.slice(-DECIMALS).replace(/0+$/, '');
4
+ export function formatUnits(atomic, symbol, decimals = DECIMALS) {
5
+ const s = atomic.toString().padStart(decimals + 1, '0');
6
+ const int = s.slice(0, -decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
7
+ const frac = s.slice(-decimals).replace(/0+$/, '');
8
8
  return `${int}${frac ? '.' + frac : ''} ${symbol}`;
9
9
  }
10
10
  /** "140,000 PREQ (140000000000 smallest units)" */
package/package.json CHANGED
@@ -27,7 +27,7 @@
27
27
  "@x402/svm": "2.31.0",
28
28
  "zod": "^4.6.7"
29
29
  },
30
- "version": "0.3.0",
30
+ "version": "0.4.0",
31
31
  "author": "Agent402",
32
32
  "license": "Apache-2.0",
33
33
  "type": "module",