@priors/mcp 0.12.2 → 0.13.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,442 @@
1
+ // AgentMarketV2's bids, the seam (the bids spec, sections 2.3 and 5; docs/AGENT-MARKET.md "Bids"): the calls, events
2
+ // and errors of the bids as the listings index (data-worker/market-index.mjs), the gas gate, Go mode, the board, the
3
+ // MCP and the contract itself (src/AgentMarketV2.sol, src/interfaces/IAgentBids.sol) all name them; the address of the
4
+ // bids' USDG spender; the lists of agent ids a bid on an origin names, as Merkle roots; `bidView`, the words an open bid
5
+ // says; and the calls an agent or a script sends. sdk/market-abi.mjs, v1's seam, stays frozen: V2 is v1's list, cancel
6
+ // and buy unchanged, plus bids and the builder share (sdk/market-builders.mjs), so V2's ABI here is v1's pieces, the
7
+ // bids and the share's.
8
+ //
9
+ // A bid is funded by allowance, not escrow. The maker approves a USDG reserve to BidSpender, a child contract the
10
+ // market creates in its constructor (its only CREATE, so the spender is CREATE(market, nonce 1): spenderOf below), and
11
+ // the USDG stays in the maker's account until an owner accepts. One reserve backs many bids. The market and the spender
12
+ // hold no USDG and no agent between calls, as v1. Bids live on chain: `bid` and `bidAny` store the bid by msg.sender
13
+ // and emit an event; there are no signatures, no off-chain store and no write API.
14
+ //
15
+ // bid(id, price, expiry, uriHash, minRepaid, minLine) a bid on one agent; uriHash 0 (any file) or
16
+ // keccak256(tokenURI) as read (market-abi uriHashOf)
17
+ // bidAny(root, count, price, expiry, minRepaid, minLine) a bid on up to `count` (1 to 20) agents of one list, named
18
+ // by its Merkle root (idsRootOf); price is for one agent
19
+ // cancelBid(bidId) the maker, at any time; never paused
20
+ // acceptBid(bidId, id, proof, minNet) the agent's owner sells it to the maker in one transaction:
21
+ // v1's rules with the caller as seller, the maker as a buyer,
22
+ // the maker's pins, then the spender pulls the agent's
23
+ // builder share to its builder, price - fee - share to the
24
+ // seller and the fee to feeTo, and the registry moves the
25
+ // agent; minNet is the seller's pin against a fee applied or
26
+ // a share changed meanwhile (both taken from the seller's
27
+ // side)
28
+ //
29
+ // A list's leaf is keccak256(bytes.concat(keccak256(abi.encode(uint256 id)))), OpenZeppelin's double-hashed leaf, and
30
+ // the tree is sdk/credit-profile.mjs's (merkleRoot, merkleProof, verifyProof): ids whole, deduplicated and sorted
31
+ // ascending, pairs hashed sorted, an odd node carried up unchanged; OpenZeppelin's MerkleProof checks its proofs.
32
+ // test/vectors/agent-bids.json (scripts/bid-vectors.mjs) holds the selectors, topics and errors, leaves, roots and proofs
33
+ // for lists of 1, 2, 3, 7 and 1,000 ids, spenderOf of three addresses and sample calls; the contract's forge tests read
34
+ // it back, and scripts/test-market-bids.mjs holds this module to it.
35
+ //
36
+ // An open bid's amount is shown as an asking price is. An accepted bid's amount is a sold price: `BidTaken` carries it
37
+ // because the chain does, and nothing here words it.
38
+ import { ethers } from "ethers";
39
+ import DEP from "../deployments/4663.v2.json" with { type: "json" };
40
+ import { MARKET_FUNCTIONS, MARKET_EVENTS, MARKET_ADMIN_EVENTS, LISTING_RULES, feeOf } from "./market-abi.mjs";
41
+ import { toId, merkleRoot, merkleProof, verifyProof } from "./credit-profile.mjs";
42
+ import { usdgText } from "./work-types.mjs";
43
+ import { BUILDER_FUNCTIONS, BUILDER_EVENTS, BUILDER_WORDS, splitOf, withShare } from "./market-builders.mjs";
44
+
45
+ /* ---- the contract ---- */
46
+
47
+ /** The constructor: v1's ten (market-abi MARKET_CONSTRUCTOR, in the same order), then `previous`: AgentMarket v1, or
48
+ * zero on a chain without one; V2 reads its lastSoldAt so the 14-day hold spans both markets. The guardian and
49
+ * `timelock` (the owner of the settings) are the Safe, as for v1; the fee still waits the market's own 48 h. */
50
+ export const MARKET_V2_CONSTRUCTOR = "constructor(address registry, address usdg, address poolV2, address poolV1, address inviteBond, address inviteBondV2, address feeTo, uint256 lineRoot, address guardian, address timelock, address previous)";
51
+
52
+ /** A bid as bidOf returns it (IAgentBids.Bid, four slots), field by field. `maker` zero: no bid (never made, cancelled,
53
+ * or used up). `target` is bytes32(agentId) for a bid on one agent, the list's root for a bid on an origin; `uriHash`
54
+ * is 0 for a bid on an origin. */
55
+ export const BID_FIELDS = Object.freeze(["maker", "expiry", "left", "any", "price", "minLine", "minRepaid", "target", "uriHash"]);
56
+ const BID_TUPLE = "tuple(address maker, uint64 expiry, uint16 left, bool any, uint96 price, uint96 minLine, uint64 minRepaid, bytes32 target, bytes32 uriHash)";
57
+
58
+ /**
59
+ * The bid calls (spec 2.3). bid, bidAny and acceptBid stop while GuardianPause is paused; cancelBid never does. The
60
+ * views: bidOf(bidId); bidTook(bidId, id), true once a bid on an origin took that agent (it never takes one twice);
61
+ * nextBidId (the first bid is 1); bidSpender (the reserve's spender, spenderOf(market)); previous (v1, or zero).
62
+ * lastSoldAt(id) is in MARKET_FUNCTIONS: on V2 it is the later of V2's own and previous's.
63
+ */
64
+ export const BID_FUNCTIONS = Object.freeze([
65
+ "function bid(uint256 id, uint256 price, uint64 expiry, bytes32 uriHash, uint256 minRepaid, uint256 minLine) returns (uint256 bidId)",
66
+ "function bidAny(bytes32 root, uint256 count, uint256 price, uint64 expiry, uint256 minRepaid, uint256 minLine) returns (uint256 bidId)",
67
+ "function cancelBid(uint256 bidId)",
68
+ "function acceptBid(uint256 bidId, uint256 id, bytes32[] proof, uint256 minNet)",
69
+ `function bidOf(uint256 bidId) view returns (${BID_TUPLE} bid)`,
70
+ "function bidTook(uint256 bidId, uint256 id) view returns (bool)",
71
+ "function nextBidId() view returns (uint256)",
72
+ "function bidSpender() view returns (address)",
73
+ "function previous() view returns (address)",
74
+ ]);
75
+
76
+ /** The four bid events the index reads, fixed now so the index and the contract agree (docs/AGENT-MARKET.md, "Bid
77
+ * events"). An accept also emits v1's `Cancelled` first when a listing of the agent stood. */
78
+ export const BID_EVENTS = Object.freeze([
79
+ "event BidMade(uint256 indexed bidId, uint256 indexed agentId, address indexed maker, uint256 price, uint64 expiry, bytes32 uriHash, uint256 minRepaid, uint256 minLine)",
80
+ "event BidAnyMade(uint256 indexed bidId, bytes32 indexed root, address indexed maker, uint256 price, uint256 count, uint64 expiry, uint256 minRepaid, uint256 minLine)",
81
+ "event BidCancelled(uint256 indexed bidId, address indexed maker)",
82
+ "event BidTaken(uint256 indexed agentId, address indexed seller, address indexed maker, uint256 bidId, uint256 price, uint256 fee, bytes32 recordHash)",
83
+ ]);
84
+
85
+ /** The bids' errors (spec 2.3): the new ones, then the four reused from v1 with v1's signatures (so v1's selectors),
86
+ * then BidSpender's. An accept also fails with any of v1's sale errors (NotOwner, OnHold, ...). Not in MARKET_V2_ABI;
87
+ * `new ethers.Interface(BID_ERRORS)` decodes them. */
88
+ export const BID_ERRORS = Object.freeze([
89
+ "error NoBid(uint256 bidId)",
90
+ "error BidExpired(uint256 bidId, uint64 expiry)",
91
+ "error BadBid()",
92
+ "error NotMaker(uint256 bidId, address caller)",
93
+ "error NotFunded(uint256 amount)",
94
+ "error NotInBid(uint256 bidId, uint256 id)",
95
+ "error AlreadyTaken(uint256 bidId, uint256 id)",
96
+ "error RecordBelow(uint256 id, uint256 loansRepaid)",
97
+ "error LineBelow(uint256 id, uint256 delegatedIn)",
98
+ "error NetBelow(uint256 net, uint256 minNet)",
99
+ "error SelfBuy()",
100
+ "error PriceTooLow(uint256 price)",
101
+ "error BadExpiry(uint64 expiry)",
102
+ "error UriChanged(uint256 id)",
103
+ "error NotMarket(address caller)",
104
+ ]);
105
+
106
+ /** V2's whole ABI, human-readable (ethers), and its Interface: v1's calls and events unchanged, plus the bids and the
107
+ * builder share's (sdk/market-builders.mjs). */
108
+ export const MARKET_V2_ABI = Object.freeze([MARKET_V2_CONSTRUCTOR, ...MARKET_FUNCTIONS, ...BID_FUNCTIONS, ...BUILDER_FUNCTIONS, ...MARKET_EVENTS, ...BID_EVENTS, ...BUILDER_EVENTS, ...MARKET_ADMIN_EVENTS]);
109
+ export const MARKET_V2_IFACE = new ethers.Interface(MARKET_V2_ABI);
110
+ /** Each bid event's topic0. */
111
+ export const BID_TOPICS = Object.freeze({
112
+ BidMade: MARKET_V2_IFACE.getEvent("BidMade").topicHash,
113
+ BidAnyMade: MARKET_V2_IFACE.getEvent("BidAnyMade").topicHash,
114
+ BidCancelled: MARKET_V2_IFACE.getEvent("BidCancelled").topicHash,
115
+ BidTaken: MARKET_V2_IFACE.getEvent("BidTaken").topicHash,
116
+ });
117
+
118
+ /* ---- the rules ---- */
119
+
120
+ const DAY = 86400;
121
+ /**
122
+ * The bid rules (amounts in USDG units, times in seconds). A bid is 5 USDG or more for one agent, as a listing, and
123
+ * lives at most 30 days (7 by default on Priors' screens). A bid on an origin takes 1 to 20 agents; an accept's proof is
124
+ * at most 32 hashes. The maker's balance and allowance must cover price × count when it bids; after that the index
125
+ * shows only the bids its funds cover. maxSponsored is Go mode's cap: all of an account's open bids together at most
126
+ * 1,000 USDG, the reserve included. A wallet of its own has no cap but its reserve.
127
+ */
128
+ export const BID_RULES = Object.freeze({
129
+ minPrice: 5_000_000n, // 5 USDG (LISTING_RULES.minPrice)
130
+ maxLifeS: 30 * DAY,
131
+ defaultDays: 7,
132
+ maxCount: 20,
133
+ maxProof: 32,
134
+ maxSponsored: 1_000_000_000n, // 1,000 USDG
135
+ });
136
+
137
+ const U64 = 2n ** 64n - 1n, U96 = 2n ** 96n - 1n;
138
+ const HEX32 = /^0x[0-9a-fA-F]{64}$/;
139
+
140
+ /** An address, checksummed or all lower case, never zero; lower case. */
141
+ function addressOf(a, what) {
142
+ let x;
143
+ try { x = ethers.getAddress(a); } catch (_) { throw new Error(`${what} must be an address`); }
144
+ if (x === ethers.ZeroAddress) throw new Error(`${what} must not be the zero address`);
145
+ return x.toLowerCase();
146
+ }
147
+
148
+ /**
149
+ * The bids' USDG spender for a market: CREATE(market, nonce 1), the BidSpender its constructor makes, lower case. Go
150
+ * mode, the gas gate and the board derive it from the market's address and check it against the market's own
151
+ * bidSpender(); the reserve is approved to it and to nothing else.
152
+ */
153
+ export const spenderOf = (market) => ethers.getCreateAddress({ from: addressOf(market, "the market"), nonce: 1 }).toLowerCase();
154
+
155
+ /* ---- the lists a bid on an origin names ---- */
156
+
157
+ const coder = ethers.AbiCoder.defaultAbiCoder();
158
+ /** An agent id's leaf: keccak256(bytes.concat(keccak256(abi.encode(uint256 id)))), lower case. */
159
+ export const leafOf = (id) => ethers.keccak256(ethers.keccak256(coder.encode(["uint256"], [toId(id, "an agent id")])));
160
+
161
+ /** A list of agent ids as its root commits to it: whole numbers (bigints, decimal strings or safe integers), each once,
162
+ * ascending, as decimal strings. At least one. */
163
+ export function listOf(ids) {
164
+ if (!Array.isArray(ids) || !ids.length) throw new Error("a list names at least one agent id");
165
+ const out = [...new Set(ids.map((v) => toId(v, "an agent id")))];
166
+ return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).map(String);
167
+ }
168
+
169
+ /** The root a bid on these ids names (bidAny's root), lower case. */
170
+ export const idsRootOf = (ids) => merkleRoot(listOf(ids).map(leafOf));
171
+
172
+ /** The proof acceptBid passes for `id` in the list `ids` (bytes32 values, lower case; [] for a list of one), or null
173
+ * when the id is not in it. */
174
+ export function proofOf(ids, id) {
175
+ const list = listOf(ids), i = list.indexOf(toId(id, "an agent id").toString());
176
+ return i < 0 ? null : merkleProof(list.map(leafOf), i);
177
+ }
178
+
179
+ /** Whether `proof` shows `id` in the list whose root is `root`, as the contract checks it (at most 32 hashes, each a
180
+ * bytes32). Anything that is not such a proof, or an id that is not a whole number, is false: an answer from elsewhere
181
+ * (the API, a link) is checked here, never trusted. */
182
+ export function inRoot(root, id, proof) {
183
+ if (typeof root !== "string" || !HEX32.test(root) || BigInt(root) === 0n) return false;
184
+ if (!Array.isArray(proof) || proof.length > BID_RULES.maxProof || !proof.every((p) => typeof p === "string" && HEX32.test(p))) return false;
185
+ let leaf;
186
+ try { leaf = leafOf(id); } catch (_) { return false; }
187
+ return verifyProof(proof.map((p) => p.toLowerCase()), root.toLowerCase(), leaf);
188
+ }
189
+
190
+ /* ---- what a bid says (spec 13) ---- */
191
+
192
+ /** An amount as the words say it: "40" for a whole amount, "40.50" otherwise (market-abi's priceWords). */
193
+ const noCents = (text) => text.replace(/\.00$/, "");
194
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
195
+ const dayWords = (s) => { const d = new Date(Number(s) * 1000); return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}`; };
196
+ /** A count with thousands marked, the same in every runtime: 1000 is "1,000". */
197
+ const countWords = (n) => String(n).replace(/\B(?=([0-9]{3})+(?![0-9]))/g, ",");
198
+ /** A UTC day ("2026-10-27", as the data Worker writes a list's day) or unix seconds, as seconds. */
199
+ function dayS(day) {
200
+ if (typeof day === "string" && /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(day)) {
201
+ const t = Date.parse(`${day}T00:00:00Z`);
202
+ if (Number.isFinite(t)) return t / 1000;
203
+ }
204
+ if (Number.isSafeInteger(day) && day > 0) return day;
205
+ throw new Error("a list's day is a UTC day like 2026-10-27");
206
+ }
207
+
208
+ /**
209
+ * The words of bids, one set for every surface (the board, Go mode and the MCP translate or show them; none says a
210
+ * sold price). The first group is bidView's: the maker's pins, then a bid on an origin's list. Then the sheet lines
211
+ * for making a bid and for accepting one, the refusals by kind, and the bell.
212
+ */
213
+ export const BID_WORDS = Object.freeze({
214
+ sameFile: "Only as its file is now.",
215
+ line: "Only with its {line} USDG line.",
216
+ repaid: "Only with {n} repaid loans or more.",
217
+ repaidOne: "Only with 1 repaid loan or more.",
218
+ anyOf: "Any one of the {n} {origin} agents the Directory listed on {date}.",
219
+ left: "{left} of {count} left.",
220
+ stays: "Your USDG stays in your account until an owner accepts. Priors holds nothing.",
221
+ making: "{price} USDG for #{id}. The owner gets {net} after the fee. Until {date}.",
222
+ makingShare: "{price} USDG for #{id}. The owner gets {net} after the fee and the builder share. Until {date}.",
223
+ newOwner: "If #{id} changes hands, its new owner can accept too.",
224
+ firstOwner: "The first owner to accept sells you one.",
225
+ reserve: "Your bids can take up to {x} USDG from your account. A bid past that waits until you add USDG.",
226
+ accepting: "{by} pays {price} USDG for #{id}. You get {net} after the fee, and #{id} goes to them at once.",
227
+ acceptingShare: "{by} pays {price} USDG for #{id}. You get {net} after the fee and the builder share, and #{id} goes to them at once.",
228
+ yours: "#{id} is yours. Lock your own {bond} USDG bond before it borrows on its line.",
229
+ errors: Object.freeze({
230
+ gone: "This bid is closed. It was cancelled, used or ran out.",
231
+ unfunded: "This bid can't be taken right now. Its maker doesn't have the USDG approved for it.",
232
+ maker: "This bid's maker can't buy right now. Choose another bid.",
233
+ card: "This agent's file changed since the bid. The bid asked for the file as it was.",
234
+ repaid: "The bid asks for {n} repaid loans or more. This agent has {m}.",
235
+ lineBelow: "The bid asks for its {line} USDG line. The line is smaller or gone now.",
236
+ notInBid: "This agent isn't in that bid's list. The list is the Directory's of {date}.",
237
+ taken: "This bid already took this agent. Choose another bid.",
238
+ selfBid: "You hold this agent. Use Sell to set a price.",
239
+ selfAccept: "This is your own bid. Cancel it from Your bids.",
240
+ listed: "It's listed for {price} USDG. Buy it instead.",
241
+ low: "A bid is 5 USDG or more. Raise it, then bid.",
242
+ over: "Go mode bids up to 1,000 USDG in all. Cancel a bid, or bid from your own wallet on the board.",
243
+ short: "You have {cash} USDG. Add {short} more, then bid.",
244
+ cantSell: "This agent can't be sold here.",
245
+ adapter: "This agent can't be sold here. Its NFT's adapter holds it.",
246
+ hold: "This agent changed hands in the last 14 days. It can be sold again on {date}.",
247
+ loan: "This agent has a loan open. Repay it, then accept.",
248
+ line: "This agent's line can't go with it. Leave the line, then accept.",
249
+ fee: "The fee changed since you looked. Read the bid again, then accept.",
250
+ paused: "Bids are paused for now. Cancelling still works.",
251
+ badSet: "This list didn't check out. Nothing was sent.",
252
+ }),
253
+ bell: Object.freeze({
254
+ made: "A bid of {price} USDG on #{id}.",
255
+ taken: "Your bid on #{id} was accepted. #{id} is yours.",
256
+ tookAny: "Your bid on any {origin} agent took #{id}.",
257
+ }),
258
+ });
259
+ /** The keys of bidView's answer, in order. */
260
+ export const BID_VIEW_KEYS = Object.freeze(["price", "fee", "sellerGets", "expiresAt", "left", "needs", "words"]);
261
+
262
+ /**
263
+ * What an open bid says, for the board, Go mode and the MCP alike: { price, fee, sellerGets (USDG, written: "40.00"),
264
+ * expiresAt, left (the agents it can still take; 1 for a bid on one agent), needs ({ sameFile, repaid, line }: the
265
+ * maker's pins; line written, or null), words (the first like a listing's, "40 USDG. Fee 1. The owner gets 39. Until 3
266
+ * Nov."; for a bid on an origin, its list and how many it can still take; then the pins) }.
267
+ *
268
+ * `item` is a bid as bidOf or the index gives it: { price (USDG units, for one agent), expiry, left, any: true (or
269
+ * kind: "any") for a bid on an origin, count (the agents it asked for; default `left`), uriHash, minRepaid, minLine }.
270
+ * `feeBps` and `minFee` are the market's now (default the rules'): an accept takes the fee then, from the owner's side,
271
+ * so a fee applied meanwhile changes what the owner gets, never what the maker pays. `origin`, `n` and `day`, for a bid
272
+ * on an origin: the origin's name, how many agents its list holds and the UTC day the Directory published it; without
273
+ * all three the list is not named. Nothing here depends on the clock, so unlike listingView it takes no `now`.
274
+ *
275
+ * `builderBps` is the agent's builder share (sdk/market-builders.mjs; 0, the default, for none, or when the agent's
276
+ * owner is its builder): an accept pays it from the owner's side too, so `share` is written after `fee`, `sellerGets`
277
+ * is lowered by it and the first line names it ("40 USDG. Fee 1. Builder share 1. The owner gets 38. Until 3 Nov.").
278
+ * null, for a bid on an origin read without an agent: what an owner gets then is at most the price less the fee
279
+ * ("20 USDG each. Fee 1. The owner gets up to 19. Until 20 Nov."). With 0 the answer is as it always was.
280
+ *
281
+ * It throws on a bid the chain could not hold or that no agent could ever fill (below 5 USDG, past uint96, more agents
282
+ * than 20 or left than asked, a file pin on a bid on an origin, a repaid pin past 2^53): callers drop it. An open bid
283
+ * only: there is no accepted price here.
284
+ */
285
+ export function bidView(item, { feeBps = LISTING_RULES.feeBps, minFee = LISTING_RULES.minFee, origin = null, n = null, day = null, builderBps = 0 } = {}) {
286
+ if (!item || typeof item !== "object") throw new Error("bidView takes a bid");
287
+ if (item.kind !== undefined && item.kind !== "agent" && item.kind !== "any") throw new Error('a bid\'s kind is "agent" or "any"');
288
+ const any = item.any === true || item.kind === "any";
289
+ const p = toId(item.price, "price");
290
+ if (p < BID_RULES.minPrice || p > U96) throw new Error("a bid is 5 USDG or more, for one agent");
291
+ const expiresAt = Number(toId(item.expiry, "expiry"));
292
+ const left = toId(item.left ?? 1, "left"), count = any ? toId(item.count ?? left, "count") : 1n;
293
+ if (left < 1n || left > count || count > BigInt(BID_RULES.maxCount) || (!any && left !== 1n)) throw new Error("a bid takes 1 to 20 agents, never more than it asked for");
294
+ const uriHash = item.uriHash == null ? ethers.ZeroHash : String(item.uriHash);
295
+ if (!HEX32.test(uriHash)) throw new Error("uriHash is a bytes32");
296
+ const sameFile = BigInt(uriHash) !== 0n;
297
+ if (any && sameFile) throw new Error("a bid on an origin pins no file");
298
+ const minRepaid = toId(item.minRepaid ?? 0, "minRepaid"), minLine = toId(item.minLine ?? 0, "minLine");
299
+ if (minRepaid > BigInt(Number.MAX_SAFE_INTEGER) || minLine > U96) throw new Error("a pin no agent could meet");
300
+ if (builderBps === null && !any) throw new Error("a bid on one agent knows its agent's builder share");
301
+ const { fee, sellerGets } = feeOf(p, { feeBps, minFee });
302
+ const price = usdgText(p), feeText = usdgText(fee), gets = usdgText(sellerGets);
303
+ const repaid = Number(minRepaid), line = minLine > 0n ? usdgText(minLine) : null;
304
+ const words = [builderBps === null
305
+ ? BUILDER_WORDS.anyEach.replace("{price}", noCents(price)).replace("{fee}", noCents(feeText)).replace("{net}", noCents(gets)).replace("{date}", dayWords(expiresAt))
306
+ : `${noCents(price)} USDG. Fee ${noCents(feeText)}. The owner gets ${noCents(gets)}. Until ${dayWords(expiresAt)}.`];
307
+ if (any) {
308
+ if (origin != null && n != null && day != null) {
309
+ if (typeof origin !== "string" || !origin.trim()) throw new Error("origin is the origin's name");
310
+ if (!Number.isSafeInteger(n) || n < 1) throw new Error("n is how many agents the list holds");
311
+ words.push(BID_WORDS.anyOf.replace("{n}", countWords(n)).replace("{origin}", origin.trim()).replace("{date}", dayWords(dayS(day))));
312
+ }
313
+ words.push(BID_WORDS.left.replace("{left}", String(left)).replace("{count}", String(count)));
314
+ }
315
+ if (sameFile) words.push(BID_WORDS.sameFile);
316
+ if (line) words.push(BID_WORDS.line.replace("{line}", noCents(line)));
317
+ if (repaid === 1) words.push(BID_WORDS.repaidOne);
318
+ else if (repaid > 1) words.push(BID_WORDS.repaid.replace("{n}", countWords(repaid)));
319
+ const view = { price, fee: feeText, sellerGets: gets, expiresAt, left: Number(left), needs: { sameFile, repaid, line }, words };
320
+ return builderBps ? withShare(view, { share: splitOf(p, { feeBps, minFee, bps: builderBps }).share }) : view;
321
+ }
322
+
323
+ /* ---- the calls, for agents and scripts ---- */
324
+
325
+ const ERC20 = new ethers.Interface(["function approve(address spender, uint256 amount) returns (bool)"]);
326
+ const marketCall = (market, fn, args) => ({ to: addressOf(market, "the market"), data: MARKET_V2_IFACE.encodeFunctionData(fn, args) });
327
+
328
+ /** The terms bid and bidAny share, checked as the contract checks them (_bidTerms): price 5 USDG or more and within
329
+ * uint96; an expiry after `now` and within 30 days (`expiry`, or `days` from `now`, 7 by default); minRepaid within
330
+ * uint64, minLine within uint96. */
331
+ function termsOf({ price, expiry, days, now, minRepaid = 0, minLine = 0 }) {
332
+ const p = toId(price, "price");
333
+ if (p < BID_RULES.minPrice) throw new Error("a bid is 5 USDG or more");
334
+ if (p > U96) throw new Error("price is out of range");
335
+ const t = now == null ? BigInt(Math.floor(Date.now() / 1000)) : toId(now, "now");
336
+ if (expiry != null && days != null) throw new Error("give expiry or days, not both");
337
+ let e;
338
+ if (expiry != null) e = toId(expiry, "expiry");
339
+ else {
340
+ const d = days ?? BID_RULES.defaultDays;
341
+ if (!Number.isSafeInteger(d) || d < 1 || d * DAY > BID_RULES.maxLifeS) throw new Error("days is 1 to 30");
342
+ e = t + BigInt(d * DAY);
343
+ }
344
+ if (e <= t || e > t + BigInt(BID_RULES.maxLifeS)) throw new Error("a bid ends after now and within 30 days");
345
+ const r = toId(minRepaid, "minRepaid"), l = toId(minLine, "minLine");
346
+ if (r > U64) throw new Error("minRepaid is out of range");
347
+ if (l > U96) throw new Error("minLine is out of range");
348
+ return { price: p, expiry: e, minRepaid: r, minLine: l };
349
+ }
350
+
351
+ /** The reserve: USDG approve(spenderOf(market), amount), what all of the maker's bids together can take. An exact
352
+ * amount, never an unlimited approval; 0 takes it back (every bid is then not funded). Go mode keeps it at most
353
+ * BID_RULES.maxSponsored. `usdg` defaults to deployments/4663.v2.json's. { to, data } */
354
+ export function reserveCall({ market, amount, usdg = DEP.usdg }) {
355
+ const a = toId(amount, "amount");
356
+ if (a === ethers.MaxUint256) throw new Error("the reserve is an amount, never an unlimited approval");
357
+ return { to: addressOf(usdg, "USDG"), data: ERC20.encodeFunctionData("approve", [spenderOf(market), a]) };
358
+ }
359
+
360
+ /** bid(id, price, expiry, uriHash, minRepaid, minLine): a bid on one agent. `uriHash` 0 (the default) takes the agent
361
+ * with any file; uriHashOf(tokenURI) only as its file is now. { to, data } */
362
+ export function bidCall({ market, id, price, expiry, days, now, uriHash = ethers.ZeroHash, minRepaid = 0, minLine = 0 }) {
363
+ const t = termsOf({ price, expiry, days, now, minRepaid, minLine });
364
+ if (typeof uriHash !== "string" || !HEX32.test(uriHash)) throw new Error("uriHash is a bytes32");
365
+ return marketCall(market, "bid", [toId(id, "id"), t.price, t.expiry, uriHash.toLowerCase(), t.minRepaid, t.minLine]);
366
+ }
367
+
368
+ /** bidAny(root, count, price, expiry, minRepaid, minLine): a bid on up to `count` agents of one list, `price` each.
369
+ * Give the list's `ids` (its root is computed here, and count is at most its size) or its `root`; with both, the root
370
+ * must be the list's. { to, data } */
371
+ export function bidAnyCall({ market, root, ids, count, price, expiry, days, now, minRepaid = 0, minLine = 0 }) {
372
+ const t = termsOf({ price, expiry, days, now, minRepaid, minLine });
373
+ const c = toId(count, "count");
374
+ if (c < 1n || c > BigInt(BID_RULES.maxCount)) throw new Error("a bid on an origin takes 1 to 20 agents");
375
+ let r = root == null ? null : String(root);
376
+ if (r != null && (!HEX32.test(r) || BigInt(r) === 0n)) throw new Error("root is a bytes32, never 0");
377
+ if (ids != null) {
378
+ const list = listOf(ids), mine = merkleRoot(list.map(leafOf));
379
+ if (r != null && r.toLowerCase() !== mine) throw new Error("the root is not the list's");
380
+ if (c > BigInt(list.length)) throw new Error("count is more than the list holds");
381
+ r = mine;
382
+ }
383
+ if (r == null) throw new Error("a bid on an origin names its list: ids or root");
384
+ return marketCall(market, "bidAny", [r.toLowerCase(), c, t.price, t.expiry, t.minRepaid, t.minLine]);
385
+ }
386
+
387
+ /** cancelBid(bidId): the maker's own bid. { to, data } */
388
+ export function cancelBidCall({ market, bidId }) {
389
+ const b = toId(bidId, "bidId");
390
+ if (b < 1n) throw new Error("bid ids start at 1");
391
+ return marketCall(market, "cancelBid", [b]);
392
+ }
393
+
394
+ /** acceptBid(bidId, id, proof, minNet) alone: the owner sells agent `id` to the bid's maker, once the registry's
395
+ * getApproved(id) is the market. To give that approval, use acceptCalls: it cancels a dormant listing first. `proof`:
396
+ * [] for a bid on one agent, proofOf(list, id) for a bid on an origin. `minNet`, the least the owner takes after the
397
+ * fee and the agent's builder share, at least 1 unit (the contract refuses an accept that pays the owner nothing, and
398
+ * so does the gas gate): give it, or give the bid's `price` (and the market's `feeBps` and `minFee`, default the
399
+ * rules', and the agent's `builderBps`, 0 for none or when the owner is its builder: read builderOf(id) or the
400
+ * contract's splitOf) and it is the exact net now. { to, data } */
401
+ export function acceptCall({ market, bidId, id, proof = [], minNet, price, feeBps, minFee, builderBps = 0 }) {
402
+ const b = toId(bidId, "bidId");
403
+ if (b < 1n) throw new Error("bid ids start at 1");
404
+ if (!Array.isArray(proof) || proof.length > BID_RULES.maxProof || !proof.every((p) => typeof p === "string" && HEX32.test(p))) throw new Error("a proof is at most 32 bytes32 values");
405
+ if (minNet == null && price == null) throw new Error("give minNet, or the bid's price");
406
+ const fees = { feeBps: feeBps ?? LISTING_RULES.feeBps, minFee: minFee ?? LISTING_RULES.minFee };
407
+ const net = minNet != null ? toId(minNet, "minNet") : builderBps ? splitOf(toId(price, "price"), { ...fees, bps: builderBps }).net : feeOf(toId(price, "price"), fees).sellerGets;
408
+ if (net < 1n) throw new Error("minNet is at least 1 USDG unit: an accept never pays the owner nothing");
409
+ return marketCall(market, "acceptBid", [b, toId(id, "id"), proof.map((p) => p.toLowerCase()), net]);
410
+ }
411
+
412
+ const REGISTRY = new ethers.Interface(["function approve(address to, uint256 tokenId)"]);
413
+ /** An address as read from the chain (listingOf's seller, getApproved), zero allowed; lower case. */
414
+ function readAddress(a, what) {
415
+ if (a == null) throw new Error(`${what} is read from the chain first (the zero address for none)`);
416
+ try { return ethers.getAddress(a).toLowerCase(); } catch (_) { throw new Error(`${what} must be an address`); }
417
+ }
418
+
419
+ /**
420
+ * The owner's whole accept, in the order a plain wallet sends it, each call only after the one before is mined (or all
421
+ * in one batch):
422
+ * 1. cancel(id), when the owner's own listing of the agent stands while the market is not approved for it. Such a
423
+ * listing is dormant, not gone: the approval below brings it back at its old price and nonce, and anyone could buy
424
+ * it there before the accept lands (docs/AGENT-MARKET.md "Stopping a sale"; the bids spec's walletAcceptPlan);
425
+ * 2. approve(market, id) on the registry, when getApproved(id) is not the market;
426
+ * 3. acceptBid, as acceptCall builds it.
427
+ * `owner` is the account that accepts; `listingSeller` (the market's listingOf(id).seller) and `approved` (the
428
+ * registry's getApproved(id)) are read just before, the zero address for none. `registry` defaults to
429
+ * deployments/4663.v2.json's. The rest is acceptCall's. [{ to, data }, ...]
430
+ */
431
+ export function acceptCalls({ market, registry = DEP.registry, owner, listingSeller, approved, ...accept }) {
432
+ const mkt = addressOf(market, "the market"), who = addressOf(owner, "the owner");
433
+ const seller = readAddress(listingSeller, "listingSeller"), now = readAddress(approved, "approved");
434
+ const last = acceptCall({ market, ...accept });
435
+ const id = toId(accept.id, "id"), calls = [];
436
+ if (now !== mkt) {
437
+ if (seller === who) calls.push(marketCall(market, "cancel", [id]));
438
+ calls.push({ to: addressOf(registry, "the registry"), data: REGISTRY.encodeFunctionData("approve", [mkt, id]) });
439
+ }
440
+ calls.push(last);
441
+ return calls;
442
+ }