@intent-engine/cli 0.1.10 → 0.1.14

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,18 +1,28 @@
1
- import { parseAmount } from "@intent-engine/core";
2
- import { chainTime, CLOCK_SYSVAR, mintOf } from "../accounts.js";
1
+ import { attestedFillMessage, buildFillAttested, decodeEvent, decodeParams, feeBpsFor, findIntentPda, formatAmount, getIntentDecoder, IntentStatus, Kind, parseAmount, signEd25519Instruction, splitFees, WARN_ATTESTOR, } from "@intent-engine/core";
2
+ import { chainTime, CLOCK_SYSVAR, loadConfig, mintOf } from "../accounts.js";
3
3
  import { ENV_KEYPAIR, WALLET_NOT_MAINNET } from "../args.js";
4
4
  import { execute } from "../flows.js";
5
- import { tokenNamed } from "../tokens.js";
5
+ import { NATIVE_MINT, TOKEN_NAMES, tokenNamed } from "../tokens.js";
6
+ import { neverLanded, unmemoized } from "../transport.js";
6
7
  import { balances, defaultMints, FAUCET, PUBLIC_FAUCET, setup, withSettings } from "../wallet.js";
7
8
  import { define } from "./actions.js";
8
- import { MAX_EXPIRES_IN, MIN_EXPIRES_IN, prepareCreate } from "./create.js";
9
+ import { MAX_EXPIRES_IN, MIN_EXPIRES_IN, prepareCreate, WRAPPED } from "./create.js";
9
10
  import { tool } from "./names.js";
10
- import { AgentRefusal } from "./problems.js";
11
+ import { AgentRefusal, problemOf } from "./problems.js";
11
12
  import { listIntents } from "./read.js";
12
- import { InvalidInput, account, amount, choice, flag, integer, list, object, optional, text } from "./schema.js";
13
- import { orderSchema } from "./shapes.js";
13
+ import { InvalidInput, account, amount, choice, flag, integer, list, object, optional, text, time } from "./schema.js";
14
+ import { orderSchema, preparedView } from "./shapes.js";
15
+ import { tokenAccountIfMissing, walletRecipient } from "./owner.js";
16
+ import { prepare } from "./prepare.js";
14
17
  import { prepareCancel } from "./settle.js";
15
18
  import { STATUS } from "../accounts.js";
19
+ export const walletGuard = (limits) => ({ limits, sales: [] });
20
+ export const SALE_WINDOW = 3600n;
21
+ export const ESTIMATE_SCAN = 12;
22
+ export const ESTIMATE_FILLS = 5;
23
+ export const WAIT_DEFAULT = 30;
24
+ export const WAIT_MAX = 40;
25
+ export const WAIT_SCAN = 10;
16
26
  export const DEFAULT_EXPIRES_IN = 3_600;
17
27
  export const LANDING_SECONDS = 10;
18
28
  export const MAINNET_GENESIS = "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d";
@@ -20,7 +30,7 @@ export const WALLET_NOTICE = [
20
30
  "Test network only: this wallet works on Solana devnet, testnet or localnet and refuses mainnet. Its tokens have no value.",
21
31
  "Your key stays on this machine: setup makes one unless a keypair is already configured, and names its file. Only signed transactions leave it.",
22
32
  "This server talks to no one but the RPC endpoint it was started with.",
23
- "Nothing moves until you approve: swaps, auctions and cancels only preview until you say yes.",
33
+ "Nothing moves until you approve: swaps, auctions, escrows, releases and cancels only preview until you say yes.",
24
34
  "Do not send real funds to this wallet or use its key anywhere else.",
25
35
  ];
26
36
  export const walletEmpty = (address) => `the wallet ${address} holds no SOL yet; request devnet SOL for it at ${FAUCET} or ${PUBLIC_FAUCET}, then try again`;
@@ -86,6 +96,62 @@ function raw(tokens, decimals, path) {
86
96
  throw new InvalidInput([{ path, message: error instanceof Error ? error.message : String(error) }]);
87
97
  }
88
98
  }
99
+ const nameOf = (mint) => TOKEN_NAMES[mint] ?? mint;
100
+ const limited = (guard) => guard.limits.perTrade.size + guard.limits.perHour.size > 0;
101
+ export function limitLines(limits) {
102
+ const mints = [...new Set([...limits.perTrade.keys(), ...limits.perHour.keys()])];
103
+ if (mints.length === 0) {
104
+ return [];
105
+ }
106
+ return [
107
+ "Whoever started this server set sell limits that no tool call can change:",
108
+ ...mints.map((mint) => {
109
+ const caps = [
110
+ ...(limits.perTrade.has(mint) ? [`${limits.perTrade.get(mint)} per trade`] : []),
111
+ ...(limits.perHour.has(mint) ? [`${limits.perHour.get(mint)} per hour`] : []),
112
+ ];
113
+ return `- ${nameOf(mint)}: at most ${caps.join(" and ")}`;
114
+ }),
115
+ "It sells no other token. Plan trades within these limits and tell the user when a request exceeds them.",
116
+ ];
117
+ }
118
+ function capOf(text, decimals, mint) {
119
+ try {
120
+ return parseAmount(text, decimals);
121
+ }
122
+ catch {
123
+ 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`);
124
+ }
125
+ }
126
+ function checkSale(guard, mint, decimals, amount, now) {
127
+ if (!limited(guard)) {
128
+ return;
129
+ }
130
+ const { perTrade, perHour } = guard.limits;
131
+ const name = nameOf(mint);
132
+ if (!perTrade.has(mint) && !perHour.has(mint)) {
133
+ const allowed = [...new Set([...perTrade.keys(), ...perHour.keys()])].map(nameOf).join(", ");
134
+ throw new AgentRefusal("WalletTokenNotAllowed", `this server sells only ${allowed}, not ${name}; its limits were set when it started`);
135
+ }
136
+ const trade = perTrade.get(mint);
137
+ if (trade !== undefined && amount > capOf(trade, decimals, mint)) {
138
+ 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`);
139
+ }
140
+ checkHour(guard, mint, decimals, amount, now);
141
+ }
142
+ function checkHour(guard, mint, decimals, amount, now) {
143
+ const hour = guard.limits.perHour.get(mint);
144
+ const name = nameOf(mint);
145
+ if (hour === undefined) {
146
+ return;
147
+ }
148
+ guard.sales = guard.sales.filter((s) => s.at > now - SALE_WINDOW);
149
+ const used = guard.sales.filter((s) => s.mint === mint).reduce((sum, s) => sum + s.amount, 0n);
150
+ const cap = capOf(hour, decimals, mint);
151
+ if (used + amount > cap) {
152
+ 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)}`);
153
+ }
154
+ }
89
155
  async function sent(ctx, signer, view, send, call) {
90
156
  for (const undo of call.undo.splice(0)) {
91
157
  undo();
@@ -139,7 +205,7 @@ export const walletBalance = define({
139
205
  return balances(ctx.transport, owner, mints);
140
206
  },
141
207
  });
142
- const offerOutput = object({
208
+ const offerFields = {
143
209
  intent: account(),
144
210
  nonce: amount(),
145
211
  summary: list(text(), 24),
@@ -147,7 +213,8 @@ const offerOutput = object({
147
213
  sent: flag(),
148
214
  signature: optional(text()),
149
215
  next: optional(text()),
150
- });
216
+ };
217
+ const offerOutput = object(offerFields);
151
218
  async function offered(ctx, call, input, terms) {
152
219
  const wallet = access(ctx);
153
220
  const signer = await signerOf(ctx);
@@ -162,14 +229,57 @@ async function offered(ctx, call, input, terms) {
162
229
  mintOf(ctx.transport, outputMint),
163
230
  chainTime(ctx.transport),
164
231
  ]);
165
- const view = (await prepareCreate.run(ctx, { owner: signer.address, input_mint: inputMint, output_mint: outputMint, ...terms(inputToken, outputToken, now) }, call));
232
+ const made = await terms(inputToken, outputToken, now, inputMint, outputMint);
233
+ checkSale(wallet.limits, inputMint, inputToken.decimals, made.order.amount_in, now);
234
+ 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));
166
235
  const { intent, nonce, summary, warnings, prepared } = view;
167
- return sent(ctx, signer, { intent, nonce, summary, warnings, prepared }, input.send, call);
236
+ const sold = made.order.amount_in;
237
+ const guard = wallet.limits;
238
+ checkSale(guard, inputMint, inputToken.decimals, sold, now);
239
+ if (input.send !== true || !limited(guard)) {
240
+ return sent(ctx, signer, { intent, nonce, summary, warnings, prepared }, input.send, call);
241
+ }
242
+ const sale = { mint: inputMint, at: now, amount: sold };
243
+ guard.sales.push(sale);
244
+ try {
245
+ return await sent(ctx, signer, { intent, nonce, summary, warnings, prepared }, input.send, call);
246
+ }
247
+ catch (error) {
248
+ if (neverLanded(error)) {
249
+ guard.sales = guard.sales.filter((s) => s !== sale);
250
+ }
251
+ throw error;
252
+ }
253
+ }
254
+ export const SWAP_FALLS_OVER = 120;
255
+ 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
+ export const SWAP_HEADROOM_BPS = 200n;
257
+ export const SWAP_BLIND_BPS = 2500n;
258
+ async function recentFills(transport, inputMint, outputMint) {
259
+ const { created, fills } = await engineHistory(transport, ESTIMATE_SCAN);
260
+ const unknown = [...new Set(fills.map((f) => f.intent).filter((intent) => !created.has(intent)))];
261
+ const views = unknown.length === 0 ? [] : await transport.getAccounts(unknown);
262
+ unknown.forEach((intent, i) => {
263
+ const view = views[i];
264
+ const pair = view === null || view === undefined ? null : pairOf(view.data);
265
+ if (pair !== null) {
266
+ created.set(intent, pair);
267
+ }
268
+ });
269
+ return fills
270
+ .filter((f) => f.amountIn > 0n && created.get(f.intent)?.inputMint === inputMint && created.get(f.intent)?.outputMint === outputMint)
271
+ .slice(0, ESTIMATE_FILLS);
272
+ }
273
+ const bestOf = (fills) => fills.reduce((a, b) => (a === undefined || b.delivered * a.amountIn > a.delivered * b.amountIn ? b : a), undefined);
274
+ 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;
168
278
  }
169
279
  const walletSwap = define({
170
280
  name: tool("wallet_swap"),
171
281
  title: "Swap from the wallet",
172
- 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.",
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.`,
173
283
  effect: "submit",
174
284
  repeats: true,
175
285
  input: object({
@@ -177,18 +287,282 @@ const walletSwap = define({
177
287
  buy: text("SOL, TEST or a mint address"),
178
288
  amount: text("whole tokens to sell, such as 0.05"),
179
289
  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")),
291
+ falls_over: optional(integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, `seconds the ask takes to fall to min_receive; default ${SWAP_FALLS_OVER}`)),
292
+ exact: optional(flag("true asks min_receive from the start, with no falling ask")),
293
+ pay_to: optional(account(PAY_TO)),
180
294
  expires_in: optional(integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, `least seconds the offer stays open once sent; default ${DEFAULT_EXPIRES_IN}`)),
181
295
  send: optional(flag("true signs and sends; leave out to preview")),
182
296
  }),
297
+ output: object({ ...offerFields, start_receive: optional(text("whole tokens asked when the offer lands; pass it back when sending")) }),
298
+ run: async (ctx, input, call) => {
299
+ let opening;
300
+ const result = await offered(ctx, call, input, async (sold, bought, now, inputMint, outputMint) => {
301
+ const amountIn = raw(input.amount, sold.decimals, "amount");
302
+ const floor = raw(input.min_receive, bought.decimals, "min_receive");
303
+ const expiresIn = BigInt(input.expires_in ?? DEFAULT_EXPIRES_IN);
304
+ const ask = input.exact === true
305
+ ? floor
306
+ : input.start_receive === undefined
307
+ ? openingAsk(await recentFills(ctx.transport, inputMint, outputMint), amountIn, floor)
308
+ : raw(input.start_receive, bought.decimals, "start_receive");
309
+ if (ask <= floor) {
310
+ return { order: { kind: "swap", amount_in: amountIn, min_out: floor }, expires_at: now + expiresIn + BigInt(LANDING_SECONDS) };
311
+ }
312
+ opening = formatAmount(ask, bought.decimals);
313
+ const start = now + BigInt(LANDING_SECONDS);
314
+ const falls = BigInt(input.falls_over ?? SWAP_FALLS_OVER);
315
+ return {
316
+ order: { kind: "dutch", amount_in: amountIn, start_out: ask, end_out: floor, start_time: start, end_time: start + falls },
317
+ expires_at: start + (expiresIn > falls ? expiresIn : falls),
318
+ };
319
+ });
320
+ return opening === undefined ? result : { ...result, start_receive: opening };
321
+ },
322
+ });
323
+ export const ESCROW_EXPIRES_IN = 86_400;
324
+ export const RECORD_MINT_NEEDED = "selling SOL on this RPC needs record_mint: any other token's mint, which only labels the escrow";
325
+ function recordedMint(sell, url, chosen) {
326
+ if (chosen !== undefined) {
327
+ return mintNamed(chosen, url, "record_mint");
328
+ }
329
+ if (sell !== NATIVE_MINT) {
330
+ return NATIVE_MINT;
331
+ }
332
+ const test = tokenNamed("TEST", url);
333
+ if (test instanceof Error) {
334
+ throw new InvalidInput([{ path: "record_mint", message: RECORD_MINT_NEEDED }]);
335
+ }
336
+ return test;
337
+ }
338
+ const walletEscrow = define({
339
+ name: tool("wallet_escrow"),
340
+ 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.`,
342
+ effect: "submit",
343
+ repeats: true,
344
+ input: object({
345
+ sell: text("SOL, TEST or a mint address: the token to pay with"),
346
+ amount: text("whole tokens to escrow, such as 0.05"),
347
+ attestor: account("the wallet whose signature alone releases the escrow"),
348
+ min_result: optional(amount("least result the attestor may attest; default 1")),
349
+ max_result: optional(amount("greatest result the attestor may attest; default min_result")),
350
+ expires_in: optional(integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, `least seconds the escrow stays open once sent; default ${ESCROW_EXPIRES_IN}`)),
351
+ 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")),
352
+ send: optional(flag("true signs and sends; leave out to preview")),
353
+ }),
183
354
  output: offerOutput,
184
- run: async (ctx, input, call) => offered(ctx, call, input, (sold, bought, now) => ({
185
- order: {
186
- kind: "swap",
187
- amount_in: raw(input.amount, sold.decimals, "amount"),
188
- min_out: raw(input.min_receive, bought.decimals, "min_receive"),
189
- },
190
- expires_at: now + BigInt((input.expires_in ?? DEFAULT_EXPIRES_IN) + LANDING_SECONDS),
191
- })),
355
+ run: async (ctx, input, call) => {
356
+ const wallet = access(ctx);
357
+ const sold = mintNamed(input.sell, wallet.url, "sell");
358
+ const least = input.min_result ?? 1n;
359
+ const most = input.max_result ?? least;
360
+ if (most < least) {
361
+ throw new InvalidInput([{ path: "max_result", message: "must be at least min_result" }]);
362
+ }
363
+ return offered(ctx, call, { sell: sold, buy: recordedMint(sold, wallet.url, input.record_mint), send: input.send }, (token, _, now) => ({
364
+ order: { kind: "attested", amount_in: raw(input.amount, token.decimals, "amount"), min_result: least, max_result: most, attestor: input.attestor },
365
+ expires_at: now + BigInt((input.expires_in ?? ESCROW_EXPIRES_IN) + LANDING_SECONDS),
366
+ }));
367
+ },
368
+ });
369
+ export const notAttestor = (attestor) => `this intent names ${attestor} as its attestor, not this server's wallet; only that key can release it`;
370
+ const walletAttest = define({
371
+ name: tool("wallet_attest"),
372
+ 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.`,
374
+ effect: "submit",
375
+ input: object({
376
+ owner: account("the wallet that made the escrow"),
377
+ nonce: amount("the escrow intent's nonce"),
378
+ pay_to: account("the wallet to pay"),
379
+ result: optional(amount("the result to attest, between the intent's min_result and max_result; default min_result")),
380
+ send: optional(flag("true signs the attestation and settles; leave out to preview")),
381
+ }),
382
+ output: object({
383
+ intent: account(),
384
+ pay_to: account(),
385
+ payee: account("pay_to's token account that receives the escrow"),
386
+ paid: text("whole tokens pay_to receives"),
387
+ fee: text("whole tokens kept as fees"),
388
+ result: amount(),
389
+ summary: list(text(), 8),
390
+ warnings: list(text(), 8),
391
+ sent: flag(),
392
+ signature: optional(text()),
393
+ next: optional(text()),
394
+ }),
395
+ run: async (ctx, input, call) => {
396
+ const signer = await signerOf(ctx);
397
+ const [intent] = await findIntentPda({ owner: input.owner, nonce: input.nonce });
398
+ const [view, { config }] = await Promise.all([ctx.transport.getAccount(intent), loadConfig(ctx.transport)]);
399
+ if (view === null) {
400
+ throw new AgentRefusal("NotFound", `no intent ${intent}; it was settled, cancelled and closed, or never made`);
401
+ }
402
+ const held = getIntentDecoder().decode(view.data);
403
+ const params = decodeParams(held.kind, Uint8Array.from(held.params));
404
+ if (params.kind !== Kind.AttestedResult) {
405
+ throw new AgentRefusal("KindMismatch", "this intent is not an attested escrow");
406
+ }
407
+ if (params.attestor !== signer.address) {
408
+ throw new AgentRefusal("Unauthorized", notAttestor(params.attestor));
409
+ }
410
+ if (held.status !== IntentStatus.Open) {
411
+ throw new AgentRefusal("InvalidTransition", `this escrow is ${STATUS[held.status] ?? "not open"}, so it can no longer be released`);
412
+ }
413
+ if (held.expiresAt <= (await chainTime(ctx.transport))) {
414
+ throw new AgentRefusal("IntentExpired", "this escrow has expired; its owner gets it back instead");
415
+ }
416
+ const result = input.result ?? params.minResult;
417
+ if (result < params.minResult || result > params.maxResult) {
418
+ throw new InvalidInput([{ path: "result", message: `must be between ${params.minResult} and ${params.maxResult}` }]);
419
+ }
420
+ await walletRecipient(ctx.transport, input.pay_to, "pay_to");
421
+ const token = await mintOf(ctx.transport, held.inputMint);
422
+ const payee = await tokenAccountIfMissing(ctx.transport, signer, input.pay_to, held.inputMint, token.tokenProgram);
423
+ const amountIn = held.escrowed - held.filled;
424
+ const maxFeeBps = feeBpsFor(config, held.kind) + held.partnerBps;
425
+ const shares = splitFees(amountIn, feeBpsFor(config, held.kind), held.partnerBps, held.partnerCutBps);
426
+ const treasury = shares.protocol > 0n
427
+ ? await tokenAccountIfMissing(ctx.transport, signer, config.feeRecipient, held.inputMint, token.tokenProgram)
428
+ : { create: [] };
429
+ const partner = shares.partner > 0n ? await tokenAccountIfMissing(ctx.transport, signer, held.partner, held.inputMint, token.tokenProgram) : { create: [] };
430
+ const message = await attestedFillMessage(signer.address, {
431
+ domain: Uint8Array.from(config.domain),
432
+ intent,
433
+ payee: payee.address,
434
+ amountIn,
435
+ result,
436
+ filled: held.filled,
437
+ revision: held.revision,
438
+ maxFeeBps,
439
+ });
440
+ const settle = await buildFillAttested({
441
+ solver: signer,
442
+ owner: input.owner,
443
+ nonce: input.nonce,
444
+ inputMint: held.inputMint,
445
+ inputTokenProgram: token.tokenProgram,
446
+ payee: payee.address,
447
+ ...(shares.protocol > 0n ? { feeRecipient: config.feeRecipient } : {}),
448
+ ...(held.partnerBps === 0 ? {} : { partner: held.partner }),
449
+ amountIn,
450
+ result,
451
+ maxFeeBps,
452
+ });
453
+ const name = TOKEN_NAMES[held.inputMint] ?? held.inputMint;
454
+ const paid = formatAmount(shares.net, token.decimals);
455
+ const setup = [...payee.create, ...treasury.create, ...partner.create];
456
+ const prepared = input.send === true
457
+ ? preparedView(await prepare(ctx.transport, [...setup, await signEd25519Instruction(signer, message), settle], signer.address))
458
+ : undefined;
459
+ const view2 = {
460
+ intent,
461
+ pay_to: input.pay_to,
462
+ payee: payee.address,
463
+ paid,
464
+ fee: formatAmount(shares.protocol + shares.partner, token.decimals),
465
+ result,
466
+ summary: [
467
+ `Pays: ${paid} of ${name} to ${input.pay_to} from ${input.owner}'s escrow${held.inputMint === NATIVE_MINT ? WRAPPED : ""}`,
468
+ `Attests: result ${result}, signed by this server's wallet as the escrow's attestor`,
469
+ ...(payee.create.length === 0 ? [] : [`Setup: creates ${input.pay_to}'s ${name} account, paid by this wallet`]),
470
+ ...(treasury.create.length === 0 ? [] : [`Setup: creates the engine treasury's ${name} account for the fee, paid by this wallet`]),
471
+ ...(partner.create.length === 0 ? [] : [`Setup: creates the partner ${held.partner}'s ${name} account for its fee, paid by this wallet`]),
472
+ ],
473
+ warnings: [WARN_ATTESTOR],
474
+ prepared,
475
+ };
476
+ return sent(ctx, signer, view2, input.send, call);
477
+ },
478
+ });
479
+ 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`;
481
+ export const MAX_EVERY = 30 * 24 * 60 * 60;
482
+ const walletRecurring = define({
483
+ name: tool("wallet_recurring"),
484
+ 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.`,
486
+ effect: "submit",
487
+ repeats: true,
488
+ input: object({
489
+ sell: text("SOL, TEST or a mint address"),
490
+ buy: text("SOL, TEST or a mint address"),
491
+ amount: text("whole tokens each order sells, such as 0.05"),
492
+ min_receive: text("least whole tokens each order receives"),
493
+ every: integer(MIN_EXPIRES_IN, MAX_EVERY, "seconds between one order opening and the next"),
494
+ 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")),
496
+ 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
+ pay_to: optional(account(PAY_TO)),
498
+ send: optional(flag("true signs and sends every order; leave out to preview")),
499
+ }),
500
+ output: object({
501
+ 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"),
503
+ warnings: list(text(), 16),
504
+ start_receive: text("whole tokens each order asks when it opens; pass it back when sending"),
505
+ sent: flag(),
506
+ next: optional(text()),
507
+ }),
508
+ run: async (ctx, input, call) => {
509
+ const wallet = access(ctx);
510
+ const inputMint = mintNamed(input.sell, wallet.url, "sell");
511
+ const outputMint = mintNamed(input.buy, wallet.url, "buy");
512
+ const [inputToken, outputToken, now] = await Promise.all([
513
+ mintOf(ctx.transport, inputMint),
514
+ mintOf(ctx.transport, outputMint),
515
+ chainTime(ctx.transport),
516
+ ]);
517
+ const amountIn = raw(input.amount, inputToken.decimals, "amount");
518
+ const floor = raw(input.min_receive, outputToken.decimals, "min_receive");
519
+ const ask = input.start_receive === undefined
520
+ ? openingAsk(await recentFills(ctx.transport, inputMint, outputMint), amountIn, floor)
521
+ : raw(input.start_receive, outputToken.decimals, "start_receive");
522
+ 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" }]);
524
+ }
525
+ checkSale(wallet.limits, inputMint, inputToken.decimals, amountIn, now);
526
+ checkHour(wallet.limits, inputMint, inputToken.decimals, amountIn * BigInt(input.times), now);
527
+ const falls = BigInt(input.falls_over ?? SWAP_FALLS_OVER);
528
+ const every = BigInt(input.every);
529
+ const life = falls > every ? falls : every;
530
+ const opens = Array.from({ length: input.times }, (_, k) => now + BigInt(LANDING_SECONDS) + every * BigInt(k));
531
+ const terms = (open) => () => ({
532
+ order: { kind: "dutch", amount_in: amountIn, start_out: ask, end_out: floor, start_time: open, end_time: open + falls },
533
+ expires_at: open + life,
534
+ });
535
+ const shown = { start_receive: formatAmount(ask, outputToken.decimals) };
536
+ const first = (await offered(ctx, call, { ...input, send: input.send }, terms(opens[0])));
537
+ 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 };
540
+ }
541
+ const orders = [{ opens_at: opens[0], intent: first["intent"], nonce: first["nonce"], signature: first["signature"] }];
542
+ for (const open of opens.slice(1)) {
543
+ try {
544
+ const made = (await offered(ctx, call, { ...input, send: true }, terms(open)));
545
+ orders.push({ opens_at: open, intent: made["intent"], nonce: made["nonce"], signature: made["signature"] });
546
+ }
547
+ catch (error) {
548
+ for (const undo of call.undo.splice(0)) {
549
+ undo();
550
+ }
551
+ const problem = problemOf(error);
552
+ return {
553
+ orders: [...orders, ...opens.slice(orders.length).map((opens_at) => ({ opens_at }))],
554
+ summary: first["summary"],
555
+ warnings: first["warnings"],
556
+ ...shown,
557
+ sent: true,
558
+ next: neverLanded(error)
559
+ ? `${orders.length} of ${input.times} orders were sent; the next failed with ${problem.code}: ${problem.hint}`
560
+ : mayHaveLanded(orders.length, input.times, `${problem.code}: ${problem.hint}`),
561
+ };
562
+ }
563
+ }
564
+ return { orders, summary: first["summary"], warnings: first["warnings"], ...shown, sent: true };
565
+ },
192
566
  });
193
567
  const walletAuction = define({
194
568
  name: tool("wallet_auction"),
@@ -204,6 +578,7 @@ const walletAuction = define({
204
578
  end_receive: text("least whole tokens accepted once the asked amount stops falling"),
205
579
  falls_over: integer(MIN_EXPIRES_IN, MAX_EXPIRES_IN, "seconds the asked amount takes to fall from start_receive to end_receive"),
206
580
  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}`)),
581
+ pay_to: optional(account(PAY_TO)),
207
582
  send: optional(flag("true signs and sends; leave out to preview")),
208
583
  }),
209
584
  output: offerOutput,
@@ -255,5 +630,170 @@ const walletCancel = define({
255
630
  return sent(ctx, signer, view, input.send, call);
256
631
  },
257
632
  });
258
- export const WALLET_ACTIONS = [walletSetup, walletBalance, walletSwap, walletAuction, walletIntents, walletCancel];
633
+ async function engineHistory(transport, limit, of) {
634
+ const created = new Map();
635
+ const fills = [];
636
+ const ended = new Map();
637
+ for (const tx of await transport.engineTransactions(limit, of)) {
638
+ if (tx.failed) {
639
+ continue;
640
+ }
641
+ const begun = new Map();
642
+ for (const event of tx.emitted.map(decodeEvent)) {
643
+ if (event === null) {
644
+ continue;
645
+ }
646
+ const fields = event.fields;
647
+ const intent = fields["intent"];
648
+ if (event.name === "IntentCreated") {
649
+ created.set(intent, { inputMint: fields["inputMint"], outputMint: fields["outputMint"] });
650
+ }
651
+ if (event.name === "FillBegun") {
652
+ begun.set(intent, fields["amountIn"]);
653
+ }
654
+ const amountIn = event.name === "IntentFilled" ? fields["amountIn"] : event.name === "FillEnded" ? begun.get(intent) : undefined;
655
+ if (amountIn !== undefined) {
656
+ fills.push({ intent, amountIn, delivered: fields["delivered"], signature: tx.signature, blockTime: tx.blockTime });
657
+ }
658
+ if (event.name === "IntentCancelled" || event.name === "IntentExpired") {
659
+ ended.set(intent, event.name === "IntentCancelled" ? "cancelled" : "expired");
660
+ }
661
+ }
662
+ }
663
+ return { created, fills, ended };
664
+ }
665
+ function pairOf(data) {
666
+ try {
667
+ const { inputMint, outputMint } = getIntentDecoder().decode(data);
668
+ return { inputMint, outputMint };
669
+ }
670
+ catch {
671
+ return null;
672
+ }
673
+ }
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";
675
+ 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
+ const walletEstimate = define({
677
+ name: tool("wallet_estimate"),
678
+ title: "Estimate a swap from recent fills",
679
+ description: `Estimate what selling an amount of one token for another gets now, from the rates of recent fills of the same pair on this cluster. It reads the engine's last ${ESTIMATE_SCAN} transactions and sends nothing. Use it before ${tool("wallet_swap")} or ${tool("wallet_auction")} to pick min_receive or the auction's start and end.`,
680
+ effect: "read",
681
+ input: object({
682
+ sell: text("SOL, TEST or a mint address"),
683
+ buy: text("SOL, TEST or a mint address"),
684
+ amount: text("whole tokens to sell, such as 0.05"),
685
+ }),
686
+ output: object({
687
+ fills: list(object({
688
+ sold: text("whole tokens of the sold token"),
689
+ received: text("whole tokens the owner received"),
690
+ at: optional(time("when the fill landed")),
691
+ signature: text(),
692
+ }), ESTIMATE_FILLS, "newest first"),
693
+ receive_at_best: optional(text("whole tokens amount would get at the best recent rate")),
694
+ receive_at_latest: optional(text("whole tokens amount would get at the newest fill's rate")),
695
+ next: text(),
696
+ }),
697
+ run: async (ctx, input) => {
698
+ const wallet = await testCluster(ctx);
699
+ const inputMint = mintNamed(input.sell, wallet.url, "sell");
700
+ const outputMint = mintNamed(input.buy, wallet.url, "buy");
701
+ const [inputToken, outputToken] = await Promise.all([mintOf(ctx.transport, inputMint), mintOf(ctx.transport, outputMint)]);
702
+ const amount = raw(input.amount, inputToken.decimals, "amount");
703
+ const matching = await recentFills(ctx.transport, inputMint, outputMint);
704
+ const shown = matching.map((f) => ({
705
+ sold: formatAmount(f.amountIn, inputToken.decimals),
706
+ received: formatAmount(f.delivered, outputToken.decimals),
707
+ ...(f.blockTime === null ? {} : { at: f.blockTime }),
708
+ signature: f.signature,
709
+ }));
710
+ const [latest] = matching;
711
+ if (latest === undefined) {
712
+ return { fills: shown, next: NO_FILLS };
713
+ }
714
+ const best = bestOf(matching) ?? latest;
715
+ 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 };
717
+ },
718
+ });
719
+ export const WAIT_STATUS = ["open", "filling", "filled", "cancelled", "expired", "closed"];
720
+ export const stillWaiting = (status) => `still ${status}; call ${tool("wallet_wait")} again to keep waiting, or ${tool("wallet_cancel")} to take the escrow back`;
721
+ const walletWait = define({
722
+ name: tool("wallet_wait"),
723
+ 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.`,
725
+ effect: "read",
726
+ input: object({
727
+ nonce: amount("the intent's nonce, from the send or wallet_intents"),
728
+ within: optional(integer(1, WAIT_MAX, `most seconds to wait; default ${WAIT_DEFAULT}`)),
729
+ }),
730
+ output: object({
731
+ intent: account(),
732
+ status: choice(WAIT_STATUS, "closed means the account is gone and its recent transactions name no fill, cancel or expiry"),
733
+ waited: integer(0, WAIT_MAX, "seconds waited"),
734
+ received: optional(text("whole tokens the fills delivered, to this wallet or the pay_to it named")),
735
+ token: optional(text("the token received")),
736
+ signature: optional(text("the fill's transaction")),
737
+ next: optional(text()),
738
+ }),
739
+ run: async (ctx, input) => {
740
+ const wallet = access(ctx);
741
+ const owner = (await signerOf(ctx)).address;
742
+ const [intent] = await findIntentPda({ owner, nonce: input.nonce });
743
+ const within = input.within ?? WAIT_DEFAULT;
744
+ const fresh = unmemoized(ctx.transport);
745
+ const deadline = wallet.now() + BigInt(within);
746
+ let waited = 0;
747
+ let pair = null;
748
+ let status = "closed";
749
+ for (;;) {
750
+ const view = await fresh.getAccount(intent);
751
+ if (view === null) {
752
+ status = "closed";
753
+ break;
754
+ }
755
+ const decoded = getIntentDecoder().decode(view.data);
756
+ pair = { inputMint: decoded.inputMint, outputMint: decoded.outputMint };
757
+ status = STATUS[decoded.status] ?? "open";
758
+ if ((status !== "open" && status !== "filling") || waited >= within || wallet.now() >= deadline || !(await wallet.sleep(1))) {
759
+ break;
760
+ }
761
+ waited += 1;
762
+ }
763
+ if (status === "open" || status === "filling") {
764
+ return { intent, status, waited, next: stillWaiting(status) };
765
+ }
766
+ if (status === "cancelled" || status === "expired") {
767
+ return { intent, status, waited };
768
+ }
769
+ const history = await engineHistory(ctx.transport, WAIT_SCAN, intent);
770
+ const fills = history.fills.filter((f) => f.intent === intent);
771
+ if (fills.length === 0) {
772
+ return { intent, status: status === "closed" ? (history.ended.get(intent) ?? status) : status, waited };
773
+ }
774
+ pair ??= history.created.get(intent) ?? null;
775
+ const decimals = pair === null ? undefined : (await mintOf(ctx.transport, pair.outputMint)).decimals;
776
+ return {
777
+ intent,
778
+ status: "filled",
779
+ waited,
780
+ received: formatAmount(fills.reduce((sum, f) => sum + f.delivered, 0n), decimals),
781
+ ...(pair === null ? {} : { token: nameOf(pair.outputMint) }),
782
+ signature: fills[0]?.signature,
783
+ };
784
+ },
785
+ });
786
+ export const WALLET_ACTIONS = [
787
+ walletSetup,
788
+ walletBalance,
789
+ walletEstimate,
790
+ walletSwap,
791
+ walletAuction,
792
+ walletRecurring,
793
+ walletEscrow,
794
+ walletAttest,
795
+ walletWait,
796
+ walletIntents,
797
+ walletCancel,
798
+ ];
259
799
  //# sourceMappingURL=wallet.js.map