@agent402-dev/pay-mcp 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 +25 -0
- package/dist/bond-job.d.ts +116 -0
- package/dist/bond-job.js +172 -0
- package/dist/bond-sign.d.ts +151 -0
- package/dist/bond-sign.js +258 -0
- package/dist/bond-tx.d.ts +81 -0
- package/dist/bond-tx.js +189 -0
- package/dist/bond.d.ts +188 -0
- package/dist/bond.js +114 -0
- package/dist/history.js +2 -1
- package/dist/server.js +3 -1
- package/dist/spend-lock.d.ts +1 -0
- package/dist/spend-lock.js +8 -0
- package/dist/tools.d.ts +8 -1
- package/dist/tools.js +43 -3
- package/dist/units.js +2 -0
- package/dist/wallet.d.ts +2 -0
- package/dist/wallet.js +6 -1
- package/package.json +2 -1
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// Agent402 Bond signing tools for a buyer agent: open (sign the seller's open transaction), confirm + pay, settle + claims.
|
|
2
|
+
// Every rule is checked before signing. Defaults refuse everything: no sellers allowed and no per-deal cap until the user sets them.
|
|
3
|
+
// Bond outflows (deposit, balance) count toward the wallet's daily USDC cap and daily payment count, like x402 payments.
|
|
4
|
+
import { getPublicKeyFromAddress, verifySignature } from '@solana/kit';
|
|
5
|
+
import { buyerDeadline, settlePreview } from '@agent402-dev/bond-client/rules';
|
|
6
|
+
import { BOND_PROGRAM, decodeDealAccount } from './bond.js';
|
|
7
|
+
import { assemble, compileMessage, confirmIx, dealPda, decodeOpenData, openIx, parseTx, payIx, settleAndClaimIxs, TOKEN_PROGRAM, txId, } from './bond-tx.js';
|
|
8
|
+
import { formatUnits } from './units.js';
|
|
9
|
+
export function bondPolicyFromEnv(env) {
|
|
10
|
+
const pos = (s) => (s && Number(s) > 0 ? Number(s) : null);
|
|
11
|
+
return {
|
|
12
|
+
sellers: (env.X402_BOND_SELLERS ?? '').split(',').map((x) => x.trim()).filter(Boolean),
|
|
13
|
+
maxPriceUsd: pos(env.X402_BOND_MAX_USD),
|
|
14
|
+
minBondBps: env.X402_BOND_MIN_SELLER_BOND_BPS && /^\d+$/.test(env.X402_BOND_MIN_SELLER_BOND_BPS) ? BigInt(env.X402_BOND_MIN_SELLER_BOND_BPS) : 500n,
|
|
15
|
+
maxDays: pos(env.X402_BOND_MAX_DAYS) ?? 30,
|
|
16
|
+
confirmAboveUsd: env.X402_BOND_CONFIRM_ABOVE_USD && Number(env.X402_BOND_CONFIRM_ABOVE_USD) >= 0 ? Number(env.X402_BOND_CONFIRM_ABOVE_USD) : 0,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export function bondRpc(url, f = fetch) {
|
|
20
|
+
const call = async (method, params) => {
|
|
21
|
+
const r = await f(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) });
|
|
22
|
+
const j = (await r.json());
|
|
23
|
+
if (j.error || j.result === undefined)
|
|
24
|
+
throw new Error(`rpc ${method}: ${j.error?.message ?? r.status}`);
|
|
25
|
+
return j.result;
|
|
26
|
+
};
|
|
27
|
+
return {
|
|
28
|
+
async latestBlockhash() { return (await call('getLatestBlockhash', [{ commitment: 'confirmed' }])).value.blockhash; },
|
|
29
|
+
async sendAndConfirm(tx) {
|
|
30
|
+
const sig = (await call('sendTransaction', [Buffer.from(tx).toString('base64'), { encoding: 'base64', preflightCommitment: 'confirmed' }]));
|
|
31
|
+
for (let i = 0; i < 90; i++) {
|
|
32
|
+
const st = (await call('getSignatureStatuses', [[sig]])).value[0];
|
|
33
|
+
if (st?.err)
|
|
34
|
+
throw new Error(`transaction ${sig} failed: ${JSON.stringify(st.err)}`);
|
|
35
|
+
if (st?.confirmationStatus === 'confirmed' || st?.confirmationStatus === 'finalized')
|
|
36
|
+
return sig;
|
|
37
|
+
await new Promise((res) => setTimeout(res, 1000));
|
|
38
|
+
}
|
|
39
|
+
throw new Error(`transaction ${sig} not confirmed in time (it may still land; check before retrying)`);
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const usdc = (v) => formatUnits(v, 'USDC');
|
|
44
|
+
const toUsd = (v) => Number(v) / 1e6;
|
|
45
|
+
function record(d, action, deal, e) {
|
|
46
|
+
d.history.add({ at: (d.now?.() ?? new Date()).toISOString(), url: `bond:${action}:${deal}`, host: 'agent402-bond', network: d.policy.network, mint: d.policy.mints.USDC, signed: false, result: 'refused', ...e });
|
|
47
|
+
}
|
|
48
|
+
/** Daily cap and payment count, shared with x402 payments. */
|
|
49
|
+
function dailyCheck(d, amount) {
|
|
50
|
+
const t = d.history.today(d.now?.());
|
|
51
|
+
const out = [];
|
|
52
|
+
if (t.count + 1 > d.policy.maxPaymentsPerDay)
|
|
53
|
+
out.push(`daily payment count reached (${d.policy.maxPaymentsPerDay}, X402_MAX_PAYMENTS_PER_DAY)`);
|
|
54
|
+
if (t.usd + toUsd(amount) > d.policy.maxUsdPerDay + 1e-9)
|
|
55
|
+
out.push(`daily USDC cap: ${t.usd} USD used + ${toUsd(amount)} USD > ${d.policy.maxUsdPerDay} USD (X402_MAX_USD_PER_DAY)`);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
async function askHuman(d, amount, text) {
|
|
59
|
+
if (toUsd(amount) < d.bond.confirmAboveUsd)
|
|
60
|
+
return null;
|
|
61
|
+
const a = await d.confirm(text);
|
|
62
|
+
if (a === 'accept')
|
|
63
|
+
return null;
|
|
64
|
+
if (a === 'unsupported')
|
|
65
|
+
return { result: 'confirmation_required', message: 'This needs human confirmation (X402_BOND_CONFIRM_ABOVE_USD) but the MCP client cannot ask. Nothing was signed.' };
|
|
66
|
+
return { result: 'declined_by_user', message: 'Declined by the user. Nothing was signed.' };
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* bond_open: the seller built an `open` transaction and signed it as fee payer; the buyer (this wallet) adds its signature.
|
|
70
|
+
* The instruction is rebuilt from its own decoded terms and the wallet address, and must match byte for byte.
|
|
71
|
+
*/
|
|
72
|
+
export async function bondOpen(d, txBase64) {
|
|
73
|
+
if (!d.signer)
|
|
74
|
+
return { result: 'refused', reasons: ['no wallet configured (X402_KEYPAIR_PATH)'] };
|
|
75
|
+
const me = d.signer.address;
|
|
76
|
+
let bytes;
|
|
77
|
+
let p;
|
|
78
|
+
try {
|
|
79
|
+
bytes = Uint8Array.from(Buffer.from(txBase64, 'base64'));
|
|
80
|
+
p = parseTx(bytes);
|
|
81
|
+
}
|
|
82
|
+
catch (e) {
|
|
83
|
+
return { result: 'refused', reasons: [`not a valid legacy transaction: ${e.message}`] };
|
|
84
|
+
}
|
|
85
|
+
// Shape: exactly one Agent402 Bond `open`, two signers (seller pays fees and rent, this wallet), nothing else.
|
|
86
|
+
const reasons = [];
|
|
87
|
+
if (p.instructions.length !== 1)
|
|
88
|
+
reasons.push(`expected exactly 1 instruction, got ${p.instructions.length}`);
|
|
89
|
+
const ixIn = p.instructions[0];
|
|
90
|
+
const decoded = ixIn && ixIn.programId === BOND_PROGRAM ? decodeOpenData(ixIn.data) : null;
|
|
91
|
+
if (!decoded)
|
|
92
|
+
reasons.push('the instruction is not an Agent402 Bond open');
|
|
93
|
+
if (p.header.numRequiredSignatures !== 2)
|
|
94
|
+
reasons.push('expected exactly 2 signers (seller and buyer)');
|
|
95
|
+
if (reasons.length) {
|
|
96
|
+
record(d, 'open', '-', { reasons });
|
|
97
|
+
return { result: 'refused', reasons };
|
|
98
|
+
}
|
|
99
|
+
const seller = p.keys[0];
|
|
100
|
+
const { nonce, terms: t } = decoded;
|
|
101
|
+
// The seller (fee payer) must already have signed this exact message; otherwise sending would only fail.
|
|
102
|
+
try {
|
|
103
|
+
const ok = await verifySignature(await getPublicKeyFromAddress(seller), p.signatures[0], p.message);
|
|
104
|
+
if (!ok)
|
|
105
|
+
reasons.push('the seller signature is missing or invalid');
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
reasons.push('the seller signature is missing or invalid');
|
|
109
|
+
}
|
|
110
|
+
const keys = { seller, buyer: me, mint: d.policy.mints.USDC, tokenProgram: TOKEN_PROGRAM, nonce };
|
|
111
|
+
const deal = await dealPda(seller, me, nonce);
|
|
112
|
+
const expected = await openIx(keys, t);
|
|
113
|
+
const same = ixIn.keys.length === expected.keys.length
|
|
114
|
+
&& ixIn.keys.every((k, i) => k.pubkey === expected.keys[i].pubkey && k.isSigner === expected.keys[i].isSigner && k.isWritable === expected.keys[i].isWritable)
|
|
115
|
+
&& Buffer.from(ixIn.data).equals(Buffer.from(expected.data));
|
|
116
|
+
if (!same)
|
|
117
|
+
reasons.push('the open instruction does not match the one rebuilt for this wallet (accounts, mint, token program or data differ)');
|
|
118
|
+
if (p.keys.indexOf(me) !== 1)
|
|
119
|
+
reasons.push('this wallet must be the second signer');
|
|
120
|
+
// Policy
|
|
121
|
+
const now = await d.clock();
|
|
122
|
+
if (!d.bond.sellers.includes(seller))
|
|
123
|
+
reasons.push(`seller ${seller} is not in X402_BOND_SELLERS`);
|
|
124
|
+
if (d.bond.maxPriceUsd === null)
|
|
125
|
+
reasons.push('X402_BOND_MAX_USD is not set');
|
|
126
|
+
else if (toUsd(t.price) > d.bond.maxPriceUsd)
|
|
127
|
+
reasons.push(`price ${usdc(t.price)} is above X402_BOND_MAX_USD (${d.bond.maxPriceUsd} USD)`);
|
|
128
|
+
if (t.sellerBond * 10000n < t.price * d.bond.minBondBps)
|
|
129
|
+
reasons.push(`seller bond ${usdc(t.sellerBond)} is below ${Number(d.bond.minBondBps) / 100}% of the price`);
|
|
130
|
+
if (t.buyerDeposit > t.price)
|
|
131
|
+
reasons.push('deposit is larger than the price');
|
|
132
|
+
if (t.deliverBy <= now)
|
|
133
|
+
reasons.push('delivery deadline is in the past');
|
|
134
|
+
else if (t.deliverBy - now > BigInt(Math.round(d.bond.maxDays * 86_400)))
|
|
135
|
+
reasons.push(`delivery deadline is more than ${d.bond.maxDays} days away (X402_BOND_MAX_DAYS)`);
|
|
136
|
+
if (toUsd(t.price - t.buyerDeposit) > d.policy.maxUsdPerDay)
|
|
137
|
+
reasons.push('the balance alone is above the daily USDC cap, so it could never be paid');
|
|
138
|
+
reasons.push(...dailyCheck(d, t.buyerDeposit));
|
|
139
|
+
if (reasons.length) {
|
|
140
|
+
record(d, 'open', deal, { amount: t.buyerDeposit.toString(), payTo: seller, reasons });
|
|
141
|
+
return { result: 'refused', deal, reasons };
|
|
142
|
+
}
|
|
143
|
+
const summary = `Open an Agent402 Bond deal with seller ${seller}: price ${usdc(t.price)}, your deposit ${usdc(t.buyerDeposit)} now, balance ${usdc(t.price - t.buyerDeposit)} after you confirm receipt. Seller bond ${usdc(t.sellerBond)}. Delivery by ${new Date(Number(t.deliverBy) * 1000).toISOString()}.`;
|
|
144
|
+
const h = await askHuman(d, t.price, summary);
|
|
145
|
+
if (h) {
|
|
146
|
+
record(d, 'open', deal, { amount: t.buyerDeposit.toString(), payTo: seller, result: h.result === 'declined_by_user' ? 'declined_by_user' : 'confirmation_required' });
|
|
147
|
+
return { ...h, deal };
|
|
148
|
+
}
|
|
149
|
+
const sig = await d.signer.signBytes(p.message);
|
|
150
|
+
const signed = assemble(p.message, [p.signatures[0], sig]);
|
|
151
|
+
try {
|
|
152
|
+
const id = await d.rpc.sendAndConfirm(signed);
|
|
153
|
+
record(d, 'open', deal, { amount: t.buyerDeposit.toString(), payTo: seller, signed: true, result: 'paid', settlementTx: id });
|
|
154
|
+
return { result: 'opened', deal, transaction: id, deposit: usdc(t.buyerDeposit), balanceLater: usdc(t.price - t.buyerDeposit), deliverBy: new Date(Number(t.deliverBy) * 1000).toISOString() };
|
|
155
|
+
}
|
|
156
|
+
catch (e) {
|
|
157
|
+
record(d, 'open', deal, { amount: t.buyerDeposit.toString(), payTo: seller, signed: true, result: 'failed', reasons: [e.message] });
|
|
158
|
+
return { result: 'failed', deal, reasons: [e.message] };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async function readDeal(d, deal) {
|
|
162
|
+
const [acc] = await d.accounts([deal]);
|
|
163
|
+
if (!acc || acc.owner !== BOND_PROGRAM)
|
|
164
|
+
return null;
|
|
165
|
+
return decodeDealAccount(acc.data);
|
|
166
|
+
}
|
|
167
|
+
async function signAndSend(d, ixs) {
|
|
168
|
+
const { message, signers } = compileMessage(d.signer.address, ixs, await d.rpc.latestBlockhash());
|
|
169
|
+
if (signers.length !== 1)
|
|
170
|
+
throw new Error('unexpected extra signer');
|
|
171
|
+
const sig = await d.signer.signBytes(message);
|
|
172
|
+
return { id: txId(sig), send: () => d.rpc.sendAndConfirm(assemble(message, [sig])) };
|
|
173
|
+
}
|
|
174
|
+
/** bond_confirm_and_pay: confirm receipt and pay the balance straight to the seller (buyer only). */
|
|
175
|
+
export async function bondConfirmAndPay(d, deal) {
|
|
176
|
+
if (!d.signer)
|
|
177
|
+
return { result: 'refused', reasons: ['no wallet configured (X402_KEYPAIR_PATH)'] };
|
|
178
|
+
const a = await readDeal(d, deal);
|
|
179
|
+
if (!a)
|
|
180
|
+
return { result: 'refused', reasons: ['not an open Agent402 Bond deal'] };
|
|
181
|
+
const reasons = [];
|
|
182
|
+
const now = await d.clock();
|
|
183
|
+
if (a.buyer !== d.signer.address)
|
|
184
|
+
reasons.push('this wallet is not the buyer of this deal');
|
|
185
|
+
if (a.outcome !== 'open')
|
|
186
|
+
reasons.push(`deal is already decided (${a.outcome})`);
|
|
187
|
+
if (a.buyerConfirm !== null)
|
|
188
|
+
reasons.push('already confirmed');
|
|
189
|
+
if (a.mint !== d.policy.mints.USDC)
|
|
190
|
+
reasons.push('only USDC deals are supported');
|
|
191
|
+
if (now > buyerDeadline(a))
|
|
192
|
+
reasons.push('the buyer deadline has passed');
|
|
193
|
+
const balance = a.terms.price - a.terms.buyerDeposit;
|
|
194
|
+
reasons.push(...dailyCheck(d, balance));
|
|
195
|
+
if (reasons.length) {
|
|
196
|
+
record(d, 'confirm_and_pay', deal, { amount: balance.toString(), payTo: a.seller, reasons });
|
|
197
|
+
return { result: 'refused', deal, reasons };
|
|
198
|
+
}
|
|
199
|
+
// Confirming transfers the whole price to the seller (the locked deposit and the balance), so the threshold is the price.
|
|
200
|
+
const h = await askHuman(d, a.terms.price, `Confirm receipt for Agent402 Bond deal ${deal}: this pays the balance ${usdc(balance)} now and releases your locked deposit ${usdc(a.terms.buyerDeposit)} to seller ${a.seller} (total ${usdc(a.terms.price)}). Only confirm if you received what was agreed: the program does not judge quality.`);
|
|
201
|
+
if (h) {
|
|
202
|
+
record(d, 'confirm_and_pay', deal, { amount: balance.toString(), payTo: a.seller, result: h.result === 'declined_by_user' ? 'declined_by_user' : 'confirmation_required' });
|
|
203
|
+
return { ...h, deal };
|
|
204
|
+
}
|
|
205
|
+
const keys = { seller: a.seller, buyer: a.buyer, mint: a.mint, tokenProgram: TOKEN_PROGRAM, nonce: a.nonce };
|
|
206
|
+
const ixs = [confirmIx(a.buyer, deal), ...(balance > 0n ? [await payIx(keys, deal)] : [])];
|
|
207
|
+
const tx = await signAndSend(d, ixs);
|
|
208
|
+
try {
|
|
209
|
+
const id = await tx.send();
|
|
210
|
+
record(d, 'confirm_and_pay', deal, { amount: balance.toString(), payTo: a.seller, signed: true, result: 'paid', settlementTx: id });
|
|
211
|
+
return { result: 'confirmed_and_paid', deal, transaction: id, paid: usdc(balance), next: 'Anyone may now settle (bond_settle).' };
|
|
212
|
+
}
|
|
213
|
+
catch (e) {
|
|
214
|
+
record(d, 'confirm_and_pay', deal, { amount: balance.toString(), payTo: a.seller, signed: true, result: 'failed', reasons: [e.message] });
|
|
215
|
+
return { result: 'failed', deal, reasons: [e.message] };
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** bond_settle: settle a deal whose outcome is fixed and send both claims (this wallet pays only the network fee). */
|
|
219
|
+
export async function bondSettle(d, deal) {
|
|
220
|
+
if (!d.signer)
|
|
221
|
+
return { result: 'refused', reasons: ['no wallet configured (X402_KEYPAIR_PATH)'] };
|
|
222
|
+
const a = await readDeal(d, deal);
|
|
223
|
+
if (!a)
|
|
224
|
+
return { result: 'refused', reasons: ['not an open Agent402 Bond deal (already closed?)'] };
|
|
225
|
+
const me = d.signer.address;
|
|
226
|
+
if (me !== a.buyer && me !== a.seller)
|
|
227
|
+
return { result: 'refused', deal, reasons: ['this wallet is neither buyer nor seller of this deal'] };
|
|
228
|
+
if (a.mint !== d.policy.mints.USDC)
|
|
229
|
+
return { result: 'refused', deal, reasons: ['only USDC deals are supported by these tools'] };
|
|
230
|
+
const keys = { seller: a.seller, buyer: a.buyer, mint: a.mint, tokenProgram: TOKEN_PROGRAM, nonce: a.nonce };
|
|
231
|
+
const [settleIx, claimBuyerIx, claimSellerIx] = await settleAndClaimIxs(keys, deal);
|
|
232
|
+
const mine = me === a.buyer ? claimBuyerIx : claimSellerIx;
|
|
233
|
+
const preview = a.outcome === 'open' ? settlePreview(a, await d.clock()) : null;
|
|
234
|
+
if (a.outcome === 'open' && !preview)
|
|
235
|
+
return { result: 'refused', deal, reasons: ['not settleable yet (see bond_deal_status for the earliest time)'] };
|
|
236
|
+
// Normal path: settle (if still open) and both claims. If the other side's token account is closed or frozen,
|
|
237
|
+
// that fails in simulation (no fee): then send only settle and this wallet's own claim.
|
|
238
|
+
const head = a.outcome === 'open' ? [settleIx] : [];
|
|
239
|
+
const attempts = [[...head, claimBuyerIx, claimSellerIx], [...head, mine]];
|
|
240
|
+
const errors = [];
|
|
241
|
+
for (const ixs of attempts) {
|
|
242
|
+
const tx = await signAndSend(d, ixs);
|
|
243
|
+
try {
|
|
244
|
+
const id = await tx.send();
|
|
245
|
+
record(d, 'settle', deal, { amount: '0', payTo: a.seller, signed: true, result: 'paid', settlementTx: id });
|
|
246
|
+
return {
|
|
247
|
+
result: 'settled', deal, transaction: id, outcome: preview?.outcome ?? a.outcome,
|
|
248
|
+
...(preview ? { toSeller: usdc(preview.toSeller), toBuyer: usdc(preview.toBuyer) } : {}),
|
|
249
|
+
...(ixs.length < attempts[0].length ? { note: 'Only your own share was claimed; the other side can claim theirs later.' } : {}),
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
catch (e) {
|
|
253
|
+
errors.push(e.message);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
record(d, 'settle', deal, { amount: '0', payTo: a.seller, signed: true, result: 'failed', reasons: errors });
|
|
257
|
+
return { result: 'failed', deal, reasons: errors };
|
|
258
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export declare const TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
2
|
+
export declare const ATA_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
|
|
3
|
+
export declare const SYSTEM_PROGRAM = "11111111111111111111111111111111";
|
|
4
|
+
/** sha256("global:<name>")[..8] — same values as @agent402-dev/bond-client DISC (checked in tests). */
|
|
5
|
+
export declare const BOND_DISC: {
|
|
6
|
+
readonly open: readonly [228, 220, 155, 71, 199, 189, 60, 45];
|
|
7
|
+
readonly confirm_receipt: readonly [203, 36, 80, 115, 249, 12, 141, 170];
|
|
8
|
+
readonly pay_balance: readonly [121, 220, 140, 105, 242, 163, 148, 24];
|
|
9
|
+
readonly settle: readonly [175, 42, 185, 87, 144, 131, 102, 212];
|
|
10
|
+
readonly claim_seller: readonly [238, 218, 144, 171, 49, 203, 29, 50];
|
|
11
|
+
readonly claim_buyer: readonly [13, 61, 90, 109, 208, 223, 195, 211];
|
|
12
|
+
};
|
|
13
|
+
export declare const configPda: () => Promise<string>;
|
|
14
|
+
export declare const counterPda: (mint: string) => Promise<string>;
|
|
15
|
+
export declare const dealPda: (seller: string, buyer: string, nonce: bigint) => Promise<string>;
|
|
16
|
+
export declare const vaultPda: (deal: string) => Promise<string>;
|
|
17
|
+
export declare const ataOf: (owner: string, mint: string, tokenProgram?: string) => Promise<string>;
|
|
18
|
+
export interface Meta {
|
|
19
|
+
pubkey: string;
|
|
20
|
+
isSigner: boolean;
|
|
21
|
+
isWritable: boolean;
|
|
22
|
+
}
|
|
23
|
+
export interface Ix {
|
|
24
|
+
programId: string;
|
|
25
|
+
keys: Meta[];
|
|
26
|
+
data: Uint8Array;
|
|
27
|
+
}
|
|
28
|
+
export interface OpenTerms {
|
|
29
|
+
price: bigint;
|
|
30
|
+
sellerBond: bigint;
|
|
31
|
+
buyerDeposit: bigint;
|
|
32
|
+
deliverBy: bigint;
|
|
33
|
+
lateWindow: bigint;
|
|
34
|
+
payWindow: bigint;
|
|
35
|
+
}
|
|
36
|
+
export interface DealKeys {
|
|
37
|
+
seller: string;
|
|
38
|
+
buyer: string;
|
|
39
|
+
mint: string;
|
|
40
|
+
tokenProgram: string;
|
|
41
|
+
nonce: bigint;
|
|
42
|
+
}
|
|
43
|
+
export declare function openData(nonce: bigint, t: OpenTerms): Uint8Array;
|
|
44
|
+
export declare function decodeOpenData(data: Uint8Array): {
|
|
45
|
+
nonce: bigint;
|
|
46
|
+
terms: OpenTerms;
|
|
47
|
+
} | null;
|
|
48
|
+
export declare function openIx(d: DealKeys, t: OpenTerms): Promise<Ix>;
|
|
49
|
+
export declare const confirmIx: (buyer: string, deal: string) => Ix;
|
|
50
|
+
export declare function payIx(d: DealKeys, deal: string): Promise<Ix>;
|
|
51
|
+
/** settle, then claim_buyer, then claim_seller (order matters: claim_seller closes the deal). */
|
|
52
|
+
export declare function settleAndClaimIxs(d: DealKeys, deal: string): Promise<Ix[]>;
|
|
53
|
+
export interface ParsedTx {
|
|
54
|
+
signatures: Uint8Array[];
|
|
55
|
+
/** Offset of the message within the transaction bytes */
|
|
56
|
+
messageOffset: number;
|
|
57
|
+
message: Uint8Array;
|
|
58
|
+
header: {
|
|
59
|
+
numRequiredSignatures: number;
|
|
60
|
+
numReadonlySigned: number;
|
|
61
|
+
numReadonlyUnsigned: number;
|
|
62
|
+
};
|
|
63
|
+
keys: string[];
|
|
64
|
+
blockhash: string;
|
|
65
|
+
instructions: {
|
|
66
|
+
programId: string;
|
|
67
|
+
keys: Meta[];
|
|
68
|
+
data: Uint8Array;
|
|
69
|
+
}[];
|
|
70
|
+
}
|
|
71
|
+
/** Parses a legacy (non-versioned) transaction. Throws on anything else or on trailing bytes. */
|
|
72
|
+
export declare function parseTx(tx: Uint8Array): ParsedTx;
|
|
73
|
+
/** Compiles a legacy message (fee payer first; signers, then writable before read-only). */
|
|
74
|
+
export declare function compileMessage(feePayer: string, ixs: Ix[], blockhash: string): {
|
|
75
|
+
message: Uint8Array;
|
|
76
|
+
signers: string[];
|
|
77
|
+
};
|
|
78
|
+
/** Wire bytes: signatures in signer order (missing ones zero) followed by the message. */
|
|
79
|
+
export declare function assemble(message: Uint8Array, signatures: Uint8Array[]): Uint8Array;
|
|
80
|
+
/** The transaction id is the first signature (base58). */
|
|
81
|
+
export declare const txId: (sig: Uint8Array) => string;
|
package/dist/bond-tx.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// Agent402 Bond transactions without web3.js: addresses, instructions, and the legacy wire format (parse, compile, sign).
|
|
2
|
+
// Parsing our own bytes lets the buyer check exactly what it signs; nothing is trusted from the counterparty.
|
|
3
|
+
import { getAddressEncoder, getBase58Decoder, getBase58Encoder, getProgramDerivedAddress } from '@solana/kit';
|
|
4
|
+
import { BOND_PROGRAM } from './bond.js';
|
|
5
|
+
export const TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
|
|
6
|
+
export const ATA_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
|
|
7
|
+
export const SYSTEM_PROGRAM = '11111111111111111111111111111111';
|
|
8
|
+
/** sha256("global:<name>")[..8] — same values as @agent402-dev/bond-client DISC (checked in tests). */
|
|
9
|
+
export const BOND_DISC = {
|
|
10
|
+
open: [228, 220, 155, 71, 199, 189, 60, 45],
|
|
11
|
+
confirm_receipt: [203, 36, 80, 115, 249, 12, 141, 170],
|
|
12
|
+
pay_balance: [121, 220, 140, 105, 242, 163, 148, 24],
|
|
13
|
+
settle: [175, 42, 185, 87, 144, 131, 102, 212],
|
|
14
|
+
claim_seller: [238, 218, 144, 171, 49, 203, 29, 50],
|
|
15
|
+
claim_buyer: [13, 61, 90, 109, 208, 223, 195, 211],
|
|
16
|
+
};
|
|
17
|
+
const enc = new TextEncoder();
|
|
18
|
+
const addrBytes = (a) => Uint8Array.from(getAddressEncoder().encode(a));
|
|
19
|
+
const b58 = { dec: getBase58Decoder(), enc: getBase58Encoder() };
|
|
20
|
+
const u64le = (v) => { const b = new Uint8Array(8); new DataView(b.buffer).setBigUint64(0, v, true); return b; };
|
|
21
|
+
const pda = async (program, seeds) => (await getProgramDerivedAddress({ programAddress: program, seeds }))[0];
|
|
22
|
+
export const configPda = () => pda(BOND_PROGRAM, [enc.encode('config')]);
|
|
23
|
+
export const counterPda = (mint) => pda(BOND_PROGRAM, [enc.encode('counter'), addrBytes(mint)]);
|
|
24
|
+
export const dealPda = (seller, buyer, nonce) => pda(BOND_PROGRAM, [enc.encode('deal'), addrBytes(seller), addrBytes(buyer), u64le(nonce)]);
|
|
25
|
+
export const vaultPda = (deal) => pda(BOND_PROGRAM, [enc.encode('vault'), addrBytes(deal)]);
|
|
26
|
+
export const ataOf = (owner, mint, tokenProgram = TOKEN_PROGRAM) => pda(ATA_PROGRAM, [addrBytes(owner), addrBytes(tokenProgram), addrBytes(mint)]);
|
|
27
|
+
const w = (pubkey, isSigner = false) => ({ pubkey, isSigner, isWritable: true });
|
|
28
|
+
const r = (pubkey, isSigner = false) => ({ pubkey, isSigner, isWritable: false });
|
|
29
|
+
const ix = (keys, data) => ({ programId: BOND_PROGRAM, keys, data });
|
|
30
|
+
export function openData(nonce, t) {
|
|
31
|
+
const b = new Uint8Array(8 + 8 * 7);
|
|
32
|
+
const v = new DataView(b.buffer);
|
|
33
|
+
b.set(BOND_DISC.open, 0);
|
|
34
|
+
[nonce, t.price, t.sellerBond, t.buyerDeposit].forEach((x, i) => v.setBigUint64(8 + 8 * i, x, true));
|
|
35
|
+
[t.deliverBy, t.lateWindow, t.payWindow].forEach((x, i) => v.setBigInt64(40 + 8 * i, x, true));
|
|
36
|
+
return b;
|
|
37
|
+
}
|
|
38
|
+
export function decodeOpenData(data) {
|
|
39
|
+
if (data.length !== 64 || BOND_DISC.open.some((x, i) => data[i] !== x))
|
|
40
|
+
return null;
|
|
41
|
+
const v = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
42
|
+
const u = (o) => v.getBigUint64(o, true), s = (o) => v.getBigInt64(o, true);
|
|
43
|
+
return { nonce: u(8), terms: { price: u(16), sellerBond: u(24), buyerDeposit: u(32), deliverBy: s(40), lateWindow: s(48), payWindow: s(56) } };
|
|
44
|
+
}
|
|
45
|
+
export async function openIx(d, t) {
|
|
46
|
+
const deal = await dealPda(d.seller, d.buyer, d.nonce);
|
|
47
|
+
return ix([
|
|
48
|
+
w(d.seller, true), r(d.buyer, true), r(d.mint),
|
|
49
|
+
w(await ataOf(d.seller, d.mint, d.tokenProgram)), w(await ataOf(d.buyer, d.mint, d.tokenProgram)),
|
|
50
|
+
w(deal), w(await vaultPda(deal)), w(await counterPda(d.mint)), r(await configPda()), r(d.tokenProgram), r(SYSTEM_PROGRAM),
|
|
51
|
+
], openData(d.nonce, t));
|
|
52
|
+
}
|
|
53
|
+
export const confirmIx = (buyer, deal) => ix([r(buyer, true), w(deal)], Uint8Array.from(BOND_DISC.confirm_receipt));
|
|
54
|
+
export async function payIx(d, deal) {
|
|
55
|
+
return ix([r(d.buyer, true), w(deal), r(d.mint), w(await ataOf(d.buyer, d.mint, d.tokenProgram)), w(await ataOf(d.seller, d.mint, d.tokenProgram)), r(d.tokenProgram)], Uint8Array.from(BOND_DISC.pay_balance));
|
|
56
|
+
}
|
|
57
|
+
/** settle, then claim_buyer, then claim_seller (order matters: claim_seller closes the deal). */
|
|
58
|
+
export async function settleAndClaimIxs(d, deal) {
|
|
59
|
+
const vault = await vaultPda(deal);
|
|
60
|
+
const claim = (to, disc) => ix([w(d.seller), w(deal), r(d.mint), w(vault), w(to), r(d.tokenProgram)], Uint8Array.from(disc));
|
|
61
|
+
return [
|
|
62
|
+
ix([w(deal), r(vault), w(await counterPda(d.mint))], Uint8Array.from(BOND_DISC.settle)),
|
|
63
|
+
claim(await ataOf(d.buyer, d.mint, d.tokenProgram), BOND_DISC.claim_buyer),
|
|
64
|
+
claim(await ataOf(d.seller, d.mint, d.tokenProgram), BOND_DISC.claim_seller),
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
// ---------- legacy wire format ----------
|
|
68
|
+
function shortvecEncode(n) {
|
|
69
|
+
const out = [];
|
|
70
|
+
for (;;) {
|
|
71
|
+
let b = n & 0x7f;
|
|
72
|
+
n >>= 7;
|
|
73
|
+
if (n)
|
|
74
|
+
b |= 0x80;
|
|
75
|
+
out.push(b);
|
|
76
|
+
if (!n)
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** compact-u16, canonical only (as the runtime accepts it). */
|
|
81
|
+
function shortvecDecode(b, o) {
|
|
82
|
+
let n = 0, shift = 0;
|
|
83
|
+
for (let i = 0; i < 3; i++) {
|
|
84
|
+
const x = b[o++];
|
|
85
|
+
if (x === undefined)
|
|
86
|
+
throw new Error('truncated');
|
|
87
|
+
if (i === 2 && x > 3)
|
|
88
|
+
throw new Error('bad shortvec');
|
|
89
|
+
n |= (x & 0x7f) << shift;
|
|
90
|
+
shift += 7;
|
|
91
|
+
if (!(x & 0x80)) {
|
|
92
|
+
if (i > 0 && x === 0)
|
|
93
|
+
throw new Error('non-canonical shortvec');
|
|
94
|
+
return [n, o];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
throw new Error('bad shortvec');
|
|
98
|
+
}
|
|
99
|
+
/** Parses a legacy (non-versioned) transaction. Throws on anything else or on trailing bytes. */
|
|
100
|
+
export function parseTx(tx) {
|
|
101
|
+
let o = 0;
|
|
102
|
+
let n;
|
|
103
|
+
[n, o] = shortvecDecode(tx, o);
|
|
104
|
+
const signatures = [];
|
|
105
|
+
if (n > 16 || o + 64 * n > tx.length)
|
|
106
|
+
throw new Error('bad signature count');
|
|
107
|
+
for (let i = 0; i < n; i++) {
|
|
108
|
+
signatures.push(tx.slice(o, o + 64));
|
|
109
|
+
o += 64;
|
|
110
|
+
}
|
|
111
|
+
const messageOffset = o;
|
|
112
|
+
if (tx[o] === undefined)
|
|
113
|
+
throw new Error('truncated');
|
|
114
|
+
if (tx[o] & 0x80)
|
|
115
|
+
throw new Error('versioned transactions are not accepted');
|
|
116
|
+
const header = { numRequiredSignatures: tx[o], numReadonlySigned: tx[o + 1], numReadonlyUnsigned: tx[o + 2] };
|
|
117
|
+
o += 3;
|
|
118
|
+
[n, o] = shortvecDecode(tx, o);
|
|
119
|
+
const keys = [];
|
|
120
|
+
for (let i = 0; i < n; i++) {
|
|
121
|
+
if (o + 32 > tx.length)
|
|
122
|
+
throw new Error('truncated');
|
|
123
|
+
keys.push(b58.dec.decode(tx.subarray(o, o + 32)));
|
|
124
|
+
o += 32;
|
|
125
|
+
}
|
|
126
|
+
const blockhash = b58.dec.decode(tx.subarray(o, o + 32));
|
|
127
|
+
o += 32;
|
|
128
|
+
const isSigner = (i) => i < header.numRequiredSignatures;
|
|
129
|
+
const isWritable = (i) => isSigner(i) ? i < header.numRequiredSignatures - header.numReadonlySigned : i < keys.length - header.numReadonlyUnsigned;
|
|
130
|
+
const meta = (i) => { if (i >= keys.length)
|
|
131
|
+
throw new Error('bad account index'); return { pubkey: keys[i], isSigner: isSigner(i), isWritable: isWritable(i) }; };
|
|
132
|
+
[n, o] = shortvecDecode(tx, o);
|
|
133
|
+
const instructions = [];
|
|
134
|
+
for (let k = 0; k < n; k++) {
|
|
135
|
+
const p = tx[o++];
|
|
136
|
+
let m;
|
|
137
|
+
[m, o] = shortvecDecode(tx, o);
|
|
138
|
+
const idx = Array.from(tx.subarray(o, o + m));
|
|
139
|
+
o += m;
|
|
140
|
+
let dl;
|
|
141
|
+
[dl, o] = shortvecDecode(tx, o);
|
|
142
|
+
const data = tx.slice(o, o + dl);
|
|
143
|
+
o += dl;
|
|
144
|
+
if (o > tx.length)
|
|
145
|
+
throw new Error('truncated');
|
|
146
|
+
instructions.push({ programId: meta(p).pubkey, keys: idx.map(meta), data });
|
|
147
|
+
}
|
|
148
|
+
if (o !== tx.length)
|
|
149
|
+
throw new Error('trailing bytes');
|
|
150
|
+
if (signatures.length !== header.numRequiredSignatures)
|
|
151
|
+
throw new Error('signature count mismatch');
|
|
152
|
+
return { signatures, messageOffset, message: tx.slice(messageOffset), header, keys, blockhash, instructions };
|
|
153
|
+
}
|
|
154
|
+
/** Compiles a legacy message (fee payer first; signers, then writable before read-only). */
|
|
155
|
+
export function compileMessage(feePayer, ixs, blockhash) {
|
|
156
|
+
const metas = new Map();
|
|
157
|
+
const add = (k, s, wr) => { const m = metas.get(k); metas.set(k, { s: (m?.s ?? false) || s, w: (m?.w ?? false) || wr }); };
|
|
158
|
+
add(feePayer, true, true);
|
|
159
|
+
for (const i of ixs) {
|
|
160
|
+
for (const k of i.keys)
|
|
161
|
+
add(k.pubkey, k.isSigner, k.isWritable);
|
|
162
|
+
add(i.programId, false, false);
|
|
163
|
+
}
|
|
164
|
+
const rank = (k) => { const m = metas.get(k); return k === feePayer ? -1 : (m.s ? 0 : 2) + (m.w ? 0 : 1); };
|
|
165
|
+
const keys = [...metas.keys()].sort((a, b) => rank(a) - rank(b));
|
|
166
|
+
const sig = keys.filter((k) => metas.get(k).s);
|
|
167
|
+
const header = [sig.length, sig.filter((k) => !metas.get(k).w).length, keys.filter((k) => !metas.get(k).s && !metas.get(k).w).length];
|
|
168
|
+
const idx = (k) => keys.indexOf(k);
|
|
169
|
+
const bytes = [...header, ...shortvecEncode(keys.length)];
|
|
170
|
+
for (const k of keys)
|
|
171
|
+
bytes.push(...addrBytes(k));
|
|
172
|
+
bytes.push(...b58.enc.encode(blockhash));
|
|
173
|
+
bytes.push(...shortvecEncode(ixs.length));
|
|
174
|
+
for (const i of ixs) {
|
|
175
|
+
bytes.push(idx(i.programId), ...shortvecEncode(i.keys.length), ...i.keys.map((k) => idx(k.pubkey)), ...shortvecEncode(i.data.length), ...i.data);
|
|
176
|
+
}
|
|
177
|
+
return { message: Uint8Array.from(bytes), signers: sig };
|
|
178
|
+
}
|
|
179
|
+
/** Wire bytes: signatures in signer order (missing ones zero) followed by the message. */
|
|
180
|
+
export function assemble(message, signatures) {
|
|
181
|
+
const head = shortvecEncode(signatures.length);
|
|
182
|
+
const out = new Uint8Array(head.length + 64 * signatures.length + message.length);
|
|
183
|
+
out.set(head, 0);
|
|
184
|
+
signatures.forEach((s, i) => out.set(s, head.length + 64 * i));
|
|
185
|
+
out.set(message, head.length + 64 * signatures.length);
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
/** The transaction id is the first signature (base58). */
|
|
189
|
+
export const txId = (sig) => b58.dec.decode(sig);
|