@agent402-dev/pay-server 0.4.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/README.md CHANGED
@@ -22,7 +22,7 @@ Not related to `agent402.tools`, `@agents402` or other similarly named sites, ac
22
22
  - It **does not operate a facilitator.** Verification and settlement are done by the external facilitators you configure.
23
23
  - It **does not hold funds.** Payments go from the buyer's wallet directly to your receiving address.
24
24
  - It **does not exchange** currencies. The PREQ rate is used only to compute the PREQ amount; there is no PREQ ↔ USDC conversion.
25
- - It **does not accept or send payments on anyone's behalf.** Your server receives only your receiving address (public key); there is no API that takes a private key.
25
+ - It **does not accept or send payments on anyone's behalf.** The x402 gate receives only your receiving address (public key). No API takes a private key: the optional Bond seller helper (below) asks for a signer function that you provide (a wallet, a KMS, or your own wrapper) and never reads or stores keys.
26
26
 
27
27
  ## PREQ option
28
28
  PREQ is offered only when all of these hold for the request:
@@ -109,6 +109,45 @@ npx -y @agent402-dev/pay-server register --host api.example.com --pay-to <receiv
109
109
  - Use a lock received by a regular key. A lock received by a multisig vault cannot sign the registration yet.
110
110
  - The format is the same for every asset. A lock is a commitment signal only; nothing can be confiscated.
111
111
 
112
+ ## Agent402 Bond, seller side (optional)
113
+ `@agent402-dev/pay-server/bond` helps a seller run [Agent402 Bond](https://github.com/agent402-dev/agent402-toolkit/tree/main/programs) deals (beta): the seller locks a bond, the buyer locks a deposit, and the outcome follows only signatures and the Solana clock. Use it for work that takes time; use the x402 gate for instant pay-per-request.
114
+
115
+ ```ts
116
+ import { createBondSeller } from '@agent402-dev/pay-server/bond';
117
+
118
+ const seller = createBondSeller({
119
+ rpcUrl,
120
+ signer, // { publicKey, signTransaction(tx) } — your wallet or KMS; the SDK never sees the key
121
+ terms: { price: 20_000_000n, sellerBond: 2_000_000n, buyerDeposit: 5_000_000n, deliverSeconds: 3_600n, lateWindow: 0n, payWindow: 86_400n },
122
+ store, // persist jobs (default: in memory)
123
+ });
124
+
125
+ seller.quote(); // terms to show the buyer
126
+ const p = await seller.prepareOpen(buyerAddress); // `open` with you as fee payer, signed by you → send p.transaction to the buyer
127
+ await seller.requireOpen(p.deal); // start work only after this passes (deposit locked, terms as prepared)
128
+ await seller.markDelivered(p.deal); // when you hand over the work, before the deadline
129
+ await seller.settle(p.deal); // once the outcome is fixed (you pay the network fee)
130
+ await seller.unmarked(); // open deals you have not marked yet, earliest deadline first
131
+ ```
132
+
133
+ - Terms are checked against the program limits before anything is signed (bond at most 20% of the price, late window up to 7 days, pay window 1 to 30 days).
134
+ - If nothing is marked or confirmed by the deadline (delivery time + 1 day + late window), the bond and the deposit go to the buyer. Run `unmarked()` on a timer.
135
+ - The program does not judge quality. If the buyer never confirms, each side gets its own money back; quality disputes are resolved between the parties.
136
+ - `bondJobService({ seller, doJob })` serves the whole [Bond Job Protocol](https://github.com/agent402-dev/agent402-toolkit/blob/main/docs/bond/JOB-PROTOCOL.md) (`GET /quote`, `POST /open`, `POST /deliver`) as a Fetch-style `handle(req)` (Node, Cloudflare Workers): it checks the buyer's signature, starts work only once the deal is open on chain, marks delivery, and returns the same result on repeat calls. **Run its `processOpenJobs()` on a timer**: it does the work and marks delivery for every deal the buyer has opened, without waiting for the buyer to ask (otherwise a buyer who never fetches the result would get your bond at the deadline); it also settles and claims once the outcome is fixed, retries failed jobs without re-running finished ones, and drops prepared deals that were never opened. Long jobs answer `202 working` on `/deliver`.
137
+ - Protections in `bondJobService` (all configurable):
138
+ - each run of `doJob` is aborted after `jobTimeoutSeconds` (default 120; `ctx.signal` fires). After `maxAttempts` failures (default 3), or 30 minutes before the mark deadline with no result, it delivers `{ "error": "job_failed" }` and marks, so a bad input ends neutral (each side gets its own money back) instead of costing your bond;
139
+ - `validateInput(input)` refuses inputs before any deal is prepared;
140
+ - a buyer sees the work before deciding to confirm, and a deal never confirmed ends neutral, so the buyer could keep the work without paying. `maxUnconfirmedPerBuyer` (default 2) refuses buyers with that history (403); a buyer can switch wallets, so price jobs with this in mind or allowlist buyers for valuable work;
141
+ - `maxPendingPerBuyer` (default 3) and `maxPending` (default 50) cap deals in progress (each one locks your bond); over the cap `/open` answers 429;
142
+ - `processOpenJobs()` reads all deals in one batch, works on the earliest deadlines first (`concurrency`, default 4), and one failing deal does not stop the others;
143
+ - when several processes share one store (several Worker isolates, several servers), give the store `lock`/`unlock` so a job runs once (the in-memory store and the Workers example have it);
144
+ - if the buyer's token account is frozen or closed, settling falls back to claiming only your share;
145
+ - delivery requests are signed for your origin and expire within 10 minutes; set `publicOrigin` if you run behind a proxy that changes the scheme or host;
146
+ - USDC prices above the program's 100 USDC beta cap, `deliverSeconds` under 60 and `prepareTtlSeconds` under 300 are refused at startup.
147
+ - Buyers can use `@agent402-dev/pay-mcp` (`bond_job_start`, or `bond_open` for a transaction you deliver another way), which rebuilds your `open` transaction for its own wallet and signs only if it matches.
148
+ - Ready-to-deploy Cloudflare Workers seller (Durable Object job store, cron that delivers and marks): [`examples/bond-seller-worker`](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/pay-server/examples/bond-seller-worker).
149
+ - Full example with a seller service and a buyer agent: [`packages/bond-client/examples/job`](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/bond-client/examples/job).
150
+
112
151
  ## Data
113
152
  - No telemetry and no analytics.
114
153
  - It contacts only the facilitators you configure (`/supported`, `/verify`, `/settle`) and the RPC you pass to `rpcChain` (settlement checks, receiving token accounts, pool prices for the PREQ rate).
package/dist/bond.d.ts ADDED
@@ -0,0 +1,239 @@
1
+ import { PublicKey, Transaction } from '@solana/web3.js';
2
+ import * as bond from '@agent402-dev/bond-client';
3
+ /** Signs a transaction (partial signatures allowed). The private key stays with you. */
4
+ export interface BondSigner {
5
+ publicKey: PublicKey;
6
+ signTransaction(tx: Transaction): Promise<Transaction>;
7
+ }
8
+ export interface BondTermsConfig {
9
+ /** All amounts in the mint's smallest unit (USDC: 1 USDC = 1,000,000) */
10
+ price: bigint;
11
+ sellerBond: bigint;
12
+ buyerDeposit: bigint;
13
+ /** How long after opening you promise to deliver (seconds) */
14
+ deliverSeconds: bigint;
15
+ /** 0..=7 days */
16
+ lateWindow: bigint;
17
+ /** 1..=30 days */
18
+ payWindow: bigint;
19
+ }
20
+ /** One prepared or opened deal, as the seller keeps it. Persist these: you must still mark delivery after a restart. */
21
+ export interface BondJob {
22
+ deal: string;
23
+ buyer: string;
24
+ nonce: string;
25
+ terms: Record<keyof bond.Terms, string>;
26
+ preparedAt: string;
27
+ markedAt?: string;
28
+ markTx?: string;
29
+ settleTx?: string;
30
+ /** Anything you want to keep with the job (the request, an order id) */
31
+ meta?: unknown;
32
+ }
33
+ export interface BondJobStore {
34
+ get(deal: string): Promise<BondJob | undefined>;
35
+ put(job: BondJob): Promise<void>;
36
+ list(): Promise<BondJob[]>;
37
+ /** Optional: remove a job (used to drop prepared deals that can no longer be opened) */
38
+ delete?(deal: string): Promise<void>;
39
+ /**
40
+ * Optional but needed when several processes or isolates share one store (Workers, several servers): take a lease on a
41
+ * deal for `ms` milliseconds; false if another holder has an unexpired lease. Without it, a job can run twice.
42
+ */
43
+ lock?(deal: string, ms: number): Promise<boolean>;
44
+ unlock?(deal: string): Promise<void>;
45
+ }
46
+ /** In-memory store (lost on restart). Use a database in production. */
47
+ export declare function memoryBondStore(): BondJobStore;
48
+ export interface BondSellerConfig {
49
+ rpcUrl: string;
50
+ signer: BondSigner;
51
+ terms: BondTermsConfig;
52
+ /** Default: mainnet USDC */
53
+ mint?: PublicKey;
54
+ tokenProgram?: PublicKey;
55
+ store?: BondJobStore;
56
+ fetchImpl?: typeof fetch;
57
+ }
58
+ /** Checks terms against the program's limits before anything is signed. */
59
+ export declare function checkBondTerms(t: BondTermsConfig): string[];
60
+ export declare function createBondSeller(cfg: BondSellerConfig): {
61
+ seller: string;
62
+ /** The job store (the one passed in, or the in-memory default) */
63
+ store: BondJobStore;
64
+ /** What you offer, before any money moves. Amounts as strings (smallest units). */
65
+ quote(): {
66
+ program: string;
67
+ seller: string;
68
+ mint: string;
69
+ tokenProgram: string;
70
+ price: string;
71
+ sellerBond: string;
72
+ buyerDeposit: string;
73
+ deliverSeconds: string;
74
+ lateWindow: string;
75
+ payWindow: string;
76
+ };
77
+ /**
78
+ * Builds `open` for this buyer, with you as fee payer, signed by you. Send `transaction` to the buyer, who verifies it,
79
+ * adds its signature and sends it. The deal exists only once that transaction lands (check with `requireOpen`).
80
+ */
81
+ prepareOpen(buyer: string, meta?: unknown): Promise<{
82
+ deal: string;
83
+ nonce: string;
84
+ terms: Record<keyof bond.Terms, string>;
85
+ transaction: string;
86
+ }>;
87
+ /** Start work only after this returns: the deal is on chain, open, yours, and matches the prepared terms. */
88
+ requireOpen: (deal: string) => Promise<bond.DealState>;
89
+ /** Many deals at once (getMultipleAccounts); null when not on chain. */
90
+ readDeals: (deals: string[]) => Promise<Map<string, bond.DealState | null>>;
91
+ /** Chain time (seconds), from the latest confirmed block */
92
+ chainNow: () => Promise<bigint>;
93
+ /** True if this on-chain deal is the one prepared for this job (seller, buyer, mint and terms). */
94
+ matches(deal: string, d: bond.DealState): Promise<boolean>;
95
+ /**
96
+ * Marks delivery. Call it when you hand over the work, before the deadline: if nothing is marked or confirmed
97
+ * by deliverBy + 1 day (+ late window), the bond and the deposit go to the buyer. Idempotent.
98
+ */
99
+ markDelivered(deal: string): Promise<{
100
+ markTx: string | null;
101
+ alreadyMarked: boolean;
102
+ }>;
103
+ /** Deadlines, possible actions and the settlement that applies now (predicted from the program rules). */
104
+ status(deal: string): Promise<{
105
+ onChain: false;
106
+ outcome?: undefined;
107
+ deal?: undefined;
108
+ timeline?: undefined;
109
+ } | {
110
+ onChain: true;
111
+ outcome: "open" | "delivered" | "buyer_default" | "disputed" | "seller_default" | "cancelled";
112
+ deal: bond.DealState;
113
+ timeline: {
114
+ now: bigint;
115
+ deliverBy: bigint;
116
+ lateUntil: bigint;
117
+ buyerDeadline: bigint;
118
+ settleBy: bigint;
119
+ lateDeduction: bigint;
120
+ settleNow: bond.Payout | null;
121
+ settleableFrom: bigint | null;
122
+ possibleActions: bond.Action[];
123
+ } | null;
124
+ }>;
125
+ /** Prepared jobs that are open on chain and not yet marked, earliest mark deadline first. Run it on a timer. */
126
+ unmarked(): Promise<{
127
+ deal: string;
128
+ markBy: string;
129
+ meta?: unknown;
130
+ }[]>;
131
+ /** Settles and sends both claims once the outcome is fixed (you pay the network fee). */
132
+ settle(deal: string): Promise<{
133
+ buyerShareLeftInVault?: boolean | undefined;
134
+ settleTx: string;
135
+ outcome: bond.Outcome;
136
+ toSeller: string;
137
+ toBuyer: string;
138
+ }>;
139
+ /** For a deal already decided but not yet claimed: send both claims (buyer share, then yours, which closes the deal). */
140
+ claim(deal: string): Promise<{
141
+ buyerShareLeftInVault?: boolean | undefined;
142
+ settleTx: string;
143
+ outcome: "delivered" | "buyer_default" | "disputed" | "seller_default" | "cancelled";
144
+ }>;
145
+ };
146
+ export type BondSeller = ReturnType<typeof createBondSeller>;
147
+ export interface BondJobHandlerOptions {
148
+ seller: BondSeller;
149
+ /**
150
+ * The work. Runs after the deposit is locked. Stop when `ctx.signal` aborts (after `jobTimeoutSeconds`).
151
+ * Treat `input` as untrusted: it comes from whoever opened the deal.
152
+ */
153
+ doJob: (input: string, ctx: {
154
+ deal: string;
155
+ buyer: string;
156
+ signal: AbortSignal;
157
+ }) => Promise<unknown>;
158
+ /** Path prefix, e.g. "/jobs/summarize" (default: none) */
159
+ basePath?: string;
160
+ /** Plain text shown in the quote (at most 500 characters) */
161
+ description?: string;
162
+ /** Refuse a buyer before any deal is prepared (403), e.g. an allowlist. Default: everyone. */
163
+ allowBuyer?: (buyer: string) => boolean | Promise<boolean>;
164
+ /** Refuse an input before any deal is prepared: return an error message, or null to accept. */
165
+ validateInput?: (input: string) => string | null | Promise<string | null>;
166
+ /** Drop prepared deals not opened on chain after this many seconds (default 600, at least 300) */
167
+ prepareTtlSeconds?: number;
168
+ /** Abort one run of the work after this many seconds (default 120) */
169
+ jobTimeoutSeconds?: number;
170
+ /**
171
+ * Runs of the work before giving up (default 3). Giving up, or reaching the mark deadline minus 30 minutes with no result,
172
+ * delivers `{ error: "job_failed" }` and marks it. With a mark and no confirmation the deal ends neutral (each side gets its
173
+ * own money back) instead of you losing the bond; the buyer sees the failure and should not confirm.
174
+ */
175
+ maxAttempts?: number;
176
+ /**
177
+ * Refuse new deals from a buyer once this many of its deals ended with the work delivered but never confirmed
178
+ * (default 2; Infinity turns it off). The program ends such deals neutral, so the buyer kept the work without paying.
179
+ * A buyer can switch wallets, so this limits repeat use, not a first one.
180
+ */
181
+ maxUnconfirmedPerBuyer?: number;
182
+ /** Deals not yet closed, per buyer (default 3) and in total (default 50). Each open deal locks your bond. */
183
+ maxPendingPerBuyer?: number;
184
+ maxPending?: number;
185
+ /** Jobs worked on at the same time by processOpenJobs (default 4) */
186
+ concurrency?: number;
187
+ /**
188
+ * The origin buyers use to reach you (e.g. "https://api.example.com"). Delivery requests are signed for it.
189
+ * Default: the origin of the request URL (set this when you run behind a proxy that changes scheme or host).
190
+ */
191
+ publicOrigin?: string;
192
+ }
193
+ /**
194
+ * Throw this from `doJob` when the result is not ready yet and will be supplied later with `submit` (for example by a
195
+ * person or an AI agent doing the work). It does not count as a failure; the deadline give-up still applies.
196
+ */
197
+ export declare class JobPending extends Error {
198
+ constructor();
199
+ }
200
+ /**
201
+ * Throw this from `doJob` when the job cannot be done for this input and retrying will not help (too large, not found).
202
+ * The failure, with this message, is delivered and marked at once (neutral outcome; your bond comes back).
203
+ */
204
+ export declare class JobFailed extends Error {
205
+ constructor(message: string);
206
+ }
207
+ /** What is delivered when the work could not be done (see maxAttempts). */
208
+ export declare const JOB_FAILED: {
209
+ readonly error: "job_failed";
210
+ readonly message: "The seller could not complete this job. Do not confirm; after the deadlines each side gets its own money back.";
211
+ };
212
+ /**
213
+ * Agent402 Bond Job Protocol v1, seller side.
214
+ * - `handle(req)`: GET {base}/quote, POST {base}/open, POST {base}/deliver. Returns null for other paths so you can chain
215
+ * your own routes. Works with any Fetch-style runtime (Node, Workers).
216
+ * - `processOpenJobs()`: run this on a timer (every few minutes). It does the work for every prepared deal that is open on
217
+ * chain and marks delivery, without waiting for the buyer to ask. Otherwise a buyer could open a deal, never fetch the
218
+ * result, and take your bond at the deadline.
219
+ */
220
+ export declare function bondJobService(o: BondJobHandlerOptions): {
221
+ handle: (req: Request) => Promise<Response | null>;
222
+ processOpenJobs: () => Promise<{
223
+ deal: string;
224
+ status: "delivered" | "working" | "not_open" | "expired" | "settled" | "closed" | "error";
225
+ error?: string;
226
+ }[]>;
227
+ /** Supply the result of a job whose `doJob` threw JobPending; marks delivery. */
228
+ submit: (deal: string, result: unknown) => Promise<bond.JobDelivery | {
229
+ status: number;
230
+ error: string;
231
+ }>;
232
+ /** Give up on a job: delivers `{ error: "job_failed", message }` and marks (neutral outcome, your bond comes back). */
233
+ decline: (deal: string, message?: string) => Promise<bond.JobDelivery | {
234
+ status: number;
235
+ error: string;
236
+ }>;
237
+ };
238
+ /** Same as `bondJobService(o).handle`. Prefer bondJobService so you can also run processOpenJobs on a timer. */
239
+ export declare const bondJobHandler: (o: BondJobHandlerOptions) => (req: Request) => Promise<Response | null>;
package/dist/bond.js ADDED
@@ -0,0 +1,606 @@
1
+ // Agent402 Bond, seller side (optional entry: @agent402-dev/pay-server/bond).
2
+ // Quote a job, prepare the `open` transaction (seller pays fees and rent, signs first), check the deal on chain before working,
3
+ // mark delivery before the deadline, read the status, and settle.
4
+ // This module never takes or stores a private key: you pass a signer (a wallet, a KMS, or your own wrapper).
5
+ import { PublicKey, Transaction } from '@solana/web3.js';
6
+ import * as bond from '@agent402-dev/bond-client';
7
+ import { t2, timeline } from '@agent402-dev/bond-client/rules';
8
+ import { JOB_MAX_INPUT, JOB_PROTOCOL, verifyDeliverSignature } from '@agent402-dev/bond-client/job';
9
+ /** Beta cap of the deployed program for USDC deals (per deal, smallest units). */
10
+ const USDC_BETA_CAP = 100000000n;
11
+ const TOKEN_PROGRAM = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
12
+ /** In-memory store (lost on restart). Use a database in production. */
13
+ export function memoryBondStore() {
14
+ const m = new Map();
15
+ const leases = new Map();
16
+ return {
17
+ async get(d) { return m.get(d); }, async put(j) { m.set(j.deal, j); }, async list() { return [...m.values()]; }, async delete(d) { m.delete(d); },
18
+ async lock(d, ms) { const now = Date.now(); if ((leases.get(d) ?? 0) > now)
19
+ return false; leases.set(d, now + ms); return true; },
20
+ async unlock(d) { leases.delete(d); },
21
+ };
22
+ }
23
+ const termsJson = (t) => Object.fromEntries(Object.entries(t).map(([k, v]) => [k, String(v)]));
24
+ const termsFrom = (j) => ({
25
+ price: BigInt(j.price), sellerBond: BigInt(j.sellerBond), buyerDeposit: BigInt(j.buyerDeposit),
26
+ deliverBy: BigInt(j.deliverBy), lateWindow: BigInt(j.lateWindow), payWindow: BigInt(j.payWindow),
27
+ });
28
+ /** Checks terms against the program's limits before anything is signed. */
29
+ export function checkBondTerms(t) {
30
+ const out = [];
31
+ if (t.price <= 0n)
32
+ out.push('price must be positive');
33
+ if (t.sellerBond <= 0n)
34
+ out.push('seller bond must be positive');
35
+ if (t.sellerBond * 10000n > t.price * 2000n)
36
+ out.push('seller bond is at most 20% of the price');
37
+ if (t.buyerDeposit < 0n || t.buyerDeposit > t.price)
38
+ out.push('deposit must be between 0 and the price');
39
+ if (t.deliverSeconds < 60n || t.deliverSeconds > 180n * 86400n)
40
+ out.push('deliverSeconds must be between 60 seconds and 180 days');
41
+ if (t.lateWindow < 0n || t.lateWindow > 7n * 86400n)
42
+ out.push('lateWindow must be 0..7 days');
43
+ if (t.payWindow < 86400n || t.payWindow > 30n * 86400n)
44
+ out.push('payWindow must be 1..30 days');
45
+ return out;
46
+ }
47
+ export function createBondSeller(cfg) {
48
+ const bad = checkBondTerms(cfg.terms);
49
+ if (bad.length)
50
+ throw new Error(`bond terms: ${bad.join('; ')}`);
51
+ const f = cfg.fetchImpl ?? fetch;
52
+ const mint = cfg.mint ?? bond.MINTS.mainnet.USDC;
53
+ const tokenProgram = cfg.tokenProgram ?? TOKEN_PROGRAM;
54
+ const store = cfg.store ?? memoryBondStore();
55
+ const seller = cfg.signer.publicKey;
56
+ if (mint.equals(bond.MINTS.mainnet.USDC) && cfg.terms.price > USDC_BETA_CAP)
57
+ throw new Error('bond terms: price is above the program cap for USDC (100 USDC per deal)');
58
+ let id = 0;
59
+ async function rpc(method, params) {
60
+ const r = await f(cfg.rpcUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: ++id, method, params }) });
61
+ const j = (await r.json());
62
+ if (j.error || j.result === undefined)
63
+ throw new Error(`rpc ${method}: ${j.error?.message ?? r.status}`);
64
+ return j.result;
65
+ }
66
+ /**
67
+ * Chain time as the program sees it: the Clock sysvar's unix_timestamp (offset 32). getBlockTime on the newest slot often
68
+ * fails on mainnet ("block not available"), so it is only the fallback.
69
+ */
70
+ const chainNow = async () => {
71
+ try {
72
+ const v = (await rpc('getAccountInfo', ['SysvarC1ock11111111111111111111111111111111', { encoding: 'base64', commitment: 'confirmed' }])).value;
73
+ if (v) {
74
+ const b = Buffer.from(v.data[0], 'base64');
75
+ if (b.length >= 40)
76
+ return b.readBigInt64LE(32);
77
+ }
78
+ }
79
+ catch { /* fall back */ }
80
+ return BigInt(await rpc('getBlockTime', [await rpc('getSlot', [{ commitment: 'confirmed' }])]));
81
+ };
82
+ const blockhash = async () => (await rpc('getLatestBlockhash', [{ commitment: 'confirmed' }])).value.blockhash;
83
+ async function readDeal(deal) {
84
+ const v = (await rpc('getAccountInfo', [deal, { encoding: 'base64', commitment: 'confirmed' }])).value;
85
+ if (!v || v.owner !== bond.BOND_PROGRAM_ID.toBase58())
86
+ return null;
87
+ return bond.decodeDeal(Uint8Array.from(Buffer.from(v.data[0], 'base64')));
88
+ }
89
+ /** Reads many deals with getMultipleAccounts (100 per request). null = not on chain (or not a deal). */
90
+ async function readDeals(deals) {
91
+ const out = new Map();
92
+ for (let i = 0; i < deals.length; i += 100) {
93
+ const chunk = deals.slice(i, i + 100);
94
+ const v = (await rpc('getMultipleAccounts', [chunk, { encoding: 'base64', commitment: 'confirmed' }])).value;
95
+ chunk.forEach((d, k) => {
96
+ const a = v[k];
97
+ let st = null;
98
+ if (a && a.owner === bond.BOND_PROGRAM_ID.toBase58()) {
99
+ try {
100
+ st = bond.decodeDeal(Uint8Array.from(Buffer.from(a.data[0], 'base64')));
101
+ }
102
+ catch {
103
+ st = null;
104
+ }
105
+ }
106
+ out.set(d, st);
107
+ });
108
+ }
109
+ return out;
110
+ }
111
+ /** Signs as the seller (fee payer), sends, waits by polling (no websocket). */
112
+ async function send(ixs) {
113
+ const tx = new Transaction().add(...ixs);
114
+ tx.recentBlockhash = await blockhash();
115
+ tx.feePayer = seller;
116
+ const signed = await cfg.signer.signTransaction(tx);
117
+ const sig = await rpc('sendTransaction', [signed.serialize().toString('base64'), { encoding: 'base64', preflightCommitment: 'confirmed' }]);
118
+ for (let i = 0; i < 90; i++) {
119
+ const st = (await rpc('getSignatureStatuses', [[sig]])).value[0];
120
+ if (st?.err)
121
+ throw new Error(`transaction ${sig} failed: ${JSON.stringify(st.err)}`);
122
+ if (st?.confirmationStatus === 'confirmed' || st?.confirmationStatus === 'finalized')
123
+ return sig;
124
+ await new Promise((res) => setTimeout(res, 1000));
125
+ }
126
+ throw new Error(`transaction ${sig} not confirmed in time (it may still land; check before retrying)`);
127
+ }
128
+ async function sendWithFallback(full, own) {
129
+ try {
130
+ return { tx: await send(full), partial: false };
131
+ }
132
+ catch (e) {
133
+ // Only a refusal in preflight simulation (nothing sent, no fee) falls back; a sent or unconfirmed transaction does not.
134
+ if (!e.message.startsWith('rpc sendTransaction:'))
135
+ throw e;
136
+ return { tx: await send(own), partial: true };
137
+ }
138
+ }
139
+ const ref = (buyer, nonce) => ({ seller, buyer, mint, tokenProgram, nonce });
140
+ const refOf = (j) => ref(new PublicKey(j.buyer), BigInt(j.nonce));
141
+ async function job(deal) {
142
+ const j = await store.get(deal);
143
+ if (!j)
144
+ throw new Error('unknown deal (not prepared by this seller)');
145
+ return j;
146
+ }
147
+ async function requireOpen(deal) {
148
+ const j = await job(deal);
149
+ const d = await readDeal(deal);
150
+ if (!d)
151
+ throw new Error('deal is not on chain yet');
152
+ const want = termsFrom(j.terms);
153
+ const same = d.seller.equals(seller) && d.buyer.toBase58() === j.buyer && d.mint.equals(mint)
154
+ && Object.keys(want).every((k) => d.terms[k] === want[k]);
155
+ if (!same)
156
+ throw new Error('on-chain deal does not match the prepared terms');
157
+ if (d.outcome !== 'open')
158
+ throw new Error(`deal is already decided (${d.outcome})`);
159
+ return d;
160
+ }
161
+ return {
162
+ seller: seller.toBase58(),
163
+ /** The job store (the one passed in, or the in-memory default) */
164
+ store,
165
+ /** What you offer, before any money moves. Amounts as strings (smallest units). */
166
+ quote() {
167
+ const t = cfg.terms;
168
+ return {
169
+ program: bond.BOND_PROGRAM_ID.toBase58(), seller: seller.toBase58(), mint: mint.toBase58(), tokenProgram: tokenProgram.toBase58(),
170
+ price: String(t.price), sellerBond: String(t.sellerBond), buyerDeposit: String(t.buyerDeposit),
171
+ deliverSeconds: String(t.deliverSeconds), lateWindow: String(t.lateWindow), payWindow: String(t.payWindow),
172
+ };
173
+ },
174
+ /**
175
+ * Builds `open` for this buyer, with you as fee payer, signed by you. Send `transaction` to the buyer, who verifies it,
176
+ * adds its signature and sends it. The deal exists only once that transaction lands (check with `requireOpen`).
177
+ */
178
+ async prepareOpen(buyer, meta) {
179
+ const b = new PublicKey(buyer);
180
+ if (b.equals(seller))
181
+ throw new Error('buyer and seller must differ');
182
+ const nonce = BigInt.asUintN(64, BigInt(`0x${Buffer.from(crypto.getRandomValues(new Uint8Array(8))).toString('hex')}`));
183
+ const t = cfg.terms;
184
+ const terms = { price: t.price, sellerBond: t.sellerBond, buyerDeposit: t.buyerDeposit, deliverBy: (await chainNow()) + t.deliverSeconds, lateWindow: t.lateWindow, payWindow: t.payWindow };
185
+ const r = ref(b, nonce);
186
+ const tx = new Transaction().add(bond.open(r, terms));
187
+ tx.recentBlockhash = await blockhash();
188
+ tx.feePayer = seller;
189
+ const signed = await cfg.signer.signTransaction(tx);
190
+ const deal = bond.dealOf(r).toBase58();
191
+ await store.put({ deal, buyer, nonce: String(nonce), terms: termsJson(terms), preparedAt: new Date().toISOString(), ...(meta !== undefined ? { meta } : {}) });
192
+ return { deal, nonce: String(nonce), terms: termsJson(terms), transaction: signed.serialize({ requireAllSignatures: false }).toString('base64') };
193
+ },
194
+ /** Start work only after this returns: the deal is on chain, open, yours, and matches the prepared terms. */
195
+ requireOpen,
196
+ /** Many deals at once (getMultipleAccounts); null when not on chain. */
197
+ readDeals,
198
+ /** Chain time (seconds), from the latest confirmed block */
199
+ chainNow,
200
+ /** True if this on-chain deal is the one prepared for this job (seller, buyer, mint and terms). */
201
+ async matches(deal, d) {
202
+ const j = await job(deal);
203
+ const want = termsFrom(j.terms);
204
+ return d.seller.equals(seller) && d.buyer.toBase58() === j.buyer && d.mint.equals(mint)
205
+ && Object.keys(want).every((k) => d.terms[k] === want[k]);
206
+ },
207
+ /**
208
+ * Marks delivery. Call it when you hand over the work, before the deadline: if nothing is marked or confirmed
209
+ * by deliverBy + 1 day (+ late window), the bond and the deposit go to the buyer. Idempotent.
210
+ */
211
+ async markDelivered(deal) {
212
+ const j = await job(deal);
213
+ const d = await requireOpen(deal);
214
+ if (d.sellerMark !== null || d.buyerConfirm !== null)
215
+ return { markTx: j.markTx ?? null, alreadyMarked: true };
216
+ if ((await chainNow()) > t2(d.terms))
217
+ throw new Error('too late to mark: the mark deadline has passed');
218
+ const markTx = await send([bond.markDelivered(refOf(j))]);
219
+ await store.put({ ...j, markedAt: new Date().toISOString(), markTx });
220
+ return { markTx, alreadyMarked: false };
221
+ },
222
+ /** Deadlines, possible actions and the settlement that applies now (predicted from the program rules). */
223
+ async status(deal) {
224
+ const d = await readDeal(deal);
225
+ if (!d)
226
+ return { onChain: false };
227
+ return { onChain: true, outcome: d.outcome, deal: d, timeline: d.outcome === 'open' ? timeline(d, await chainNow()) : null };
228
+ },
229
+ /** Prepared jobs that are open on chain and not yet marked, earliest mark deadline first. Run it on a timer. */
230
+ async unmarked() {
231
+ const out = [];
232
+ for (const j of await store.list()) {
233
+ if (j.markedAt || j.settleTx)
234
+ continue;
235
+ const d = await readDeal(j.deal);
236
+ if (!d || d.outcome !== 'open' || d.sellerMark !== null || d.buyerConfirm !== null)
237
+ continue;
238
+ out.push({ deal: j.deal, markBy: new Date(Number(t2(d.terms)) * 1000).toISOString(), ...(j.meta !== undefined ? { meta: j.meta } : {}) });
239
+ }
240
+ return out.sort((a, b) => a.markBy.localeCompare(b.markBy));
241
+ },
242
+ /** Settles and sends both claims once the outcome is fixed (you pay the network fee). */
243
+ async settle(deal) {
244
+ const j = await job(deal);
245
+ const d = await readDeal(deal);
246
+ if (!d)
247
+ throw new Error('deal not found (already settled and closed?)');
248
+ if (d.outcome !== 'open')
249
+ throw new Error(`already decided (${d.outcome}); send claims with bond-client claimBuyer/claimSeller`);
250
+ const tl = timeline(d, await chainNow());
251
+ if (!tl.settleNow)
252
+ throw new Error(`not settleable yet${tl.settleableFrom ? ` (from ${new Date(Number(tl.settleableFrom) * 1000).toISOString()})` : ''}`);
253
+ const r = refOf(j);
254
+ // If the buyer's token account is closed or frozen, its claim fails and would block the whole transaction:
255
+ // then settle and claim only your share (the buyer's share stays in the vault for the buyer to claim later).
256
+ const { tx: settleTx, partial } = await sendWithFallback([bond.settle(r), bond.claimBuyer(r), bond.claimSeller(r)], [bond.settle(r), bond.claimSeller(r)]);
257
+ await store.put({ ...j, settleTx });
258
+ return { settleTx, outcome: tl.settleNow.outcome, toSeller: String(tl.settleNow.toSeller), toBuyer: String(tl.settleNow.toBuyer), ...(partial ? { buyerShareLeftInVault: true } : {}) };
259
+ },
260
+ /** For a deal already decided but not yet claimed: send both claims (buyer share, then yours, which closes the deal). */
261
+ async claim(deal) {
262
+ const j = await job(deal);
263
+ const d = await readDeal(deal);
264
+ if (!d)
265
+ throw new Error('deal not found (already closed?)');
266
+ if (d.outcome === 'open')
267
+ throw new Error('not decided yet; use settle');
268
+ const r = refOf(j);
269
+ const { tx: settleTx, partial } = await sendWithFallback([bond.claimBuyer(r), bond.claimSeller(r)], [bond.claimSeller(r)]);
270
+ await store.put({ ...j, settleTx });
271
+ return { settleTx, outcome: d.outcome, ...(partial ? { buyerShareLeftInVault: true } : {}) };
272
+ },
273
+ };
274
+ }
275
+ /**
276
+ * Throw this from `doJob` when the result is not ready yet and will be supplied later with `submit` (for example by a
277
+ * person or an AI agent doing the work). It does not count as a failure; the deadline give-up still applies.
278
+ */
279
+ export class JobPending extends Error {
280
+ constructor() { super('waiting for the result'); this.name = 'JobPending'; }
281
+ }
282
+ /**
283
+ * Throw this from `doJob` when the job cannot be done for this input and retrying will not help (too large, not found).
284
+ * The failure, with this message, is delivered and marked at once (neutral outcome; your bond comes back).
285
+ */
286
+ export class JobFailed extends Error {
287
+ constructor(message) { super(message); this.name = 'JobFailed'; }
288
+ }
289
+ /** What is delivered when the work could not be done (see maxAttempts). */
290
+ export const JOB_FAILED = { error: 'job_failed', message: 'The seller could not complete this job. Do not confirm; after the deadlines each side gets its own money back.' };
291
+ /**
292
+ * Agent402 Bond Job Protocol v1, seller side.
293
+ * - `handle(req)`: GET {base}/quote, POST {base}/open, POST {base}/deliver. Returns null for other paths so you can chain
294
+ * your own routes. Works with any Fetch-style runtime (Node, Workers).
295
+ * - `processOpenJobs()`: run this on a timer (every few minutes). It does the work for every prepared deal that is open on
296
+ * chain and marks delivery, without waiting for the buyer to ask. Otherwise a buyer could open a deal, never fetch the
297
+ * result, and take your bond at the deadline.
298
+ */
299
+ export function bondJobService(o) {
300
+ const base = (o.basePath ?? '').replace(/\/+$/, '');
301
+ if (o.description !== undefined && o.description.length > 500)
302
+ throw new Error('description is at most 500 characters');
303
+ const ttlSeconds = o.prepareTtlSeconds ?? 600;
304
+ if (ttlSeconds < 300)
305
+ throw new Error('prepareTtlSeconds is at least 300 (an open transaction can land for a while after it is prepared)');
306
+ const timeoutMs = (o.jobTimeoutSeconds ?? 120) * 1000;
307
+ const maxAttempts = Math.max(1, o.maxAttempts ?? 3);
308
+ const perBuyer = o.maxPendingPerBuyer ?? 3;
309
+ const maxUnconfirmed = o.maxUnconfirmedPerBuyer ?? 2;
310
+ const total = o.maxPending ?? 50;
311
+ const concurrency = Math.max(1, o.concurrency ?? 4);
312
+ const GIVE_UP_BEFORE = 1800n; // seconds before the mark deadline
313
+ const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
314
+ const body = async (req) => {
315
+ const t = await req.text();
316
+ if (t.length > JOB_MAX_INPUT * 4 + 1_024)
317
+ throw Object.assign(new Error('body too large'), { status: 413 });
318
+ try {
319
+ return JSON.parse(t || '{}');
320
+ }
321
+ catch {
322
+ throw Object.assign(new Error('invalid JSON'), { status: 400 });
323
+ }
324
+ };
325
+ const store = o.seller.store;
326
+ const inflight = new Map();
327
+ const metaOf = (j) => (j.meta ?? {});
328
+ const active = (j) => { const m = metaOf(j); return !m.closed && !m.expired; };
329
+ async function patch(deal, m) {
330
+ const j = await store.get(deal);
331
+ if (j)
332
+ await store.put({ ...j, meta: { ...metaOf(j), ...m } });
333
+ }
334
+ async function runWithTimeout(input, ctx) {
335
+ const ac = new AbortController();
336
+ let timer;
337
+ const timeout = new Promise((_, rej) => { timer = setTimeout(() => { ac.abort(); rej(new Error('timed out')); }, timeoutMs); });
338
+ try {
339
+ return await Promise.race([o.doJob(input, { ...ctx, signal: ac.signal }), timeout]);
340
+ }
341
+ finally {
342
+ clearTimeout(timer);
343
+ }
344
+ }
345
+ /**
346
+ * Does the work for a deal that is open on chain (or already paid for), keeps the result, marks delivery.
347
+ * Same answer on repeat calls; a stored result is never recomputed. 202 = being worked on or will be retried.
348
+ */
349
+ function deliverJob(deal, known) {
350
+ const running = inflight.get(deal);
351
+ if (running)
352
+ return running;
353
+ const p = (async () => {
354
+ // Already delivered: answer from the store without waiting for a lease another process may still hold.
355
+ const done = await store.get(deal);
356
+ if (done && metaOf(done).delivered)
357
+ return { deal, result: metaOf(done).result, markTx: done.markTx ?? null };
358
+ const leaseMs = timeoutMs + 120_000;
359
+ if (store.lock && !(await store.lock(deal, leaseMs)))
360
+ return { status: 202, error: 'working' };
361
+ try {
362
+ const j = await store.get(deal);
363
+ if (!j)
364
+ return { status: 404, error: 'unknown deal' };
365
+ const meta = metaOf(j);
366
+ if (meta.delivered)
367
+ return { deal, result: meta.result, markTx: j.markTx ?? null };
368
+ const d = known !== undefined ? known : (await o.seller.readDeals([deal])).get(deal) ?? null;
369
+ if (!d)
370
+ return { status: 409, error: 'deal is not on chain' };
371
+ if (!(await o.seller.matches(deal, d)))
372
+ return { status: 409, error: 'on-chain deal does not match the prepared terms' };
373
+ // Open: work and mark. Already decided: work only if the buyer confirmed (it paid), never mark.
374
+ const paid = d.outcome !== 'open' && d.buyerConfirm !== null;
375
+ if (d.outcome !== 'open' && !paid)
376
+ return { status: 409, error: `deal is already decided (${d.outcome})` };
377
+ let result = meta.result;
378
+ if (!meta.hasResult) {
379
+ const attempts = meta.attempts ?? 0;
380
+ const late = d.outcome === 'open' && (await o.seller.chainNow()) >= t2(d.terms) - GIVE_UP_BEFORE;
381
+ let failed = attempts >= maxAttempts || late;
382
+ let failMessage;
383
+ if (!failed) {
384
+ try {
385
+ result = await runWithTimeout(meta.input ?? '', { deal, buyer: j.buyer });
386
+ await patch(deal, { result, hasResult: true, attempts: attempts + 1, lastError: undefined });
387
+ }
388
+ catch (e) {
389
+ if (e instanceof JobPending || e?.name === 'JobPending')
390
+ return { status: 202, error: 'waiting for the result' };
391
+ const n = attempts + 1;
392
+ await patch(deal, { attempts: n, lastError: e.message.slice(0, 300) });
393
+ const permanent = e instanceof JobFailed || e?.name === 'JobFailed';
394
+ if (!permanent && n < maxAttempts)
395
+ return { status: 202, error: 'the job failed; it will be retried' };
396
+ failed = true;
397
+ if (permanent)
398
+ failMessage = e.message.slice(0, 300);
399
+ }
400
+ }
401
+ if (failed) {
402
+ result = failMessage ? { ...JOB_FAILED, message: failMessage } : JOB_FAILED;
403
+ await patch(deal, { result, hasResult: true, failed: true });
404
+ }
405
+ }
406
+ if (paid) {
407
+ await patch(deal, { delivered: true });
408
+ return { deal, result, markTx: j.markTx ?? null };
409
+ }
410
+ // Mark before the deadline. With no mark and no confirmation, the bond goes to the buyer.
411
+ const { markTx } = await o.seller.markDelivered(deal);
412
+ await patch(deal, { delivered: true });
413
+ return { deal, result, markTx };
414
+ }
415
+ finally {
416
+ if (store.unlock)
417
+ await store.unlock(deal).catch(() => undefined);
418
+ }
419
+ })().finally(() => inflight.delete(deal));
420
+ inflight.set(deal, p);
421
+ return p;
422
+ }
423
+ async function handle(req) {
424
+ const url = new URL(req.url);
425
+ const path = url.pathname;
426
+ if (!path.startsWith(base + '/'))
427
+ return null;
428
+ const route = path.slice(base.length);
429
+ try {
430
+ if (req.method === 'GET' && route === '/quote') {
431
+ const q = { protocol: JOB_PROTOCOL, ...o.seller.quote(), ...(o.description ? { description: o.description } : {}) };
432
+ return json(200, q);
433
+ }
434
+ if (req.method === 'POST' && route === '/open') {
435
+ const b = await body(req);
436
+ const input = typeof b.input === 'string' ? b.input : '';
437
+ if (!input)
438
+ return json(400, { error: 'input required' });
439
+ if (new TextEncoder().encode(input).length > JOB_MAX_INPUT)
440
+ return json(413, { error: `input is at most ${JOB_MAX_INPUT} bytes` });
441
+ let buyer;
442
+ try {
443
+ buyer = new PublicKey(String(b.buyer)).toBase58();
444
+ }
445
+ catch {
446
+ return json(400, { error: 'buyer must be a Solana address' });
447
+ }
448
+ if (o.allowBuyer && !(await o.allowBuyer(buyer)))
449
+ return json(403, { error: 'this seller does not take deals from this buyer' });
450
+ if (o.validateInput) {
451
+ const why = await o.validateInput(input);
452
+ if (why)
453
+ return json(400, { error: why.slice(0, 300) });
454
+ }
455
+ const all = await store.list();
456
+ if (all.filter((j) => j.buyer === buyer && metaOf(j).unconfirmed).length >= maxUnconfirmed) {
457
+ return json(403, { error: 'this buyer has received work without confirming before; no new deals' });
458
+ }
459
+ const jobs = all.filter(active);
460
+ if (jobs.length >= total)
461
+ return json(429, { error: 'too many deals in progress; try again later' });
462
+ if (jobs.filter((j) => j.buyer === buyer).length >= perBuyer)
463
+ return json(429, { error: 'too many deals in progress for this buyer' });
464
+ const p = await o.seller.prepareOpen(buyer, { input });
465
+ const out = { deal: p.deal, nonce: p.nonce, terms: p.terms, transaction: p.transaction };
466
+ return json(200, out);
467
+ }
468
+ if (req.method === 'POST' && route === '/deliver') {
469
+ const b = await body(req);
470
+ const deal = String(b.deal ?? '');
471
+ const j = await store.get(deal);
472
+ if (!j)
473
+ return json(404, { error: 'unknown deal' });
474
+ // Only the deal's buyer may fetch the result; the request is signed for this server and expires.
475
+ const origin = (o.publicOrigin ?? url.origin).replace(/\/+$/, '');
476
+ if (!(await verifyDeliverSignature(new PublicKey(j.buyer).toBytes(), deal, origin, Number(b.expires), String(b.signature ?? '')))) {
477
+ return json(401, { error: 'bad or expired signature' });
478
+ }
479
+ // A long job already running (from the timer or another request): answer at once, the buyer asks again later.
480
+ if (inflight.has(deal) && !metaOf(j).delivered)
481
+ return json(202, { deal, status: 'working' });
482
+ const r = await deliverJob(deal);
483
+ if ('error' in r)
484
+ return r.status === 202 ? json(202, { deal, status: 'working' }) : json(r.status, { error: r.error });
485
+ return json(200, r);
486
+ }
487
+ return null;
488
+ }
489
+ catch (e) {
490
+ const status = e.status ?? 500;
491
+ if (status !== 500)
492
+ return json(status, { error: e.message });
493
+ // Which RPC step failed (method and the node's message only; the RPC address is never part of these messages)
494
+ const m = String(e?.message ?? '');
495
+ const detail = m.startsWith('rpc ') ? m.replace(/https?:\/\/\S+/g, '[address]').slice(0, 160) : undefined;
496
+ return json(500, { error: 'internal error', ...(detail ? { detail } : {}) });
497
+ }
498
+ }
499
+ /**
500
+ * Run on a timer. Reads all tracked deals in one batch, then, earliest mark deadline first:
501
+ * - opened on chain, not delivered → do the work (or give up, see maxAttempts), keep the result, mark delivery;
502
+ * - delivered and settleable → settle and claim, so your bond comes back even if the buyer goes away;
503
+ * - decided on chain → claim (after doing the work if the buyer paid for it);
504
+ * - closed on chain → stop tracking;
505
+ * - prepared but not opened after `prepareTtlSeconds` → drop.
506
+ * One failing deal does not stop the others.
507
+ */
508
+ async function processOpenJobs() {
509
+ const jobs = (await store.list()).filter(active);
510
+ if (!jobs.length)
511
+ return [];
512
+ const chain = await o.seller.readDeals(jobs.map((j) => j.deal));
513
+ const now = await o.seller.chainNow();
514
+ const key = (j) => { const d = chain.get(j.deal); return d && d.outcome === 'open' ? t2(d.terms) : BigInt(Number.MAX_SAFE_INTEGER); };
515
+ jobs.sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
516
+ async function noteUnconfirmed(j, d) {
517
+ const m = (await store.get(j.deal))?.meta;
518
+ if (m?.delivered && !m.failed && d.buyerConfirm === null)
519
+ await patch(j.deal, { unconfirmed: true });
520
+ }
521
+ async function one(j) {
522
+ const meta = metaOf(j);
523
+ const d = chain.get(j.deal) ?? null;
524
+ try {
525
+ if (!d) {
526
+ if (meta.delivered || j.settleTx) {
527
+ await patch(j.deal, { closed: true });
528
+ return { deal: j.deal, status: 'closed' };
529
+ }
530
+ if (Date.now() - Date.parse(j.preparedAt) > ttlSeconds * 1000) {
531
+ if (store.delete)
532
+ await store.delete(j.deal);
533
+ else
534
+ await patch(j.deal, { expired: true });
535
+ return { deal: j.deal, status: 'expired' };
536
+ }
537
+ return { deal: j.deal, status: 'not_open' };
538
+ }
539
+ const paid = d.outcome !== 'open' && d.buyerConfirm !== null;
540
+ if (!meta.delivered && (d.outcome === 'open' || paid)) {
541
+ const r = await deliverJob(j.deal, d);
542
+ if ('error' in r)
543
+ return r.status === 202 ? { deal: j.deal, status: 'working' } : { deal: j.deal, status: 'error', error: r.error };
544
+ if (d.outcome === 'open')
545
+ return { deal: j.deal, status: 'delivered' };
546
+ }
547
+ if (d.outcome === 'open') {
548
+ if (timeline(d, now).settleNow) {
549
+ await noteUnconfirmed(j, d);
550
+ await o.seller.settle(j.deal);
551
+ return { deal: j.deal, status: 'settled' };
552
+ }
553
+ return null; // delivered, waiting for the buyer or the deadlines
554
+ }
555
+ // Our share already claimed, the buyer's left in the vault for the buyer: nothing more to do here.
556
+ if (j.settleTx) {
557
+ await patch(j.deal, { closed: true });
558
+ return { deal: j.deal, status: 'closed' };
559
+ }
560
+ // Decided (by us or anyone) but not claimed: claim. Closing the deal ends tracking on the next run.
561
+ await noteUnconfirmed(j, d);
562
+ await o.seller.claim(j.deal);
563
+ return { deal: j.deal, status: 'settled' };
564
+ }
565
+ catch (e) {
566
+ return { deal: j.deal, status: 'error', error: e.message };
567
+ }
568
+ }
569
+ const out = new Array(jobs.length);
570
+ let next = 0;
571
+ await Promise.all(Array.from({ length: Math.min(concurrency, jobs.length) }, async () => {
572
+ while (next < jobs.length) {
573
+ const k = next++;
574
+ out[k] = await one(jobs[k]);
575
+ }
576
+ }));
577
+ return out.filter((x) => x !== null);
578
+ }
579
+ /** Stores a result for a deal that is open on chain (or paid) and has none yet, then marks delivery. */
580
+ async function supply(deal, m) {
581
+ const j = await store.get(deal);
582
+ if (!j)
583
+ return { status: 404, error: 'unknown deal' };
584
+ if (metaOf(j).hasResult)
585
+ return { status: 409, error: 'a result is already stored for this deal' };
586
+ const d = (await o.seller.readDeals([deal])).get(deal) ?? null;
587
+ if (!d)
588
+ return { status: 409, error: 'deal is not on chain (not opened yet, or already closed)' };
589
+ if (!(await o.seller.matches(deal, d)))
590
+ return { status: 409, error: 'on-chain deal does not match the prepared terms' };
591
+ if (d.outcome !== 'open' && d.buyerConfirm === null)
592
+ return { status: 409, error: `deal is already decided (${d.outcome})` };
593
+ await patch(deal, { ...m, hasResult: true, lastError: undefined });
594
+ return deliverJob(deal, d);
595
+ }
596
+ return {
597
+ handle,
598
+ processOpenJobs,
599
+ /** Supply the result of a job whose `doJob` threw JobPending; marks delivery. */
600
+ submit: (deal, result) => supply(deal, { result }),
601
+ /** Give up on a job: delivers `{ error: "job_failed", message }` and marks (neutral outcome, your bond comes back). */
602
+ decline: (deal, message) => supply(deal, { result: { ...JOB_FAILED, ...(message ? { message: message.slice(0, 300) } : {}) }, failed: true }),
603
+ };
604
+ }
605
+ /** Same as `bondJobService(o).handle`. Prefer bondJobService so you can also run processOpenJobs on a timer. */
606
+ export const bondJobHandler = (o) => bondJobService(o).handle;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent402-dev/pay-server",
3
- "description": "Server helpers for x402 on Solana: accept USDC and optionally PREQ (Token-2022) through external facilitators. Verify, run your handler, then settle. Holds no funds and no private keys.",
3
+ "description": "Server helpers for x402 on Solana: accept USDC and optionally PREQ (Token-2022) through external facilitators. Verify, run your handler, then settle. Holds no funds and takes no private keys.",
4
4
  "keywords": [
5
5
  "x402",
6
6
  "solana",
@@ -24,11 +24,12 @@
24
24
  }
25
25
  },
26
26
  "dependencies": {
27
+ "@agent402-dev/bond-client": "^0.2.0",
27
28
  "@solana/web3.js": "^1.98.0",
28
29
  "@x402/core": "2.31.0",
29
30
  "@x402/svm": "2.31.0"
30
31
  },
31
- "version": "0.4.0",
32
+ "version": "0.5.0",
32
33
  "author": "Agent402",
33
34
  "license": "Apache-2.0",
34
35
  "type": "module",