@priors/mcp 0.12.2 → 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,824 @@
1
+ // The market's planner for a wallet that signs its own transactions (the P7 spec, section 5): what an agent's own key
2
+ // reads, checks and sends to list, cancel, buy, bid on and accept a bid for an agent, on AgentMarket v1 or AgentMarketV2,
3
+ // one plain transaction at a time. @priors/mcp's market tools (packages/mcp/src/market-tools.mjs) run it; the package
4
+ // holds a byte-for-byte copy (scripts/test-packages.mjs fails on any drift). Pure: no network, no clock, no file.
5
+ //
6
+ // 1. kindReads(market): which market answers at the address, v1 or V2, at one block (marketKindOf). v1's bidSpender()
7
+ // reverts with no data; V2's is CREATE(market, 1) (market-bids spenderOf), whose market() is the market. Its
8
+ // registry and USDG must be the package's record's. A V2 with the builder share (the P5 spec, section 2) answers
9
+ // MAX_BUILDER_BPS(); one without it reverts with no data, and every sale then pays no share. Its owner's switch,
10
+ // buildersOn() (false until the Safe calls enableBuilders(), once, for good), is read with each agent's reads, at
11
+ // the plan's block, never kept: while it is off no share can be set, and none is reported.
12
+ // 2. agentReads, accountReads, bidReads, then moreReads (the agent's sponsor's followsLine, the seller's and the
13
+ // makers' accounts): one Multicall3 aggregate3 each, every call allowed to fail, all at one block. readsOut decodes
14
+ // them into `c`, the object every plan reads; a read that failed is null, and a plan given null answers "unread",
15
+ // never a guess.
16
+ // 3. sellPlan, buyPlan, cancelPlan, bidPlan, bidAnyPlan, cancelBidPlan, acceptPlan: the contract's rules in its order
17
+ // (web/board-wallet-core.js sellState and buyPlan, web/board-wallet-bids-core.js, which a test holds this to), then
18
+ // the steps, each one transaction: { steps, pins, ... } or { error: kind, ...vars }.
19
+ // 4. stepCalls(step, o): a step's { to, data }, from market-abi's MARKET_IFACE and market-bids' call builders.
20
+ // 5. MARKET_ERRORS and errorKindOf(revertData, role): a revert's kind; PLAN_WORDS and planWords(kind, vars): its words.
21
+ //
22
+ // What a sale leaves the seller is computed in netOf alone: price - fee - the builder's share, the share only where the
23
+ // market answers builderOf (P5), else price - fee. An open asking price and an open bid are worded; a price paid or taken
24
+ // is never worded after the fact.
25
+ import { ethers } from "ethers";
26
+ import { MARKET_IFACE, LISTING_RULES, feeOf } from "./market-abi.mjs";
27
+ import { BID_RULES, BID_WORDS, spenderOf, idsRootOf, listOf, inRoot, reserveCall, bidCall, bidAnyCall, cancelBidCall, acceptCall } from "./market-bids.mjs";
28
+
29
+ /* ---- small helpers ---- */
30
+
31
+ const ZERO = ethers.ZeroAddress, ZERO32 = ethers.ZeroHash;
32
+ const HEX32 = /^0x[0-9a-fA-F]{64}$/;
33
+ const DAY = 86400;
34
+ const lc = (a) => String(a).toLowerCase();
35
+ const isAddr = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a) && BigInt(a) !== 0n;
36
+ const same = (a, b) => isAddr(a) && isAddr(b) && lc(a) === lc(b);
37
+ const big = (v) => (typeof v === "bigint" ? v : BigInt(v));
38
+ /** bytes32(id): a bid on one agent's target. */
39
+ const idWord = (id) => ethers.toBeHex(big(id), 32);
40
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
41
+ /** A UTC day as the words say it: "3 Nov". */
42
+ export const dayText = (s) => { const d = new Date(Number(s) * 1000); return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}`; };
43
+ /** USDG units as the words say them: "120", "1.20", "0.25". */
44
+ export function amountText(units) {
45
+ const n = big(units), whole = n / 1_000_000n, frac = (n % 1_000_000n).toString().padStart(6, "0").replace(/0+$/, "");
46
+ const w = String(whole).replace(/\B(?=([0-9]{3})+(?![0-9]))/g, ",");
47
+ return frac ? `${w}.${frac.padEnd(2, "0")}` : w;
48
+ }
49
+
50
+ /* ---- the reads ---- */
51
+
52
+ /** Multicall3, at the same address on every chain (data-worker/registry.mjs). */
53
+ export const MULTICALL3 = "0xca11bde05977b3631167028862be2a173976ca11";
54
+ const MC3 = new ethers.Interface(["function aggregate3((address target, bool allowFailure, bytes callData)[] calls) payable returns ((bool success, bytes returnData)[] returnData)"]);
55
+
56
+ const LISTING = "tuple(address seller, uint256 price, uint64 expiry, uint256 nonce, bytes32 uriHash, uint256 loansRepaid)";
57
+ const BID = "tuple(address maker, uint64 expiry, uint16 left, bool any, uint96 price, uint96 minLine, uint64 minRepaid, bytes32 target, bytes32 uriHash)";
58
+ const AGENT_V2 = "tuple(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)";
59
+ const AGENT_V1 = "tuple(bool enrolled, bool isRoot, bool defaulted, uint64 enrolledAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 earned, uint256 stake, uint256 principalOut, uint256 activeLoans, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 recourseHonored, uint256 childrenDefaulted, uint64 epochStart, uint256 earnedThisEpoch, uint256 qualifiedRepaid, uint256 dollarSecondsRepaid)";
60
+ /** Every view a plan reads, by the contract that answers it (src/AgentMarket.sol, src/AgentMarketV2.sol, BidSpender,
61
+ * the ERC-8004 registry, CreditPoolV2, CreditPool v1, InviteBond v1 and V2, USDG). Pool v1 and the two bonds answer
62
+ * their own structs under the same selectors, so each contract has its own Interface. */
63
+ export const READS = Object.freeze({
64
+ market: new ethers.Interface([
65
+ `function listingOf(uint256 id) view returns (${LISTING})`, "function feeBps() view returns (uint256)", "function minFee() view returns (uint256)",
66
+ "function lastSoldAt(uint256 id) view returns (uint64)", "function refused(address account) view returns (bool)", "function followsLine(uint256 root) view returns (bool)",
67
+ "function recordHash(uint256 id) view returns (bytes32)", "function paused() view returns (bool)", "function pausedUntil() view returns (uint64)",
68
+ "function registry() view returns (address)", "function usdg() view returns (address)", "function poolV2() view returns (address)", "function poolV1() view returns (address)",
69
+ "function inviteBond() view returns (address)", "function inviteBondV2() view returns (address)", "function bidSpender() view returns (address)", "function previous() view returns (address)",
70
+ `function bidOf(uint256 bidId) view returns (${BID})`, "function bidTook(uint256 bidId, uint256 id) view returns (bool)", "function nextBidId() view returns (uint256)",
71
+ // the builder share, on a V2 that has it (the P5 spec, 2.2 and 2.3)
72
+ "function MAX_BUILDER_BPS() view returns (uint256)", "function builderOf(uint256 id) view returns (tuple(address to, uint16 bps))",
73
+ "function saleSplit(uint256 id) view returns (uint256 fee, uint256 share, uint256 net)", "function buildersOn() view returns (bool)",
74
+ ]),
75
+ spender: new ethers.Interface(["function market() view returns (address)"]),
76
+ registry: new ethers.Interface(["function ownerOf(uint256 tokenId) view returns (address)", "function getApproved(uint256 tokenId) view returns (address)", "function tokenURI(uint256 tokenId) view returns (string)"]),
77
+ poolV2: new ethers.Interface([`function getAgent(uint256 id) view returns (${AGENT_V2})`, "function custodian(address account) view returns (bool)", "function ownerDefaults(address account) view returns (uint256)"]),
78
+ poolV1: new ethers.Interface([`function getAgent(uint256 id) view returns (${AGENT_V1})`]),
79
+ bondV1: new ethers.Interface(["function bonds(uint256 id) view returns (tuple(address depositor, uint64 at, uint256 amount, uint256 qualifiedAt))"]),
80
+ bondV2: new ethers.Interface(["function bonds(uint256 id) view returns (tuple(address depositor, uint64 at, uint256 amount))", "function amount() view returns (uint256)"]),
81
+ usdg: new ethers.Interface(["function balanceOf(address account) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)"]),
82
+ });
83
+
84
+ /** One read: { key, to, data, as: [contract, fn] }. A read on a zero address is never made (that contract isn't on
85
+ * this chain): its key stays absent from `c`. */
86
+ function adder(out) {
87
+ return (key, to, as, fn, args = []) => { if (isAddr(to)) out.push({ key, to: lc(to), data: READS[as].encodeFunctionData(fn, args), as: [as, fn] }); };
88
+ }
89
+ /** aggregate3's call for `reads`, each allowed to fail: { to, data }. */
90
+ export const aggregateCall = (reads) => ({ to: MULTICALL3, data: MC3.encodeFunctionData("aggregate3", [reads.map((r) => [r.to, true, r.data])]) });
91
+ /** aggregate3's answer: [{ ok, data }], in the reads' order. */
92
+ export function aggregateOut(hex) {
93
+ const [rs] = MC3.decodeFunctionResult("aggregate3", hex);
94
+ return rs.map(([ok, data]) => ({ ok: ok === true, data: lc(data) }));
95
+ }
96
+ /** A decoded value as plans read it: addresses lower case, a struct as an object, bigints as they are. */
97
+ function plain(v) {
98
+ if (typeof v === "string") return /^0x[0-9a-fA-F]{40}$/.test(v) ? lc(v) : v;
99
+ if (v instanceof ethers.Result) {
100
+ let o = null;
101
+ try { o = v.toObject(); } catch (_) { o = null; } // an unnamed value: a list
102
+ return o ? Object.fromEntries(Object.entries(o).map(([k, x]) => [k, plain(x)])) : [...v].map(plain);
103
+ }
104
+ return v;
105
+ }
106
+ /**
107
+ * The answers by key, decoded (`results`: aggregateOut's, in the reads' order): each value, or null for a read that
108
+ * failed or can't be decoded. `c.failed[key]` says how one failed: "empty" (no data back: the function isn't there, as
109
+ * v1's bidSpender() or a V2 without the builder share reverts with none, or no contract is at the address, which
110
+ * Multicall3 answers as a success with no data), "reverted" (with data) or "bad" (no such answer).
111
+ * Keys "bid:<id>", "took:<id>" and "<what>:<maker>" go into the maps c.bids (bidOf's, its maker zero for a bid that
112
+ * doesn't stand; null unread; absent: not asked), c.took and c.makers.
113
+ */
114
+ export function readsOut(reads, results, into = null) {
115
+ const c = into || { failed: {}, bids: new Map(), took: new Map(), makers: new Map() };
116
+ (reads || []).forEach((r, i) => {
117
+ const x = results && results[i];
118
+ let v = null;
119
+ if (x && x.ok && (x.data === "0x" || x.data === "")) c.failed[r.key] = "empty";
120
+ else if (x && x.ok) {
121
+ try {
122
+ const out = READS[r.as[0]].decodeFunctionResult(r.as[1], x.data);
123
+ v = out.length === 1 ? plain(out[0]) : plain(out);
124
+ } catch (_) { v = null; c.failed[r.key] = "bad"; }
125
+ } else c.failed[r.key] = x && !x.ok ? (x.data === "0x" || x.data === "" ? "empty" : "reverted") : "bad";
126
+ const at = r.key.indexOf(":");
127
+ if (at < 0) { c[r.key] = v; return; }
128
+ const kind = r.key.slice(0, at), k = r.key.slice(at + 1);
129
+ if (kind === "bid") c.bids.set(k, v);
130
+ else if (kind === "took") c.took.set(k, v === null ? null : v === true);
131
+ else { if (!c.makers.has(k)) c.makers.set(k, {}); c.makers.get(k)[kind] = v; }
132
+ });
133
+ return c;
134
+ }
135
+
136
+ /** Which market answers at `market`, and its own addresses: the spender's market() is read in the same call, at the
137
+ * address V2's spender would have (spenderOf). */
138
+ export function kindReads(market) {
139
+ const out = [], add = adder(out), m = lc(market);
140
+ for (const k of ["bidSpender", "feeBps", "previous", "registry", "usdg", "poolV2", "poolV1", "inviteBond", "inviteBondV2", "MAX_BUILDER_BPS"]) add(k, m, "market", k);
141
+ add("spenderMarket", spenderOf(m), "spender", "market");
142
+ return out;
143
+ }
144
+ /**
145
+ * The market `c` (kindReads' answers) shows, against the package's `record` ({ registry, usdg }): { kind: "v1" | "v2",
146
+ * addr: { market, registry, usdg, poolV2, poolV1, inviteBond, inviteBondV2, spender (V2's), previous (V2's v1, or
147
+ * null) }, shares (V2 with the builder share) }, or { error }: "unread" (a read failed: try again), "mismatch" (its
148
+ * registry or USDG isn't the record's), "unknown" (neither v1's nor V2's answers).
149
+ */
150
+ export function marketKindOf(c, { market, record }) {
151
+ const f = c.failed || {}, z = (a) => (isAddr(a) ? lc(a) : null);
152
+ if (c.registry == null || c.usdg == null || c.poolV2 == null) return { error: f.registry === "empty" || f.usdg === "empty" ? "unknown" : "unread" };
153
+ if (!same(c.registry, record && record.registry) || !same(c.usdg, record && record.usdg)) return { error: "mismatch" };
154
+ const addr = { market: lc(market), registry: lc(c.registry), usdg: lc(c.usdg), poolV2: z(c.poolV2), poolV1: z(c.poolV1), inviteBond: z(c.inviteBond), inviteBondV2: z(c.inviteBondV2), spender: null, previous: null };
155
+ if (c.bidSpender == null && f.bidSpender === "empty") {
156
+ if (c.feeBps == null) return { error: "unread" };
157
+ return { kind: "v1", addr, shares: false };
158
+ }
159
+ if (c.bidSpender == null) return { error: f.bidSpender === "reverted" ? "unknown" : "unread" };
160
+ const spender = spenderOf(market);
161
+ if (!same(c.bidSpender, spender) || !same(c.spenderMarket, market)) return { error: "unknown" };
162
+ let shares = null;
163
+ if (c.MAX_BUILDER_BPS != null) shares = true;
164
+ else if (f.MAX_BUILDER_BPS === "empty") shares = false;
165
+ if (shares === null) return { error: "unread" };
166
+ return { kind: "v2", addr: { ...addr, spender, previous: z(c.previous) }, shares };
167
+ }
168
+
169
+ /** What a sale reads of agent `id` (round one): its listing on the market and on `previous`, owner, approval, token
170
+ * URI, the market's record pin, both pools' records, both bonds and the bond's amount, its last sale, and its builder
171
+ * share where the market has one, with the owner's switch for shares (buildersOn) at the same block. */
172
+ export function agentReads({ addr, id, shares = false }) {
173
+ const a = addr || {}, i = big(id), out = [], add = adder(out);
174
+ add("listing", a.market, "market", "listingOf", [i]);
175
+ add("prevListing", a.previous, "market", "listingOf", [i]);
176
+ add("owner", a.registry, "registry", "ownerOf", [i]);
177
+ add("approved", a.registry, "registry", "getApproved", [i]);
178
+ add("uri", a.registry, "registry", "tokenURI", [i]);
179
+ add("record", a.market, "market", "recordHash", [i]);
180
+ add("agent", a.poolV2, "poolV2", "getAgent", [i]);
181
+ add("agentV1", a.poolV1, "poolV1", "getAgent", [i]);
182
+ add("bondV1", a.inviteBond, "bondV1", "bonds", [i]);
183
+ add("bondV2", a.inviteBondV2, "bondV2", "bonds", [i]);
184
+ add("bondAmount", a.inviteBondV2, "bondV2", "amount");
185
+ add("soldAt", a.market, "market", "lastSoldAt", [i]);
186
+ if (shares) { add("builder", a.market, "market", "builderOf", [i]); add("saleSplit", a.market, "market", "saleSplit", [i]); add("buildersOn", a.market, "market", "buildersOn"); }
187
+ return out;
188
+ }
189
+ /** The wallet's own (`me`): its standing (the pool's custodian and marks, the market's refusal), the pause and the
190
+ * fee, its USDG and what it approved to the market, to InviteBondV2 and (V2) to the bids' spender; `self`, the agent
191
+ * the server acts for, adds that agent's pool record (its open loans). */
192
+ export function accountReads({ addr, me, self = null }) {
193
+ const a = addr || {}, out = [], add = adder(out), w = lc(me);
194
+ add("paused", a.market, "market", "paused");
195
+ add("pausedUntil", a.market, "market", "pausedUntil");
196
+ add("feeBps", a.market, "market", "feeBps");
197
+ add("minFee", a.market, "market", "minFee");
198
+ if (!isAddr(w)) return out;
199
+ add("custodian", a.poolV2, "poolV2", "custodian", [w]);
200
+ add("marked", a.poolV2, "poolV2", "ownerDefaults", [w]);
201
+ add("refused", a.market, "market", "refused", [w]);
202
+ add("cash", a.usdg, "usdg", "balanceOf", [w]);
203
+ add("allowance", a.usdg, "usdg", "allowance", [w, a.market]);
204
+ if (isAddr(a.inviteBondV2)) add("bondAllowance", a.usdg, "usdg", "allowance", [w, a.inviteBondV2]);
205
+ if (isAddr(a.spender)) add("reserve", a.usdg, "usdg", "allowance", [w, a.spender]);
206
+ if (self != null) add("selfAgent", a.poolV2, "poolV2", "getAgent", [big(self)]);
207
+ return out;
208
+ }
209
+ /** Bids by id (bidOf), each read on chain whatever an index said of it. */
210
+ export function bidReads({ addr, bidIds = [] }) {
211
+ const a = addr || {}, out = [], add = adder(out);
212
+ for (const b of [...new Set(bidIds.map(String))]) add("bid:" + b, a.market, "market", "bidOf", [big(b)]);
213
+ return out;
214
+ }
215
+ /**
216
+ * Round two, at the same block, from round one's `c`: whether the market lets the agent's sponsor's line go with it;
217
+ * the listing's seller's standing (a buy's checks of the seller); for agent `id`, each bid on an origin's take of it
218
+ * (bidTook); and each maker's USDG, its reserve to the spender and its standing.
219
+ */
220
+ export function moreReads(c, { addr, id = null }) {
221
+ const a = addr || {}, out = [], add = adder(out), s = c && c.agent ? big(c.agent.sponsor) : 0n;
222
+ if (s !== 0n) add("followed", a.market, "market", "followsLine", [s]);
223
+ const l = c && c.listing;
224
+ if (l && isAddr(l.seller)) {
225
+ add("sellerCustodian", a.poolV2, "poolV2", "custodian", [l.seller]);
226
+ add("sellerMarked", a.poolV2, "poolV2", "ownerDefaults", [l.seller]);
227
+ add("sellerRefused", a.market, "market", "refused", [l.seller]);
228
+ }
229
+ const makers = new Set();
230
+ for (const [k, b] of (c && c.bids) || new Map()) {
231
+ if (!b || !isAddr(b.maker)) continue;
232
+ makers.add(lc(b.maker));
233
+ if (b.any && id != null) add("took:" + k, a.market, "market", "bidTook", [big(k), big(id)]);
234
+ }
235
+ for (const m of makers) {
236
+ add("cash:" + m, a.usdg, "usdg", "balanceOf", [m]);
237
+ if (isAddr(a.spender)) add("reserve:" + m, a.usdg, "usdg", "allowance", [m, a.spender]);
238
+ add("refused:" + m, a.market, "market", "refused", [m]);
239
+ add("custodian:" + m, a.poolV2, "poolV2", "custodian", [m]);
240
+ add("marked:" + m, a.poolV2, "poolV2", "ownerDefaults", [m]);
241
+ }
242
+ return out;
243
+ }
244
+
245
+ /* ---- what a sale pays ---- */
246
+
247
+ /**
248
+ * The fee on `price` and what the seller gets, after the builder's share (the P5 spec, 2.5): fee as the market's
249
+ * (market-abi feeOf, with its feeBps and minFee), the share `builder.bps` of the price rounded down, never more than
250
+ * what the fee leaves, none when no share is set (`builder` null or its `to` zero, as on v1 and on a V2 without
251
+ * shares) or when the seller is the builder. { fee, share, net }.
252
+ */
253
+ export function netOf(price, { feeBps = LISTING_RULES.feeBps, minFee = LISTING_RULES.minFee, builder = null, seller = null } = {}) {
254
+ const p = big(price), { fee } = feeOf(p, { feeBps, minFee });
255
+ let share = 0n;
256
+ if (builder && isAddr(builder.to) && !same(builder.to, seller)) {
257
+ share = (p * big(builder.bps)) / 10_000n;
258
+ if (share > p - fee) share = p - fee;
259
+ }
260
+ return { fee, share, net: p - fee - share };
261
+ }
262
+ /** The fee settings a plan reads (the market's, read at the block). */
263
+ const feesOf = (c) => ({ feeBps: c.feeBps, minFee: c.minFee });
264
+
265
+ /* ---- the plans ---- */
266
+
267
+ const unread = (...v) => v.some((x) => x == null);
268
+ /** An unexpired listing (listingOf) of `who` at `now`, or null. */
269
+ function ownListing(l, who, now) {
270
+ return l && same(l.seller, who) && Number(l.expiry) > Number(now) ? { seller: lc(l.seller), price: big(l.price), expiry: Number(l.expiry), nonce: big(l.nonce) } : null;
271
+ }
272
+ /** A listing's end: `now` plus `days` (1 to 30), or null. A plan's `expiry` given (the first plan's) wins: each later
273
+ * plan of the same call keeps it. */
274
+ function expiryOf({ days, expiry, now }) {
275
+ if (expiry != null) return Number(expiry);
276
+ if (!Number.isSafeInteger(days) || days < 1 || days > 30) return null;
277
+ return Math.min(Number(now) + days * DAY, Number(now) + 30 * DAY - 300);
278
+ }
279
+ const holdUntil = (c) => { const s = Number(c.soldAt); return s === 0 ? 0 : s + LISTING_RULES.holdS; };
280
+ /** The registry's ownerOf reverted with data: no such agent (ERC721NonexistentToken), not a read that failed. */
281
+ const noAgent = (c) => c.owner == null && c.failed && c.failed.owner === "reverted";
282
+
283
+ /**
284
+ * The sale's checks with `me` as the seller, in the contract's order (web/board-wallet-core.js sellState): { error }
285
+ * ("unread", "notOwner", "account", "marked", "root", "loan", "defaulted", "line", "shortBond" with `bond`, `short` and
286
+ * `cash`, "firstBond", "hold" with `until`, "paused" with `until`), or { bond (InviteBondV2's amount when the line lends
287
+ * and has no V2 bond; else 0), bondApprove }.
288
+ */
289
+ function saleChecks(c, { me, now }) {
290
+ const t = Number(now);
291
+ if (noAgent(c)) return { error: "notOwner", owner: null };
292
+ if (unread(c.owner, c.listing, c.approved)) return { error: "unread" };
293
+ if (!same(c.owner, me)) return { error: "notOwner", owner: isAddr(c.owner) ? lc(c.owner) : null };
294
+ if (unread(c.custodian, c.refused, c.marked)) return { error: "unread" };
295
+ if (c.custodian === true || c.refused === true) return { error: "account" };
296
+ if (big(c.marked) !== 0n) return { error: "marked" };
297
+ const a = c.agent;
298
+ if (a == null) return { error: "unread" };
299
+ if (a.isRoot) return { error: "root" };
300
+ if (big(a.activeLoans) !== 0n) return { error: "loan" };
301
+ if (a.defaulted) return { error: "defaulted" };
302
+ const sponsor = big(a.sponsor), lent = big(a.delegatedIn);
303
+ let bond = 0n, bondApprove = false;
304
+ if (sponsor !== 0n || lent !== 0n) {
305
+ if (sponsor !== 0n && c.followed == null) return { error: "unread" };
306
+ if (sponsor === 0n || c.followed !== true) return { error: "line" };
307
+ if (lent !== 0n) {
308
+ if (c.bondV2 == null) return { error: "unread" };
309
+ if (!isAddr(c.bondV2.depositor)) {
310
+ if (unread(c.bondAmount, c.cash)) return { error: "unread" };
311
+ bond = big(c.bondAmount);
312
+ bondApprove = c.bondAllowance == null || big(c.bondAllowance) < bond;
313
+ if (big(c.cash) < bond) return { error: "shortBond", bond, short: bond - big(c.cash), cash: big(c.cash) };
314
+ }
315
+ }
316
+ }
317
+ if (c.agentV1 !== undefined) {
318
+ const o = c.agentV1;
319
+ if (o == null) return { error: "unread" };
320
+ if (o.isRoot) return { error: "root" };
321
+ if (big(o.activeLoans) !== 0n) return { error: "loan" };
322
+ if (o.defaulted) return { error: "defaulted" };
323
+ }
324
+ if (c.bondV1 !== undefined) {
325
+ if (c.bondV1 == null) return { error: "unread" };
326
+ if (isAddr(c.bondV1.depositor)) return { error: "firstBond" };
327
+ }
328
+ if (c.soldAt == null) return { error: "unread" };
329
+ const until = holdUntil(c);
330
+ if (until !== 0 && t < until) return { error: "hold", until };
331
+ if (c.paused == null) return { error: "unread" };
332
+ if (c.paused === true) return { error: "paused", until: c.pausedUntil == null ? null : Number(c.pausedUntil) };
333
+ return { bond, bondApprove };
334
+ }
335
+ /** The builder share `c` read (null: none, or a market without shares), checked: a share the market answers with an
336
+ * address and at most 5% (MAX_BUILDER_BPS), else unread. While the owner's switch reads off (buildersOn false) no share
337
+ * can be set, so none is reported, whatever builderOf says; a V2 without the switch (buildersOn answers no data), or
338
+ * a switch read that failed, leaves it to builderOf. */
339
+ function builderIn(c, shares) {
340
+ if (!shares || c.buildersOn === false) return { builder: null };
341
+ if (c.builder == null) return { error: "unread" };
342
+ const b = c.builder;
343
+ if (!isAddr(b.to)) return { builder: null };
344
+ if (big(b.bps) > 500n) return { error: "unread" };
345
+ return { builder: { to: lc(b.to), bps: big(b.bps) } };
346
+ }
347
+
348
+ /**
349
+ * Listing agent `id` from `me` (sellState with the terms): `price` (USDG units, 5 USDG or more), `days` (1 to 30) or
350
+ * the first plan's `expiry`. { error } ("price", "days", then saleChecks'), or { steps, price, expiry, bond, fee, share,
351
+ * net, mine (its own listing standing before), pins }. Steps, each one transaction, in order: "cancelOldPrev" (V2:
352
+ * this wallet's own v1 listing of the agent, which an approval back to v1 would bring back), "cancelOld" (its own
353
+ * listing here while the market isn't approved: approving brings it back at its old price), "bondApprove" and "bond"
354
+ * (InviteBondV2's deposit, when the treasury line lends with no V2 bond), "approve" (the registry's, for this agent
355
+ * only), "list".
356
+ */
357
+ export function sellPlan(c, { addr, me, now, price, days, expiry = null, shares = false }) {
358
+ c = c || {};
359
+ const p = typeof price === "bigint" ? price : null;
360
+ if (p == null || p < LISTING_RULES.minPrice) return { error: "price" };
361
+ const e = expiryOf({ days, expiry, now });
362
+ if (e == null || e <= Number(now) || e > Number(now) + 30 * DAY) return { error: "days" };
363
+ const s = saleChecks(c, { me, now });
364
+ if (s.error) return s;
365
+ const bi = builderIn(c, shares);
366
+ if (bi.error) return bi;
367
+ if (unread(c.feeBps, c.minFee)) return { error: "unread" };
368
+ const approved = same(c.approved, addr.market), mine = ownListing(c.listing, me, now);
369
+ let prevMine = null;
370
+ if (addr.previous) { if (c.prevListing == null) return { error: "unread" }; prevMine = ownListing(c.prevListing, me, now); }
371
+ const steps = [...(prevMine ? ["cancelOldPrev"] : []), ...(mine && !approved ? ["cancelOld"] : []), ...(s.bond > 0n && s.bondApprove ? ["bondApprove"] : []),
372
+ ...(s.bond > 0n ? ["bond"] : []), ...(approved ? [] : ["approve"]), "list"];
373
+ const { fee, share, net } = netOf(p, { ...feesOf(c), builder: bi.builder, seller: me });
374
+ return { steps, price: p, expiry: e, bond: s.bond, fee, share, net, mine, pins: { price: p, expiry: e } };
375
+ }
376
+
377
+ /** The listing of `c` a buyer could take at `now` by its own terms (its seller holds the agent, the market is approved
378
+ * for it, it hasn't ended): { seller, price, expiry, nonce }, or null. */
379
+ function liveListing(c, { addr, now }) {
380
+ const l = c.listing;
381
+ return l && isAddr(l.seller) && Number(l.expiry) > Number(now) && same(l.seller, c.owner) && same(c.approved, addr.market) ? { seller: lc(l.seller), price: big(l.price), expiry: Number(l.expiry), nonce: big(l.nonce) } : null;
382
+ }
383
+ /**
384
+ * What stops any buyer from taking that listing, past the buyer's own checks, in the contract's order (the seller's
385
+ * _checkAccount, then _checkSale and buy's pins): { error } ("unread", "sellerBlocked", "defaulted", "loan", "root",
386
+ * "line", "firstBond", "hold" with `until`, "stale": the agent's file or its repaid loans changed after it was listed,
387
+ * so no buy of that listing goes through until its seller lists again), or { follows, lent, uriHash } when nothing does.
388
+ */
389
+ function takeChecks(c, { now }) {
390
+ const a = c.agent, o = c.agentV1;
391
+ if (unread(c.sellerCustodian, c.sellerRefused, c.sellerMarked)) return { error: "unread" };
392
+ if (c.sellerCustodian === true || c.sellerRefused === true || big(c.sellerMarked) !== 0n) return { error: "sellerBlocked" };
393
+ if (a == null || o === null) return { error: "unread" };
394
+ if (a.defaulted || (o && o.defaulted)) return { error: "defaulted" };
395
+ if (big(a.activeLoans) !== 0n || (o && big(o.activeLoans) !== 0n)) return { error: "loan" };
396
+ if (a.isRoot || (o && o.isRoot)) return { error: "root" };
397
+ const sponsor = big(a.sponsor), lent = big(a.delegatedIn);
398
+ if (sponsor !== 0n && c.followed == null) return { error: "unread" };
399
+ const follows = sponsor !== 0n && c.followed === true;
400
+ if (sponsor !== 0n || lent !== 0n) {
401
+ if (!follows) return { error: "line" };
402
+ if (lent !== 0n && c.bondV2 == null) return { error: "unread" };
403
+ if (lent !== 0n && !isAddr(c.bondV2.depositor)) return { error: "line" };
404
+ }
405
+ if (c.bondV1 === null || c.soldAt == null) return { error: "unread" };
406
+ if (c.bondV1 && isAddr(c.bondV1.depositor)) return { error: "firstBond" };
407
+ const until = holdUntil(c);
408
+ if (until !== 0 && Number(now) < until) return { error: "hold", until };
409
+ if (unread(c.uri, c.record) || !HEX32.test(String(c.record))) return { error: "unread" };
410
+ const uriHash = lc(ethers.keccak256(ethers.toUtf8Bytes(c.uri)));
411
+ if (uriHash !== lc(c.listing.uriHash) || big(a.loansRepaid) !== big(c.listing.loansRepaid)) return { error: "stale" };
412
+ return { follows, lent, uriHash };
413
+ }
414
+ /**
415
+ * Whether any buyer can take agent `id`'s listing on the market now (round one and two's reads of `c`): null when one
416
+ * can, else why not: { error } "unread", "gone" (none stands that a buyer can take: none, ended, its seller no longer
417
+ * holds the agent, or the market isn't approved for it), "paused" (`until`), or takeChecks'. market_agent's "For sale"
418
+ * and a bid's "listed" read it, so neither sends the model to a buy that buyPlan refuses.
419
+ */
420
+ export function listingBlock(c, { addr, now }) {
421
+ c = c || {};
422
+ if (noAgent(c)) return { error: "gone" };
423
+ if (unread(c.listing, c.owner, c.approved)) return { error: "unread" };
424
+ if (!liveListing(c, { addr, now })) return { error: "gone" };
425
+ if (c.paused == null) return { error: "unread" };
426
+ if (c.paused === true) return { error: "paused", until: c.pausedUntil == null ? null : Number(c.pausedUntil) };
427
+ const k = takeChecks(c, { now });
428
+ return k.error ? k : null;
429
+ }
430
+
431
+ /**
432
+ * Buying agent `id` from `me` at `maxPrice` at most (web/board-wallet-core.js buyPlan, a price cap in place of the
433
+ * listing first shown; `seen`, a later plan's: the first plan's { price, nonce }). { error } ("unread", "gone",
434
+ * "relisted" with `price` (a nonce or price other than `seen`'s), "changed" with `price` (above `maxPrice`), "self",
435
+ * "paused", "account", "marked", takeChecks' kinds, "record" with `n` and `m` (fewer repaid loans than `minRecord`),
436
+ * "short" with `short` and `cash`), or { steps ("approveUsdg": exactly the price, while the USDG approved to the market
437
+ * is short of it; "buy"), listing, follows (the treasury line comes with it), line, bond (what the buyer locks before it
438
+ * borrows on it), fee, share, net (the seller's), pins: { price, nonce, uriHash (the token URI's bytes hashed here),
439
+ * recordHash (the market's own, at the same block) } }.
440
+ */
441
+ export function buyPlan(c, { addr, me, now, maxPrice, seen = null, minRecord = 0n, shares = false }) {
442
+ c = c || {};
443
+ if (noAgent(c)) return { error: "gone" };
444
+ if (unread(c.listing, c.owner, c.approved)) return { error: "unread" };
445
+ const listing = liveListing(c, { addr, now });
446
+ if (!listing) return { error: "gone" };
447
+ if (seen && (big(seen.nonce) !== listing.nonce || big(seen.price) !== listing.price)) return { error: "relisted", price: listing.price };
448
+ if (listing.price > big(maxPrice)) return { error: "changed", price: listing.price };
449
+ if (same(listing.seller, me)) return { error: "self" };
450
+ if (c.paused == null) return { error: "unread" };
451
+ if (c.paused === true) return { error: "paused", until: c.pausedUntil == null ? null : Number(c.pausedUntil) };
452
+ if (unread(c.custodian, c.refused, c.marked)) return { error: "unread" };
453
+ if (c.custodian === true || c.refused === true) return { error: "account" };
454
+ if (big(c.marked) !== 0n) return { error: "marked" };
455
+ const k = takeChecks(c, { now });
456
+ if (k.error) return k;
457
+ const a = c.agent, { follows, lent, uriHash } = k;
458
+ if (big(a.loansRepaid) < big(minRecord)) return { error: "record", n: big(minRecord), m: big(a.loansRepaid) };
459
+ const wants = follows && lent > 0n && !same(c.bondV2 && c.bondV2.depositor, me);
460
+ if (wants && c.bondAmount == null) return { error: "unread" };
461
+ if (unread(c.cash, c.allowance, c.feeBps, c.minFee)) return { error: "unread" };
462
+ if (big(c.cash) < listing.price) return { error: "short", short: listing.price - big(c.cash), cash: big(c.cash) };
463
+ const bi = builderIn(c, shares);
464
+ if (bi.error) return bi;
465
+ // what the seller gets: the market's own split when it answers one (the lower fee and share of list and now), else
466
+ // the fee and the share now
467
+ const split = shares && c.saleSplit ? { fee: big(c.saleSplit.fee), share: big(c.saleSplit.share), net: big(c.saleSplit.net) } : netOf(listing.price, { ...feesOf(c), builder: bi.builder, seller: listing.seller });
468
+ return {
469
+ steps: [...(big(c.allowance) < listing.price ? ["approveUsdg"] : []), "buy"], listing, follows, line: follows ? lent : 0n, bond: wants ? big(c.bondAmount) : 0n,
470
+ fee: split.fee, share: split.share, net: split.net,
471
+ pins: { price: listing.price, nonce: listing.nonce, uriHash, recordHash: lc(c.record) },
472
+ };
473
+ }
474
+
475
+ /**
476
+ * Cancelling the listings of agent `id` that `me` may cancel: its own on the market and on `previous` (V2's v1), and a
477
+ * former owner's of an agent `me` now holds (`cancel` allows it once the owner changed, src/AgentMarket.sol:223).
478
+ * { error: "unread" | "noListing" }, or { steps ("cancel", "cancelPrev"), listing, prevListing }. Never paused.
479
+ */
480
+ export function cancelPlan(c, { addr, me }) {
481
+ c = c || {};
482
+ if (unread(c.listing, c.owner) || (addr.previous && c.prevListing == null)) return { error: "unread" };
483
+ const may = (l) => l && isAddr(l.seller) && (same(l.seller, me) || (same(c.owner, me) && !same(l.seller, me)));
484
+ const here = may(c.listing), there = addr.previous ? may(c.prevListing) : false;
485
+ if (!here && !there) return { error: "noListing" };
486
+ return { steps: [...(here ? ["cancel"] : []), ...(there ? ["cancelPrev"] : [])], listing: here ? c.listing : null, prevListing: there ? c.prevListing : null };
487
+ }
488
+
489
+ /** The reserve all of `me`'s open bids take together: price × left over `ids` (bidOf's in c.bids) that `me` made and
490
+ * that stand at `now`, but `except`, plus `extra`. null while one is unread. */
491
+ function reserveOf(c, { ids, me, now, except = [], extra = 0n }) {
492
+ let sum = big(extra);
493
+ for (const k of new Set(ids.map(String))) {
494
+ if (except.includes(k)) continue;
495
+ const b = c.bids.get(k);
496
+ if (b === undefined) continue; // not asked
497
+ if (b === null) return null; // asked, and the read failed
498
+ if (same(b.maker, me) && Number(b.expiry) > Number(now)) sum += big(b.price) * big(b.left);
499
+ }
500
+ return sum;
501
+ }
502
+ /** The terms both bids check first, in the contract's order: the pause, the wallet's standing, the price, the days. */
503
+ function bidTerms(c, { me, now, price, days, expiry }) {
504
+ if (unread(c.paused, c.custodian, c.refused, c.marked, c.cash, c.reserve, c.feeBps, c.minFee)) return { error: "unread" };
505
+ if (c.paused === true) return { error: "paused", until: c.pausedUntil == null ? null : Number(c.pausedUntil) };
506
+ if (c.custodian === true || c.refused === true) return { error: "account" };
507
+ if (big(c.marked) !== 0n) return { error: "marked" };
508
+ const p = typeof price === "bigint" ? price : null;
509
+ if (p == null || p < BID_RULES.minPrice || p >= 2n ** 96n) return { error: "low" };
510
+ const e = expiryOf({ days, expiry, now });
511
+ if (e == null || e <= Number(now) || e > Number(now) + 30 * DAY) return { error: "days" };
512
+ return { p, e, me };
513
+ }
514
+ /**
515
+ * A bid on agent `id` from `me` (web/board-wallet-bids-core.js walletBidPlan, with this server's limits). `myBids`:
516
+ * this wallet's bid ids (its record's and the index's), each read by bidOf in `c.bids`. { error } ("unread", "paused",
517
+ * "account", "marked", "low", "days", "selfBid", "cantSell", "adapter", "record" (`n`, `m`), "listed" (`price`: a
518
+ * listing at or below the bid that a buyer can take now, by buyPlan's rules: one held by a loan, a hold or a seller the
519
+ * market stops doesn't count, as bid() takes the bid then), "short" (`short`, `cash`), "over" (`reserve`, `max`)), or
520
+ * { steps ("approveReserve": the reserve set to exactly what all its open bids and this one take, when the allowance
521
+ * is under it or above `maxReserve`; "bid"), reserve, price, expiry, uriHash (only as its file is now: the URI's bytes
522
+ * hashed here, with `sameFile`), minRepaid, minLine, fee, share, net (what the owner gets now), pins }.
523
+ */
524
+ export function bidPlan(c, { addr, me, id, now, price, days, expiry = null, sameFile = true, minRepaid = 0n, minLine = 0n, myBids = [], maxReserve, minRecord = 0n, adapters = [], shares = false }) {
525
+ c = c || {};
526
+ const t = bidTerms(c, { me, now, price, days, expiry });
527
+ if (t.error) return t;
528
+ const a = c.agent, o = c.agentV1;
529
+ if (noAgent(c)) return { error: "cantSell" };
530
+ if (c.owner == null || a == null || o === null || c.listing == null || c.approved == null || (sameFile && c.uri == null)) return { error: "unread" };
531
+ if (!isAddr(c.owner)) return { error: "cantSell" };
532
+ if (same(c.owner, me)) return { error: "selfBid" };
533
+ if (adapters.some((x) => same(x, c.owner))) return { error: "adapter" };
534
+ if (a.isRoot || a.defaulted || (o && (o.isRoot || o.defaulted))) return { error: "cantSell" };
535
+ if (big(a.loansRepaid) < big(minRecord)) return { error: "record", n: big(minRecord), m: big(a.loansRepaid) };
536
+ const l = liveListing(c, { addr, now });
537
+ if (l && l.price <= t.p) {
538
+ const k = takeChecks(c, { now });
539
+ if (k.error === "unread") return k;
540
+ if (!k.error) return { error: "listed", price: l.price };
541
+ }
542
+ if (big(c.cash) < t.p) return { error: "short", short: t.p - big(c.cash), cash: big(c.cash) };
543
+ const reserve = reserveOf(c, { ids: myBids, me, now, extra: t.p });
544
+ if (reserve == null) return { error: "unread" };
545
+ if (reserve > big(maxReserve)) return { error: "over", reserve, max: big(maxReserve) };
546
+ const bi = builderIn(c, shares);
547
+ if (bi.error) return bi;
548
+ const { fee, share, net } = netOf(t.p, { ...feesOf(c), builder: bi.builder, seller: c.owner });
549
+ const uriHash = sameFile ? lc(ethers.keccak256(ethers.toUtf8Bytes(c.uri))) : ZERO32;
550
+ const r = big(c.reserve), mr = big(minRepaid), ml = big(minLine);
551
+ return { steps: [...(r < reserve || r > big(maxReserve) ? ["approveReserve"] : []), "bid"], reserve, price: t.p, expiry: t.e, uriHash, minRepaid: mr, minLine: ml, fee, share, net,
552
+ pins: { id: big(id), price: t.p, expiry: t.e, uriHash, minRepaid: mr, minLine: ml } };
553
+ }
554
+ /**
555
+ * A bid on up to `count` agents of an origin's list (`set`: /api/hub/origin-set's { root, ids }), `price` each: "badSet"
556
+ * first (its ids don't make its root: the index's answer is refused), "count" (1 to 20, at most the list's size: `max`),
557
+ * then bidPlan's terms, "short" (price × count), "over"; else { steps ("approveReserve", "bidAny"), reserve, price,
558
+ * total, count, root, expiry, minRepaid, minLine, fee, net (what an owner gets now; no share is known before an agent
559
+ * is), pins }.
560
+ */
561
+ export function bidAnyPlan(c, { me, now, set, count, price, days, expiry = null, minRepaid = 0n, minLine = 0n, myBids = [], maxReserve }) {
562
+ c = c || {};
563
+ let root;
564
+ try { root = set && Array.isArray(set.ids) && set.ids.length ? idsRootOf(set.ids) : null; } catch (_) { root = null; }
565
+ if (!root || !HEX32.test(String(set.root)) || lc(set.root) !== root) return { error: "badSet" };
566
+ const max = Math.min(BID_RULES.maxCount, listOf(set.ids).length);
567
+ if (!Number.isSafeInteger(count) || count < 1 || count > max) return { error: "count", max };
568
+ const t = bidTerms(c, { me, now, price, days, expiry });
569
+ if (t.error) return t;
570
+ const total = t.p * BigInt(count);
571
+ if (big(c.cash) < total) return { error: "short", short: total - big(c.cash), cash: big(c.cash) };
572
+ const reserve = reserveOf(c, { ids: myBids, me, now, extra: total });
573
+ if (reserve == null) return { error: "unread" };
574
+ if (reserve > big(maxReserve)) return { error: "over", reserve, max: big(maxReserve) };
575
+ const { fee, net } = netOf(t.p, feesOf(c));
576
+ const r = big(c.reserve), mr = big(minRepaid), ml = big(minLine);
577
+ return { steps: [...(r < reserve || r > big(maxReserve) ? ["approveReserve"] : []), "bidAny"], reserve, price: t.p, total, count, root, expiry: t.e, minRepaid: mr, minLine: ml, fee, net,
578
+ pins: { root, count, price: t.p, expiry: t.e, minRepaid: mr, minLine: ml } };
579
+ }
580
+ /**
581
+ * Cancelling `bidIds` (at most 10) of `me`'s: { error } ("tooMany", "unread", "bidGone" with `bidId`: closed or never
582
+ * made, "notMaker" with `bidId`), or { steps ("cancelBid:<id>" each, then "approveReserve" down to `reserveAfter` when
583
+ * the allowance stands above it), reserveAfter (what its open bids in `myBids` still take) }. Never paused.
584
+ */
585
+ export function cancelBidPlan(c, { me, now, bidIds, myBids = [] }) {
586
+ c = c || {};
587
+ const ids = [...new Set(bidIds.map(String))];
588
+ if (ids.length > 10) return { error: "tooMany" };
589
+ if (!ids.length) return { error: "bidGone", bidId: null };
590
+ for (const k of ids) {
591
+ const b = c.bids.get(k);
592
+ if (b == null) return { error: "unread" };
593
+ if (!isAddr(b.maker)) return { error: "bidGone", bidId: k };
594
+ if (!same(b.maker, me)) return { error: "notMaker", bidId: k };
595
+ }
596
+ if (c.reserve == null) return { error: "unread" };
597
+ const reserveAfter = reserveOf(c, { ids: [...myBids, ...ids], me, now, except: ids });
598
+ if (reserveAfter == null) return { error: "unread" };
599
+ return { steps: [...ids.map((k) => `cancelBid:${k}`), ...(big(c.reserve) > reserveAfter ? ["approveReserve"] : [])], reserveAfter, reserve: reserveAfter, pins: { bidIds: ids } };
600
+ }
601
+ /**
602
+ * Accepting bid `bidId` for agent `id` held by `me` (web/board-wallet-bids-core.js walletAcceptPlan): the bid, its
603
+ * target or list (`proof`, checked with inRoot, never trusted), the maker as a buyer, the sale's rules with `me` as the
604
+ * seller, the maker's pins, the net. { error } ("unread", "gone", "notInBid", "taken", "selfAccept", "maker",
605
+ * "unfunded", "paused", saleChecks' kinds, "repaid" (`n`, `m`), "lineBelow" (`line`), "card", "noNet" (`price`, `fee`:
606
+ * the fee takes the whole price, which the contract allows only when the bid is at the minimum fee)), or { steps
607
+ * ("cancelOldPrev", "cancelOld", "bondApprove", "bond", "approve", "accept", in acceptCalls' order), price, maker,
608
+ * proof, fee, share, net (minNet: exact at the read block; a fee changes only after the market's 48 h, and a share only
609
+ * lower), bond, pins }.
610
+ */
611
+ export function acceptPlan(c, { addr, me, now, bidId, id, proof = [], shares = false }) {
612
+ c = c || {};
613
+ const key = String(bidId), b = c.bids.get(key);
614
+ if (b == null) return { error: "unread" };
615
+ if (!isAddr(b.maker) || Number(b.expiry) <= Number(now)) return { error: "gone" };
616
+ if (!b.any ? lc(b.target) !== lc(idWord(id)) : !inRoot(b.target, String(id), proof)) return { error: "notInBid" };
617
+ if (b.any) { const tk = c.took.get(key); if (tk == null) return { error: "unread" }; if (tk) return { error: "taken" }; }
618
+ if (same(b.maker, me)) return { error: "selfAccept" };
619
+ const mk = c.makers.get(lc(b.maker));
620
+ if (!mk || unread(mk.refused, mk.custodian, mk.marked, mk.cash, mk.reserve)) return { error: "unread" };
621
+ if (mk.refused === true || mk.custodian === true || big(mk.marked) !== 0n) return { error: "maker" };
622
+ if (big(mk.cash) < big(b.price) || big(mk.reserve) < big(b.price)) return { error: "unfunded" };
623
+ const s = saleChecks(c, { me, now });
624
+ if (s.error) return s;
625
+ const a = c.agent;
626
+ if (c.uri == null || unread(c.feeBps, c.minFee)) return { error: "unread" };
627
+ if (big(a.loansRepaid) < big(b.minRepaid)) return { error: "repaid", n: big(b.minRepaid), m: big(a.loansRepaid) };
628
+ if (big(b.minLine) !== 0n && big(a.delegatedIn) < big(b.minLine)) return { error: "lineBelow", line: big(b.minLine) };
629
+ if (BigInt(b.uriHash) !== 0n && lc(ethers.keccak256(ethers.toUtf8Bytes(c.uri))) !== lc(b.uriHash)) return { error: "card" };
630
+ const bi = builderIn(c, shares);
631
+ if (bi.error) return bi;
632
+ const { fee, share, net } = netOf(big(b.price), { ...feesOf(c), builder: bi.builder, seller: me });
633
+ if (net < 1n) return { error: "noNet", price: big(b.price), fee };
634
+ const approved = same(c.approved, addr.market), mine = ownListing(c.listing, me, now);
635
+ let prevMine = null;
636
+ if (addr.previous) { if (c.prevListing == null) return { error: "unread" }; prevMine = ownListing(c.prevListing, me, now); }
637
+ const steps = [...(prevMine ? ["cancelOldPrev"] : []), ...(mine && !approved ? ["cancelOld"] : []), ...(s.bond > 0n && s.bondApprove ? ["bondApprove"] : []),
638
+ ...(s.bond > 0n ? ["bond"] : []), ...(approved ? [] : ["approve"]), "accept"];
639
+ const pr = b.any ? proof.map(lc) : [];
640
+ return { steps, price: big(b.price), maker: lc(b.maker), any: b.any === true, proof: pr, fee, share, net, bond: s.bond,
641
+ pins: { bidId: key, id: big(id), price: big(b.price), maker: lc(b.maker), minNet: net } };
642
+ }
643
+
644
+ /* ---- the calls ---- */
645
+
646
+ const ERC20 = new ethers.Interface(["function approve(address spender, uint256 amount) returns (bool)"]);
647
+ const REGISTRY = new ethers.Interface(["function approve(address to, uint256 tokenId)"]);
648
+ const BOND_V2 = new ethers.Interface(["function deposit(uint256 agentId)"]);
649
+ const to_ = (a) => ethers.getAddress(a).toLowerCase();
650
+ /**
651
+ * One step's transaction: { to, data }. `o`: { addr (marketKindOf's), id, now (the block's time, for the bids' terms),
652
+ * and the plan's own: price, expiry, bond, pins, reserve, proof, net, root, count, uriHash, minRepaid, minLine }.
653
+ */
654
+ export function stepCalls(step, o) {
655
+ const a = o.addr, id = o.id == null ? null : big(o.id);
656
+ const market = (fn, args) => ({ to: to_(a.market), data: MARKET_IFACE.encodeFunctionData(fn, args) });
657
+ if (step === "cancelOld" || step === "cancel") return market("cancel", [id]);
658
+ if (step === "cancelOldPrev" || step === "cancelPrev") return { to: to_(a.previous), data: MARKET_IFACE.encodeFunctionData("cancel", [id]) };
659
+ if (step === "bondApprove") return { to: to_(a.usdg), data: ERC20.encodeFunctionData("approve", [to_(a.inviteBondV2), big(o.bond)]) };
660
+ if (step === "bond") return { to: to_(a.inviteBondV2), data: BOND_V2.encodeFunctionData("deposit", [id]) };
661
+ if (step === "approve") return { to: to_(a.registry), data: REGISTRY.encodeFunctionData("approve", [to_(a.market), id]) };
662
+ if (step === "list") return market("list", [id, big(o.price), BigInt(o.expiry)]);
663
+ if (step === "approveUsdg") return { to: to_(a.usdg), data: ERC20.encodeFunctionData("approve", [to_(a.market), big(o.pins.price)]) };
664
+ if (step === "buy") return market("buy", [id, big(o.pins.price), big(o.pins.nonce), o.pins.uriHash, o.pins.recordHash]);
665
+ if (step === "approveReserve") return reserveCall({ market: a.market, amount: big(o.reserve), usdg: a.usdg });
666
+ if (step === "bid") return bidCall({ market: a.market, id, price: o.price, expiry: o.expiry, now: o.now, uriHash: o.uriHash, minRepaid: o.minRepaid, minLine: o.minLine });
667
+ if (step === "bidAny") return bidAnyCall({ market: a.market, root: o.root, count: o.count, price: o.price, expiry: o.expiry, now: o.now, minRepaid: o.minRepaid, minLine: o.minLine });
668
+ if (step.startsWith("cancelBid:")) return cancelBidCall({ market: a.market, bidId: step.slice("cancelBid:".length) });
669
+ if (step === "accept") return acceptCall({ market: a.market, bidId: o.pins.bidId, id, proof: o.proof || [], minNet: o.pins.minNet });
670
+ throw new Error(`no such step: ${step}`);
671
+ }
672
+ /** What a step's receipt must hold from the market: the event, by name, the final step of each tool ends with. */
673
+ export const STEP_EVENTS = Object.freeze({ list: "Listed", cancel: "Cancelled", cancelPrev: "Cancelled", buy: "Sold", bid: "BidMade", bidAny: "BidAnyMade", accept: "BidTaken" });
674
+
675
+ /* ---- the errors ---- */
676
+
677
+ /**
678
+ * Every error a step can revert with, by signature, and its kind: AgentMarket's and AgentMarketV2's (src/AgentMarket.sol
679
+ * 123-151, src/AgentMarketV2.sol 151-190, the builder share's of the P5 spec 2.8), the pause's (src/GuardianPause.sol
680
+ * 27-32), BidSpender's (src/BidSpender.sol 22), USDG's two as deployed, the registry's approve from a wallet that doesn't
681
+ * hold the agent, and InviteBondV2's deposit's. The board's ERR set (web/board-wallet-core.js) and the bids' (web/
682
+ * board-wallet-bids-core.js), one table. "failed": nothing a plan checks; the step's own words.
683
+ */
684
+ export const MARKET_ERRORS = Object.freeze({
685
+ "NotOwner(uint256,address)": "notOwner", "NotApproved(uint256)": "notApproved", "IsRoot(uint256,address)": "root", "Custodian(address)": "account",
686
+ "Refused(address)": "account", "Marked(address)": "marked", "LoanOpen(uint256,address)": "loan", "AgentDefaulted(uint256,address)": "defaulted",
687
+ "HasLine(uint256)": "line", "Bonded(uint256,address)": "firstBond", "Unbonded(uint256)": "line", "BadRoot(uint256)": "failed",
688
+ "OnHold(uint256,uint256)": "hold", "PriceTooLow(uint256)": "price", "BadExpiry(uint64)": "days", "NoListing(uint256)": "noListing",
689
+ "ListingExpired(uint256,uint64)": "gone", "PriceAbove(uint256,uint256)": "changed", "SelfBuy()": "self", "NonceChanged(uint256,uint256)": "relisted",
690
+ "UriChanged(uint256)": "stale", "LoansChanged(uint256)": "stale", "RecordChanged(uint256)": "recordMoved", "NotTransferred(uint256)": "failed",
691
+ "CannotCancel(uint256,address)": "cannotCancel", "BadFee(uint256,uint256)": "failed", "BadFeeTo(address)": "failed", "NoPendingFee()": "failed",
692
+ "FeeNotReady(uint64)": "failed",
693
+ // V2's bids
694
+ "NoBid(uint256)": "gone", "BidExpired(uint256,uint64)": "gone", "BadBid()": "failed", "NotMaker(uint256,address)": "notMaker", "NotFunded(uint256)": "short",
695
+ "NotInBid(uint256,uint256)": "notInBid", "AlreadyTaken(uint256,uint256)": "taken", "RecordBelow(uint256,uint256)": "repaid", "LineBelow(uint256,uint256)": "lineBelow",
696
+ "NetBelow(uint256,uint256)": "fee",
697
+ // the builder share (the P5 spec, 2.8), once V2 has it: a seller or a buyer never sets one here (BuildersOff: setBuilder
698
+ // before the owner turned shares on)
699
+ "NotBuilder(uint256,address)": "failed", "BuilderTaken(uint256)": "failed", "AlreadySold(uint256)": "failed", "BadShare(uint256)": "failed", "BadBuilder(address)": "failed",
700
+ "PayOutOfGas()": "failed", "BuildersOff()": "failed",
701
+ // the pause
702
+ "IsPaused(uint64)": "paused", "NotGuardian(address)": "failed", "NotTimelock(address)": "failed", "PauseRefused(uint64)": "failed", "BadPause(uint64)": "failed", "ZeroAddress()": "failed",
703
+ // BidSpender: its pull is the market's alone
704
+ "NotMarket(address)": "failed",
705
+ // USDG as deployed, the registry, InviteBondV2's deposit
706
+ "InsufficientAllowance()": "allowance", "InsufficientFunds()": "short", "ERC721InvalidApprover(address)": "notOwner", "ERC721NonexistentToken(uint256)": "cantSell",
707
+ "NotOwner(uint256)": "notOwner", "AgentDefaulted(uint256)": "defaulted", "LoanOpen(uint256)": "loan", "NotTreasuryLine(uint256)": "line", "AlreadyBonded(uint256)": "failed",
708
+ });
709
+ const SELECTORS = new Map(Object.entries(MARKET_ERRORS).map(([sig, kind]) => [ethers.id(sig).slice(0, 10), { sig, kind }]));
710
+ /**
711
+ * A revert's kind from its data ("0x" and the error's selector first; a message that quotes it works too): the known
712
+ * selector found earliest, else "failed". `role` ("accept", "bid", "buy", "sell", "cancel", "cancelBid"): on an accept,
713
+ * a pull that the maker's USDG refused is "unfunded" and UriChanged is the bid's file pin ("card"); SelfBuy is
714
+ * "selfAccept" or "selfBid"; NoBid on a cancel of bids is "bidGone".
715
+ */
716
+ export function errorKindOf(revertData, role = null) {
717
+ const s = String(revertData || "").toLowerCase();
718
+ let best = null, at = Infinity;
719
+ for (const m of s.matchAll(/0x[0-9a-f]{8}/g)) {
720
+ const hit = SELECTORS.get(m[0]);
721
+ if (hit && m.index < at) { best = hit; at = m.index; }
722
+ }
723
+ if (!best) return { kind: "failed", sig: null };
724
+ let kind = best.kind;
725
+ if (role === "accept" && (kind === "allowance" || kind === "short")) kind = "unfunded";
726
+ if (role === "accept" && best.sig === "UriChanged(uint256)") kind = "card";
727
+ if (role === "cancelBid" && kind === "gone") kind = "bidGone";
728
+ if (kind === "self" && role === "accept") kind = "selfAccept";
729
+ if (kind === "self" && role === "bid") kind = "selfBid";
730
+ if (kind === "price" && role === "bid") kind = "low";
731
+ return { kind, sig: best.sig };
732
+ }
733
+
734
+ /* ---- the words ---- */
735
+
736
+ /**
737
+ * The refusals by kind (the P7 spec, section 10.3), {placeholders} filled by planWords. Each says what is wrong, then
738
+ * what to do; the tool adds "Nothing was signed or sent." A bid's and an accept's own kinds take BID_REFUSALS first.
739
+ */
740
+ export const PLAN_WORDS = Object.freeze({
741
+ // this server's settings
742
+ sellOff: "This server doesn't sell agents. The user can allow it with PRIORS_MARKET_SELL.",
743
+ sellNotListed: "This server doesn't sell #{id}. The user can add it to PRIORS_MARKET_SELL.",
744
+ ownAgent: "#{id} is the agent this server acts for, and this server never sells it. Sell it from Go mode or the board.",
745
+ floor: "{price} USDG is under this server's floor of {floor} USDG for one agent. Ask more, or the user can lower PRIORS_MARKET_MIN_SELL_USD.",
746
+ floorNet: "This would leave this wallet {net} USDG after the fee{and}, under this server's floor of {floor} USDG for one agent. The user can lower PRIORS_MARKET_MIN_SELL_USD.",
747
+ ceiling: "This could take {amount} USDG, above this server's limit of {max} USDG for one buy or bid. The user can raise PRIORS_MAX_MARKET_USD.",
748
+ day: "This would bring today's buys and bids for agent #{self} and this wallet to {total} USDG, above {cap} USDG a day. {used} USDG was counted today, and the limit starts again at 00:00 UTC.",
749
+ bidsOver: "Your open bids would take up to {reserve} USDG, above this server's limit of {max} USDG. Cancel a bid, then bid.",
750
+ dupBid: "This wallet made bid #{bidId} on the same terms in the last 10 minutes, and it is still open. To bid again, cancel it with market_cancel_bid, then bid.",
751
+ record: "#{id} has {m} repaid loan{s}. This server buys and bids only on agents with {n} or more.",
752
+ // money
753
+ keepBack: "Agent #{self} owes {owed} USDG on its open loans, due {due}. This would leave {left} USDG to repay them. Repay the loans, or add USDG.",
754
+ short: "This wallet holds {cash} USDG. Add {short} USDG, then try again.",
755
+ shortBond: "#{id}'s line needs a {bond} USDG bond before it can change hands, and this wallet holds {cash} USDG. Add {short} USDG, then try again.",
756
+ noEth: "This wallet holds no ETH on Robinhood Chain for gas. Add a little ETH, then try again.",
757
+ lowEth: "This wallet holds {have} ETH on Robinhood Chain, and these steps need up to {need} ETH for gas. Add ETH, then try again.",
758
+ // the agent
759
+ notOwner: "This wallet doesn't hold #{id}. Its owner is {owner}.",
760
+ gone: "#{id} isn't for sale now. Its listing ended, or its seller no longer holds it or no longer lets the market move it.",
761
+ changed: "#{id} asks {price} USDG now, above your {max}. Read it again, then buy.",
762
+ relisted: "#{id}'s listing changed since it was read. It asks {price} USDG now. Read it again, then buy.",
763
+ stale: "#{id}'s file or its record changed after it was listed, so this listing can't be bought. Its seller has to list it again.",
764
+ recordMoved: "#{id}'s record changed since it was read. Read it again, then buy.",
765
+ fileMoved: "#{id}'s file changed since it was read. Read it again, then bid.",
766
+ sellerBlocked: "#{id}'s seller can't sell on the market now, so its listing can't be bought.",
767
+ self: "This wallet listed #{id}. Use market_cancel to stop selling.",
768
+ loan: "#{id} has a loan open. It can change hands once the loan is repaid.",
769
+ line: "#{id}'s line can't go with it. Its owner leaves the line before a sale.",
770
+ hold: "#{id} changed hands in the last 14 days. It can change hands again on {date}.",
771
+ root: "#{id} backs other agents' lines. It can't be sold here.",
772
+ defaulted: "#{id} has a default on the pool. It can't be sold here.",
773
+ firstBond: "#{id} has a bond on the older InviteBond. It can't change hands here while that bond stands.",
774
+ cantSell: "#{id} can't be sold here.",
775
+ adapter: "#{id} can't be sold here. Its NFT's adapter holds it.",
776
+ noListing: "This wallet has no listing of #{id} to cancel.",
777
+ cannotCancel: "This listing of #{id} isn't this wallet's to cancel. Its seller still holds the agent.",
778
+ notApproved: "The market isn't approved for #{id}. Nothing of it can move until it is.",
779
+ price: "A listing asks 5 USDG or more. Raise the price, then list.",
780
+ days: "A listing or a bid lasts 1 to 30 days. Pick a number of days in that range.",
781
+ // the account and the market
782
+ account: "This wallet can't buy or sell on the market.",
783
+ marked: "This wallet has a default on the pool. It can't buy or sell on the market.",
784
+ paused: "The market is paused{until}. Cancelling still works.",
785
+ unknownMarket: "The market at {market} doesn't answer as the market this server knows. Update @priors/mcp.",
786
+ unread: "The chain couldn't be read just now. Try again in a minute.",
787
+ allowance: "The USDG approved for this step was short when it ran. Read it again, then try again.",
788
+ failed: "The market refused this step ({why}). Read the agent again with market_agent.",
789
+ // the bids, where a sale's word is wrong
790
+ notMaker: "Bid #{bidId} isn't this wallet's. Only its maker can cancel it.",
791
+ bidGone: "Bid #{bidId} isn't open now. It was cancelled, taken or ran out, or there is no such bid.",
792
+ noNet: "This bid is {price} USDG and the market's fee is {fee} USDG, so it would leave this wallet nothing. It can't be accepted.",
793
+ tooMany: "market_cancel_bid cancels at most 10 bids a call. Cancel the rest in another call.",
794
+ count: "A bid on an origin takes 1 to {max} agents here. Pick a count in that range.",
795
+ noBids: "This wallet has no open bid to cancel.",
796
+ badSet: "Priors' hub answered a list whose ids don't make its root, so this server didn't use it. Try again later.",
797
+ // the hub
798
+ hubDown: "Priors' hub at {hub} didn't answer, so {what} can't be read. Try again later.",
799
+ noSet: "Priors' hub has no list for {origin} now. Bid on one agent instead.",
800
+ });
801
+ /** A bid's and an accept's refusals: market-bids' BID_WORDS.errors as they are, but "over" (this server's own limit),
802
+ * the two that name Go mode's buttons, which this server doesn't have, "notInBid", said here without the list's day
803
+ * (an accept may not have read it), and "badSet", which says what the hub did (the tool adds that nothing was sent). */
804
+ export const BID_REFUSALS = Object.freeze({
805
+ ...BID_WORDS.errors,
806
+ over: PLAN_WORDS.bidsOver,
807
+ selfBid: "This wallet holds #{id}. Use market_list to set a price.",
808
+ selfAccept: "This is this wallet's own bid. Cancel it with market_cancel_bid.",
809
+ notInBid: "This agent isn't in that bid's list. market_agent shows the bids it can take, with their proofs.",
810
+ badSet: PLAN_WORDS.badSet,
811
+ });
812
+ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
813
+ /** The words of kind `kind` for `role` ("bid" and "accept" read BID_REFUSALS first), {placeholders} filled from `vars`:
814
+ * bigints as USDG amounts ("1.20"), but ids (id, bidId, self: "#7311") and counts (n, m, count: "1,204") as whole
815
+ * numbers. */
816
+ export function planWords(kind, vars = {}, role = null) {
817
+ const t = (role === "bid" || role === "accept") && own(BID_REFUSALS, kind) ? BID_REFUSALS[kind] : own(PLAN_WORDS, kind) ? PLAN_WORDS[kind] : PLAN_WORDS.failed;
818
+ return t.replace(/\{(\w+)\}/g, (_, k) => {
819
+ const v = vars[k];
820
+ if (v == null) return k === "until" ? "" : k === "why" ? "no reason given" : `{${k}}`;
821
+ if (typeof v === "bigint") return ["id", "bidId", "self"].includes(k) ? String(v) : ["n", "m", "count"].includes(k) ? String(v).replace(/\B(?=([0-9]{3})+(?![0-9]))/g, ",") : amountText(v);
822
+ return String(v);
823
+ });
824
+ }