@intent-engine/cli 0.1.14 → 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,9 +1,11 @@
1
- import { attestedFillMessage, buildFillAttested, decodeEvent, decodeParams, feeBpsFor, findIntentPda, formatAmount, getIntentDecoder, IntentStatus, Kind, parseAmount, signEd25519Instruction, splitFees, WARN_ATTESTOR, } from "@intent-engine/core";
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";
2
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
7
  import { NATIVE_MINT, TOKEN_NAMES, tokenNamed } from "../tokens.js";
6
- import { neverLanded, unmemoized } from "../transport.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
11
  import { MAX_EXPIRES_IN, MIN_EXPIRES_IN, prepareCreate, WRAPPED } from "./create.js";
@@ -255,6 +257,7 @@ export const SWAP_FALLS_OVER = 120;
255
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";
256
258
  export const SWAP_HEADROOM_BPS = 200n;
257
259
  export const SWAP_BLIND_BPS = 2500n;
260
+ export const SWAP_CAP_BPS = 20000n;
258
261
  async function recentFills(transport, inputMint, outputMint) {
259
262
  const { created, fills } = await engineHistory(transport, ESTIMATE_SCAN);
260
263
  const unknown = [...new Set(fills.map((f) => f.intent).filter((intent) => !created.has(intent)))];
@@ -270,16 +273,21 @@ async function recentFills(transport, inputMint, outputMint) {
270
273
  .filter((f) => f.amountIn > 0n && created.get(f.intent)?.inputMint === inputMint && created.get(f.intent)?.outputMint === outputMint)
271
274
  .slice(0, ESTIMATE_FILLS);
272
275
  }
273
- const bestOf = (fills) => fills.reduce((a, b) => (a === undefined || b.delivered * a.amountIn > a.delivered * b.amountIn ? b : a), undefined);
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)];
274
279
  function openingAsk(fills, amount, floor) {
275
- const best = bestOf(fills);
276
- const ask = best === undefined ? (floor * (10000n + SWAP_BLIND_BPS)) / 10000n : (amount * best.delivered * (10000n + SWAP_HEADROOM_BPS)) / (best.amountIn * 10000n);
277
- return ask > floor ? ask : 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;
278
286
  }
279
287
  const walletSwap = define({
280
288
  name: tool("wallet_swap"),
281
289
  title: "Swap from the wallet",
282
- 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 best recent fill, 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.`,
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.`,
283
291
  effect: "submit",
284
292
  repeats: true,
285
293
  input: object({
@@ -287,7 +295,7 @@ const walletSwap = define({
287
295
  buy: text("SOL, TEST or a mint address"),
288
296
  amount: text("whole tokens to sell, such as 0.05"),
289
297
  min_receive: text("least whole tokens to receive for all of it"),
290
- start_receive: optional(text("whole tokens asked when the offer lands; default a little above the best recent fill")),
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")),
291
299
  falls_over: optional(integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, `seconds the ask takes to fall to min_receive; default ${SWAP_FALLS_OVER}`)),
292
300
  exact: optional(flag("true asks min_receive from the start, with no falling ask")),
293
301
  pay_to: optional(account(PAY_TO)),
@@ -338,7 +346,7 @@ function recordedMint(sell, url, chosen) {
338
346
  const walletEscrow = define({
339
347
  name: tool("wallet_escrow"),
340
348
  title: "Escrow a payment for an attestor to release",
341
- description: `Lock 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. 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.`,
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.`,
342
350
  effect: "submit",
343
351
  repeats: true,
344
352
  input: object({
@@ -366,17 +374,31 @@ const walletEscrow = define({
366
374
  }));
367
375
  },
368
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
+ }
369
389
  export const notAttestor = (attestor) => `this intent names ${attestor} as its attestor, not this server's wallet; only that key can release it`;
370
390
  const walletAttest = define({
371
391
  name: tool("wallet_attest"),
372
392
  title: "Release an escrow as its attestor",
373
- 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, 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. Without send it only previews and signs nothing; show the user the summary and call again with send: true once they approve.`,
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.`,
374
394
  effect: "submit",
375
395
  input: object({
376
396
  owner: account("the wallet that made the escrow"),
377
397
  nonce: amount("the escrow intent's nonce"),
378
398
  pay_to: account("the wallet to pay"),
379
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")),
380
402
  send: optional(flag("true signs the attestation and settles; leave out to preview")),
381
403
  }),
382
404
  output: object({
@@ -386,6 +408,8 @@ const walletAttest = define({
386
408
  paid: text("whole tokens pay_to receives"),
387
409
  fee: text("whole tokens kept as fees"),
388
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")),
389
413
  summary: list(text(), 8),
390
414
  warnings: list(text(), 8),
391
415
  sent: flag(),
@@ -420,13 +444,21 @@ const walletAttest = define({
420
444
  await walletRecipient(ctx.transport, input.pay_to, "pay_to");
421
445
  const token = await mintOf(ctx.transport, held.inputMint);
422
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
+ }
423
454
  const amountIn = held.escrowed - held.filled;
424
455
  const maxFeeBps = feeBpsFor(config, held.kind) + held.partnerBps;
425
456
  const shares = splitFees(amountIn, feeBpsFor(config, held.kind), held.partnerBps, held.partnerCutBps);
426
457
  const treasury = shares.protocol > 0n
427
458
  ? await tokenAccountIfMissing(ctx.transport, signer, config.feeRecipient, held.inputMint, token.tokenProgram)
428
459
  : { create: [] };
429
- const partner = shares.partner > 0n ? await tokenAccountIfMissing(ctx.transport, signer, held.partner, held.inputMint, token.tokenProgram) : { create: [] };
460
+ const partnerPaid = shares.partner > 0n;
461
+ const partner = partnerPaid ? await tokenAccountIfMissing(ctx.transport, signer, held.partner, held.inputMint, token.tokenProgram) : { create: [] };
430
462
  const message = await attestedFillMessage(signer.address, {
431
463
  domain: Uint8Array.from(config.domain),
432
464
  intent,
@@ -445,7 +477,7 @@ const walletAttest = define({
445
477
  inputTokenProgram: token.tokenProgram,
446
478
  payee: payee.address,
447
479
  ...(shares.protocol > 0n ? { feeRecipient: config.feeRecipient } : {}),
448
- ...(held.partnerBps === 0 ? {} : { partner: held.partner }),
480
+ ...(partnerPaid ? { partner: held.partner } : {}),
449
481
  amountIn,
450
482
  result,
451
483
  maxFeeBps,
@@ -453,8 +485,17 @@ const walletAttest = define({
453
485
  const name = TOKEN_NAMES[held.inputMint] ?? held.inputMint;
454
486
  const paid = formatAmount(shares.net, token.decimals);
455
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
+ }
456
497
  const prepared = input.send === true
457
- ? preparedView(await prepare(ctx.transport, [...setup, await signEd25519Instruction(signer, message), settle], signer.address))
498
+ ? preparedView(await prepare(ctx.transport, [...setup, await signEd25519Instruction(signer, message), settle, ...memo], signer.address))
458
499
  : undefined;
459
500
  const view2 = {
460
501
  intent,
@@ -463,9 +504,12 @@ const walletAttest = define({
463
504
  paid,
464
505
  fee: formatAmount(shares.protocol + shares.partner, token.decimals),
465
506
  result,
507
+ approval,
508
+ ...(delivered === undefined ? {} : { delivered_sha256: delivered }),
466
509
  summary: [
467
510
  `Pays: ${paid} of ${name} to ${input.pay_to} from ${input.owner}'s escrow${held.inputMint === NATIVE_MINT ? WRAPPED : ""}`,
468
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`]),
469
513
  ...(payee.create.length === 0 ? [] : [`Setup: creates ${input.pay_to}'s ${name} account, paid by this wallet`]),
470
514
  ...(treasury.create.length === 0 ? [] : [`Setup: creates the engine treasury's ${name} account for the fee, paid by this wallet`]),
471
515
  ...(partner.create.length === 0 ? [] : [`Setup: creates the partner ${held.partner}'s ${name} account for its fee, paid by this wallet`]),
@@ -477,12 +521,16 @@ const walletAttest = define({
477
521
  },
478
522
  });
479
523
  export const MAX_RECURRING = 12;
480
- 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`;
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;
481
529
  export const MAX_EVERY = 30 * 24 * 60 * 60;
482
530
  const walletRecurring = define({
483
531
  name: tool("wallet_recurring"),
484
532
  title: "Repeat a swap on a schedule",
485
- 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, a little above the best recent fill, 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. 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.`,
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.`,
486
534
  effect: "submit",
487
535
  repeats: true,
488
536
  input: object({
@@ -492,14 +540,14 @@ const walletRecurring = define({
492
540
  min_receive: text("least whole tokens each order receives"),
493
541
  every: integer(MIN_EXPIRES_IN, MAX_EVERY, "seconds between one order opening and the next"),
494
542
  times: integer(2, MAX_RECURRING, "how many orders"),
495
- start_receive: optional(text("whole tokens each order asks when it opens; default a little above the best recent fill")),
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")),
496
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}`)),
497
545
  pay_to: optional(account(PAY_TO)),
498
546
  send: optional(flag("true signs and sends every order; leave out to preview")),
499
547
  }),
500
548
  output: object({
501
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),
502
- summary: list(text(), 24, "the first order"),
550
+ summary: list(text(), 24, "the whole plan, then the first order"),
503
551
  warnings: list(text(), 16),
504
552
  start_receive: text("whole tokens each order asks when it opens; pass it back when sending"),
505
553
  sent: flag(),
@@ -520,7 +568,9 @@ const walletRecurring = define({
520
568
  ? openingAsk(await recentFills(ctx.transport, inputMint, outputMint), amountIn, floor)
521
569
  : raw(input.start_receive, outputToken.decimals, "start_receive");
522
570
  if (ask <= floor) {
523
- throw new InvalidInput([{ path: "start_receive", message: "must be more than min_receive, or the order has no ask to fall" }]);
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
+ ]);
524
574
  }
525
575
  checkSale(wallet.limits, inputMint, inputToken.decimals, amountIn, now);
526
576
  checkHour(wallet.limits, inputMint, inputToken.decimals, amountIn * BigInt(input.times), now);
@@ -533,10 +583,22 @@ const walletRecurring = define({
533
583
  expires_at: open + life,
534
584
  });
535
585
  const shown = { start_receive: formatAmount(ask, outputToken.decimals) };
586
+ const last = opens[opens.length - 1];
536
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
+ ];
537
600
  if (input.send !== true) {
538
- const { summary, warnings, next } = first;
539
- return { orders: opens.map((opens_at) => ({ opens_at })), summary, warnings, ...shown, sent: false, next };
601
+ return { orders: opens.map((opens_at) => ({ opens_at })), summary: plan, warnings, ...shown, sent: false, next: first["next"] };
540
602
  }
541
603
  const orders = [{ opens_at: opens[0], intent: first["intent"], nonce: first["nonce"], signature: first["signature"] }];
542
604
  for (const open of opens.slice(1)) {
@@ -551,17 +613,17 @@ const walletRecurring = define({
551
613
  const problem = problemOf(error);
552
614
  return {
553
615
  orders: [...orders, ...opens.slice(orders.length).map((opens_at) => ({ opens_at }))],
554
- summary: first["summary"],
555
- warnings: first["warnings"],
616
+ summary: plan,
617
+ warnings,
556
618
  ...shown,
557
619
  sent: true,
558
- next: neverLanded(error)
559
- ? `${orders.length} of ${input.times} orders were sent; the next failed with ${problem.code}: ${problem.hint}`
620
+ next: refusedBeforeSending(error)
621
+ ? partlySent(orders.length, input.times, `${problem.code}: ${problem.hint}`)
560
622
  : mayHaveLanded(orders.length, input.times, `${problem.code}: ${problem.hint}`),
561
623
  };
562
624
  }
563
625
  }
564
- return { orders, summary: first["summary"], warnings: first["warnings"], ...shown, sent: true };
626
+ return { orders, summary: plan, warnings, ...shown, sent: true };
565
627
  },
566
628
  });
567
629
  const walletAuction = define({
@@ -612,7 +674,7 @@ const walletIntents = define({
612
674
  const walletCancel = define({
613
675
  name: tool("wallet_cancel"),
614
676
  title: "Cancel a wallet intent",
615
- 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.",
616
678
  effect: "submit",
617
679
  input: object({ nonce: amount("the intent's nonce, from wallet_intents"), send: optional(flag("true signs and sends; leave out to preview")) }),
618
680
  output: object({
@@ -634,7 +696,11 @@ async function engineHistory(transport, limit, of) {
634
696
  const created = new Map();
635
697
  const fills = [];
636
698
  const ended = new Map();
699
+ let unread = 0;
637
700
  for (const tx of await transport.engineTransactions(limit, of)) {
701
+ if (tx.unread === true) {
702
+ unread += 1;
703
+ }
638
704
  if (tx.failed) {
639
705
  continue;
640
706
  }
@@ -660,7 +726,7 @@ async function engineHistory(transport, limit, of) {
660
726
  }
661
727
  }
662
728
  }
663
- return { created, fills, ended };
729
+ return { created, fills, ended, unread };
664
730
  }
665
731
  function pairOf(data) {
666
732
  try {
@@ -671,7 +737,7 @@ function pairOf(data) {
671
737
  return null;
672
738
  }
673
739
  }
674
- 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";
675
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`;
676
742
  const walletEstimate = define({
677
743
  name: tool("wallet_estimate"),
@@ -690,7 +756,8 @@ const walletEstimate = define({
690
756
  at: optional(time("when the fill landed")),
691
757
  signature: text(),
692
758
  }), ESTIMATE_FILLS, "newest first"),
693
- 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")),
694
761
  receive_at_latest: optional(text("whole tokens amount would get at the newest fill's rate")),
695
762
  next: text(),
696
763
  }),
@@ -713,15 +780,16 @@ const walletEstimate = define({
713
780
  }
714
781
  const best = bestOf(matching) ?? latest;
715
782
  const at = (f) => formatAmount((amount * f.delivered) / f.amountIn, outputToken.decimals);
716
- 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 };
717
784
  },
718
785
  });
719
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`;
720
788
  export const stillWaiting = (status) => `still ${status}; call ${tool("wallet_wait")} again to keep waiting, or ${tool("wallet_cancel")} to take the escrow back`;
721
789
  const walletWait = define({
722
790
  name: tool("wallet_wait"),
723
791
  title: "Wait for a wallet intent",
724
- 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.`,
725
793
  effect: "read",
726
794
  input: object({
727
795
  nonce: amount("the intent's nonce, from the send or wallet_intents"),
@@ -769,7 +837,8 @@ const walletWait = define({
769
837
  const history = await engineHistory(ctx.transport, WAIT_SCAN, intent);
770
838
  const fills = history.fills.filter((f) => f.intent === intent);
771
839
  if (fills.length === 0) {
772
- 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 } : {}) };
773
842
  }
774
843
  pair ??= history.created.get(intent) ?? null;
775
844
  const decimals = pair === null ? undefined : (await mintOf(ctx.transport, pair.outputMint)).decimals;
@@ -783,6 +852,74 @@ const walletWait = define({
783
852
  };
784
853
  },
785
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
+ });
786
923
  export const WALLET_ACTIONS = [
787
924
  walletSetup,
788
925
  walletBalance,
@@ -793,6 +930,7 @@ export const WALLET_ACTIONS = [
793
930
  walletEscrow,
794
931
  walletAttest,
795
932
  walletWait,
933
+ walletReceipt,
796
934
  walletIntents,
797
935
  walletCancel,
798
936
  ];