@intent-engine/cli 0.1.11 → 0.1.15

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.
@@ -1,17 +1,21 @@
1
- import { decodeEvent, findIntentPda, formatAmount, getIntentDecoder, IntentStatus, parseAmount } from "@intent-engine/core";
2
- import { chainTime, CLOCK_SYSVAR, mintOf } from "../accounts.js";
1
+ import { createHash } from "node:crypto";
2
+ import { AccountRole, getAddressDecoder } from "@solana/kit";
3
+ import { attestedFillMessage, buildFillAttested, decodeEvent, decodeParams, feeBpsFor, findIntentPda, formatAmount, formatTime, getIntentDecoder, IntentStatus, Kind, LONG_LIVED_SECONDS, parseAmount, signEd25519Instruction, splitFees, WARN_ATTESTOR, WARN_LONG_LIVED, } from "@intent-engine/core";
4
+ import { chainTime, CLOCK_SYSVAR, loadConfig, mintOf } from "../accounts.js";
3
5
  import { ENV_KEYPAIR, WALLET_NOT_MAINNET } from "../args.js";
4
6
  import { execute } from "../flows.js";
5
- import { TOKEN_NAMES, tokenNamed } from "../tokens.js";
6
- import { unmemoized } from "../transport.js";
7
+ import { NATIVE_MINT, TOKEN_NAMES, tokenNamed } from "../tokens.js";
8
+ import { MEMO_PROGRAM_ADDRESS, neverLanded, unmemoized } from "../transport.js";
7
9
  import { balances, defaultMints, FAUCET, PUBLIC_FAUCET, setup, withSettings } from "../wallet.js";
8
10
  import { define } from "./actions.js";
9
- import { MAX_EXPIRES_IN, MIN_EXPIRES_IN, prepareCreate } from "./create.js";
11
+ import { MAX_EXPIRES_IN, MIN_EXPIRES_IN, prepareCreate, WRAPPED } from "./create.js";
10
12
  import { tool } from "./names.js";
11
- import { AgentRefusal } from "./problems.js";
13
+ import { AgentRefusal, problemOf } from "./problems.js";
12
14
  import { listIntents } from "./read.js";
13
15
  import { InvalidInput, account, amount, choice, flag, integer, list, object, optional, text, time } from "./schema.js";
14
- import { orderSchema } from "./shapes.js";
16
+ import { orderSchema, preparedView } from "./shapes.js";
17
+ import { tokenAccountIfMissing, walletRecipient } from "./owner.js";
18
+ import { prepare } from "./prepare.js";
15
19
  import { prepareCancel } from "./settle.js";
16
20
  import { STATUS } from "../accounts.js";
17
21
  export const walletGuard = (limits) => ({ limits, sales: [] });
@@ -19,7 +23,7 @@ export const SALE_WINDOW = 3600n;
19
23
  export const ESTIMATE_SCAN = 12;
20
24
  export const ESTIMATE_FILLS = 5;
21
25
  export const WAIT_DEFAULT = 30;
22
- export const WAIT_MAX = 55;
26
+ export const WAIT_MAX = 40;
23
27
  export const WAIT_SCAN = 10;
24
28
  export const DEFAULT_EXPIRES_IN = 3_600;
25
29
  export const LANDING_SECONDS = 10;
@@ -28,7 +32,7 @@ export const WALLET_NOTICE = [
28
32
  "Test network only: this wallet works on Solana devnet, testnet or localnet and refuses mainnet. Its tokens have no value.",
29
33
  "Your key stays on this machine: setup makes one unless a keypair is already configured, and names its file. Only signed transactions leave it.",
30
34
  "This server talks to no one but the RPC endpoint it was started with.",
31
- "Nothing moves until you approve: swaps, auctions and cancels only preview until you say yes.",
35
+ "Nothing moves until you approve: swaps, auctions, escrows, releases and cancels only preview until you say yes.",
32
36
  "Do not send real funds to this wallet or use its key anywhere else.",
33
37
  ];
34
38
  export const walletEmpty = (address) => `the wallet ${address} holds no SOL yet; request devnet SOL for it at ${FAUCET} or ${PUBLIC_FAUCET}, then try again`;
@@ -113,7 +117,14 @@ export function limitLines(limits) {
113
117
  "It sells no other token. Plan trades within these limits and tell the user when a request exceeds them.",
114
118
  ];
115
119
  }
116
- const capOf = (text, decimals) => parseAmount(text, decimals);
120
+ function capOf(text, decimals, mint) {
121
+ try {
122
+ return parseAmount(text, decimals);
123
+ }
124
+ catch {
125
+ throw new AgentRefusal("WalletTokenNotAllowed", `this server's limit of ${text} ${nameOf(mint)} does not fit a token with ${decimals} decimals, so it sells none; the user restarts it with a valid limit`);
126
+ }
127
+ }
117
128
  function checkSale(guard, mint, decimals, amount, now) {
118
129
  if (!limited(guard)) {
119
130
  return;
@@ -125,16 +136,20 @@ function checkSale(guard, mint, decimals, amount, now) {
125
136
  throw new AgentRefusal("WalletTokenNotAllowed", `this server sells only ${allowed}, not ${name}; its limits were set when it started`);
126
137
  }
127
138
  const trade = perTrade.get(mint);
128
- if (trade !== undefined && amount > capOf(trade, decimals)) {
139
+ if (trade !== undefined && amount > capOf(trade, decimals, mint)) {
129
140
  throw new AgentRefusal("WalletTradeLimit", `this server sells at most ${trade} ${name} per trade and this sells ${formatAmount(amount, decimals)}; sell less, or the user restarts the server with a higher --wallet-per-trade`);
130
141
  }
131
- const hour = perHour.get(mint);
142
+ checkHour(guard, mint, decimals, amount, now);
143
+ }
144
+ function checkHour(guard, mint, decimals, amount, now) {
145
+ const hour = guard.limits.perHour.get(mint);
146
+ const name = nameOf(mint);
132
147
  if (hour === undefined) {
133
148
  return;
134
149
  }
135
150
  guard.sales = guard.sales.filter((s) => s.at > now - SALE_WINDOW);
136
151
  const used = guard.sales.filter((s) => s.mint === mint).reduce((sum, s) => sum + s.amount, 0n);
137
- const cap = capOf(hour, decimals);
152
+ const cap = capOf(hour, decimals, mint);
138
153
  if (used + amount > cap) {
139
154
  throw new AgentRefusal("WalletHourLimit", `this server sells at most ${hour} ${name} per hour and has ${formatAmount(cap > used ? cap - used : 0n, decimals)} left; this sells ${formatAmount(amount, decimals)}`);
140
155
  }
@@ -192,7 +207,7 @@ export const walletBalance = define({
192
207
  return balances(ctx.transport, owner, mints);
193
208
  },
194
209
  });
195
- const offerOutput = object({
210
+ const offerFields = {
196
211
  intent: account(),
197
212
  nonce: amount(),
198
213
  summary: list(text(), 24),
@@ -200,7 +215,8 @@ const offerOutput = object({
200
215
  sent: flag(),
201
216
  signature: optional(text()),
202
217
  next: optional(text()),
203
- });
218
+ };
219
+ const offerOutput = object(offerFields);
204
220
  async function offered(ctx, call, input, terms) {
205
221
  const wallet = access(ctx);
206
222
  const signer = await signerOf(ctx);
@@ -215,9 +231,9 @@ async function offered(ctx, call, input, terms) {
215
231
  mintOf(ctx.transport, outputMint),
216
232
  chainTime(ctx.transport),
217
233
  ]);
218
- const made = terms(inputToken, outputToken, now);
234
+ const made = await terms(inputToken, outputToken, now, inputMint, outputMint);
219
235
  checkSale(wallet.limits, inputMint, inputToken.decimals, made.order.amount_in, now);
220
- const view = (await prepareCreate.run(ctx, { owner: signer.address, input_mint: inputMint, output_mint: outputMint, ...made }, call));
236
+ const view = (await prepareCreate.run(ctx, { owner: signer.address, input_mint: inputMint, output_mint: outputMint, ...(input.pay_to === undefined ? {} : { pay_to: input.pay_to }), ...made }, call));
221
237
  const { intent, nonce, summary, warnings, prepared } = view;
222
238
  const sold = made.order.amount_in;
223
239
  const guard = wallet.limits;
@@ -231,14 +247,47 @@ async function offered(ctx, call, input, terms) {
231
247
  return await sent(ctx, signer, { intent, nonce, summary, warnings, prepared }, input.send, call);
232
248
  }
233
249
  catch (error) {
234
- guard.sales = guard.sales.filter((s) => s !== sale);
250
+ if (neverLanded(error)) {
251
+ guard.sales = guard.sales.filter((s) => s !== sale);
252
+ }
235
253
  throw error;
236
254
  }
237
255
  }
256
+ export const SWAP_FALLS_OVER = 120;
257
+ export const PAY_TO = "the wallet that receives what is bought, such as someone this wallet pays; default this wallet. This wallet pays for its token account if it has none";
258
+ export const SWAP_HEADROOM_BPS = 200n;
259
+ export const SWAP_BLIND_BPS = 2500n;
260
+ export const SWAP_CAP_BPS = 20000n;
261
+ async function recentFills(transport, inputMint, outputMint) {
262
+ const { created, fills } = await engineHistory(transport, ESTIMATE_SCAN);
263
+ const unknown = [...new Set(fills.map((f) => f.intent).filter((intent) => !created.has(intent)))];
264
+ const views = unknown.length === 0 ? [] : await transport.getAccounts(unknown);
265
+ unknown.forEach((intent, i) => {
266
+ const view = views[i];
267
+ const pair = view === null || view === undefined ? null : pairOf(view.data);
268
+ if (pair !== null) {
269
+ created.set(intent, pair);
270
+ }
271
+ });
272
+ return fills
273
+ .filter((f) => f.amountIn > 0n && created.get(f.intent)?.inputMint === inputMint && created.get(f.intent)?.outputMint === outputMint)
274
+ .slice(0, ESTIMATE_FILLS);
275
+ }
276
+ const byRate = (fills) => [...fills].sort((a, b) => (a.delivered * b.amountIn < b.delivered * a.amountIn ? -1 : a.delivered * b.amountIn > b.delivered * a.amountIn ? 1 : 0));
277
+ const bestOf = (fills) => byRate(fills).at(-1);
278
+ const medianOf = (fills) => byRate(fills)[Math.floor((fills.length - 1) / 2)];
279
+ function openingAsk(fills, amount, floor) {
280
+ const typical = medianOf(fills);
281
+ const blind = (floor * (10000n + SWAP_BLIND_BPS)) / 10000n;
282
+ const seen = typical === undefined ? 0n : (amount * typical.delivered * (10000n + SWAP_HEADROOM_BPS)) / (typical.amountIn * 10000n);
283
+ const cap = (floor * SWAP_CAP_BPS) / 10000n;
284
+ const ask = seen > blind ? seen : blind;
285
+ return ask < cap ? ask : cap;
286
+ }
238
287
  const walletSwap = define({
239
288
  name: tool("wallet_swap"),
240
289
  title: "Swap from the wallet",
241
- description: "Offer an exact amount of one token for at least an amount of another, from this server's wallet: the tokens are escrowed in an intent that a solver fills or that the wallet gets back. Amounts are whole tokens such as 0.05. Selling SOL wraps it first. Without send it only previews; show the user the summary and call again with send: true once they approve.",
290
+ description: `Sell an exact amount of one token for at least min_receive of another, from this server's wallet: the tokens are escrowed in an intent that a solver fills or that the wallet gets back. Solvers pay the least an intent asks, so by default the ask starts at start_receive, a little above the median of recent fills but at least a quarter above min_receive and at most twice it, and falls to min_receive over falls_over seconds (default ${SWAP_FALLS_OVER}): a solver takes it near the most it can pay. exact: true asks min_receive from the start instead. Amounts are whole tokens such as 0.05. Selling SOL wraps it first. Without send it only previews; show the user the summary, then call again with send: true and the start_receive the preview returned once they approve.`,
242
291
  effect: "submit",
243
292
  repeats: true,
244
293
  input: object({
@@ -246,18 +295,336 @@ const walletSwap = define({
246
295
  buy: text("SOL, TEST or a mint address"),
247
296
  amount: text("whole tokens to sell, such as 0.05"),
248
297
  min_receive: text("least whole tokens to receive for all of it"),
298
+ start_receive: optional(text("whole tokens asked when the offer lands; default a little above the median recent fill, between 1.25 and 2 times min_receive")),
299
+ falls_over: optional(integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, `seconds the ask takes to fall to min_receive; default ${SWAP_FALLS_OVER}`)),
300
+ exact: optional(flag("true asks min_receive from the start, with no falling ask")),
301
+ pay_to: optional(account(PAY_TO)),
249
302
  expires_in: optional(integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, `least seconds the offer stays open once sent; default ${DEFAULT_EXPIRES_IN}`)),
250
303
  send: optional(flag("true signs and sends; leave out to preview")),
251
304
  }),
305
+ output: object({ ...offerFields, start_receive: optional(text("whole tokens asked when the offer lands; pass it back when sending")) }),
306
+ run: async (ctx, input, call) => {
307
+ let opening;
308
+ const result = await offered(ctx, call, input, async (sold, bought, now, inputMint, outputMint) => {
309
+ const amountIn = raw(input.amount, sold.decimals, "amount");
310
+ const floor = raw(input.min_receive, bought.decimals, "min_receive");
311
+ const expiresIn = BigInt(input.expires_in ?? DEFAULT_EXPIRES_IN);
312
+ const ask = input.exact === true
313
+ ? floor
314
+ : input.start_receive === undefined
315
+ ? openingAsk(await recentFills(ctx.transport, inputMint, outputMint), amountIn, floor)
316
+ : raw(input.start_receive, bought.decimals, "start_receive");
317
+ if (ask <= floor) {
318
+ return { order: { kind: "swap", amount_in: amountIn, min_out: floor }, expires_at: now + expiresIn + BigInt(LANDING_SECONDS) };
319
+ }
320
+ opening = formatAmount(ask, bought.decimals);
321
+ const start = now + BigInt(LANDING_SECONDS);
322
+ const falls = BigInt(input.falls_over ?? SWAP_FALLS_OVER);
323
+ return {
324
+ order: { kind: "dutch", amount_in: amountIn, start_out: ask, end_out: floor, start_time: start, end_time: start + falls },
325
+ expires_at: start + (expiresIn > falls ? expiresIn : falls),
326
+ };
327
+ });
328
+ return opening === undefined ? result : { ...result, start_receive: opening };
329
+ },
330
+ });
331
+ export const ESCROW_EXPIRES_IN = 86_400;
332
+ export const RECORD_MINT_NEEDED = "selling SOL on this RPC needs record_mint: any other token's mint, which only labels the escrow";
333
+ function recordedMint(sell, url, chosen) {
334
+ if (chosen !== undefined) {
335
+ return mintNamed(chosen, url, "record_mint");
336
+ }
337
+ if (sell !== NATIVE_MINT) {
338
+ return NATIVE_MINT;
339
+ }
340
+ const test = tokenNamed("TEST", url);
341
+ if (test instanceof Error) {
342
+ throw new InvalidInput([{ path: "record_mint", message: RECORD_MINT_NEEDED }]);
343
+ }
344
+ return test;
345
+ }
346
+ const walletEscrow = define({
347
+ name: tool("wallet_escrow"),
348
+ title: "Escrow a payment for an attestor to release",
349
+ description: `Hold an exact amount of one token from this server's wallet in an attested intent: it goes, minus the engine fee, to whichever wallet the named attestor later signs for, once the attestor attests a result between min_result and max_result. Use it to pay another agent for work that a third agent or a person judges. The attestor alone decides who is paid; nothing else is checked on chain, so name an attestor the user trusts. Have the worker deliver to the attestor rather than to this wallet, since this wallet can cancel until the release; ${tool("wallet_receipt")} later shows what the release recorded. Until then the wallet can cancel it with ${tool("wallet_cancel")}, and after it expires anyone can return the escrow. Amounts are whole tokens such as 0.05. Without send it only previews; show the user the summary and call again with send: true once they approve.`,
350
+ effect: "submit",
351
+ repeats: true,
352
+ input: object({
353
+ sell: text("SOL, TEST or a mint address: the token to pay with"),
354
+ amount: text("whole tokens to escrow, such as 0.05"),
355
+ attestor: account("the wallet whose signature alone releases the escrow"),
356
+ min_result: optional(amount("least result the attestor may attest; default 1")),
357
+ max_result: optional(amount("greatest result the attestor may attest; default min_result")),
358
+ expires_in: optional(integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, `least seconds the escrow stays open once sent; default ${ESCROW_EXPIRES_IN}`)),
359
+ record_mint: optional(text("a token the escrow records as its output, other than sell; only a label. Default SOL, or TEST when selling SOL on devnet")),
360
+ send: optional(flag("true signs and sends; leave out to preview")),
361
+ }),
252
362
  output: offerOutput,
253
- run: async (ctx, input, call) => offered(ctx, call, input, (sold, bought, now) => ({
254
- order: {
255
- kind: "swap",
256
- amount_in: raw(input.amount, sold.decimals, "amount"),
257
- min_out: raw(input.min_receive, bought.decimals, "min_receive"),
258
- },
259
- expires_at: now + BigInt((input.expires_in ?? DEFAULT_EXPIRES_IN) + LANDING_SECONDS),
260
- })),
363
+ run: async (ctx, input, call) => {
364
+ const wallet = access(ctx);
365
+ const sold = mintNamed(input.sell, wallet.url, "sell");
366
+ const least = input.min_result ?? 1n;
367
+ const most = input.max_result ?? least;
368
+ if (most < least) {
369
+ throw new InvalidInput([{ path: "max_result", message: "must be at least min_result" }]);
370
+ }
371
+ return offered(ctx, call, { sell: sold, buy: recordedMint(sold, wallet.url, input.record_mint), send: input.send }, (token, _, now) => ({
372
+ order: { kind: "attested", amount_in: raw(input.amount, token.decimals, "amount"), min_result: least, max_result: most, attestor: input.attestor },
373
+ expires_at: now + BigInt((input.expires_in ?? ESCROW_EXPIRES_IN) + LANDING_SECONDS),
374
+ }));
375
+ },
376
+ });
377
+ export const PAYEE_MOVED = "this wallet's token account for the escrowed token now belongs to someone else, so a release would not reach it; ask the payee for another wallet";
378
+ export const RELEASE_CHANGED = "this release differs from its preview: the payee, amount, result, fee or the escrow itself changed, or no approval was given; preview it again and show the user";
379
+ export const approvalOf = (message, memo = "") => createHash("sha256").update(message).update(memo).digest("hex").slice(0, 16);
380
+ export const DELIVERY_PREFIX = "delivery sha256:";
381
+ const DELIVERY_MEMO = /^delivery sha256:([0-9a-f]{64})$/;
382
+ function sha256Of(text, path) {
383
+ const hex = text.trim().toLowerCase();
384
+ if (!/^[0-9a-f]{64}$/.test(hex)) {
385
+ throw new InvalidInput([{ path, message: "give a sha256 as 64 hex digits" }]);
386
+ }
387
+ return hex;
388
+ }
389
+ export const notAttestor = (attestor) => `this intent names ${attestor} as its attestor, not this server's wallet; only that key can release it`;
390
+ const walletAttest = define({
391
+ name: tool("wallet_attest"),
392
+ title: "Release an escrow as its attestor",
393
+ description: `As the attestor an escrow names, sign that it pays pay_to and settle it on chain from this server's wallet: the escrowed tokens, minus the engine fee and any partner fee, go to pay_to's token account, which this creates if needed. Use it when this server's wallet was named attestor of an intent made with ${tool("wallet_escrow")} and the work it pays for is done. A release cannot be undone. Without send it only previews and signs nothing; show the user the summary and, once they approve, call again with send: true and the approval the preview returned, which holds the send to exactly what was previewed.`,
394
+ effect: "submit",
395
+ input: object({
396
+ owner: account("the wallet that made the escrow"),
397
+ nonce: amount("the escrow intent's nonce"),
398
+ pay_to: account("the wallet to pay"),
399
+ result: optional(amount("the result to attest, between the intent's min_result and max_result; default min_result")),
400
+ delivered_sha256: optional(text(`the sha256, as 64 hex digits, of the work this release pays for; recorded in a memo this wallet signs with the release, so the payer can check what it receives with ${tool("wallet_receipt")}`)),
401
+ approval: optional(text("the approval the preview returned; needed with send")),
402
+ send: optional(flag("true signs the attestation and settles; leave out to preview")),
403
+ }),
404
+ output: object({
405
+ intent: account(),
406
+ pay_to: account(),
407
+ payee: account("pay_to's token account that receives the escrow"),
408
+ paid: text("whole tokens pay_to receives"),
409
+ fee: text("whole tokens kept as fees"),
410
+ result: amount(),
411
+ approval: text("pass it back with send: true; a send that would differ from this preview is refused"),
412
+ delivered_sha256: optional(text("the sha256 the release records")),
413
+ summary: list(text(), 8),
414
+ warnings: list(text(), 8),
415
+ sent: flag(),
416
+ signature: optional(text()),
417
+ next: optional(text()),
418
+ }),
419
+ run: async (ctx, input, call) => {
420
+ const signer = await signerOf(ctx);
421
+ const [intent] = await findIntentPda({ owner: input.owner, nonce: input.nonce });
422
+ const [view, { config }] = await Promise.all([ctx.transport.getAccount(intent), loadConfig(ctx.transport)]);
423
+ if (view === null) {
424
+ throw new AgentRefusal("NotFound", `no intent ${intent}; it was settled, cancelled and closed, or never made`);
425
+ }
426
+ const held = getIntentDecoder().decode(view.data);
427
+ const params = decodeParams(held.kind, Uint8Array.from(held.params));
428
+ if (params.kind !== Kind.AttestedResult) {
429
+ throw new AgentRefusal("KindMismatch", "this intent is not an attested escrow");
430
+ }
431
+ if (params.attestor !== signer.address) {
432
+ throw new AgentRefusal("Unauthorized", notAttestor(params.attestor));
433
+ }
434
+ if (held.status !== IntentStatus.Open) {
435
+ throw new AgentRefusal("InvalidTransition", `this escrow is ${STATUS[held.status] ?? "not open"}, so it can no longer be released`);
436
+ }
437
+ if (held.expiresAt <= (await chainTime(ctx.transport))) {
438
+ throw new AgentRefusal("IntentExpired", "this escrow has expired; its owner gets it back instead");
439
+ }
440
+ const result = input.result ?? params.minResult;
441
+ if (result < params.minResult || result > params.maxResult) {
442
+ throw new InvalidInput([{ path: "result", message: `must be between ${params.minResult} and ${params.maxResult}` }]);
443
+ }
444
+ await walletRecipient(ctx.transport, input.pay_to, "pay_to");
445
+ const token = await mintOf(ctx.transport, held.inputMint);
446
+ const payee = await tokenAccountIfMissing(ctx.transport, signer, input.pay_to, held.inputMint, token.tokenProgram);
447
+ if (payee.create.length === 0) {
448
+ const existing = await ctx.transport.getAccount(payee.address);
449
+ const holder = existing === null || existing.data.length < 64 ? null : getAddressDecoder().decode(existing.data.subarray(32, 64));
450
+ if (holder !== input.pay_to) {
451
+ throw new InvalidInput([{ path: "pay_to", message: PAYEE_MOVED }]);
452
+ }
453
+ }
454
+ const amountIn = held.escrowed - held.filled;
455
+ const maxFeeBps = feeBpsFor(config, held.kind) + held.partnerBps;
456
+ const shares = splitFees(amountIn, feeBpsFor(config, held.kind), held.partnerBps, held.partnerCutBps);
457
+ const treasury = shares.protocol > 0n
458
+ ? await tokenAccountIfMissing(ctx.transport, signer, config.feeRecipient, held.inputMint, token.tokenProgram)
459
+ : { create: [] };
460
+ const partnerPaid = shares.partner > 0n;
461
+ const partner = partnerPaid ? await tokenAccountIfMissing(ctx.transport, signer, held.partner, held.inputMint, token.tokenProgram) : { create: [] };
462
+ const message = await attestedFillMessage(signer.address, {
463
+ domain: Uint8Array.from(config.domain),
464
+ intent,
465
+ payee: payee.address,
466
+ amountIn,
467
+ result,
468
+ filled: held.filled,
469
+ revision: held.revision,
470
+ maxFeeBps,
471
+ });
472
+ const settle = await buildFillAttested({
473
+ solver: signer,
474
+ owner: input.owner,
475
+ nonce: input.nonce,
476
+ inputMint: held.inputMint,
477
+ inputTokenProgram: token.tokenProgram,
478
+ payee: payee.address,
479
+ ...(shares.protocol > 0n ? { feeRecipient: config.feeRecipient } : {}),
480
+ ...(partnerPaid ? { partner: held.partner } : {}),
481
+ amountIn,
482
+ result,
483
+ maxFeeBps,
484
+ });
485
+ const name = TOKEN_NAMES[held.inputMint] ?? held.inputMint;
486
+ const paid = formatAmount(shares.net, token.decimals);
487
+ const setup = [...payee.create, ...treasury.create, ...partner.create];
488
+ const delivered = input.delivered_sha256 === undefined ? undefined : sha256Of(input.delivered_sha256, "delivered_sha256");
489
+ const memoText = delivered === undefined ? "" : `${DELIVERY_PREFIX}${delivered}`;
490
+ const memo = delivered === undefined
491
+ ? []
492
+ : [{ programAddress: MEMO_PROGRAM_ADDRESS, accounts: [{ address: signer.address, role: AccountRole.READONLY_SIGNER, signer }], data: new TextEncoder().encode(memoText) }];
493
+ const approval = approvalOf(message, memoText);
494
+ if (input.send === true && input.approval !== approval) {
495
+ throw new AgentRefusal("ReleaseChanged", RELEASE_CHANGED);
496
+ }
497
+ const prepared = input.send === true
498
+ ? preparedView(await prepare(ctx.transport, [...setup, await signEd25519Instruction(signer, message), settle, ...memo], signer.address))
499
+ : undefined;
500
+ const view2 = {
501
+ intent,
502
+ pay_to: input.pay_to,
503
+ payee: payee.address,
504
+ paid,
505
+ fee: formatAmount(shares.protocol + shares.partner, token.decimals),
506
+ result,
507
+ approval,
508
+ ...(delivered === undefined ? {} : { delivered_sha256: delivered }),
509
+ summary: [
510
+ `Pays: ${paid} of ${name} to ${input.pay_to} from ${input.owner}'s escrow${held.inputMint === NATIVE_MINT ? WRAPPED : ""}`,
511
+ `Attests: result ${result}, signed by this server's wallet as the escrow's attestor`,
512
+ ...(delivered === undefined ? [] : [`Records: the delivered work's sha256 ${delivered}, in a memo this wallet signs with the release`]),
513
+ ...(payee.create.length === 0 ? [] : [`Setup: creates ${input.pay_to}'s ${name} account, paid by this wallet`]),
514
+ ...(treasury.create.length === 0 ? [] : [`Setup: creates the engine treasury's ${name} account for the fee, paid by this wallet`]),
515
+ ...(partner.create.length === 0 ? [] : [`Setup: creates the partner ${held.partner}'s ${name} account for its fee, paid by this wallet`]),
516
+ ],
517
+ warnings: [WARN_ATTESTOR],
518
+ prepared,
519
+ };
520
+ return sent(ctx, signer, view2, input.send, call);
521
+ },
522
+ });
523
+ export const MAX_RECURRING = 12;
524
+ export const mayHaveLanded = (sent, times, problem) => `${sent} of ${times} orders were sent and the next may have landed too (${problem}); check ${tool("wallet_intents")} before sending any again, and do not repeat this call`;
525
+ export const partlySent = (sent, times, problem) => `${sent} of ${times} orders were sent; the next failed with ${problem}. To finish, schedule only the ${times - sent} remaining orders; do not repeat this call`;
526
+ export const WARN_EARLY = "an order fills before its turn if a solver can already pay its start_receive";
527
+ export const NO_FALL = "must be more than 0, or the orders have no ask to fall";
528
+ const refusedBeforeSending = (error) => neverLanded(error) || error instanceof AgentRefusal || error instanceof InvalidInput;
529
+ export const MAX_EVERY = 30 * 24 * 60 * 60;
530
+ const walletRecurring = define({
531
+ name: tool("wallet_recurring"),
532
+ title: "Repeat a swap on a schedule",
533
+ description: `Sell the same amount of one token for another several times, every so many seconds, from this server's wallet, with no bot left running: all orders are sent now and escrowed now. Each order holds its ask at start_receive until its turn, then lets it fall to min_receive over falls_over seconds; it expires when the next one opens, or falls_over seconds after its own opening if that is later, and anyone can then return its escrow. An order fills before its turn if a solver can already pay start_receive, so set it above what solvers pay now to hold the orders. Any order can be cancelled with ${tool("wallet_cancel")}. Each order pays the create fee and rent, and the rent returns when it closes. Amounts are whole tokens per order. Without send it only previews; show the user the summary, then call again with send: true and the start_receive the preview returned once they approve.`,
534
+ effect: "submit",
535
+ repeats: true,
536
+ input: object({
537
+ sell: text("SOL, TEST or a mint address"),
538
+ buy: text("SOL, TEST or a mint address"),
539
+ amount: text("whole tokens each order sells, such as 0.05"),
540
+ min_receive: text("least whole tokens each order receives"),
541
+ every: integer(MIN_EXPIRES_IN, MAX_EVERY, "seconds between one order opening and the next"),
542
+ times: integer(2, MAX_RECURRING, "how many orders"),
543
+ start_receive: optional(text("whole tokens each order asks until and when it opens; default a little above the median recent fill, between 1.25 and 2 times min_receive")),
544
+ falls_over: optional(integer(MIN_EXPIRES_IN, MAX_EVERY, `seconds each order's ask takes to fall to min_receive; default ${SWAP_FALLS_OVER}`)),
545
+ pay_to: optional(account(PAY_TO)),
546
+ send: optional(flag("true signs and sends every order; leave out to preview")),
547
+ }),
548
+ output: object({
549
+ orders: list(object({ opens_at: time("when the order's ask starts to fall"), intent: optional(account()), nonce: optional(amount()), signature: optional(text()) }), MAX_RECURRING),
550
+ summary: list(text(), 24, "the whole plan, then the first order"),
551
+ warnings: list(text(), 16),
552
+ start_receive: text("whole tokens each order asks when it opens; pass it back when sending"),
553
+ sent: flag(),
554
+ next: optional(text()),
555
+ }),
556
+ run: async (ctx, input, call) => {
557
+ const wallet = access(ctx);
558
+ const inputMint = mintNamed(input.sell, wallet.url, "sell");
559
+ const outputMint = mintNamed(input.buy, wallet.url, "buy");
560
+ const [inputToken, outputToken, now] = await Promise.all([
561
+ mintOf(ctx.transport, inputMint),
562
+ mintOf(ctx.transport, outputMint),
563
+ chainTime(ctx.transport),
564
+ ]);
565
+ const amountIn = raw(input.amount, inputToken.decimals, "amount");
566
+ const floor = raw(input.min_receive, outputToken.decimals, "min_receive");
567
+ const ask = input.start_receive === undefined
568
+ ? openingAsk(await recentFills(ctx.transport, inputMint, outputMint), amountIn, floor)
569
+ : raw(input.start_receive, outputToken.decimals, "start_receive");
570
+ if (ask <= floor) {
571
+ throw new InvalidInput([
572
+ input.start_receive === undefined ? { path: "min_receive", message: NO_FALL } : { path: "start_receive", message: "must be more than min_receive, or the order has no ask to fall" },
573
+ ]);
574
+ }
575
+ checkSale(wallet.limits, inputMint, inputToken.decimals, amountIn, now);
576
+ checkHour(wallet.limits, inputMint, inputToken.decimals, amountIn * BigInt(input.times), now);
577
+ const falls = BigInt(input.falls_over ?? SWAP_FALLS_OVER);
578
+ const every = BigInt(input.every);
579
+ const life = falls > every ? falls : every;
580
+ const opens = Array.from({ length: input.times }, (_, k) => now + BigInt(LANDING_SECONDS) + every * BigInt(k));
581
+ const terms = (open) => () => ({
582
+ order: { kind: "dutch", amount_in: amountIn, start_out: ask, end_out: floor, start_time: open, end_time: open + falls },
583
+ expires_at: open + life,
584
+ });
585
+ const shown = { start_receive: formatAmount(ask, outputToken.decimals) };
586
+ const last = opens[opens.length - 1];
587
+ const first = (await offered(ctx, call, { ...input, send: input.send }, terms(opens[0])));
588
+ const sold = TOKEN_NAMES[inputMint] ?? inputMint;
589
+ const plan = [
590
+ `Plan: ${input.times} orders of ${formatAmount(amountIn, inputToken.decimals)} of ${sold}, ${formatAmount(amountIn * BigInt(input.times), inputToken.decimals)} of ${sold} in all, escrowed now`,
591
+ `Schedule: the orders open from ${formatTime(opens[0])} to ${formatTime(last)}; the last expires ${formatTime(last + life)}`,
592
+ ...first["summary"],
593
+ ];
594
+ const warned = first["warnings"];
595
+ const warnings = [
596
+ ...warned,
597
+ WARN_EARLY,
598
+ ...(last + life - now > LONG_LIVED_SECONDS && !warned.includes(WARN_LONG_LIVED) ? [WARN_LONG_LIVED] : []),
599
+ ];
600
+ if (input.send !== true) {
601
+ return { orders: opens.map((opens_at) => ({ opens_at })), summary: plan, warnings, ...shown, sent: false, next: first["next"] };
602
+ }
603
+ const orders = [{ opens_at: opens[0], intent: first["intent"], nonce: first["nonce"], signature: first["signature"] }];
604
+ for (const open of opens.slice(1)) {
605
+ try {
606
+ const made = (await offered(ctx, call, { ...input, send: true }, terms(open)));
607
+ orders.push({ opens_at: open, intent: made["intent"], nonce: made["nonce"], signature: made["signature"] });
608
+ }
609
+ catch (error) {
610
+ for (const undo of call.undo.splice(0)) {
611
+ undo();
612
+ }
613
+ const problem = problemOf(error);
614
+ return {
615
+ orders: [...orders, ...opens.slice(orders.length).map((opens_at) => ({ opens_at }))],
616
+ summary: plan,
617
+ warnings,
618
+ ...shown,
619
+ sent: true,
620
+ next: refusedBeforeSending(error)
621
+ ? partlySent(orders.length, input.times, `${problem.code}: ${problem.hint}`)
622
+ : mayHaveLanded(orders.length, input.times, `${problem.code}: ${problem.hint}`),
623
+ };
624
+ }
625
+ }
626
+ return { orders, summary: plan, warnings, ...shown, sent: true };
627
+ },
261
628
  });
262
629
  const walletAuction = define({
263
630
  name: tool("wallet_auction"),
@@ -273,6 +640,7 @@ const walletAuction = define({
273
640
  end_receive: text("least whole tokens accepted once the asked amount stops falling"),
274
641
  falls_over: integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, "seconds the asked amount takes to fall from start_receive to end_receive"),
275
642
  expires_in: optional(integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, `least seconds the offer stays open once sent, never less than falls_over; default ${DEFAULT_EXPIRES_IN}`)),
643
+ pay_to: optional(account(PAY_TO)),
276
644
  send: optional(flag("true signs and sends; leave out to preview")),
277
645
  }),
278
646
  output: offerOutput,
@@ -306,7 +674,7 @@ const walletIntents = define({
306
674
  const walletCancel = define({
307
675
  name: tool("wallet_cancel"),
308
676
  title: "Cancel a wallet intent",
309
- description: "Cancel an open intent of this server's wallet by its nonce: the escrow returns to the wallet and the intent account closes, returning its rent. Without send it only previews; call again with send: true once the user approves.",
677
+ description: "Cancel an open intent of this server's wallet by its nonce: the escrow returns to the wallet's token account (wrapped SOL for SOL) and the intent account closes, returning its rent. Without send it only previews; call again with send: true once the user approves.",
310
678
  effect: "submit",
311
679
  input: object({ nonce: amount("the intent's nonce, from wallet_intents"), send: optional(flag("true signs and sends; leave out to preview")) }),
312
680
  output: object({
@@ -328,7 +696,11 @@ async function engineHistory(transport, limit, of) {
328
696
  const created = new Map();
329
697
  const fills = [];
330
698
  const ended = new Map();
699
+ let unread = 0;
331
700
  for (const tx of await transport.engineTransactions(limit, of)) {
701
+ if (tx.unread === true) {
702
+ unread += 1;
703
+ }
332
704
  if (tx.failed) {
333
705
  continue;
334
706
  }
@@ -354,7 +726,7 @@ async function engineHistory(transport, limit, of) {
354
726
  }
355
727
  }
356
728
  }
357
- return { created, fills, ended };
729
+ return { created, fills, ended, unread };
358
730
  }
359
731
  function pairOf(data) {
360
732
  try {
@@ -365,7 +737,7 @@ function pairOf(data) {
365
737
  return null;
366
738
  }
367
739
  }
368
- export const ESTIMATE_NEXT = "solvers pay the least an intent asks, so these fills show what owners asked and got, not the most a solver would pay; ask a minimum near receive_at_best, or auction from a little above it down to the least the user accepts to find the price";
740
+ export const ESTIMATE_NEXT = "solvers pay the least an intent asks, so these fills show what owners asked and got, not the most a solver would pay; ask a minimum near receive_at_median, since a single fill can be staged by one party on both sides, or auction from a little above it down to the least the user accepts to find the price";
369
741
  export const NO_FILLS = `no recent fill sold this token for that one; auction from a high ask down to the least the user accepts with ${tool("wallet_auction")} to find the price`;
370
742
  const walletEstimate = define({
371
743
  name: tool("wallet_estimate"),
@@ -384,7 +756,8 @@ const walletEstimate = define({
384
756
  at: optional(time("when the fill landed")),
385
757
  signature: text(),
386
758
  }), ESTIMATE_FILLS, "newest first"),
387
- receive_at_best: optional(text("whole tokens amount would get at the best recent rate")),
759
+ receive_at_best: optional(text("whole tokens amount would get at the best recent rate; one fill can be staged by its own two sides")),
760
+ receive_at_median: optional(text("whole tokens amount would get at the median recent rate")),
388
761
  receive_at_latest: optional(text("whole tokens amount would get at the newest fill's rate")),
389
762
  next: text(),
390
763
  }),
@@ -394,19 +767,7 @@ const walletEstimate = define({
394
767
  const outputMint = mintNamed(input.buy, wallet.url, "buy");
395
768
  const [inputToken, outputToken] = await Promise.all([mintOf(ctx.transport, inputMint), mintOf(ctx.transport, outputMint)]);
396
769
  const amount = raw(input.amount, inputToken.decimals, "amount");
397
- const { created, fills } = await engineHistory(ctx.transport, ESTIMATE_SCAN);
398
- const unknown = [...new Set(fills.map((f) => f.intent).filter((intent) => !created.has(intent)))];
399
- const views = unknown.length === 0 ? [] : await ctx.transport.getAccounts(unknown);
400
- unknown.forEach((intent, i) => {
401
- const view = views[i];
402
- const pair = view === null || view === undefined ? null : pairOf(view.data);
403
- if (pair !== null) {
404
- created.set(intent, pair);
405
- }
406
- });
407
- const matching = fills
408
- .filter((f) => f.amountIn > 0n && created.get(f.intent)?.inputMint === inputMint && created.get(f.intent)?.outputMint === outputMint)
409
- .slice(0, ESTIMATE_FILLS);
770
+ const matching = await recentFills(ctx.transport, inputMint, outputMint);
410
771
  const shown = matching.map((f) => ({
411
772
  sold: formatAmount(f.amountIn, inputToken.decimals),
412
773
  received: formatAmount(f.delivered, outputToken.decimals),
@@ -417,17 +778,18 @@ const walletEstimate = define({
417
778
  if (latest === undefined) {
418
779
  return { fills: shown, next: NO_FILLS };
419
780
  }
420
- const best = matching.reduce((a, b) => (b.delivered * a.amountIn > a.delivered * b.amountIn ? b : a));
781
+ const best = bestOf(matching) ?? latest;
421
782
  const at = (f) => formatAmount((amount * f.delivered) / f.amountIn, outputToken.decimals);
422
- return { fills: shown, receive_at_best: at(best), receive_at_latest: at(latest), next: ESTIMATE_NEXT };
783
+ return { fills: shown, receive_at_best: at(best), receive_at_median: at(medianOf(matching) ?? latest), receive_at_latest: at(latest), next: ESTIMATE_NEXT };
423
784
  },
424
785
  });
425
786
  export const WAIT_STATUS = ["open", "filling", "filled", "cancelled", "expired", "closed"];
787
+ export const UNREAD = `the node could not yet return all of this intent's transactions, so whether it filled is unknown; call ${tool("wallet_wait")} again in a few seconds before acting on it`;
426
788
  export const stillWaiting = (status) => `still ${status}; call ${tool("wallet_wait")} again to keep waiting, or ${tool("wallet_cancel")} to take the escrow back`;
427
789
  const walletWait = define({
428
790
  name: tool("wallet_wait"),
429
791
  title: "Wait for a wallet intent",
430
- description: `Wait until an intent of this server's wallet is filled, cancelled or expired, or until within seconds pass, then say which and, for a fill, how much the wallet received. Use it after sending instead of asking the user to check again; call it again while the status is still open.`,
792
+ description: `Wait until an intent of this server's wallet is filled, cancelled or expired, or until within seconds pass, then say which and, for a fill, how much it delivered to this wallet or to the pay_to it named. Use it after sending instead of asking the user to check again; call it again while the status is still open.`,
431
793
  effect: "read",
432
794
  input: object({
433
795
  nonce: amount("the intent's nonce, from the send or wallet_intents"),
@@ -437,7 +799,7 @@ const walletWait = define({
437
799
  intent: account(),
438
800
  status: choice(WAIT_STATUS, "closed means the account is gone and its recent transactions name no fill, cancel or expiry"),
439
801
  waited: integer(0, WAIT_MAX, "seconds waited"),
440
- received: optional(text("whole tokens the wallet received from fills")),
802
+ received: optional(text("whole tokens the fills delivered, to this wallet or the pay_to it named")),
441
803
  token: optional(text("the token received")),
442
804
  signature: optional(text("the fill's transaction")),
443
805
  next: optional(text()),
@@ -448,6 +810,7 @@ const walletWait = define({
448
810
  const [intent] = await findIntentPda({ owner, nonce: input.nonce });
449
811
  const within = input.within ?? WAIT_DEFAULT;
450
812
  const fresh = unmemoized(ctx.transport);
813
+ const deadline = wallet.now() + BigInt(within);
451
814
  let waited = 0;
452
815
  let pair = null;
453
816
  let status = "closed";
@@ -460,7 +823,7 @@ const walletWait = define({
460
823
  const decoded = getIntentDecoder().decode(view.data);
461
824
  pair = { inputMint: decoded.inputMint, outputMint: decoded.outputMint };
462
825
  status = STATUS[decoded.status] ?? "open";
463
- if ((status !== "open" && status !== "filling") || waited >= within || !(await wallet.sleep(1))) {
826
+ if ((status !== "open" && status !== "filling") || waited >= within || wallet.now() >= deadline || !(await wallet.sleep(1))) {
464
827
  break;
465
828
  }
466
829
  waited += 1;
@@ -474,7 +837,8 @@ const walletWait = define({
474
837
  const history = await engineHistory(ctx.transport, WAIT_SCAN, intent);
475
838
  const fills = history.fills.filter((f) => f.intent === intent);
476
839
  if (fills.length === 0) {
477
- return { intent, status: status === "closed" ? (history.ended.get(intent) ?? status) : status, waited };
840
+ const ended = status === "closed" ? (history.ended.get(intent) ?? status) : status;
841
+ return { intent, status: ended, waited, ...(ended === "closed" && history.unread > 0 ? { next: UNREAD } : {}) };
478
842
  }
479
843
  pair ??= history.created.get(intent) ?? null;
480
844
  const decimals = pair === null ? undefined : (await mintOf(ctx.transport, pair.outputMint)).decimals;
@@ -488,13 +852,85 @@ const walletWait = define({
488
852
  };
489
853
  },
490
854
  });
855
+ export const NOT_RELEASED = `no release of this escrow is among its recent transactions; ${tool("wallet_wait")} or ${tool("wallet_intents")} shows whether it is still open`;
856
+ const walletReceipt = define({
857
+ name: tool("wallet_receipt"),
858
+ title: "Check an escrow's release",
859
+ description: `Look up whether an escrow made with ${tool("wallet_escrow")} was released: to whom, for how much, by which attestor, and which delivered work the release recorded. Give sha256, the hash of the work you received, to check it is the work that was paid for. It reads the escrow's own transactions and sends nothing.`,
860
+ effect: "read",
861
+ input: object({
862
+ owner: optional(account("the wallet that made the escrow; default this server's wallet")),
863
+ nonce: amount("the escrow intent's nonce"),
864
+ sha256: optional(text("the sha256, as 64 hex digits, of the work you received, to compare with the one the release recorded")),
865
+ }),
866
+ output: object({
867
+ intent: account(),
868
+ released: flag(),
869
+ paid_to: optional(account("the wallet the release paid")),
870
+ payee: optional(account("the token account the release paid")),
871
+ paid: optional(text("whole tokens the payee received")),
872
+ attestor: optional(account()),
873
+ result: optional(amount()),
874
+ signature: optional(text("the release's transaction")),
875
+ delivered_sha256: optional(text("the sha256 the release recorded, if any")),
876
+ matches: optional(flag("whether sha256 equals the recorded one")),
877
+ next: optional(text()),
878
+ }),
879
+ run: async (ctx, input) => {
880
+ const owner = input.owner ?? (await signerOf(ctx)).address;
881
+ const wanted = input.sha256 === undefined ? undefined : sha256Of(input.sha256, "sha256");
882
+ const [intent] = await findIntentPda({ owner, nonce: input.nonce });
883
+ const transactions = await ctx.transport.engineTransactions(WAIT_SCAN, intent);
884
+ let mint;
885
+ for (const tx of transactions) {
886
+ for (const event of tx.emitted.map(decodeEvent)) {
887
+ const fields = (event?.fields ?? {});
888
+ if (event?.name === "IntentCreated" && fields["intent"] === intent) {
889
+ mint = fields["inputMint"];
890
+ }
891
+ }
892
+ }
893
+ for (const tx of transactions) {
894
+ if (tx.failed) {
895
+ continue;
896
+ }
897
+ const release = tx.emitted.map(decodeEvent).find((event) => event?.name === "IntentAttested" && event.fields["intent"] === intent);
898
+ if (release === undefined || release === null) {
899
+ continue;
900
+ }
901
+ const fields = release.fields;
902
+ const payee = fields["payee"];
903
+ const held = await ctx.transport.getAccount(payee);
904
+ mint ??= held === null || held.data.length < 64 ? undefined : getAddressDecoder().decode(held.data.subarray(0, 32));
905
+ const decimals = mint === undefined ? undefined : (await mintOf(ctx.transport, mint)).decimals;
906
+ const recorded = (tx.memos ?? []).map((memo) => DELIVERY_MEMO.exec(memo)?.[1]).find((hash) => hash !== undefined);
907
+ return {
908
+ intent,
909
+ released: true,
910
+ ...(held === null || held.data.length < 64 ? {} : { paid_to: getAddressDecoder().decode(held.data.subarray(32, 64)) }),
911
+ payee,
912
+ paid: formatAmount(fields["net"], decimals),
913
+ attestor: fields["attestor"],
914
+ result: fields["result"],
915
+ signature: tx.signature,
916
+ ...(recorded === undefined ? {} : { delivered_sha256: recorded }),
917
+ ...(wanted === undefined ? {} : { matches: wanted === recorded }),
918
+ };
919
+ }
920
+ return { intent, released: false, next: NOT_RELEASED };
921
+ },
922
+ });
491
923
  export const WALLET_ACTIONS = [
492
924
  walletSetup,
493
925
  walletBalance,
494
926
  walletEstimate,
495
927
  walletSwap,
496
928
  walletAuction,
929
+ walletRecurring,
930
+ walletEscrow,
931
+ walletAttest,
497
932
  walletWait,
933
+ walletReceipt,
498
934
  walletIntents,
499
935
  walletCancel,
500
936
  ];