@agent402-dev/bond-client 0.1.0 → 0.2.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 +6 -4
- package/dist/index.d.ts +9 -0
- package/dist/index.js +12 -2
- package/dist/job.d.ts +68 -0
- package/dist/job.js +87 -0
- package/dist/rules.d.ts +67 -0
- package/dist/rules.js +107 -0
- package/package.json +15 -3
package/README.md
CHANGED
|
@@ -15,14 +15,13 @@ Not related to `agent402.tools`, `@agents402` or other similarly named sites, ac
|
|
|
15
15
|
|
|
16
16
|
## Install
|
|
17
17
|
```bash
|
|
18
|
-
npm install @agent402-dev/bond-client @solana/web3.js
|
|
18
|
+
npm install @agent402-dev/bond-client @solana/web3.js
|
|
19
19
|
```
|
|
20
|
-
`@solana/web3.js` (v1)
|
|
20
|
+
`@solana/web3.js` (v1) is a peer dependency. `@agent402-dev/bond-client/rules` (deadlines, possible actions, settlement preview) has no dependencies at all. Node 20+.
|
|
21
21
|
|
|
22
22
|
## Usage
|
|
23
23
|
```ts
|
|
24
24
|
import { Transaction } from '@solana/web3.js';
|
|
25
|
-
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
|
|
26
25
|
import * as bond from '@agent402-dev/bond-client';
|
|
27
26
|
|
|
28
27
|
const U = 1_000_000n; // USDC has 6 decimals; all amounts are in the smallest unit
|
|
@@ -30,7 +29,7 @@ const now = BigInt((await connection.getBlockTime(await connection.getSlot()))!)
|
|
|
30
29
|
const deal: bond.DealRef = {
|
|
31
30
|
seller, buyer, // PublicKey
|
|
32
31
|
mint: bond.MINTS.mainnet.USDC,
|
|
33
|
-
tokenProgram: TOKEN_PROGRAM_ID,
|
|
32
|
+
tokenProgram: bond.TOKEN_PROGRAM_ID,
|
|
34
33
|
nonce: 1n, // unique per seller + buyer pair
|
|
35
34
|
};
|
|
36
35
|
const terms: bond.Terms = {
|
|
@@ -60,6 +59,9 @@ Both sides can end a deal early with `cancelAndClaim` (both sign; each side gets
|
|
|
60
59
|
| `cancel`, `cancelAndClaim` | Closing a deal by mutual agreement |
|
|
61
60
|
| `dealPda`, `vaultPda`, `counterPda`, `configPda`, `dealOf` | Addresses |
|
|
62
61
|
| `decodeDeal`, `OUTCOMES` | Reading a deal |
|
|
62
|
+
| `timeline`, `settlePreview`, `buyerDeadline`, `possibleActions`, `settleBy` | The program's settlement rules in TypeScript (also at `@agent402-dev/bond-client/rules`, no dependencies): deadlines, what each side can do, what settlement pays |
|
|
63
|
+
| `associatedTokenAddress`, `TOKEN_PROGRAM_ID`, `TOKEN_2022_PROGRAM_ID` | Token account helpers |
|
|
64
|
+
| `JOB_PROTOCOL`, `checkJobQuote`, `termsMatchQuote`, `deliverMessage`, `verifyDeliverSignature` | [Bond Job Protocol](https://github.com/agent402-dev/agent402-toolkit/blob/main/docs/bond/JOB-PROTOCOL.md) helpers shared by sellers and buyers (also at `@agent402-dev/bond-client/job`, no dependencies) |
|
|
63
65
|
| `setPaused`, `setAdmin`, `acceptAdmin`, `proposeCaps`, `observePrice`, `activatePriceMode` | Operator and price-record instructions (the operator is a Squads multisig) |
|
|
64
66
|
|
|
65
67
|
## Things to get right
|
package/dist/index.d.ts
CHANGED
|
@@ -78,6 +78,13 @@ export interface DealRef {
|
|
|
78
78
|
nonce: bigint;
|
|
79
79
|
}
|
|
80
80
|
export declare const dealOf: (d: DealRef) => PublicKey;
|
|
81
|
+
/** SPL Token and Token-2022 program ids (so you do not need @solana/spl-token for these). */
|
|
82
|
+
export declare const TOKEN_PROGRAM_ID: PublicKey;
|
|
83
|
+
export declare const TOKEN_2022_PROGRAM_ID: PublicKey;
|
|
84
|
+
/** Associated token account program (same derivation as @solana/spl-token getAssociatedTokenAddressSync; checked in tests). */
|
|
85
|
+
export declare const ATA_PROGRAM_ID: PublicKey;
|
|
86
|
+
/** The owner's associated token account for a mint under a token program (SPL Token or Token-2022). */
|
|
87
|
+
export declare const associatedTokenAddress: (owner: PublicKey, mint: PublicKey, tokenProgram: PublicKey) => PublicKey;
|
|
81
88
|
/** Both seller and buyer must sign. Locks the bond and the deposit. */
|
|
82
89
|
export declare function open(d: DealRef, t: Terms, sellerToken?: PublicKey, buyerToken?: PublicKey): TransactionInstruction;
|
|
83
90
|
export declare const markDelivered: (d: DealRef) => TransactionInstruction;
|
|
@@ -112,3 +119,5 @@ export interface DealState {
|
|
|
112
119
|
}
|
|
113
120
|
/** Decodes a Deal account (Anchor layout, 8-byte discriminator first). */
|
|
114
121
|
export declare function decodeDeal(raw: Uint8Array): DealState;
|
|
122
|
+
export * from './rules.js';
|
|
123
|
+
export * from './job.js';
|
package/dist/index.js
CHANGED
|
@@ -11,7 +11,6 @@
|
|
|
11
11
|
* amount is returned to the buyer.
|
|
12
12
|
*/
|
|
13
13
|
import { PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js';
|
|
14
|
-
import { getAssociatedTokenAddressSync } from '@solana/spl-token';
|
|
15
14
|
/** Same program id on devnet and mainnet. */
|
|
16
15
|
export const BOND_PROGRAM_ID = new PublicKey('9hiCZZ6ddFG9oJBR1Su43Pj4JRFHeHC5cGiCgXtTuAaK');
|
|
17
16
|
export const MINTS = {
|
|
@@ -78,7 +77,14 @@ export const proposeCaps = (admin, mint, perDeal, total) => ix([r(admin, true),
|
|
|
78
77
|
export const observePrice = (preqMint, quoteVault) => ix([w(counterPda(preqMint)), r(PREQ_POOL), r(quoteVault)], data(DISC.observe_price));
|
|
79
78
|
export const activatePriceMode = (preqMint, quoteVault) => ix([w(counterPda(preqMint)), r(PREQ_POOL), r(quoteVault)], data(DISC.activate_price_mode));
|
|
80
79
|
export const dealOf = (d) => dealPda(d.seller, d.buyer, d.nonce);
|
|
81
|
-
|
|
80
|
+
/** SPL Token and Token-2022 program ids (so you do not need @solana/spl-token for these). */
|
|
81
|
+
export const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
|
|
82
|
+
export const TOKEN_2022_PROGRAM_ID = new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
|
|
83
|
+
/** Associated token account program (same derivation as @solana/spl-token getAssociatedTokenAddressSync; checked in tests). */
|
|
84
|
+
export const ATA_PROGRAM_ID = new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
|
|
85
|
+
/** The owner's associated token account for a mint under a token program (SPL Token or Token-2022). */
|
|
86
|
+
export const associatedTokenAddress = (owner, mint, tokenProgram) => PublicKey.findProgramAddressSync([owner.toBytes(), tokenProgram.toBytes(), mint.toBytes()], ATA_PROGRAM_ID)[0];
|
|
87
|
+
const ata = (owner, d) => associatedTokenAddress(owner, d.mint, d.tokenProgram);
|
|
82
88
|
/** Both seller and buyer must sign. Locks the bond and the deposit. */
|
|
83
89
|
export function open(d, t, sellerToken = ata(d.seller, d), buyerToken = ata(d.buyer, d)) {
|
|
84
90
|
const deal = dealOf(d);
|
|
@@ -145,3 +151,7 @@ export function decodeDeal(raw) {
|
|
|
145
151
|
balancePaid, outcome, owedSeller,
|
|
146
152
|
};
|
|
147
153
|
}
|
|
154
|
+
// Settlement rules (deadlines, possible actions, settlement preview), ported from the program's Rust core.
|
|
155
|
+
export * from './rules.js';
|
|
156
|
+
// Bond Job Protocol v1 (shared by sellers and buyers): quote checks, deliver message, signature check.
|
|
157
|
+
export * from './job.js';
|
package/dist/job.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent402 Bond Job Protocol v1 — the parts both sides share (no dependencies).
|
|
3
|
+
* Spec: docs/bond/JOB-PROTOCOL.md
|
|
4
|
+
*
|
|
5
|
+
* GET {base}/quote -> JobQuote
|
|
6
|
+
* POST {base}/open { buyer, input } -> JobOpen (open transaction signed by the seller)
|
|
7
|
+
* POST {base}/deliver { deal, expires, signature } -> JobDelivery (after the work, delivery marked on chain)
|
|
8
|
+
*/
|
|
9
|
+
export declare const JOB_PROTOCOL = "agent402-bond-job/1";
|
|
10
|
+
/** Max input size in bytes (UTF-8). */
|
|
11
|
+
export declare const JOB_MAX_INPUT = 16384;
|
|
12
|
+
export interface JobQuote {
|
|
13
|
+
protocol: typeof JOB_PROTOCOL;
|
|
14
|
+
program: string;
|
|
15
|
+
seller: string;
|
|
16
|
+
mint: string;
|
|
17
|
+
tokenProgram: string;
|
|
18
|
+
/** Amounts in the mint's smallest unit, as decimal strings */
|
|
19
|
+
price: string;
|
|
20
|
+
sellerBond: string;
|
|
21
|
+
buyerDeposit: string;
|
|
22
|
+
/** Seconds after opening the seller promises to deliver */
|
|
23
|
+
deliverSeconds: string;
|
|
24
|
+
lateWindow: string;
|
|
25
|
+
payWindow: string;
|
|
26
|
+
/** Free text: what the job is (plain text, at most 500 characters) */
|
|
27
|
+
description?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface JobTerms {
|
|
30
|
+
price: string;
|
|
31
|
+
sellerBond: string;
|
|
32
|
+
buyerDeposit: string;
|
|
33
|
+
deliverBy: string;
|
|
34
|
+
lateWindow: string;
|
|
35
|
+
payWindow: string;
|
|
36
|
+
}
|
|
37
|
+
export interface JobOpen {
|
|
38
|
+
deal: string;
|
|
39
|
+
nonce: string;
|
|
40
|
+
terms: JobTerms;
|
|
41
|
+
transaction: string;
|
|
42
|
+
}
|
|
43
|
+
export interface JobDelivery {
|
|
44
|
+
deal: string;
|
|
45
|
+
result: unknown;
|
|
46
|
+
markTx: string | null;
|
|
47
|
+
}
|
|
48
|
+
/** Returns the problems with a quote (empty if it is well formed). Business rules (limits, allowlists) are the buyer's own. */
|
|
49
|
+
export declare function checkJobQuote(q: unknown): string[];
|
|
50
|
+
/** Whether the terms of an `open` match a quote (deliverBy within deliverSeconds of `now`, allowing `slack` seconds). */
|
|
51
|
+
export declare function termsMatchQuote(t: JobTerms, q: JobQuote, now: bigint, slack?: bigint): string[];
|
|
52
|
+
/** A delivery request signature is valid for at most this many seconds. */
|
|
53
|
+
export declare const JOB_DELIVER_MAX_AGE = 600;
|
|
54
|
+
/**
|
|
55
|
+
* Bytes the buyer signs to fetch a delivery: bound to the deal, to the seller's origin (scheme://host[:port]) and to an
|
|
56
|
+
* expiry (unix seconds), so a signature given to one server cannot be replayed to another or reused later.
|
|
57
|
+
* They start with 0xff so they can never be read as a Solana transaction message (same idea as Solana off-chain messages).
|
|
58
|
+
*/
|
|
59
|
+
export declare function deliverMessage(deal: string, origin: string, expires: number): Uint8Array;
|
|
60
|
+
/** Shape check for the terms in an /open response (before any arithmetic on them). */
|
|
61
|
+
export declare function checkJobTerms(t: unknown): string[];
|
|
62
|
+
export declare const toBase64: (b: Uint8Array) => string;
|
|
63
|
+
export declare const fromBase64: (s: string) => Uint8Array<ArrayBuffer>;
|
|
64
|
+
/**
|
|
65
|
+
* Verifies a delivery request with Web Crypto (Node 20+, Cloudflare Workers, browsers): ed25519 by `publicKey`
|
|
66
|
+
* (32 raw bytes) over deliverMessage(deal, origin, expires), and `expires` between now and now + JOB_DELIVER_MAX_AGE.
|
|
67
|
+
*/
|
|
68
|
+
export declare function verifyDeliverSignature(publicKey: Uint8Array, deal: string, origin: string, expires: number, signatureBase64: string, nowSeconds?: number): Promise<boolean>;
|
package/dist/job.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent402 Bond Job Protocol v1 — the parts both sides share (no dependencies).
|
|
3
|
+
* Spec: docs/bond/JOB-PROTOCOL.md
|
|
4
|
+
*
|
|
5
|
+
* GET {base}/quote -> JobQuote
|
|
6
|
+
* POST {base}/open { buyer, input } -> JobOpen (open transaction signed by the seller)
|
|
7
|
+
* POST {base}/deliver { deal, expires, signature } -> JobDelivery (after the work, delivery marked on chain)
|
|
8
|
+
*/
|
|
9
|
+
export const JOB_PROTOCOL = 'agent402-bond-job/1';
|
|
10
|
+
/** Max input size in bytes (UTF-8). */
|
|
11
|
+
export const JOB_MAX_INPUT = 16_384;
|
|
12
|
+
const DEC = /^\d{1,20}$/;
|
|
13
|
+
const B58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
14
|
+
/** Returns the problems with a quote (empty if it is well formed). Business rules (limits, allowlists) are the buyer's own. */
|
|
15
|
+
export function checkJobQuote(q) {
|
|
16
|
+
const out = [];
|
|
17
|
+
const o = (q ?? {});
|
|
18
|
+
if (o.protocol !== JOB_PROTOCOL)
|
|
19
|
+
out.push(`protocol must be ${JOB_PROTOCOL}`);
|
|
20
|
+
for (const k of ['program', 'seller', 'mint', 'tokenProgram'])
|
|
21
|
+
if (typeof o[k] !== 'string' || !B58.test(o[k]))
|
|
22
|
+
out.push(`${k} must be a base58 address`);
|
|
23
|
+
for (const k of ['price', 'sellerBond', 'buyerDeposit', 'deliverSeconds', 'lateWindow', 'payWindow'])
|
|
24
|
+
if (typeof o[k] !== 'string' || !DEC.test(o[k]))
|
|
25
|
+
out.push(`${k} must be a decimal string`);
|
|
26
|
+
if (o.description !== undefined && (typeof o.description !== 'string' || o.description.length > 500))
|
|
27
|
+
out.push('description must be text up to 500 characters');
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
/** Whether the terms of an `open` match a quote (deliverBy within deliverSeconds of `now`, allowing `slack` seconds). */
|
|
31
|
+
export function termsMatchQuote(t, q, now, slack = 120n) {
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const k of ['price', 'sellerBond', 'buyerDeposit', 'lateWindow', 'payWindow'])
|
|
34
|
+
if (t[k] !== q[k])
|
|
35
|
+
out.push(`${k} differs from the quote`);
|
|
36
|
+
const by = BigInt(t.deliverBy);
|
|
37
|
+
if (by <= now)
|
|
38
|
+
out.push('deliverBy is in the past');
|
|
39
|
+
if (by > now + BigInt(q.deliverSeconds) + slack)
|
|
40
|
+
out.push('deliverBy is later than the quote allows');
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
const enc = new TextEncoder();
|
|
44
|
+
/** A delivery request signature is valid for at most this many seconds. */
|
|
45
|
+
export const JOB_DELIVER_MAX_AGE = 600;
|
|
46
|
+
/**
|
|
47
|
+
* Bytes the buyer signs to fetch a delivery: bound to the deal, to the seller's origin (scheme://host[:port]) and to an
|
|
48
|
+
* expiry (unix seconds), so a signature given to one server cannot be replayed to another or reused later.
|
|
49
|
+
* They start with 0xff so they can never be read as a Solana transaction message (same idea as Solana off-chain messages).
|
|
50
|
+
*/
|
|
51
|
+
export function deliverMessage(deal, origin, expires) {
|
|
52
|
+
const body = enc.encode(`${JOB_PROTOCOL}:deliver:${deal}:${origin}:${expires}`);
|
|
53
|
+
const out = new Uint8Array(1 + body.length);
|
|
54
|
+
out[0] = 0xff;
|
|
55
|
+
out.set(body, 1);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
const DEC_TERMS = /^\d{1,20}$/;
|
|
59
|
+
/** Shape check for the terms in an /open response (before any arithmetic on them). */
|
|
60
|
+
export function checkJobTerms(t) {
|
|
61
|
+
const o = (t ?? {});
|
|
62
|
+
return ['price', 'sellerBond', 'buyerDeposit', 'deliverBy', 'lateWindow', 'payWindow']
|
|
63
|
+
.filter((k) => typeof o[k] !== 'string' || !DEC_TERMS.test(o[k]))
|
|
64
|
+
.map((k) => `terms.${k} must be a decimal string`);
|
|
65
|
+
}
|
|
66
|
+
const b64 = (b) => btoa(String.fromCharCode(...b));
|
|
67
|
+
const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
|
68
|
+
export const toBase64 = b64;
|
|
69
|
+
export const fromBase64 = unb64;
|
|
70
|
+
/**
|
|
71
|
+
* Verifies a delivery request with Web Crypto (Node 20+, Cloudflare Workers, browsers): ed25519 by `publicKey`
|
|
72
|
+
* (32 raw bytes) over deliverMessage(deal, origin, expires), and `expires` between now and now + JOB_DELIVER_MAX_AGE.
|
|
73
|
+
*/
|
|
74
|
+
export async function verifyDeliverSignature(publicKey, deal, origin, expires, signatureBase64, nowSeconds = Math.floor(Date.now() / 1000)) {
|
|
75
|
+
try {
|
|
76
|
+
if (!Number.isSafeInteger(expires) || expires < nowSeconds || expires > nowSeconds + JOB_DELIVER_MAX_AGE)
|
|
77
|
+
return false;
|
|
78
|
+
const sig = unb64(signatureBase64);
|
|
79
|
+
if (sig.length !== 64 || publicKey.length !== 32)
|
|
80
|
+
return false;
|
|
81
|
+
const key = await crypto.subtle.importKey('raw', new Uint8Array(publicKey), { name: 'Ed25519' }, false, ['verify']);
|
|
82
|
+
return await crypto.subtle.verify('Ed25519', key, new Uint8Array(sig), new Uint8Array(deliverMessage(deal, origin, expires)));
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
package/dist/rules.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Agent402 Bond settlement rules, ported one-to-one from the program's
|
|
3
|
+
* pure Rust crate (programs/agent402-bond-core). Use it to show a deal's
|
|
4
|
+
* deadlines, what each side can still do, and what settlement would pay.
|
|
5
|
+
*
|
|
6
|
+
* The program is the source of truth. These functions only predict its
|
|
7
|
+
* answers from a deal's on-chain state; times are the Solana clock (unix seconds).
|
|
8
|
+
*/
|
|
9
|
+
import type { DealState, Terms } from './index.js';
|
|
10
|
+
export declare const DAY = 86400n;
|
|
11
|
+
export declare const GRACE = 86400n;
|
|
12
|
+
export declare const MAX_TERM: bigint;
|
|
13
|
+
export declare const MAX_LATE_WINDOW: bigint;
|
|
14
|
+
export declare const MIN_PAY_WINDOW = 86400n;
|
|
15
|
+
export declare const MAX_PAY_WINDOW: bigint;
|
|
16
|
+
export declare const MAX_BOND_BPS = 2000n;
|
|
17
|
+
export type Outcome = 'delivered' | 'buyer_default' | 'disputed' | 'seller_default' | 'cancelled';
|
|
18
|
+
export interface Payout {
|
|
19
|
+
toSeller: bigint;
|
|
20
|
+
toBuyer: bigint;
|
|
21
|
+
outcome: Outcome;
|
|
22
|
+
}
|
|
23
|
+
/** The parts of a deal the rules depend on (a subset of `DealState`). */
|
|
24
|
+
export interface RuleDeal {
|
|
25
|
+
terms: Terms;
|
|
26
|
+
openedAt: bigint;
|
|
27
|
+
sellerMark: bigint | null;
|
|
28
|
+
buyerConfirm: bigint | null;
|
|
29
|
+
balancePaid: boolean;
|
|
30
|
+
}
|
|
31
|
+
export declare const balanceOf: (t: Terms) => bigint;
|
|
32
|
+
export declare const t1: (t: Terms) => bigint;
|
|
33
|
+
export declare const t2: (t: Terms) => bigint;
|
|
34
|
+
/** Delivery time once the buyer has confirmed. */
|
|
35
|
+
export declare function deliveryTime(d: RuleDeal): bigint | null;
|
|
36
|
+
/** Last moment the buyer may confirm or pay the balance. */
|
|
37
|
+
export declare function buyerDeadline(d: RuleDeal): bigint;
|
|
38
|
+
/** Pro-rata late deduction from the seller bond, paid to the buyer. */
|
|
39
|
+
export declare function lateDeduction(d: RuleDeal): bigint;
|
|
40
|
+
/** What `settle` would pay at `now`, or null if the program would refuse (not yet settleable). */
|
|
41
|
+
export declare function settlePreview(d: RuleDeal, now: bigint): Payout | null;
|
|
42
|
+
/** Latest time at which `settle` is guaranteed to succeed. */
|
|
43
|
+
export declare const settleBy: (d: RuleDeal) => bigint;
|
|
44
|
+
/** Earliest time `settle` succeeds if nobody acts again (null if it already does at `now`). */
|
|
45
|
+
export declare function settleableFrom(d: RuleDeal, now: bigint): bigint | null;
|
|
46
|
+
export interface Action {
|
|
47
|
+
action: string;
|
|
48
|
+
who: 'seller' | 'buyer' | 'both' | 'anyone';
|
|
49
|
+
until?: bigint;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* What can still be done at `now` according to the program's rules.
|
|
53
|
+
* `cancel` and `extend` need both signatures and are listed while the deal is open.
|
|
54
|
+
*/
|
|
55
|
+
export declare function possibleActions(d: RuleDeal, now: bigint): Action[];
|
|
56
|
+
/** Summary of an open deal at `now`: deadlines, possible actions and the settlement that applies now or later. */
|
|
57
|
+
export declare function timeline(d: RuleDeal | DealState, now: bigint): {
|
|
58
|
+
now: bigint;
|
|
59
|
+
deliverBy: bigint;
|
|
60
|
+
lateUntil: bigint;
|
|
61
|
+
buyerDeadline: bigint;
|
|
62
|
+
settleBy: bigint;
|
|
63
|
+
lateDeduction: bigint;
|
|
64
|
+
settleNow: Payout | null;
|
|
65
|
+
settleableFrom: bigint | null;
|
|
66
|
+
possibleActions: Action[];
|
|
67
|
+
};
|
package/dist/rules.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
export const DAY = 86400n;
|
|
2
|
+
export const GRACE = DAY;
|
|
3
|
+
export const MAX_TERM = 180n * DAY;
|
|
4
|
+
export const MAX_LATE_WINDOW = 7n * DAY;
|
|
5
|
+
export const MIN_PAY_WINDOW = DAY;
|
|
6
|
+
export const MAX_PAY_WINDOW = 30n * DAY;
|
|
7
|
+
export const MAX_BOND_BPS = 2000n;
|
|
8
|
+
const max = (a, b) => (a > b ? a : b);
|
|
9
|
+
const min = (a, b) => (a < b ? a : b);
|
|
10
|
+
export const balanceOf = (t) => t.price - t.buyerDeposit;
|
|
11
|
+
export const t1 = (t) => t.deliverBy + GRACE;
|
|
12
|
+
export const t2 = (t) => t1(t) + t.lateWindow;
|
|
13
|
+
/** Delivery time once the buyer has confirmed. */
|
|
14
|
+
export function deliveryTime(d) {
|
|
15
|
+
if (d.buyerConfirm === null)
|
|
16
|
+
return null;
|
|
17
|
+
return d.sellerMark === null ? d.buyerConfirm : min(d.sellerMark, d.buyerConfirm);
|
|
18
|
+
}
|
|
19
|
+
/** Last moment the buyer may confirm or pay the balance. */
|
|
20
|
+
export function buyerDeadline(d) {
|
|
21
|
+
const t = d.terms;
|
|
22
|
+
const first = d.sellerMark !== null && d.buyerConfirm !== null
|
|
23
|
+
? min(d.sellerMark, d.buyerConfirm)
|
|
24
|
+
: (d.sellerMark ?? d.buyerConfirm);
|
|
25
|
+
if (first === null)
|
|
26
|
+
return t2(t);
|
|
27
|
+
const w = max(first, t1(t)) + t.payWindow + GRACE;
|
|
28
|
+
return d.buyerConfirm === null ? max(w, t2(t)) : w;
|
|
29
|
+
}
|
|
30
|
+
/** Pro-rata late deduction from the seller bond, paid to the buyer. */
|
|
31
|
+
export function lateDeduction(d) {
|
|
32
|
+
const dt = deliveryTime(d);
|
|
33
|
+
if (dt === null)
|
|
34
|
+
return 0n;
|
|
35
|
+
const start = t1(d.terms);
|
|
36
|
+
if (dt <= start || d.terms.lateWindow === 0n)
|
|
37
|
+
return 0n;
|
|
38
|
+
const late = min(dt - start, d.terms.lateWindow);
|
|
39
|
+
return (d.terms.sellerBond * late) / d.terms.lateWindow;
|
|
40
|
+
}
|
|
41
|
+
/** What `settle` would pay at `now`, or null if the program would refuse (not yet settleable). */
|
|
42
|
+
export function settlePreview(d, now) {
|
|
43
|
+
const t = d.terms;
|
|
44
|
+
if (d.buyerConfirm !== null) {
|
|
45
|
+
const deduct = lateDeduction(d);
|
|
46
|
+
let outcome;
|
|
47
|
+
if (d.balancePaid)
|
|
48
|
+
outcome = 'delivered';
|
|
49
|
+
else if (now > buyerDeadline(d))
|
|
50
|
+
outcome = 'buyer_default';
|
|
51
|
+
else
|
|
52
|
+
return null;
|
|
53
|
+
return { toSeller: t.sellerBond - deduct + t.buyerDeposit, toBuyer: deduct, outcome };
|
|
54
|
+
}
|
|
55
|
+
if (d.sellerMark !== null) {
|
|
56
|
+
if (now <= buyerDeadline(d))
|
|
57
|
+
return null;
|
|
58
|
+
return { toSeller: t.sellerBond, toBuyer: t.buyerDeposit, outcome: 'disputed' };
|
|
59
|
+
}
|
|
60
|
+
if (now <= t2(t))
|
|
61
|
+
return null;
|
|
62
|
+
return { toSeller: 0n, toBuyer: t.sellerBond + t.buyerDeposit, outcome: 'seller_default' };
|
|
63
|
+
}
|
|
64
|
+
/** Latest time at which `settle` is guaranteed to succeed. */
|
|
65
|
+
export const settleBy = (d) => t2(d.terms) + d.terms.payWindow + GRACE + 1n;
|
|
66
|
+
/** Earliest time `settle` succeeds if nobody acts again (null if it already does at `now`). */
|
|
67
|
+
export function settleableFrom(d, now) {
|
|
68
|
+
if (settlePreview(d, now) !== null)
|
|
69
|
+
return null;
|
|
70
|
+
if (d.buyerConfirm !== null || d.sellerMark !== null)
|
|
71
|
+
return buyerDeadline(d) + 1n;
|
|
72
|
+
return t2(d.terms) + 1n;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* What can still be done at `now` according to the program's rules.
|
|
76
|
+
* `cancel` and `extend` need both signatures and are listed while the deal is open.
|
|
77
|
+
*/
|
|
78
|
+
export function possibleActions(d, now) {
|
|
79
|
+
const out = [];
|
|
80
|
+
const bd = buyerDeadline(d);
|
|
81
|
+
if (d.sellerMark === null && d.buyerConfirm === null && now <= t2(d.terms)) {
|
|
82
|
+
out.push({ action: 'mark_delivered', who: 'seller', until: t2(d.terms) });
|
|
83
|
+
}
|
|
84
|
+
if (d.buyerConfirm === null && now <= bd)
|
|
85
|
+
out.push({ action: 'confirm_receipt', who: 'buyer', until: bd });
|
|
86
|
+
if (d.buyerConfirm !== null && !d.balancePaid && now <= bd)
|
|
87
|
+
out.push({ action: 'pay_balance', who: 'buyer', until: bd });
|
|
88
|
+
if (settlePreview(d, now) !== null)
|
|
89
|
+
out.push({ action: 'settle_and_claim', who: 'anyone' });
|
|
90
|
+
out.push({ action: 'cancel', who: 'both' }, { action: 'extend', who: 'both' });
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
/** Summary of an open deal at `now`: deadlines, possible actions and the settlement that applies now or later. */
|
|
94
|
+
export function timeline(d, now) {
|
|
95
|
+
const r = d;
|
|
96
|
+
return {
|
|
97
|
+
now,
|
|
98
|
+
deliverBy: r.terms.deliverBy,
|
|
99
|
+
lateUntil: t2(r.terms),
|
|
100
|
+
buyerDeadline: buyerDeadline(r),
|
|
101
|
+
settleBy: settleBy(r),
|
|
102
|
+
lateDeduction: lateDeduction(r),
|
|
103
|
+
settleNow: settlePreview(r, now),
|
|
104
|
+
settleableFrom: settleableFrom(r, now),
|
|
105
|
+
possibleActions: possibleActions(r, now),
|
|
106
|
+
};
|
|
107
|
+
}
|
package/package.json
CHANGED
|
@@ -14,13 +14,25 @@
|
|
|
14
14
|
".": {
|
|
15
15
|
"types": "./dist/index.d.ts",
|
|
16
16
|
"default": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./rules": {
|
|
19
|
+
"types": "./dist/rules.d.ts",
|
|
20
|
+
"default": "./dist/rules.js"
|
|
21
|
+
},
|
|
22
|
+
"./job": {
|
|
23
|
+
"types": "./dist/job.d.ts",
|
|
24
|
+
"default": "./dist/job.js"
|
|
17
25
|
}
|
|
18
26
|
},
|
|
19
27
|
"peerDependencies": {
|
|
20
|
-
"@solana/web3.js": "^1.98.0"
|
|
21
|
-
"@solana/spl-token": "^0.4.13"
|
|
28
|
+
"@solana/web3.js": "^1.98.0"
|
|
22
29
|
},
|
|
23
|
-
"
|
|
30
|
+
"peerDependenciesMeta": {
|
|
31
|
+
"@solana/web3.js": {
|
|
32
|
+
"optional": true
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"version": "0.2.0",
|
|
24
36
|
"author": "Agent402",
|
|
25
37
|
"license": "Apache-2.0",
|
|
26
38
|
"type": "module",
|