@priors/mcp 0.12.1 → 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,254 @@
1
+ // AgentMarketV2's builder share, the seam (the builder share spec, sections 2, 5 and 10; docs/AGENT-MARKET.md "Builder
2
+ // share"): the calls, events and errors of the share as the listings index, the gas gate, Go mode, the board, the MCP
3
+ // and the contract itself (src/AgentMarketV2.sol, src/interfaces/IAgentBuilders.sol) all name them; the split of a
4
+ // price into the fee, the share and the seller's net, exactly as the contract's splitOf makes it; what a listing or a
5
+ // bid says once a share applies; and the calls an agent or a script sends. sdk/market-bids.mjs folds the calls and
6
+ // events into V2's ABI (MARKET_V2_ABI); this module imports nothing from it, so either can be loaded first.
7
+ //
8
+ // The account that holds an agent never sold here (on V2 or on v1, `previous`) sets, once, a share of 1 to 500 bps
9
+ // (0.01% to 5%) of each later sale's price, paid to an address it names, the builder. After that only the builder
10
+ // changes it: lower, or to another address; never higher. The seller pays it out of the price, after the fee and never
11
+ // more than the fee leaves; none when the seller is the builder. The buyer, and a bid's maker, pay the price and no
12
+ // more. A buy pays the lower of the share at list and at buy, as it does the fee; an accept pays the share then, and
13
+ // the seller's minNet holds it. Nobody gets an agent whose share it could not read first: a share is never set while a
14
+ // listing of the agent stands (on V2 or v1: cancel, set, list again), and an accept refuses a bid made before the
15
+ // share was set (builderSince). A builder USDG refuses never stops a sale: the seller gets the share, and the market
16
+ // logs BuilderMissed.
17
+ //
18
+ // setBuilder(id, to, bps) the agent's holder, once, before any sale here and with no listing standing; paused
19
+ // with the trading calls
20
+ // changeBuilder(id, to, bps) the builder only: bps at most the current one (0 allowed), `to` the next builder;
21
+ // never paused
22
+ // enableBuilders() the owner (the Safe) only, once and for good: shares are off from the deploy until
23
+ // then (setBuilder refuses with BuildersOff, so none exists; paused, with IsPaused
24
+ // first); buildersOn() reads it
25
+ //
26
+ // test/vectors/agent-builders.json (scripts/builder-vectors.mjs) holds the selectors, topics, errors, splits and sample
27
+ // calls; the contract's forge tests read it back, and scripts/test-market-builders.mjs holds this module to it.
28
+ //
29
+ // A builder's paid amount is a sold price divided by its rate: `BuilderPaid` carries it because the chain does, and
30
+ // nothing here reads or words it.
31
+ import { ethers } from "ethers";
32
+ import { LISTING_RULES, feeOf } from "./market-abi.mjs";
33
+ import { toId } from "./credit-profile.mjs";
34
+ import { usdgText, usdgUnits } from "./work-types.mjs";
35
+
36
+ /* ---- the contract ---- */
37
+
38
+ /** A share as builderOf returns it (IAgentBuilders.Builder, one slot). `to` zero: no share was ever set. */
39
+ export const BUILDER_FIELDS = Object.freeze(["to", "bps"]);
40
+ const BUILDER_TUPLE = "tuple(address to, uint16 bps)";
41
+
42
+ /**
43
+ * The share's calls (spec 2.4). setBuilder stops while GuardianPause is paused; changeBuilder never does. The views:
44
+ * builderOf(id); builderSince(id), the first bid id an accept of the agent takes (nextBidId when its share was set; 0
45
+ * for none): an older bid is refused; saleSplit(id), what a buy of the standing listing pays now (zeros: no listing),
46
+ * the pins at list included; splitOf(id, price, seller), what an accept at `price` by `seller` pays now;
47
+ * MAX_BUILDER_BPS, 500. The switch: enableBuilders(), the owner's only, once (a second call changes nothing), and
48
+ * buildersOn(), false until then.
49
+ */
50
+ export const BUILDER_FUNCTIONS = Object.freeze([
51
+ "function setBuilder(uint256 id, address to, uint256 bps)",
52
+ "function changeBuilder(uint256 id, address to, uint256 bps)",
53
+ `function builderOf(uint256 id) view returns (${BUILDER_TUPLE} builder)`,
54
+ "function builderSince(uint256 id) view returns (uint256)",
55
+ "function saleSplit(uint256 id) view returns (uint256 fee, uint256 share, uint256 net)",
56
+ "function splitOf(uint256 id, uint256 price, address seller) view returns (uint256 fee, uint256 share, uint256 net)",
57
+ "function MAX_BUILDER_BPS() view returns (uint256)",
58
+ "function enableBuilders()",
59
+ "function buildersOn() view returns (bool)",
60
+ ]);
61
+
62
+ /** The share's events (docs/AGENT-MARKET.md, "Builder events"). A sale that pays a share logs BuilderPaid, or
63
+ * BuilderMissed when USDG refused the builder, just before its Sold or BidTaken. The index reads who and whether,
64
+ * never the amount. BuildersEnabled, with no field, is the owner's switch: logged once, when shares turn on. */
65
+ export const BUILDER_EVENTS = Object.freeze([
66
+ "event BuilderSet(uint256 indexed agentId, address indexed to, uint256 bps)",
67
+ "event BuilderPaid(uint256 indexed agentId, address indexed to, uint256 amount)",
68
+ "event BuilderMissed(uint256 indexed agentId, address indexed to, uint256 amount)",
69
+ "event BuildersEnabled()",
70
+ ]);
71
+
72
+ /** The share's errors (spec 2.8): the new ones, PayOutOfGas (the market's and BidSpender's, one selector), BuildersOff
73
+ * (setBuilder's while the owner has not turned shares on), then the two reused from v1 with v1's signatures.
74
+ * ListingStands names the market where the listing stands (V2 or v1); BuilderAfterBid is acceptBid's, for a bid made
75
+ * before the share was set. `new ethers.Interface(BUILDER_ERRORS)` decodes them. */
76
+ export const BUILDER_ERRORS = Object.freeze([
77
+ "error NotBuilder(uint256 id, address caller)",
78
+ "error BuilderTaken(uint256 id)",
79
+ "error AlreadySold(uint256 id)",
80
+ "error BadShare(uint256 bps)",
81
+ "error BadBuilder(address to)",
82
+ "error ListingStands(uint256 id, address market)",
83
+ "error BuilderAfterBid(uint256 bidId, uint256 id)",
84
+ "error PayOutOfGas()",
85
+ "error BuildersOff()",
86
+ "error NotOwner(uint256 id, address seller)",
87
+ "error PriceTooLow(uint256 price)",
88
+ ]);
89
+
90
+ const IFACE = new ethers.Interface([...BUILDER_FUNCTIONS, ...BUILDER_EVENTS]);
91
+ /** Each builder event's topic0. */
92
+ export const BUILDER_TOPICS = Object.freeze({
93
+ BuilderSet: IFACE.getEvent("BuilderSet").topicHash,
94
+ BuilderPaid: IFACE.getEvent("BuilderPaid").topicHash,
95
+ BuilderMissed: IFACE.getEvent("BuilderMissed").topicHash,
96
+ BuildersEnabled: IFACE.getEvent("BuildersEnabled").topicHash,
97
+ });
98
+
99
+ /* ---- the rules and the split ---- */
100
+
101
+ /** A share is 1 to 500 bps of the price (0.01% to 5%; MAX_BUILDER_BPS); a change may take it to 0. Go mode's form
102
+ * starts at 2.5%. */
103
+ export const BUILDER_RULES = Object.freeze({ minBps: 1, maxBps: 500, defaultBps: 250 });
104
+
105
+ /** Whole bps from 0 (or `min`) to 500. */
106
+ function bpsOf(v, min, what = "bps") {
107
+ if (!Number.isSafeInteger(v) || v < min || v > BUILDER_RULES.maxBps) throw new Error(`${what} is a whole number from ${min} to ${BUILDER_RULES.maxBps}`);
108
+ return v;
109
+ }
110
+
111
+ /**
112
+ * The split of `price` (USDG units) as the contract's splitOf makes it: { fee, share, net } in USDG units. The fee is
113
+ * market-abi's feeOf (`feeBps` and `minFee` the market's now, default the rules'); the share is `bps` of the price,
114
+ * rounded down, never more than what the fee leaves, and none when the seller is the builder (`sellerIsBuilder`) or
115
+ * `bps` is 0. A price under 5 USDG throws, as the contract reverts. A buy of a standing listing pays the lower fee and
116
+ * the lower share of list and now: read saleSplit(id) for that.
117
+ */
118
+ export function splitOf(price, { feeBps = LISTING_RULES.feeBps, minFee = LISTING_RULES.minFee, bps = 0, sellerIsBuilder = false } = {}) {
119
+ const p = toId(price, "price");
120
+ if (p < LISTING_RULES.minPrice) throw new Error("a price is 5 USDG or more");
121
+ const b = BigInt(bpsOf(bps, 0));
122
+ if (typeof sellerIsBuilder !== "boolean") throw new Error("sellerIsBuilder is true or false");
123
+ const { fee } = feeOf(p, { feeBps, minFee });
124
+ let share = sellerIsBuilder ? 0n : (p * b) / 10_000n;
125
+ if (share > p - fee) share = p - fee;
126
+ return { fee, share, net: p - fee - share };
127
+ }
128
+
129
+ /** A share's rate as the words say it: 250 is "2.5%", 500 "5%", 1 "0.01%". */
130
+ export function pctText(bps) {
131
+ const b = bpsOf(bps, 0);
132
+ const frac = String(b % 100).padStart(2, "0").replace(/0+$/, "");
133
+ return `${Math.floor(b / 100)}${frac ? "." + frac : ""}%`;
134
+ }
135
+
136
+ /** An address, checksummed or all lower case, never zero; lower case. */
137
+ function addressOf(a, what) {
138
+ let x;
139
+ try { x = ethers.getAddress(a); } catch (_) { throw new Error(`${what} must be an address`); }
140
+ if (x === ethers.ZeroAddress) throw new Error(`${what} must not be the zero address`);
141
+ return x.toLowerCase();
142
+ }
143
+ const shortAddr = (a) => `${a.slice(0, 6)}…${a.slice(-4)}`;
144
+
145
+ /* ---- the words (spec 10) ---- */
146
+
147
+ /**
148
+ * The words of the builder share, one set for every surface (the board, Go mode and the MCP translate or show them).
149
+ * None says an amount a builder was paid, and none says "royalty". `errors.off` answers BuildersOff, and a paused
150
+ * setBuilder's IsPaused too while buildersOn() is false: the pause is checked first, and `errors.paused` would promise
151
+ * a set once it ends.
152
+ */
153
+ export const BUILDER_WORDS = Object.freeze({
154
+ label: "Builder share",
155
+ yours: "Your builder shares",
156
+ paidTo: "Paid to",
157
+ setShare: "Set builder share",
158
+ lower: "Lower",
159
+ handOver: "Hand over",
160
+ row: "{pct} to {addr}",
161
+ listing: "{price} USDG. Fee {fee}. Builder share {share}. The seller gets {net}. Until {date}.",
162
+ buy: "When you sell #{id} here, {pct} of the price goes to its builder.",
163
+ sell: "{pct} of your price goes to its builder, {addr}.",
164
+ anyEach: "{price} USDG each. Fee {fee}. The owner gets up to {net}. Until {date}.",
165
+ mcp: "Builder share: {pct} of each sale here goes to {addr}.",
166
+ setting: Object.freeze({
167
+ gets: "You get {pct} of the price each time #{id} sells here.",
168
+ later: "You can lower it or hand it to another address later. You can't raise it.",
169
+ before: "It can only be set while #{id} has never been sold here.",
170
+ here: "Sales outside this market pay no share.",
171
+ sellFirst: "Set a builder share before you list. It can't be set once #{id} is sold here.",
172
+ }),
173
+ errors: Object.freeze({
174
+ taken: "#{id} already has a builder share. Only its builder can change it.",
175
+ sold: "#{id} has been sold here already. A builder share can only be set before that.",
176
+ notYours: "Only the account that holds #{id} can set its builder share. Use the account that holds it.",
177
+ high: "A builder share is 5% at most. Lower it, then set it.",
178
+ low: "A builder share is at least 0.01%. Raise it, then set it.",
179
+ raise: "A builder share can only go down. Choose {pct} or less.",
180
+ notBuilder: "Only the builder can change this share. Use the account it pays.",
181
+ badTo: "That address can't receive the share. Choose another address.",
182
+ paused: "Setting a share is paused for now. Lowering one still works.",
183
+ listed: "#{id} is listed for sale. Cancel the listing, set the share, then list it again.",
184
+ afterBid: "This bid was made before #{id} had a builder share, so it can't be accepted. A bid made since can.",
185
+ off: "Builder shares can't be set on this market yet.",
186
+ }),
187
+ bell: Object.freeze({
188
+ paid: "#{id} changed hands here. Your builder share went to your account.",
189
+ missed: "Your builder share for #{id} couldn't be paid. The seller kept it.",
190
+ }),
191
+ });
192
+
193
+ /** A share as the sheet shows it: { to (lower case), bps, pct ("2.5%"), words ("2.5% to 0x1234…abcd") }. `to` is the
194
+ * builder; `bps` 0 to 500 (a share lowered to 0 still has its builder). Null for none (`to` zero or missing). */
195
+ export function builderView(b) {
196
+ if (!b || b.to == null || BigInt(b.to) === 0n) return null;
197
+ const to = addressOf(b.to, "the builder"), bps = bpsOf(Number(b.bps), 0), pct = pctText(bps);
198
+ return { to, bps, pct, words: BUILDER_WORDS.row.replace("{pct}", pct).replace("{addr}", shortAddr(to)) };
199
+ }
200
+
201
+ const noCents = (text) => text.replace(/\.00$/, "");
202
+ /** A listingView's or bidView's first line: "{price} USDG. Fee {fee}. The seller|owner gets {net}. Until {date}." */
203
+ const LINE = /^(.+ USDG\. Fee [0-9]+(?:\.[0-9]+)?\.) The (seller|owner) gets [0-9]+(?:\.[0-9]+)?\. (Until .+\.)$/;
204
+
205
+ /**
206
+ * A listingView (sdk/market-abi.mjs) or bidView (sdk/market-bids.mjs) answer with a builder `share` (USDG units, the
207
+ * contract's: saleSplit's for a listing, splitOf's for a bid) taken from what the seller gets: `share` written after
208
+ * `fee`, `sellerGets` lowered by it, and the first line naming it ("120 USDG. Fee 1.20. Builder share 3. The seller
209
+ * gets 115.80. Until 20 Nov."). A share of 0 returns the view as it is. It throws on a share more than the seller
210
+ * gets, a view that has one already, or a first line it does not know.
211
+ */
212
+ export function withShare(view, { share = 0 } = {}) {
213
+ const s = toId(share, "share");
214
+ if (s === 0n) return view;
215
+ if (!view || typeof view !== "object" || !Array.isArray(view.words)) throw new Error("withShare takes a listingView or a bidView");
216
+ if ("share" in view) throw new Error("the view has a share already");
217
+ const gets = usdgUnits(view.sellerGets);
218
+ if (s > gets) throw new Error("the share is more than the seller gets");
219
+ const m = LINE.exec(view.words[0]);
220
+ if (!m) throw new Error("the view's first line is not a price line");
221
+ const bid = "needs" in view; // a bid's line says every amount without cents, a listing's the net exactly
222
+ const shareText = usdgText(s), netText = usdgText(gets - s);
223
+ const line = `${m[1]} Builder share ${noCents(shareText)}. The ${m[2]} gets ${bid ? noCents(netText) : netText}. ${m[3]}`;
224
+ const out = {};
225
+ for (const [k, v] of Object.entries(view)) {
226
+ out[k] = k === "sellerGets" ? netText : k === "words" ? [line, ...view.words.slice(1)] : v;
227
+ if (k === "fee") out.share = shareText;
228
+ }
229
+ return out;
230
+ }
231
+
232
+ /* ---- the calls, for agents and scripts ---- */
233
+
234
+ /** A builder's address as the contract takes it: never zero, the market or its bids' spender (CREATE(market, 1),
235
+ * sdk/market-bids.mjs spenderOf): a share sent to either would stay there. The contract also refuses v1
236
+ * (`previous`), USDG and the registry, which this module does not know: a caller that does refuses them first. */
237
+ function builderTo(market, to) {
238
+ const mkt = addressOf(market, "the market"), t = addressOf(to, "the builder");
239
+ if (t === mkt || t === ethers.getCreateAddress({ from: mkt, nonce: 1 }).toLowerCase()) throw new Error("the builder is never the market or its spender");
240
+ return { mkt, t };
241
+ }
242
+
243
+ /** setBuilder(id, to, bps): the agent's holder sets its share, once, before any sale here. `bps` 1 to 500. { to, data } */
244
+ export function setBuilderCall({ market, id, to, bps }) {
245
+ const { mkt, t } = builderTo(market, to);
246
+ return { to: mkt, data: IFACE.encodeFunctionData("setBuilder", [toId(id, "id"), t, bpsOf(bps, BUILDER_RULES.minBps)]) };
247
+ }
248
+
249
+ /** changeBuilder(id, to, bps): the builder lowers its share (0 allowed: it stays set and pays nothing) or hands it to
250
+ * `to`; the contract refuses a raise. { to, data } */
251
+ export function changeBuilderCall({ market, id, to, bps }) {
252
+ const { mkt, t } = builderTo(market, to);
253
+ return { to: mkt, data: IFACE.encodeFunctionData("changeBuilder", [toId(id, "id"), t, bpsOf(bps, 0)]) };
254
+ }