@priors/mcp 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,361 @@
1
+ // Stock tokens bought and sold from an agent's own key (docs/STOCK-ZAP-SPEC.md 15: "Agent tools" and "Selling";
2
+ // @priors/mcp's stock_buy and stock_sell behind PRIORS_STOCKS): USDG to one of the zap's pinned Stock Tokens and back,
3
+ // on its pinned Uniswap pools (deployments/stock-zap.4663.json, through sdk/stock-zap.mjs's buildBuy and buildSell),
4
+ // each trade two plain transactions from the account: an approval of exactly the amount, then the exact-input swap
5
+ // paying the account itself, with a minimum out from a fresh quote less the slippage. Its gas is the account's own ETH:
6
+ // never Priors' gas gate, never $PRIORS, never a loan.
7
+ //
8
+ // import { stockQuote, stockBuy, stockSell, openLoansOwed, ELIGIBILITY_STATEMENT } from "./sdk/stock-trade.mjs";
9
+ // const rpc = "https://rpc.mainnet.chain.robinhood.com"; // or a viem client, an ethers provider
10
+ // await stockQuote(rpc, { side: "buy", symbol: "NVDA", amount: 25, account, eligible: true, agentId: 1234 });
11
+ // await stockBuy(rpc, { symbol: "NVDA", amount: 25, eligible: true, agentId: 1234, wallet }); // signs and sends
12
+ // await stockSell(rpc, { symbol: "NVDA", amount: "all", eligible: true, wallet });
13
+ //
14
+ // The zap's limits and the Autopilot's price guards (autopilot/rules.mjs), each refused before anything is signed with a
15
+ // StockTradeError and its `code`:
16
+ // ELIGIBILITY `eligible: true` is not given: the caller's statement, ELIGIBILITY_STATEMENT, the web zap's tick word for
17
+ // word (web/account.html's #as-ok); nothing is read before it
18
+ // PRIORS $PRIORS, by name or address: never
19
+ // NOT_OFFERED a token that is not one of the zap's 30 pinned tokens (the five thin ones included)
20
+ // SLIPPAGE a slippage above the record's cap (2%)
21
+ // AMOUNT a trade under 1 USDG or over 1,000 USDG (a sale by its quote), or over the caller's `maxUsdg`
22
+ // OPEN_LOANS a buy with no `agentId` (the agent whose open loans the USDG must cover; null: the account acts for none)
23
+ // PAUSED, BLOCKED the token, or all 35, paused by the issuer; the account on its block list
24
+ // NO_QUOTE no pinned pool quotes the trade
25
+ // STALE_PRICE Chainlink's price unreadable, its oracle paused, or older than PRICE_MAX_AGE_S (4 h)
26
+ // OFF_PRICE the trade's price more than MAX_DEVIATION_BPS (5%) from Chainlink's, either way
27
+ // IMPACT a price impact at or over the record's stop (3%)
28
+ // MOVED the fresh quote under the caller's `minOut`: past the slippage the caller saw
29
+ // BALANCE more than the account holds
30
+ // KEEP_BACK a buy that would leave less USDG than `agentId`'s open loans owe (less `savedUsdg`, the savings that
31
+ // count, as the MCP's market tools count them), plus `keepUsdg`
32
+ // NO_GAS too little ETH for the trade's transactions
33
+ // A trade's reads are taken at one block. Sending (`wallet`): each step simulated just before it is signed (sdk/pt-usdg.mjs
34
+ // sendCalls: a lost answer is TX_UNCONFIRMED, never a bare error), and after the approval everything is read and planned
35
+ // again on the same pool: a refusal then, or a quote under the first plan's minimum, stops the trade, and the error says
36
+ // the approval stands (its spender pulls only from its caller, so only this account's own swap can use it).
37
+ // `beforeSend(plan)` is called once a plan has passed every check, before anything is signed (a throw stops the trade
38
+ // with nothing sent); `onSend(hash, what, step)` as each step leaves ("approve" or "swap").
39
+ import { decodeFunctionResult, encodeFunctionData, formatUnits, getAddress, isAddress, parseAbi, parseUnits } from "viem";
40
+ import { ZAP, ERC20_ABI, READS_ABI, V3_QUOTER_ABI, V4_QUOTER_ABI, buildBuy, buildSell, impactBps, minOutOf, pinnedPool } from "./stock-zap.mjs";
41
+ import { rpc, sendCalls } from "./pt-usdg.mjs";
42
+ import V2 from "../deployments/4663.v2.json" with { type: "json" };
43
+
44
+ /** The web zap's eligibility tick, word for word (web/account.html's #as-ok, the deposit sheet's and the buy drawer's),
45
+ * less its link to the list (RESTRICTED_URL). `eligible: true` states it. */
46
+ export const ELIGIBILITY_STATEMENT = "I am not a person of the United States, the United Kingdom, Canada or Switzerland, nor of Cuba, Belarus, Iran, North Korea, Russia, Syria, Ukraine, South Sudan, Sudan, Myanmar or Venezuela, nor of the United Arab Emirates, where the offer of stock tokens is restricted, and I am not acting for one.";
47
+ export const RESTRICTED_URL = "https://docs.robinhood.com/rhj/restricted-jurisdictions";
48
+ // the Autopilot's (autopilot/rules.mjs): a price older than this is no price, and a trade this far from it is skipped
49
+ export const PRICE_MAX_AGE_S = 4 * 3600;
50
+ export const MAX_DEVIATION_BPS = 500;
51
+ // the zap's day caps (gas-worker/gate.mjs LIMITS.userStockBuys): a caller that keeps a day's count (the MCP) holds buys,
52
+ // and sales likewise, to this many a UTC day
53
+ export const TRADES_PER_DAY = 5;
54
+ export const PRIORS_TOKEN = getAddress(V2.priors);
55
+ const POOL = getAddress(V2.pool);
56
+ // SHORTCUT: the swap can't be estimated before its approval is mined, so the ETH check takes this ceiling for it, over
57
+ // twice what a pinned pool's swap used on an anvil fork of chain 4663 (2026-10-29). Ceiling: a pool or chain change
58
+ // that makes a swap cost more. Upgrade trigger: a trade that stops for gas after its approval.
59
+ export const SWAP_GAS = 400_000n;
60
+
61
+ const LOAN_T = "(uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)";
62
+ const AGENT_T = "(bool enrolled, bool isRoot, bool defaulted, bool frozen, bool importedFromV1, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 recourseHonored, uint256 childrenDefaulted, uint256 qualifiedRepaid, uint256 dollarSecondsRepaid)";
63
+ const POOL_ABI = parseAbi(["function loansOf(uint256 id) view returns (uint256[])", `function getLoan(uint256 loanId) view returns (${LOAN_T})`, `function getAgent(uint256 id) view returns (${AGENT_T})`]);
64
+ const ORACLE_PAUSED_ABI = parseAbi(["function oraclePaused() view returns (bool)"]);
65
+ const TRANSFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
66
+
67
+ export class StockTradeError extends Error {
68
+ constructor(code, message, extra = {}) { super(message); this.name = "StockTradeError"; this.code = code; Object.assign(this, extra); }
69
+ }
70
+ const no = (side, code, why, extra) => { throw new StockTradeError(code, `stock ${side}: ${why}`, extra); };
71
+ const lc = (a) => String(a).toLowerCase();
72
+ const hex = (n) => `0x${BigInt(n).toString(16)}`;
73
+ const fmt = (units, decimals) => formatUnits(units, decimals);
74
+ const usdg = (units) => `${formatUnits(units, 6)} USDG`;
75
+
76
+ /** A pool in words: "Uniswap v3, 0.05% pool". */
77
+ export const poolLabel = (p) => `Uniswap v${p.v}, ${Number((p.fee / 10_000).toFixed(4))}% pool`;
78
+
79
+ /** The pinned token `symbol` names (a ticker, any case, a leading $ allowed, or its address), or the refusal. */
80
+ export function stockToken(symbol, side = "trade", conf = ZAP) {
81
+ const raw = String(symbol ?? "").trim();
82
+ if (isAddress(raw)) {
83
+ if (lc(raw) === lc(PRIORS_TOKEN)) no(side, "PRIORS", "$PRIORS is never traded here");
84
+ const t = conf.tokens.find((x) => lc(x.token) === lc(raw));
85
+ if (!t) no(side, "NOT_OFFERED", `${getAddress(raw)} is not one of the ${conf.tokens.length} pinned stock tokens`);
86
+ return t;
87
+ }
88
+ const sym = raw.replace(/^\$/, "").toUpperCase();
89
+ if (sym === "PRIORS") no(side, "PRIORS", "$PRIORS is never traded here");
90
+ if (Object.prototype.hasOwnProperty.call(conf.notOffered, sym)) no(side, "NOT_OFFERED", `${sym} is not offered: its pools on Robinhood Chain are too small`);
91
+ const t = conf.bySymbol.get(sym);
92
+ if (!t) no(side, "NOT_OFFERED", `${raw.slice(0, 12) || "no symbol"} is not one of the ${conf.tokens.length} pinned stock tokens`);
93
+ return t;
94
+ }
95
+
96
+ /** `amount` in base units of `decimals`: a bigint is raw; a number or a decimal string is whole tokens. */
97
+ function unitsOf(amount, decimals, side, what) {
98
+ if (typeof amount === "bigint") { if (amount <= 0n) no(side, "AMOUNT", `${what} must be above zero`); return amount; }
99
+ const s = typeof amount === "number" ? String(amount) : String(amount ?? "").trim();
100
+ if (!new RegExp(`^\\d+(\\.\\d{1,${decimals}})?$`).test(s)) no(side, "AMOUNT", `${what} must be a decimal amount with at most ${decimals} decimals`);
101
+ const u = parseUnits(s, decimals);
102
+ if (u <= 0n) no(side, "AMOUNT", `${what} must be above zero`);
103
+ return u;
104
+ }
105
+
106
+ async function blockOf(client) {
107
+ const b = await rpc(client, "eth_getBlockByNumber", ["latest", false]);
108
+ if (!b || b.number == null) throw new StockTradeError("UNREAD", "stock trade: the latest block could not be read");
109
+ return { number: BigInt(b.number), at: Number(BigInt(b.timestamp)) };
110
+ }
111
+ /** One view at `tag`: the decoded result, or throws. */
112
+ async function view(client, tag, address, abi, functionName, args = [], from) {
113
+ const out = await rpc(client, "eth_call", [{ to: address, data: encodeFunctionData({ abi, functionName, args }), ...(from ? { from } : {}) }, tag]);
114
+ return decodeFunctionResult({ abi, functionName, data: typeof out === "string" ? out : out.data });
115
+ }
116
+ const maybe = (p) => p.then((v) => v, () => null);
117
+
118
+ /** What agent `agentId`'s open loans on the pool owe now (principal plus fee of each active loan): { owed, loans:
119
+ * [{ loanId, due, dueAt }] }. The pool's record counts them (activeLoans): none is read for an agent with none, and
120
+ * the loans are read newest first until that many active ones are found (an agent with a long record has hundreds). */
121
+ export async function openLoansOwed(client, agentId, { tag = "latest" } = {}) {
122
+ const id = BigInt(agentId);
123
+ const open = Number((await view(client, tag, POOL, POOL_ABI, "getAgent", [id])).activeLoans);
124
+ const loans = [];
125
+ if (open > 0) {
126
+ const ids = await view(client, tag, POOL, POOL_ABI, "loansOf", [id]);
127
+ for (let i = ids.length - 1; i >= 0 && loans.length < open; i--) {
128
+ const l = await view(client, tag, POOL, POOL_ABI, "getLoan", [ids[i]]);
129
+ if (Number(l.status) === 1) loans.push({ loanId: ids[i], due: l.principal + l.fee, dueAt: Number(l.dueAt) });
130
+ }
131
+ if (loans.length < open) throw new Error(`the pool counts ${open} open loans of agent #${id} and ${loans.length} were found`);
132
+ }
133
+ return { owed: loans.reduce((a, l) => a + l.due, 0n), loans };
134
+ }
135
+
136
+ /** USD value, in USDG units, of `units` of a token at Chainlink's `answer`. */
137
+ const usdOf = (units, answer, t) => (units * BigInt(answer) * 1_000_000n) / (10n ** BigInt(t.decimals) * 10n ** BigInt(t.feedDecimals));
138
+
139
+ /** The side, and the caller's statement: first, so that nothing is read for a caller that has not made it. */
140
+ function stated(o) {
141
+ const side = o.side;
142
+ if (side !== "buy" && side !== "sell") throw new StockTradeError("SIDE", 'stock trade: side is "buy" or "sell"');
143
+ if (o.eligible !== true) no(side, "ELIGIBILITY", `refused: the caller has not stated its eligibility (eligible: true), which states: "${ELIGIBILITY_STATEMENT}" (${RESTRICTED_URL})`);
144
+ return side;
145
+ }
146
+
147
+ /**
148
+ * The plan of one trade, read at one block, every check passed, or the refusal (StockTradeError). o: { side ("buy" |
149
+ * "sell"), symbol, amount (a buy: USDG; a sale: the token, or "all"), account, eligible, slippageBps (default the
150
+ * record's, 1%), minOut (the least the caller accepts, in the token out), agentId (a buy: the agent whose open loans
151
+ * stay covered, or null), savedUsdg, keepUsdg, maxUsdg, pool (a record pool: the trade quotes that one only) }.
152
+ * Returns { side, symbol, name, token, decimals, account, block, at, pool, label, spender, amountIn, out, minOut,
153
+ * slippageBps, impactBps, price, priceAt, priceAge, deviationBps, valueUsdg, held: { usdg, token }, owed, keep,
154
+ * allowance, deadline, calls: [{ to, data, value, what, step }] } (the approval left out when the allowance is already
155
+ * exactly the amount).
156
+ */
157
+ export async function stockTradePlan(client, o = {}, conf = ZAP) {
158
+ const side = stated(o);
159
+ const t = stockToken(o.symbol, side, conf);
160
+ const slip = o.slippageBps ?? conf.defaultSlippageBps;
161
+ if (!(Number.isInteger(slip) && slip > 0 && slip <= conf.maxSlippageBps)) no(side, "SLIPPAGE", `the slippage is at most ${conf.maxSlippageBps / 100}% (${conf.maxSlippageBps} bps)`);
162
+ const cap = o.maxUsdg != null && BigInt(o.maxUsdg) < conf.maxUsdgPerOp ? BigInt(o.maxUsdg) : conf.maxUsdgPerOp;
163
+ let amountIn = null;
164
+ if (side === "buy") {
165
+ amountIn = unitsOf(o.amount, 6, side, "the amount of USDG");
166
+ if (amountIn < conf.minUsdgPerOp) no(side, "AMOUNT", `the smallest trade is ${usdg(conf.minUsdgPerOp)}`);
167
+ if (amountIn > cap) no(side, "AMOUNT", `one trade is at most ${usdg(cap)}`);
168
+ if (o.agentId === undefined) no(side, "OPEN_LOANS", "name agentId, the agent whose open loans this USDG must still cover (null: this account acts for no agent)");
169
+ } else if (o.amount !== "all") amountIn = unitsOf(o.amount, t.decimals, side, `the amount of ${t.symbol}`);
170
+ const minWanted = o.minOut != null ? BigInt(o.minOut) : null;
171
+ if (!o.account || !isAddress(o.account)) throw new StockTradeError("ACCOUNT", `stock ${side}: give the account that signs`);
172
+ const account = getAddress(o.account);
173
+ const forced = o.pool != null ? pinnedPool(t, o.pool) : null;
174
+ if (o.pool != null && !forced) no(side, "NOT_OFFERED", `not a pinned pool of ${t.symbol}`);
175
+
176
+ let b, r;
177
+ try {
178
+ b = await blockOf(client);
179
+ const tag = hex(b.number);
180
+ const [cash, held, paused, allPaused, blocked, round, oraclePaused] = await Promise.all([
181
+ view(client, tag, conf.usdg, ERC20_ABI, "balanceOf", [account]),
182
+ view(client, tag, t.token, ERC20_ABI, "balanceOf", [account]),
183
+ view(client, tag, t.token, READS_ABI, "tokenPaused"),
184
+ view(client, tag, conf.registry, READS_ABI, "paused"),
185
+ view(client, tag, conf.registry, READS_ABI, "isBlocked", [account]),
186
+ maybe(view(client, tag, t.feed, READS_ABI, "latestRoundData")),
187
+ maybe(view(client, tag, t.token, ORACLE_PAUSED_ABI, "oraclePaused")),
188
+ ]);
189
+ r = { tag, cash, held, paused, allPaused, blocked, round, oraclePaused };
190
+ } catch (e) {
191
+ if (e instanceof StockTradeError) throw e;
192
+ throw new StockTradeError("UNREAD", `stock ${side}: the chain could not be read just now (${e?.shortMessage || e?.message || e})`);
193
+ }
194
+ if (r.allPaused) no(side, "PAUSED", "stock tokens are paused by their issuer, so none can be traded right now");
195
+ if (r.paused) no(side, "PAUSED", `${t.symbol} is paused by its issuer, so it can't be traded right now`);
196
+ if (r.blocked) no(side, "BLOCKED", "the stock tokens' issuer has blocked this account");
197
+ if (side === "sell" && amountIn === null) {
198
+ amountIn = r.held;
199
+ if (amountIn === 0n) no(side, "BALANCE", `${account} holds no ${t.symbol}`);
200
+ }
201
+ if (side === "buy" && r.cash < amountIn) no(side, "BALANCE", `this takes ${usdg(amountIn)} and ${account} holds ${usdg(r.cash)}`);
202
+ if (side === "sell" && r.held < amountIn) no(side, "BALANCE", `this sells ${fmt(amountIn, t.decimals)} ${t.symbol} and ${account} holds ${fmt(r.held, t.decimals)}`);
203
+ // Chainlink's price: fresh, unpaused
204
+ const answer = r.round ? r.round[1] : null, priceAt = r.round ? Number(r.round[3]) : null;
205
+ if (!(answer > 0n) || priceAt === null) no(side, "STALE_PRICE", `Chainlink's price of ${t.symbol} can't be read just now`);
206
+ if (r.oraclePaused === true) no(side, "STALE_PRICE", `Chainlink's price of ${t.symbol} is paused by its issuer (a corporate action)`);
207
+ const age = b.at - priceAt;
208
+ if (age > PRICE_MAX_AGE_S) no(side, "STALE_PRICE", `Chainlink's price of ${t.symbol} is ${Math.round(age / 60)} minutes old, over ${PRICE_MAX_AGE_S / 3600} hours (the US market may be closed)`);
209
+
210
+ // each pinned pool's quote (or the one asked), at the same block
211
+ const pools = forced ? [forced] : t.pools;
212
+ const quotes = await Promise.all(pools.map(async (p) => {
213
+ try {
214
+ const out = p.v === 4
215
+ ? (await view(client, r.tag, conf.v4.quoter, V4_QUOTER_ABI, "quoteExactInputSingle", [{ poolKey: p.key, zeroForOne: side === "buy" ? p.zeroForOne : !p.zeroForOne, exactAmount: amountIn, hookData: "0x" }]))[0]
216
+ : (await view(client, r.tag, conf.v3.quoter, V3_QUOTER_ABI, "quoteExactInputSingle", [{ tokenIn: side === "buy" ? conf.usdg : t.token, tokenOut: side === "buy" ? t.token : conf.usdg, amountIn, fee: p.fee, sqrtPriceLimitX96: 0n }]))[0];
217
+ const s0 = await maybe(p.v === 4 ? view(client, r.tag, conf.v4.stateView, READS_ABI, "getSlot0", [p.id]) : view(client, r.tag, p.pool, READS_ABI, "slot0"));
218
+ // the input is token0 for a buy when USDG is (p.zeroForOne), for a sale when the token is
219
+ return { pool: p, out, impactBps: s0 ? impactBps({ usdgIn: amountIn, out, sqrtPriceX96: s0[0], fee: p.fee, usdgIsToken0: side === "buy" ? p.zeroForOne : !p.zeroForOne }) : null };
220
+ } catch (_) { return { pool: p, out: null, impactBps: null }; }
221
+ }));
222
+ const ok = quotes.filter((q) => q.out !== null && q.out > 0n);
223
+ if (!ok.length) no(side, "NO_QUOTE", `no pinned pool quotes ${fmt(amountIn, side === "buy" ? 6 : t.decimals)} ${side === "buy" ? "USDG" : t.symbol} of ${t.symbol} right now`);
224
+ const best = ok.reduce((a, q) => (q.out > a.out ? q : a));
225
+ if (best.impactBps !== null && best.impactBps >= conf.impactStopBps) no(side, "IMPACT", `the price impact would be ${(best.impactBps / 100).toFixed(2)}%, at or over ${conf.impactStopBps / 100}%: try a smaller amount`);
226
+ // the trade against Chainlink's price, either way
227
+ const usdIn = side === "buy" ? amountIn : usdOf(amountIn, answer, t), usdOut = side === "buy" ? usdOf(best.out, answer, t) : best.out;
228
+ const deviationBps = usdIn > 0n ? Number(((usdIn > usdOut ? usdIn - usdOut : usdOut - usdIn) * 10_000n) / usdIn) : 0;
229
+ if (deviationBps > MAX_DEVIATION_BPS) no(side, "OFF_PRICE", `the trade's price is ${(deviationBps / 100).toFixed(2)}% from Chainlink's, over ${MAX_DEVIATION_BPS / 100}%`);
230
+ const valueUsdg = side === "buy" ? amountIn : best.out;
231
+ if (side === "sell" && valueUsdg < conf.minUsdgPerOp) no(side, "AMOUNT", `the smallest trade is ${usdg(conf.minUsdgPerOp)} (this sale quotes ${usdg(valueUsdg)})`);
232
+ if (side === "sell" && valueUsdg > cap) no(side, "AMOUNT", `one trade is at most ${usdg(cap)} (this sale quotes ${usdg(valueUsdg)})`);
233
+ // the minimum out: the quote less the slippage, and never under what the caller saw
234
+ let minOut = minOutOf(best.out, slip, conf);
235
+ const outDec = side === "buy" ? t.decimals : 6, outName = side === "buy" ? t.symbol : "USDG";
236
+ if (minWanted !== null) {
237
+ if (best.out < minWanted) no(side, "MOVED", `the price moved past the slippage: a fresh quote gives ${fmt(best.out, outDec)} ${outName}, under the ${fmt(minWanted, outDec)} ${outName} asked for at least`, { quoteOut: best.out });
238
+ if (minWanted > minOut) minOut = minWanted;
239
+ }
240
+ if (!(minOut > 0n)) no(side, "AMOUNT", "the amount is too small to name a minimum out");
241
+ // a buy leaves what the open loans owe (the savings that count), and what the caller keeps back
242
+ let owed = 0n, keep = o.keepUsdg != null ? BigInt(o.keepUsdg) : 0n;
243
+ if (side === "buy") {
244
+ if (o.agentId !== null) {
245
+ try { owed = (await openLoansOwed(client, o.agentId, { tag: r.tag })).owed; } catch (e) { throw new StockTradeError("UNREAD", `stock buy: agent #${o.agentId}'s open loans could not be read just now (${e?.shortMessage || e?.message || e})`); }
246
+ }
247
+ const saved = o.savedUsdg != null ? BigInt(o.savedUsdg) : 0n;
248
+ keep += owed > saved ? owed - saved : 0n;
249
+ if (r.cash - amountIn < keep) {
250
+ const room = r.cash > keep ? r.cash - keep : 0n;
251
+ no(side, "KEEP_BACK", `this would leave ${usdg(r.cash - amountIn)} in the wallet, under the ${usdg(keep)} it keeps back${owed > 0n ? ` (agent #${o.agentId}'s open loans owe ${usdg(owed)}${saved > 0n ? `, ${usdg(saved)} of it covered by savings` : ""})` : ""}: at most ${usdg(room)} can buy now. Stock is never bought with USDG a loan needs back`, { owed, keep, room });
252
+ }
253
+ }
254
+ const p = best.pool, spender = p.v === 4 ? conf.v4.swapper : conf.v3.router;
255
+ const tokenIn = side === "buy" ? conf.usdg : t.token;
256
+ let allowance;
257
+ try { allowance = await view(client, r.tag, tokenIn, ERC20_ABI, "allowance", [account, spender]); } catch (_) { allowance = 0n; }
258
+ const deadline = b.at + conf.deadlineS;
259
+ const built = side === "buy"
260
+ ? buildBuy({ account, symbol: t.symbol, pool: p, usdgIn: amountIn, minOut, deadline }, conf)
261
+ : buildSell({ account, symbol: t.symbol, pool: p, amountIn, minOut, deadline }, conf);
262
+ const inText = side === "buy" ? usdg(amountIn) : `${fmt(amountIn, t.decimals)} ${t.symbol}`;
263
+ const spenderName = p.v === 4 ? "V4SwapOnce" : "SwapRouter02";
264
+ const calls = [
265
+ ...(allowance === amountIn ? [] : [{ ...built[0], value: 0n, step: "approve", what: `the approval of ${inText} to ${spenderName}` }]),
266
+ { ...built[1], value: 0n, step: "swap", what: `the ${side === "buy" ? "buy" : "sale"} of ${inText} for at least ${fmt(minOut, outDec)} ${outName} (${poolLabel(p)})` },
267
+ ];
268
+ return {
269
+ side, symbol: t.symbol, name: t.name, token: t.token, decimals: t.decimals, account, block: b.number, at: b.at,
270
+ pool: p, label: poolLabel(p), spender, amountIn, out: best.out, minOut, slippageBps: slip, impactBps: best.impactBps,
271
+ price: answer, priceAt, priceAge: age, feedDecimals: t.feedDecimals, deviationBps, valueUsdg,
272
+ held: { usdg: r.cash, token: r.held }, owed, keep, allowance, deadline, calls,
273
+ };
274
+ }
275
+
276
+ /** A plan in words, one line: "10 USDG -> about 0.0412 NVDA (at least 0.0408), Uniswap v3, 0.05% pool; ...". */
277
+ export function planText(p) {
278
+ const [inD, inN, outD, outN] = p.side === "buy" ? [6, "USDG", p.decimals, p.symbol] : [p.decimals, p.symbol, 6, "USDG"];
279
+ return `${fmt(p.amountIn, inD)} ${inN} -> about ${fmt(p.out, outD)} ${outN} (at least ${fmt(p.minOut, outD)}, ${p.slippageBps / 100}% slippage), ${p.label}${p.impactBps !== null ? `, price impact ${(p.impactBps / 100).toFixed(2)}%` : ""}; Chainlink's ${p.symbol} round ${Math.round(p.priceAge / 60)} min old, the trade ${(p.deviationBps / 100).toFixed(2)}% from it; block ${p.block}.`;
280
+ }
281
+
282
+ /** The account that signs: `account`, else the wallet's own address. */
283
+ async function accountOf(account, wallet) {
284
+ if (account) return getAddress(account);
285
+ if (wallet && wallet.account && wallet.account.address) return getAddress(wallet.account.address); // viem WalletClient
286
+ if (wallet && typeof wallet.getAddress === "function") return getAddress(await wallet.getAddress()); // ethers Signer
287
+ throw new StockTradeError("ACCOUNT", "stock trade: give the account that signs (account) or a wallet to send with");
288
+ }
289
+
290
+ /** The account's ETH covers the steps at today's gas price: the first's estimate (+25%), SWAP_GAS for a swap after it. */
291
+ async function gasCheck(client, side, account, calls) {
292
+ let price, eth, est;
293
+ try {
294
+ price = BigInt(await rpc(client, "eth_gasPrice", []));
295
+ eth = BigInt(await rpc(client, "eth_getBalance", [account, "latest"]));
296
+ } catch (e) { throw new StockTradeError("UNREAD", `stock ${side}: the gas price or the account's ETH could not be read just now`); }
297
+ try { est = BigInt(await rpc(client, "eth_estimateGas", [{ from: account, to: calls[0].to, data: calls[0].data }])); } catch (_) { est = calls[0].step === "swap" ? SWAP_GAS : 75_000n; }
298
+ const need = (est + est / 4n + (calls.length > 1 ? SWAP_GAS : 0n)) * price;
299
+ if (eth < need) no(side, "NO_GAS", `${account} has ${formatUnits(eth, 18)} ETH, under the ${formatUnits(need, 18)} ETH its ${calls.length > 1 ? "two transactions" : "transaction"} may cost in gas`);
300
+ }
301
+
302
+ /** What `account` received of `token` in the receipt of `hash` (its Transfer logs), or null when unread. */
303
+ async function receivedIn(client, hash, token, account) {
304
+ try {
305
+ const rc = await rpc(client, "eth_getTransactionReceipt", [hash]);
306
+ const to = `0x${lc(account).slice(2).padStart(64, "0")}`;
307
+ return (rc.logs || []).filter((l) => lc(l.address) === lc(token) && l.topics && lc(l.topics[0]) === TRANSFER && lc(l.topics[2]) === to).reduce((a, l) => a + BigInt(l.data), 0n);
308
+ } catch (_) { return null; }
309
+ }
310
+
311
+ /** A plan that stopped after its approval: the error, with what stands. */
312
+ function stoppedAfter(e, p, hashes) {
313
+ const inText = p.side === "buy" ? usdg(p.amountIn) : `${fmt(p.amountIn, p.decimals)} ${p.symbol}`;
314
+ const why = e?.message ? String(e.message).replace(/^stock (buy|sale|sell): /, "") : String(e);
315
+ return new StockTradeError(e?.code || "STOPPED", `stock ${p.side}: the approval was sent (tx ${hashes.join(", ")}), then the trade stopped: ${why}. Nothing more was sent. The approval of exactly ${inText} to ${p.spender} stands; its spender pulls only from its caller, so only this account's own swap can use it`, { hashes: [...hashes], stoppedAfterApproval: true, cause: e });
316
+ }
317
+
318
+ /**
319
+ * One trade: the plan, and with `wallet` (an ethers Wallet or Signer, a viem WalletClient) its steps sent. o: as
320
+ * stockTradePlan, plus wallet, waitTimeoutMs, beforeSend(plan), onSend(hash, what, step). Returns the plan, and once sent
321
+ * { ...plan, hashes, received } (received: what the swap's receipt paid the account, or null when unread).
322
+ */
323
+ export async function stockTrade(client, o = {}, conf = ZAP) {
324
+ stated(o);
325
+ const account = await accountOf(o.account, o.wallet).catch((e) => { throw e instanceof StockTradeError ? e : new StockTradeError("ACCOUNT", String(e?.message || e)); });
326
+ let p = await stockTradePlan(client, { ...o, account }, conf);
327
+ if (!o.wallet) return p;
328
+ await gasCheck(client, p.side, account, p.calls);
329
+ if (o.beforeSend) await o.beforeSend(p);
330
+ const recheck = `this account's USDG and ${p.symbol} (wallet_balance, or the token's balanceOf)`;
331
+ // each step's nonce, read here just before it: a wallet whose provider caches its reads (ethers' default, 250 ms) could
332
+ // give a step the one the step before it took (the approval's, or the last trade's), and the node would refuse it
333
+ const send = async (c) => {
334
+ let n = c;
335
+ try { n = { ...c, nonce: Number(BigInt(await rpc(client, "eth_getTransactionCount", [account, "pending"]))) }; } catch (_) { /* the wallet's own */ }
336
+ return sendCalls(client, o.wallet, [n], account, { waitTimeoutMs: o.waitTimeoutMs, recheck, onSend: o.onSend ? (h, what) => o.onSend(h, what, c.step) : undefined });
337
+ };
338
+ const hashes = [];
339
+ if (p.calls.length === 2) {
340
+ hashes.push(...(await send(p.calls[0])));
341
+ // read and planned again at the latest block, on the same pool and amount, never under the first minimum
342
+ let again;
343
+ try { again = await stockTradePlan(client, { ...o, account, amount: p.amountIn, pool: p.pool, minOut: p.minOut, slippageBps: p.slippageBps }, conf); } catch (e) { throw stoppedAfter(e, p, hashes); }
344
+ if (again.calls.length !== 1) throw stoppedAfter(new Error("the approval is not the amount the swap takes"), p, hashes);
345
+ p = again;
346
+ }
347
+ try { hashes.push(...(await send(p.calls[p.calls.length - 1]))); } catch (e) {
348
+ if (hashes.length && !e?.unconfirmed) throw stoppedAfter(e, p, hashes);
349
+ if (hashes.length && e?.unconfirmed) e.hashes = [...hashes, ...(e.hashes || [])];
350
+ throw e;
351
+ }
352
+ const received = await receivedIn(client, hashes[hashes.length - 1], p.side === "buy" ? p.token : conf.usdg, account);
353
+ return { ...p, hashes, received };
354
+ }
355
+
356
+ /** A quote and the calls, sent nothing: stockTradePlan for `side`. */
357
+ export const stockQuote = (client, o = {}, conf = ZAP) => stockTradePlan(client, o, conf);
358
+ /** Buy `amount` USDG of `symbol`: the calls, sent when `wallet` is given. */
359
+ export const stockBuy = (client, o = {}, conf = ZAP) => stockTrade(client, { ...o, side: "buy" }, conf);
360
+ /** Sell `amount` of `symbol` (or "all") for USDG: the calls, sent when `wallet` is given. */
361
+ export const stockSell = (client, o = {}, conf = ZAP) => stockTrade(client, { ...o, side: "sell" }, conf);