@priors/mcp 0.14.1 → 0.16.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.
- package/CHANGELOG.md +85 -0
- package/README.md +67 -11
- package/deployments/4663.agent-lease.json +46 -0
- package/package.json +2 -2
- package/src/agent-lease.mjs +656 -0
- package/src/key-file.mjs +37 -12
- package/src/market-plan.mjs +111 -37
- package/src/market-tools.mjs +175 -59
- package/src/rialto.mjs +155 -0
- package/src/server.mjs +115 -27
- package/src/stock-tools.mjs +63 -10
- package/src/stock-trade.mjs +197 -11
- package/src/work-types.mjs +71 -10
package/src/key-file.mjs
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
// read one another user owns (a key mounted owner-only into a container), but only when every directory above it, on
|
|
9
9
|
// the path as given and on the path it resolves to, belongs to root or to the file's owner and nobody else can write
|
|
10
10
|
// it: OpenSSH's secure_path rule (in /tmp, or under a directory another user owns, anyone could have put their own key
|
|
11
|
-
// at that path). On Windows, a file whose ACL lets nobody read it but the user, SYSTEM
|
|
12
|
-
// (the rule OpenSSH for Windows applies), read with PowerShell's Get-Acl by SID so the answer does not depend on the
|
|
11
|
+
// at that path). On Windows, a file whose ACL lets nobody read it, or change it or who may read it, but the user, SYSTEM
|
|
12
|
+
// and the Administrators group (the rule OpenSSH for Windows applies), read with PowerShell's Get-Acl by SID so the answer does not depend on the
|
|
13
13
|
// system's language; PowerShell is run from System32 by its full path, never looked up by name (Windows searches the
|
|
14
14
|
// working directory, which the MCP client chooses, before PATH). Anything else is refused, and the key is not read at
|
|
15
15
|
// all: the server then starts with its read-only tools, and every tool that moves money says what to fix.
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
// The path may start with ~/ (or ~\ on Windows), the user's home directory; otherwise it must be absolute, since an
|
|
20
20
|
// MCP client starts the server in a directory of its own choosing. Setting both PRIORS_KEY and PRIORS_KEY_FILE is
|
|
21
21
|
// refused: the server never guesses which key signs.
|
|
22
|
-
import { closeSync, constants, fstatSync, openSync, readSync, realpathSync, statSync } from "node:fs";
|
|
22
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readlinkSync, realpathSync, statSync } from "node:fs";
|
|
23
23
|
import { homedir as osHomedir } from "node:os";
|
|
24
24
|
import path from "node:path";
|
|
25
25
|
import { spawnSync } from "node:child_process";
|
|
@@ -33,6 +33,10 @@ const WIN_TRUSTED = new Set(["S-1-5-18", "S-1-5-32-544"]);
|
|
|
33
33
|
/** FileSystemRights bits that let a holder read the content: ReadData, GENERIC_ALL, GENERIC_READ (FullControl, Modify,
|
|
34
34
|
* Read and ReadAndExecute all include ReadData). */
|
|
35
35
|
const WIN_READ_BITS = [0x1, 0x10000000, 0x80000000];
|
|
36
|
+
/** And the bits that let a holder change the content or who may read it (GHSA-m2h8-m55f-9j66): WriteData, AppendData,
|
|
37
|
+
* WRITE_DAC (a holder grants itself read), WRITE_OWNER (takes the file, then the same) and GENERIC_WRITE. WriteAttributes
|
|
38
|
+
* and Delete are not among them: neither reads the key nor puts another key in its place. */
|
|
39
|
+
const WIN_WRITE_BITS = [0x2, 0x4, 0x40000, 0x80000, 0x40000000];
|
|
36
40
|
|
|
37
41
|
/**
|
|
38
42
|
* The Get-Acl report for `p`, as lines: "ME <sid>", "OWNER <sid>", then "ACE <sid> <Allow|Deny> <rights>" per rule,
|
|
@@ -49,7 +53,8 @@ const ACL_SCRIPT = [
|
|
|
49
53
|
].join("; ");
|
|
50
54
|
|
|
51
55
|
/** Who may read a Windows file, from Get-Acl's report (aclReport): null when only the user, SYSTEM and Administrators
|
|
52
|
-
* can, else a sentence naming the first other SID (and what to
|
|
56
|
+
* can read it or change it (its content, or who may read it), else a sentence naming the first other SID (and what to
|
|
57
|
+
* run). Pure, for tests. */
|
|
53
58
|
export function aclVerdict(report, file) {
|
|
54
59
|
const lines = String(report ?? "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
55
60
|
const me = lines.find((l) => l.startsWith("ME "))?.slice(3).trim();
|
|
@@ -61,9 +66,10 @@ export function aclVerdict(report, file) {
|
|
|
61
66
|
const [, who, type, rights] = l.split(/\s+/);
|
|
62
67
|
if (type !== "Allow") continue; // a Deny rule only takes access away
|
|
63
68
|
const mask = Number(rights) >>> 0; // GENERIC_READ comes back negative as a 32-bit enum
|
|
64
|
-
|
|
69
|
+
const reads = WIN_READ_BITS.some((b) => (mask & b) !== 0), writes = WIN_WRITE_BITS.some((b) => (mask & b) !== 0);
|
|
70
|
+
if (!reads && !writes) continue;
|
|
65
71
|
if (who === me || WIN_TRUSTED.has(who)) continue;
|
|
66
|
-
return `${who === "S-1-1-0" ? "Everyone" : who === "S-1-5-32-545" ? "the Users group" : who === "S-1-5-11" ? "Authenticated Users" : `another account (${who})`} can read it. Let only your own user read it: ${fix}`;
|
|
72
|
+
return `${who === "S-1-1-0" ? "Everyone" : who === "S-1-5-32-545" ? "the Users group" : who === "S-1-5-11" ? "Authenticated Users" : `another account (${who})`} ${reads ? "can read it" : "can change it, or who may read it"}. Let only your own user read it: ${fix}`;
|
|
67
73
|
}
|
|
68
74
|
return null;
|
|
69
75
|
}
|
|
@@ -89,20 +95,39 @@ export function windowsAclReport(file, { spawn = spawnSync, env = process.env }
|
|
|
89
95
|
return r.stdout;
|
|
90
96
|
}
|
|
91
97
|
|
|
98
|
+
/** The paths a chain of symlinks passes through on its way from `p` (each link of its last component, read with lstat
|
|
99
|
+
* and readlink, up to 40), `p` first: a link in the middle of a chain sits in a directory that is neither on the path
|
|
100
|
+
* as given nor on the path it resolves to, and whoever can write that directory can point the chain elsewhere
|
|
101
|
+
* (GHSA-m2h8-m55f-9j66). An lstat or readlink that cannot answer ends the walk there (the realpath check still runs). */
|
|
102
|
+
function chainOf(p, fs) {
|
|
103
|
+
const out = [p];
|
|
104
|
+
if (typeof fs.lstatSync !== "function" || typeof fs.readlinkSync !== "function") return out;
|
|
105
|
+
let cur = p;
|
|
106
|
+
for (let i = 0; i < 40; i++) {
|
|
107
|
+
let next;
|
|
108
|
+
try { if (!fs.lstatSync(cur).isSymbolicLink()) break; next = path.posix.resolve(path.posix.dirname(cur), String(fs.readlinkSync(cur))); } catch (_) { break; }
|
|
109
|
+
if (out.includes(next)) break;
|
|
110
|
+
out.push(next);
|
|
111
|
+
cur = next;
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
92
116
|
/**
|
|
93
117
|
* For root reading a POSIX file another user owns: null when nobody but root and the file's owner could have put it at
|
|
94
118
|
* `file`, else what is wrong (in words, never the content). OpenSSH's secure_path rule: every directory above the file
|
|
95
119
|
* belongs to root or to the file's owner and has no group or other write bit (a root-owned sticky /tmp fails too). It
|
|
96
|
-
* is checked on the path as given (whoever can write one of its directories could have put a symlink there)
|
|
97
|
-
*
|
|
98
|
-
* fstat: same device and inode), so nothing was
|
|
120
|
+
* is checked on the path as given (whoever can write one of its directories could have put a symlink there), on each
|
|
121
|
+
* link a chain of symlinks passes through on the way (chainOf), and on the path that resolves to (realpath), up to /,
|
|
122
|
+
* and the resolved file must be the one that was opened (`st`, its fstat: same device and inode), so nothing was
|
|
123
|
+
* swapped in between. `fs` needs realpathSync and statSync (lstatSync and readlinkSync for the chain).
|
|
99
124
|
*/
|
|
100
125
|
export function securePathProblem(file, st, fs) {
|
|
101
126
|
let real, rs;
|
|
102
127
|
try { real = fs.realpathSync(file); rs = fs.statSync(real); } catch (e) { return `its path could not be resolved (${e?.code || "error"})`; }
|
|
103
128
|
if (rs.dev !== st.dev || rs.ino !== st.ino) return "it changed while it was being checked";
|
|
104
129
|
const dirs = [];
|
|
105
|
-
for (const p of [file, real]) {
|
|
130
|
+
for (const p of [...chainOf(file, fs), real]) {
|
|
106
131
|
for (let d = path.posix.dirname(p); ; d = path.posix.dirname(d)) {
|
|
107
132
|
if (!dirs.includes(d)) dirs.push(d);
|
|
108
133
|
if (d === path.posix.dirname(d)) break;
|
|
@@ -132,7 +157,7 @@ export function stateDirProblem(dir, { fs, uid }) {
|
|
|
132
157
|
if (st.uid !== uid) return `it belongs to another user (uid ${st.uid})`;
|
|
133
158
|
if ((st.mode & 0o022) !== 0) return `other users can write to it (mode ${(st.mode & 0o7777).toString(8).padStart(4, "0")})`;
|
|
134
159
|
const dirs = [];
|
|
135
|
-
for (const p of [dir, real]) {
|
|
160
|
+
for (const p of [...chainOf(dir, fs), real]) {
|
|
136
161
|
for (let d = path.posix.dirname(p); ; d = path.posix.dirname(d)) {
|
|
137
162
|
if (!dirs.includes(d)) dirs.push(d);
|
|
138
163
|
if (d === path.posix.dirname(d)) break;
|
|
@@ -168,7 +193,7 @@ export function keyFilePath(raw, { platform = process.platform, homedir = osHome
|
|
|
168
193
|
*/
|
|
169
194
|
export function keyFromEnv(env = process.env, deps = {}) {
|
|
170
195
|
const platform = deps.platform ?? process.platform;
|
|
171
|
-
const fs = deps.fs ?? { openSync, fstatSync, readSync, closeSync, statSync, realpathSync };
|
|
196
|
+
const fs = deps.fs ?? { openSync, fstatSync, readSync, closeSync, statSync, realpathSync, lstatSync, readlinkSync };
|
|
172
197
|
const inline = typeof env.PRIORS_KEY === "string" ? env.PRIORS_KEY.trim() : "";
|
|
173
198
|
const fileRaw = typeof env.PRIORS_KEY_FILE === "string" ? env.PRIORS_KEY_FILE.trim() : "";
|
|
174
199
|
if (!fileRaw) return { key: inline, source: inline ? "PRIORS_KEY" : null, problem: null };
|
package/src/market-plan.mjs
CHANGED
|
@@ -3,12 +3,13 @@
|
|
|
3
3
|
// one plain transaction at a time. @priors/mcp's market tools (packages/mcp/src/market-tools.mjs) run it; the package
|
|
4
4
|
// holds a byte-for-byte copy (scripts/test-packages.mjs fails on any drift). Pure: no network, no clock, no file.
|
|
5
5
|
//
|
|
6
|
-
// 1. kindReads(market): which market answers at the address, v1 or V2, at one block (marketKindOf). v1's
|
|
7
|
-
// reverts with no data; V2's is CREATE(market, 1) (market-bids spenderOf), whose market() is the
|
|
8
|
-
// registry and USDG must be the package's record's. A V2 with the builder share (the P5 spec, section 2)
|
|
9
|
-
// MAX_BUILDER_BPS(); one without it reverts with no data, and every sale then pays no share. Its owner's
|
|
10
|
-
// buildersOn() (false until the Safe calls enableBuilders(), once, for good), is read with each agent's
|
|
11
|
-
// the plan's block, never kept: while it is off no share can be set, and none is reported.
|
|
6
|
+
// 1. kindReads(market, lease): which market answers at the address, v1 or V2, at one block (marketKindOf). v1's
|
|
7
|
+
// bidSpender() reverts with no data; V2's is CREATE(market, 1) (market-bids spenderOf), whose market() is the
|
|
8
|
+
// market. Its registry and USDG must be the package's record's. A V2 with the builder share (the P5 spec, section 2)
|
|
9
|
+
// answers MAX_BUILDER_BPS(); one without it reverts with no data, and every sale then pays no share. Its owner's
|
|
10
|
+
// switch, buildersOn() (false until the Safe calls enableBuilders(), once, for good), is read with each agent's
|
|
11
|
+
// reads, at the plan's block, never kept: while it is off no share can be set, and none is reported. With the
|
|
12
|
+
// package's AgentLease record, the lease's market() must be this market (addr.lease).
|
|
12
13
|
// 2. agentReads, accountReads, bidReads, then moreReads (the agent's sponsor's followsLine, the seller's and the
|
|
13
14
|
// makers' accounts): one Multicall3 aggregate3 each, every call allowed to fail, all at one block. readsOut decodes
|
|
14
15
|
// them into `c`, the object every plan reads; a read that failed is null, and a plan given null answers "unread",
|
|
@@ -16,15 +17,24 @@
|
|
|
16
17
|
// 3. sellPlan, buyPlan, cancelPlan, bidPlan, bidAnyPlan, cancelBidPlan, acceptPlan: the contract's rules in its order
|
|
17
18
|
// (web/board-wallet-core.js sellState and buyPlan, web/board-wallet-bids-core.js, which a test holds this to), then
|
|
18
19
|
// 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
|
|
20
|
+
// 4. stepCalls(step, o): a step's { to, data }, from market-abi's MARKET_IFACE, market-bids' call builders and the
|
|
21
|
+
// lease seam's handoverCalls (sdk/agent-lease.mjs).
|
|
20
22
|
// 5. MARKET_ERRORS and errorKindOf(revertData, role): a revert's kind; PLAN_WORDS and planWords(kind, vars): its words.
|
|
21
23
|
//
|
|
22
24
|
// What a sale leaves the seller is computed in netOf alone: price - fee - the builder's share, the share only where the
|
|
23
25
|
// market answers builderOf (P5), else price - fee. An open asking price and an open bid are worded; a price paid or taken
|
|
24
26
|
// is never worded after the fact.
|
|
27
|
+
//
|
|
28
|
+
// Renting (AgentLease, docs/AGENT-LEASE.md): only where the package records the lease (addr.lease) does agentReads read
|
|
29
|
+
// the lease stored on the agent (leaseOf), and while one is stored (its renter not zero: running, or ended and not paid
|
|
30
|
+
// out) buyPlan and acceptPlan claim on the lease before and after the change of hands, as every change of hands on
|
|
31
|
+
// Priors does (the client rule): "claimBefore" pays each day ended to whoever held the agent when it ended, and
|
|
32
|
+
// "claimAfter" records the new holder at once. Without the lease's record every read, plan and call is as before.
|
|
25
33
|
import { ethers } from "ethers";
|
|
26
34
|
import { MARKET_IFACE, LISTING_RULES, feeOf } from "./market-abi.mjs";
|
|
27
35
|
import { BID_RULES, BID_WORDS, spenderOf, idsRootOf, listOf, inRoot, reserveCall, bidCall, bidAnyCall, cancelBidCall, acceptCall } from "./market-bids.mjs";
|
|
36
|
+
import { LEASE_IFACE, LEASE_WORDS, handoverCalls } from "./agent-lease.mjs";
|
|
37
|
+
import { BUILDER_WORDS } from "./market-builders.mjs";
|
|
28
38
|
|
|
29
39
|
/* ---- small helpers ---- */
|
|
30
40
|
|
|
@@ -58,8 +68,9 @@ const BID = "tuple(address maker, uint64 expiry, uint16 left, bool any, uint96 p
|
|
|
58
68
|
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
69
|
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
70
|
/** 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
|
|
62
|
-
* their own structs under the same selectors, so each
|
|
71
|
+
* the ERC-8004 registry, CreditPoolV2, CreditPool v1, InviteBond v1 and V2, USDG, and AgentLease as the lease's seam
|
|
72
|
+
* names it: leaseOf and market()). Pool v1 and the two bonds answer their own structs under the same selectors, so each
|
|
73
|
+
* contract has its own Interface. */
|
|
63
74
|
export const READS = Object.freeze({
|
|
64
75
|
market: new ethers.Interface([
|
|
65
76
|
`function listingOf(uint256 id) view returns (${LISTING})`, "function feeBps() view returns (uint256)", "function minFee() view returns (uint256)",
|
|
@@ -71,6 +82,7 @@ export const READS = Object.freeze({
|
|
|
71
82
|
// the builder share, on a V2 that has it (the P5 spec, 2.2 and 2.3)
|
|
72
83
|
"function MAX_BUILDER_BPS() view returns (uint256)", "function builderOf(uint256 id) view returns (tuple(address to, uint16 bps))",
|
|
73
84
|
"function saleSplit(uint256 id) view returns (uint256 fee, uint256 share, uint256 net)", "function buildersOn() view returns (bool)",
|
|
85
|
+
"function builderSince(uint256 id) view returns (uint256)",
|
|
74
86
|
]),
|
|
75
87
|
spender: new ethers.Interface(["function market() view returns (address)"]),
|
|
76
88
|
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)"]),
|
|
@@ -79,6 +91,7 @@ export const READS = Object.freeze({
|
|
|
79
91
|
bondV1: new ethers.Interface(["function bonds(uint256 id) view returns (tuple(address depositor, uint64 at, uint256 amount, uint256 qualifiedAt))"]),
|
|
80
92
|
bondV2: new ethers.Interface(["function bonds(uint256 id) view returns (tuple(address depositor, uint64 at, uint256 amount))", "function amount() view returns (uint256)"]),
|
|
81
93
|
usdg: new ethers.Interface(["function balanceOf(address account) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)"]),
|
|
94
|
+
lease: LEASE_IFACE,
|
|
82
95
|
});
|
|
83
96
|
|
|
84
97
|
/** One read: { key, to, data, as: [contract, fn] }. A read on a zero address is never made (that contract isn't on
|
|
@@ -134,27 +147,30 @@ export function readsOut(reads, results, into = null) {
|
|
|
134
147
|
}
|
|
135
148
|
|
|
136
149
|
/** 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) {
|
|
150
|
+
* address V2's spender would have (spenderOf); with `lease` (the package's AgentLease record), the lease's market(). */
|
|
151
|
+
export function kindReads(market, lease = null) {
|
|
139
152
|
const out = [], add = adder(out), m = lc(market);
|
|
140
153
|
for (const k of ["bidSpender", "feeBps", "previous", "registry", "usdg", "poolV2", "poolV1", "inviteBond", "inviteBondV2", "MAX_BUILDER_BPS"]) add(k, m, "market", k);
|
|
141
154
|
add("spenderMarket", spenderOf(m), "spender", "market");
|
|
155
|
+
add("leaseMarket", lease, "lease", "market");
|
|
142
156
|
return out;
|
|
143
157
|
}
|
|
144
158
|
/**
|
|
145
159
|
* The market `c` (kindReads' answers) shows, against the package's `record` ({ registry, usdg }): { kind: "v1" | "v2",
|
|
146
160
|
* 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
|
|
148
|
-
* registry or USDG isn't the record's), "unknown" (neither v1's nor V2's answers)
|
|
161
|
+
* null), lease (only with `lease`) }, shares (V2 with the builder share) }, or { error }: "unread" (a read failed: try
|
|
162
|
+
* again), "mismatch" (its registry or USDG isn't the record's), "unknown" (neither v1's nor V2's answers),
|
|
163
|
+
* "unknownLease" (`lease`, the package's AgentLease, answers no market() or another market's: it reads this market's
|
|
164
|
+
* sales, so only this one's lease is claimed on).
|
|
149
165
|
*/
|
|
150
|
-
export function marketKindOf(c, { market, record }) {
|
|
166
|
+
export function marketKindOf(c, { market, record, lease = null }) {
|
|
151
167
|
const f = c.failed || {}, z = (a) => (isAddr(a) ? lc(a) : null);
|
|
152
168
|
if (c.registry == null || c.usdg == null || c.poolV2 == null) return { error: f.registry === "empty" || f.usdg === "empty" ? "unknown" : "unread" };
|
|
153
169
|
if (!same(c.registry, record && record.registry) || !same(c.usdg, record && record.usdg)) return { error: "mismatch" };
|
|
154
170
|
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
171
|
if (c.bidSpender == null && f.bidSpender === "empty") {
|
|
156
172
|
if (c.feeBps == null) return { error: "unread" };
|
|
157
|
-
return { kind: "v1", addr, shares: false };
|
|
173
|
+
return leaseIn({ kind: "v1", addr, shares: false }, c, { market, lease });
|
|
158
174
|
}
|
|
159
175
|
if (c.bidSpender == null) return { error: f.bidSpender === "reverted" ? "unknown" : "unread" };
|
|
160
176
|
const spender = spenderOf(market);
|
|
@@ -163,12 +179,21 @@ export function marketKindOf(c, { market, record }) {
|
|
|
163
179
|
if (c.MAX_BUILDER_BPS != null) shares = true;
|
|
164
180
|
else if (f.MAX_BUILDER_BPS === "empty") shares = false;
|
|
165
181
|
if (shares === null) return { error: "unread" };
|
|
166
|
-
return { kind: "v2", addr: { ...addr, spender, previous: z(c.previous) }, shares };
|
|
182
|
+
return leaseIn({ kind: "v2", addr: { ...addr, spender, previous: z(c.previous) }, shares }, c, { market, lease });
|
|
183
|
+
}
|
|
184
|
+
/** Market `k` with the package's `lease` confirmed (its market(), `c.leaseMarket`, is `market`): k.addr.lease. No
|
|
185
|
+
* lease: `k` as it is. */
|
|
186
|
+
function leaseIn(k, c, { market, lease }) {
|
|
187
|
+
if (lease == null) return k;
|
|
188
|
+
if (c.leaseMarket == null) return { error: c.failed && ["empty", "reverted"].includes(c.failed.leaseMarket) ? "unknownLease" : "unread" };
|
|
189
|
+
if (!isAddr(lease) || !same(c.leaseMarket, market)) return { error: "unknownLease" };
|
|
190
|
+
return { ...k, addr: { ...k.addr, lease: lc(lease) } };
|
|
167
191
|
}
|
|
168
192
|
|
|
169
193
|
/** 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,
|
|
171
|
-
* share where the market has one, with the owner's switch for shares (buildersOn) at the same block
|
|
194
|
+
* URI, the market's record pin, both pools' records, both bonds and the bond's amount, its last sale, its builder
|
|
195
|
+
* share where the market has one, with the owner's switch for shares (buildersOn) at the same block, and the lease
|
|
196
|
+
* stored on it where the package records AgentLease (addr.lease). */
|
|
172
197
|
export function agentReads({ addr, id, shares = false }) {
|
|
173
198
|
const a = addr || {}, i = big(id), out = [], add = adder(out);
|
|
174
199
|
add("listing", a.market, "market", "listingOf", [i]);
|
|
@@ -183,7 +208,8 @@ export function agentReads({ addr, id, shares = false }) {
|
|
|
183
208
|
add("bondV2", a.inviteBondV2, "bondV2", "bonds", [i]);
|
|
184
209
|
add("bondAmount", a.inviteBondV2, "bondV2", "amount");
|
|
185
210
|
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"); }
|
|
211
|
+
if (shares) { add("builder", a.market, "market", "builderOf", [i]); add("saleSplit", a.market, "market", "saleSplit", [i]); add("buildersOn", a.market, "market", "buildersOn"); add("builderSince", a.market, "market", "builderSince", [i]); }
|
|
212
|
+
add("lease", a.lease, "lease", "leaseOf", [i]);
|
|
187
213
|
return out;
|
|
188
214
|
}
|
|
189
215
|
/** The wallet's own (`me`): its standing (the pool's custodian and marks, the market's refusal), the pause and the
|
|
@@ -344,6 +370,34 @@ function builderIn(c, shares) {
|
|
|
344
370
|
if (big(b.bps) > 500n) return { error: "unread" };
|
|
345
371
|
return { builder: { to: lc(b.to), bps: big(b.bps) } };
|
|
346
372
|
}
|
|
373
|
+
/** Whether an accept of agent `c` read can take bid `bidId` by its builder share (acceptBid's rule: a bid made before
|
|
374
|
+
* the share was set, its id under builderSince, is refused, BuilderAfterBid): true, false, or null while unread. A
|
|
375
|
+
* market without shares, or with the owner's switch off (no share can be set), never refuses one; nor does a market
|
|
376
|
+
* whose builderSince answers no data, or a `c` that never asked it. */
|
|
377
|
+
export function takesBid(c, bidId, shares) {
|
|
378
|
+
if (!shares || c.buildersOn === false) return true;
|
|
379
|
+
if (c.builderSince === undefined) return true; // not asked (as for buildersOn): agentReads asks it with the share
|
|
380
|
+
if (c.builderSince === null) return c.failed && c.failed.builderSince === "empty" ? true : null; // no such view: none; failed: unread
|
|
381
|
+
return big(bidId) >= big(c.builderSince);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* The claims on the lease around a change of hands of the agent `c` read (the client rule, docs/AGENT-LEASE.md), where
|
|
386
|
+
* the package records AgentLease (addr.lease): while leaseOf names a renter (a lease that runs, or one that ended and
|
|
387
|
+
* isn't paid out yet), "claimBefore" first, so each day ended goes to whoever held the agent when it ended, and
|
|
388
|
+
* "claimAfter" last, so the new holder is recorded at once. A later plan of the same call gives `leased` (the first
|
|
389
|
+
* plan's: the bracket holds whatever leaseOf says now, since the claim before may close a lease that ran out and a
|
|
390
|
+
* claim with nothing stored returns 0) and `claimed` (the claim before was sent). { steps, leased } with the claims;
|
|
391
|
+
* { steps } as they are without them; { error: "unread" } while the lease's read failed.
|
|
392
|
+
*/
|
|
393
|
+
function bracket(c, steps, { addr, leased = false, claimed = false }) {
|
|
394
|
+
if (!addr || !isAddr(addr.lease)) return { steps };
|
|
395
|
+
if (!leased) {
|
|
396
|
+
if (c.lease == null) return { error: "unread" };
|
|
397
|
+
if (!isAddr(c.lease.renter)) return { steps };
|
|
398
|
+
}
|
|
399
|
+
return { steps: [...(claimed ? [] : ["claimBefore"]), ...steps, "claimAfter"], leased: true };
|
|
400
|
+
}
|
|
347
401
|
|
|
348
402
|
/**
|
|
349
403
|
* Listing agent `id` from `me` (sellState with the terms): `price` (USDG units, 5 USDG or more), `days` (1 to 30) or
|
|
@@ -434,11 +488,12 @@ export function listingBlock(c, { addr, now }) {
|
|
|
434
488
|
* "relisted" with `price` (a nonce or price other than `seen`'s), "changed" with `price` (above `maxPrice`), "self",
|
|
435
489
|
* "paused", "account", "marked", takeChecks' kinds, "record" with `n` and `m` (fewer repaid loans than `minRecord`),
|
|
436
490
|
* "short" with `short` and `cash`), or { steps ("approveUsdg": exactly the price, while the USDG approved to the market
|
|
437
|
-
* is short of it; "buy"
|
|
438
|
-
*
|
|
439
|
-
*
|
|
491
|
+
* is short of it; "buy"; "claimBefore" first and "claimAfter" last while a lease is stored, with `leased`: bracket's,
|
|
492
|
+
* from its `leased` and `claimed`), listing, follows (the treasury line comes with it), line, bond (what the buyer locks
|
|
493
|
+
* before it borrows on it), fee, share, net (the seller's), pins: { price, nonce, uriHash (the token URI's bytes hashed
|
|
494
|
+
* here), recordHash (the market's own, at the same block) } }.
|
|
440
495
|
*/
|
|
441
|
-
export function buyPlan(c, { addr, me, now, maxPrice, seen = null, minRecord = 0n, shares = false }) {
|
|
496
|
+
export function buyPlan(c, { addr, me, now, maxPrice, seen = null, minRecord = 0n, shares = false, leased = false, claimed = false }) {
|
|
442
497
|
c = c || {};
|
|
443
498
|
if (noAgent(c)) return { error: "gone" };
|
|
444
499
|
if (unread(c.listing, c.owner, c.approved)) return { error: "unread" };
|
|
@@ -465,8 +520,10 @@ export function buyPlan(c, { addr, me, now, maxPrice, seen = null, minRecord = 0
|
|
|
465
520
|
// what the seller gets: the market's own split when it answers one (the lower fee and share of list and now), else
|
|
466
521
|
// the fee and the share now
|
|
467
522
|
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 });
|
|
523
|
+
const br = bracket(c, [...(big(c.allowance) < listing.price ? ["approveUsdg"] : []), "buy"], { addr, leased, claimed });
|
|
524
|
+
if (br.error) return br;
|
|
468
525
|
return {
|
|
469
|
-
steps:
|
|
526
|
+
steps: br.steps, ...(br.leased ? { leased: true } : {}), listing, follows, line: follows ? lent : 0n, bond: wants ? big(c.bondAmount) : 0n,
|
|
470
527
|
fee: split.fee, share: split.share, net: split.net,
|
|
471
528
|
pins: { price: listing.price, nonce: listing.nonce, uriHash, recordHash: lc(c.record) },
|
|
472
529
|
};
|
|
@@ -602,13 +659,14 @@ export function cancelBidPlan(c, { me, now, bidIds, myBids = [] }) {
|
|
|
602
659
|
* Accepting bid `bidId` for agent `id` held by `me` (web/board-wallet-bids-core.js walletAcceptPlan): the bid, its
|
|
603
660
|
* target or list (`proof`, checked with inRoot, never trusted), the maker as a buyer, the sale's rules with `me` as the
|
|
604
661
|
* 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", "
|
|
606
|
-
* the
|
|
607
|
-
*
|
|
608
|
-
*
|
|
609
|
-
*
|
|
662
|
+
* "unfunded", "paused", saleChecks' kinds, "repaid" (`n`, `m`), "lineBelow" (`line`), "card", "afterBid" (a bid made
|
|
663
|
+
* before the agent's builder share was set, which acceptBid refuses), "noNet" (`price`, `fee`: the fee takes the whole
|
|
664
|
+
* price, which the contract allows only when the bid is at the minimum fee)), or { steps
|
|
665
|
+
* ("cancelOldPrev", "cancelOld", "bondApprove", "bond", "approve", "accept", in acceptCalls' order; "claimBefore" first
|
|
666
|
+
* and "claimAfter" last while a lease is stored, with `leased`, as buyPlan's), price, maker, proof, fee, share, net
|
|
667
|
+
* (minNet: exact at the read block; a fee changes only after the market's 48 h, and a share only lower), bond, pins }.
|
|
610
668
|
*/
|
|
611
|
-
export function acceptPlan(c, { addr, me, now, bidId, id, proof = [], shares = false }) {
|
|
669
|
+
export function acceptPlan(c, { addr, me, now, bidId, id, proof = [], shares = false, leased = false, claimed = false }) {
|
|
612
670
|
c = c || {};
|
|
613
671
|
const key = String(bidId), b = c.bids.get(key);
|
|
614
672
|
if (b == null) return { error: "unread" };
|
|
@@ -629,15 +687,21 @@ export function acceptPlan(c, { addr, me, now, bidId, id, proof = [], shares = f
|
|
|
629
687
|
if (BigInt(b.uriHash) !== 0n && lc(ethers.keccak256(ethers.toUtf8Bytes(c.uri))) !== lc(b.uriHash)) return { error: "card" };
|
|
630
688
|
const bi = builderIn(c, shares);
|
|
631
689
|
if (bi.error) return bi;
|
|
690
|
+
// a bid made before the agent's builder share was set: acceptBid refuses it (BuilderAfterBid), so nothing is sent for
|
|
691
|
+
// it, no cancel, bond or approval first (GHSA-m2h8-m55f-9j66)
|
|
692
|
+
const takes = takesBid(c, key, shares);
|
|
693
|
+
if (takes === null) return { error: "unread" };
|
|
694
|
+
if (!takes) return { error: "afterBid" };
|
|
632
695
|
const { fee, share, net } = netOf(big(b.price), { ...feesOf(c), builder: bi.builder, seller: me });
|
|
633
696
|
if (net < 1n) return { error: "noNet", price: big(b.price), fee };
|
|
634
697
|
const approved = same(c.approved, addr.market), mine = ownListing(c.listing, me, now);
|
|
635
698
|
let prevMine = null;
|
|
636
699
|
if (addr.previous) { if (c.prevListing == null) return { error: "unread" }; prevMine = ownListing(c.prevListing, me, now); }
|
|
637
|
-
const
|
|
638
|
-
...(s.bond > 0n ? ["bond"] : []), ...(approved ? [] : ["approve"]), "accept"];
|
|
700
|
+
const br = bracket(c, [...(prevMine ? ["cancelOldPrev"] : []), ...(mine && !approved ? ["cancelOld"] : []), ...(s.bond > 0n && s.bondApprove ? ["bondApprove"] : []),
|
|
701
|
+
...(s.bond > 0n ? ["bond"] : []), ...(approved ? [] : ["approve"]), "accept"], { addr, leased, claimed });
|
|
702
|
+
if (br.error) return br;
|
|
639
703
|
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,
|
|
704
|
+
return { steps: br.steps, ...(br.leased ? { leased: true } : {}), price: big(b.price), maker: lc(b.maker), any: b.any === true, proof: pr, fee, share, net, bond: s.bond,
|
|
641
705
|
pins: { bidId: key, id: big(id), price: big(b.price), maker: lc(b.maker), minNet: net } };
|
|
642
706
|
}
|
|
643
707
|
|
|
@@ -648,8 +712,9 @@ const REGISTRY = new ethers.Interface(["function approve(address to, uint256 tok
|
|
|
648
712
|
const BOND_V2 = new ethers.Interface(["function deposit(uint256 agentId)"]);
|
|
649
713
|
const to_ = (a) => ethers.getAddress(a).toLowerCase();
|
|
650
714
|
/**
|
|
651
|
-
* One step's transaction: { to, data }. `o`: { addr (marketKindOf's), id, now (the block's
|
|
652
|
-
* and the plan's own: price, expiry, bond, pins, reserve, proof, net, root, count, uriHash,
|
|
715
|
+
* One step's transaction: { to, data }. `o`: { addr (marketKindOf's; its `lease` for the claims), id, now (the block's
|
|
716
|
+
* time, for the bids' terms), and the plan's own: price, expiry, bond, pins, reserve, proof, net, root, count, uriHash,
|
|
717
|
+
* minRepaid, minLine }. "claimBefore" and "claimAfter" are the seam's handoverCalls: claim(id) on the lease.
|
|
653
718
|
*/
|
|
654
719
|
export function stepCalls(step, o) {
|
|
655
720
|
const a = o.addr, id = o.id == null ? null : big(o.id);
|
|
@@ -667,6 +732,7 @@ export function stepCalls(step, o) {
|
|
|
667
732
|
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
733
|
if (step.startsWith("cancelBid:")) return cancelBidCall({ market: a.market, bidId: step.slice("cancelBid:".length) });
|
|
669
734
|
if (step === "accept") return acceptCall({ market: a.market, bidId: o.pins.bidId, id, proof: o.proof || [], minNet: o.pins.minNet });
|
|
735
|
+
if (step === "claimBefore" || step === "claimAfter") { const h = handoverCalls({ lease: a.lease, id, leased: true }); return (step === "claimBefore" ? h.before : h.after)[0]; }
|
|
670
736
|
throw new Error(`no such step: ${step}`);
|
|
671
737
|
}
|
|
672
738
|
/** What a step's receipt must hold from the market: the event, by name, the final step of each tool ends with. */
|
|
@@ -678,7 +744,8 @@ export const STEP_EVENTS = Object.freeze({ list: "Listed", cancel: "Cancelled",
|
|
|
678
744
|
* Every error a step can revert with, by signature, and its kind: AgentMarket's and AgentMarketV2's (src/AgentMarket.sol
|
|
679
745
|
* 123-151, src/AgentMarketV2.sol 151-190, the builder share's of the P5 spec 2.8), the pause's (src/GuardianPause.sol
|
|
680
746
|
* 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,
|
|
747
|
+
* hold the agent, InviteBondV2's deposit's, and AgentLease's claim's (src/AgentLease.sol: its payout's PayOutOfGas is
|
|
748
|
+
* the builder share's selector). The board's ERR set (web/board-wallet-core.js) and the bids' (web/
|
|
682
749
|
* board-wallet-bids-core.js), one table. "failed": nothing a plan checks; the step's own words.
|
|
683
750
|
*/
|
|
684
751
|
export const MARKET_ERRORS = Object.freeze({
|
|
@@ -697,7 +764,7 @@ export const MARKET_ERRORS = Object.freeze({
|
|
|
697
764
|
// the builder share (the P5 spec, 2.8), once V2 has it: a seller or a buyer never sets one here (BuildersOff: setBuilder
|
|
698
765
|
// before the owner turned shares on)
|
|
699
766
|
"NotBuilder(uint256,address)": "failed", "BuilderTaken(uint256)": "failed", "AlreadySold(uint256)": "failed", "BadShare(uint256)": "failed", "BadBuilder(address)": "failed",
|
|
700
|
-
"PayOutOfGas()": "failed", "BuildersOff()": "failed",
|
|
767
|
+
"PayOutOfGas()": "failed", "BuildersOff()": "failed", "BuilderAfterBid(uint256,uint256)": "afterBid",
|
|
701
768
|
// the pause
|
|
702
769
|
"IsPaused(uint64)": "paused", "NotGuardian(address)": "failed", "NotTimelock(address)": "failed", "PauseRefused(uint64)": "failed", "BadPause(uint64)": "failed", "ZeroAddress()": "failed",
|
|
703
770
|
// BidSpender: its pull is the market's alone
|
|
@@ -705,6 +772,8 @@ export const MARKET_ERRORS = Object.freeze({
|
|
|
705
772
|
// USDG as deployed, the registry, InviteBondV2's deposit
|
|
706
773
|
"InsufficientAllowance()": "allowance", "InsufficientFunds()": "short", "ERC721InvalidApprover(address)": "notOwner", "ERC721NonexistentToken(uint256)": "cantSell",
|
|
707
774
|
"NotOwner(uint256)": "notOwner", "AgentDefaulted(uint256)": "defaulted", "LoanOpen(uint256)": "loan", "NotTreasuryLine(uint256)": "line", "AlreadyBonded(uint256)": "failed",
|
|
775
|
+
// AgentLease's claim around a change of hands: never paused, it waits while the registry doesn't answer
|
|
776
|
+
"RegistryFailed(uint256)": "registry",
|
|
708
777
|
});
|
|
709
778
|
const SELECTORS = new Map(Object.entries(MARKET_ERRORS).map(([sig, kind]) => [ethers.id(sig).slice(0, 10), { sig, kind }]));
|
|
710
779
|
/**
|
|
@@ -751,6 +820,7 @@ export const PLAN_WORDS = Object.freeze({
|
|
|
751
820
|
record: "#{id} has {m} repaid loan{s}. This server buys and bids only on agents with {n} or more.",
|
|
752
821
|
// money
|
|
753
822
|
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.",
|
|
823
|
+
keepBackHeld: "Agent #{self} owes {owed} USDG on its open loans, due {due}. This would leave {left} USDG to repay them, after the {held} USDG this wallet's open bids and signed payments still hold. Repay the loans, cancel a bid, or add USDG.",
|
|
754
824
|
short: "This wallet holds {cash} USDG. Add {short} USDG, then try again.",
|
|
755
825
|
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
826
|
noEth: "This wallet holds no ETH on Robinhood Chain for gas. Add a little ETH, then try again.",
|
|
@@ -790,6 +860,7 @@ export const PLAN_WORDS = Object.freeze({
|
|
|
790
860
|
notMaker: "Bid #{bidId} isn't this wallet's. Only its maker can cancel it.",
|
|
791
861
|
bidGone: "Bid #{bidId} isn't open now. It was cancelled, taken or ran out, or there is no such bid.",
|
|
792
862
|
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.",
|
|
863
|
+
afterBid: BUILDER_WORDS.errors.afterBid,
|
|
793
864
|
tooMany: "market_cancel_bid cancels at most 10 bids a call. Cancel the rest in another call.",
|
|
794
865
|
count: "A bid on an origin takes 1 to {max} agents here. Pick a count in that range.",
|
|
795
866
|
noBids: "This wallet has no open bid to cancel.",
|
|
@@ -797,6 +868,9 @@ export const PLAN_WORDS = Object.freeze({
|
|
|
797
868
|
// the hub
|
|
798
869
|
hubDown: "Priors' hub at {hub} didn't answer, so {what} can't be read. Try again later.",
|
|
799
870
|
noSet: "Priors' hub has no list for {origin} now. Bid on one agent instead.",
|
|
871
|
+
// the lease's claims around a change of hands (AgentLease, where the package records it)
|
|
872
|
+
unknownLease: "The lease at {lease} doesn't answer as the lease of the market this server knows. Update @priors/mcp.",
|
|
873
|
+
registry: LEASE_WORDS.errors.registry,
|
|
800
874
|
});
|
|
801
875
|
/** A bid's and an accept's refusals: market-bids' BID_WORDS.errors as they are, but "over" (this server's own limit),
|
|
802
876
|
* the two that name Go mode's buttons, which this server doesn't have, "notInBid", said here without the list's day
|