@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
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
// AgentLease, the seam (the renting spec, P11, with the owner's answers of 2026-10-27, 2026-10-30 and 2026-10-31;
|
|
2
|
+
// docs/AGENT-LEASE.md): the calls, events and errors of the lease as the index, the gas gate, Go mode, the board, the
|
|
3
|
+
// MCP and the contract itself (src/AgentLease.sol, src/interfaces/IAgentLease.sol) all name them; the rent, the fee,
|
|
4
|
+
// the days paid and the refunds, exactly as the contract computes them; the words a lease or an offer shows; and the
|
|
5
|
+
// calls an account sends.
|
|
6
|
+
//
|
|
7
|
+
// A renter runs an agent on Priors for 1 to 90 days: it sells the agent's work and takes paid jobs under its name, paid
|
|
8
|
+
// to its own address. It never borrows on the agent's line, never becomes its wallet or its delegate, and never
|
|
9
|
+
// changes its file. The agent stays in its owner's wallet the whole time: the lease never moves it, so its record, its
|
|
10
|
+
// line and its Score v2 stay where they are, and the owner can sell it like any other agent.
|
|
11
|
+
//
|
|
12
|
+
// The renter pays the whole term into the contract at `rent`, and none of it goes to the owner or to the market's feeTo
|
|
13
|
+
// then: the fee is never taken from what `rent` or `extend` pays in. (A rent that closes a lease which ran out
|
|
14
|
+
// unclaimed pays that old lease out first, as `claim` would.) Each day is paid once it has ended (`claim`, anyone, at
|
|
15
|
+
// any time), less its own share of the fee: day k (0-based) carries F(k+1) - F(k), where F(n) is the market's rule on n
|
|
16
|
+
// days' rent at the lease's pin, the lower rate and the lower minimum of the offer's fee and the market's at the rent
|
|
17
|
+
// (leaseFee, pinOf). The fee is always read live from the market: no helper here assumes one. A payout splits the days
|
|
18
|
+
// at the market's last sale since the last payout: the holder at the last payout gets the days that ended by it, the
|
|
19
|
+
// owner now the rest. That is each day to whoever held the agent when it ended for one market sale since the last
|
|
20
|
+
// payout (a V2 buy or acceptBid, or a v1 sale), and only then: a plain transfer with no sale since gives every unpaid
|
|
21
|
+
// day to its receiver, and with two changes of hands between payouts the middle holder is paid nothing (its days go to
|
|
22
|
+
// the holder at the last payout when the later change is a market sale, to the owner now when it is a plain transfer).
|
|
23
|
+
// So every operation on Priors that changes hands claims before and after the change, in the same operation
|
|
24
|
+
// (handoverCalls). Owners collect their own rent. An end first pays the days that ended to their holders (the renter's
|
|
25
|
+
// own end of a sound lease, the day under way too; the owner's, whoever holds the agent then, sends that day back),
|
|
26
|
+
// then sends every day not paid back to the renter, in full, and never less than the `minRefund` its caller names:
|
|
27
|
+
// refundsOf, not leaseOf, gives that figure, and a renter that also holds the agent ends as the renter (refundsOf,
|
|
28
|
+
// earlyEnd). Anyone ends a broken agent's lease, and every end of it sends the day under way back, whoever ends: with
|
|
29
|
+
// an owner (a default), every ended day still goes to its holders; with none (burnt, or held by the lease), only the
|
|
30
|
+
// days that ended by a market sale since the last payout are paid (brokenEnd). `extend` adds days at the lease's own
|
|
31
|
+
// day price, up to the rented offer's longest term (extendQuote). A listing of the agent that stands on V2 or v1 bars
|
|
32
|
+
// `rent` and `extend`, whoever listed it: the owner's own refuses them, and one whose seller no longer holds the agent
|
|
33
|
+
// is cancelled first, which anyone may do (rentCalls, extendCalls). A day price of 0 is allowed for one named address:
|
|
34
|
+
// no USDG moves and no fee is taken.
|
|
35
|
+
//
|
|
36
|
+
// offerRent(id, dayPrice, minDays, maxDays, renter, expiry) the owner; renter zero: anyone; paused with rent
|
|
37
|
+
// cancelOffer(id) the offer's owner, or anyone once it can't be taken
|
|
38
|
+
// rent(id, days, maxTotal, recordHash, uriHash) the renter, after approve(lease, total) when total > 0
|
|
39
|
+
// extend(id, days, maxTotal, recordHash, uriHash) the renter, after approve(lease, total) when total > 0
|
|
40
|
+
// claim(id) anyone: pays the days ended; 0 with nothing stored
|
|
41
|
+
// endLease(id, minRefund) the renter, the owner now, anyone once broken
|
|
42
|
+
// withdraw(account) anyone: sends `account` what USDG refused it
|
|
43
|
+
// cancel(id), on V2 or v1 anyone, for a listing whose seller no longer holds
|
|
44
|
+
// the agent: before a rent or an extension
|
|
45
|
+
//
|
|
46
|
+
// test/vectors/agent-lease.json (scripts/lease-vectors.mjs) holds the selectors, topics, errors, quotes, schedules,
|
|
47
|
+
// sales, defaults, extensions and calls (a market's cancel before a rent or an extension included); the contract's
|
|
48
|
+
// forge tests read it back (test/AgentLeaseVectors.t.sol), and scripts/test-agent-lease.mjs holds this module to it.
|
|
49
|
+
//
|
|
50
|
+
// A lease's amounts and a refund are on chain because the chain carries them: nothing here words a past lease's price
|
|
51
|
+
// or who ended a lease.
|
|
52
|
+
import { ethers } from "ethers";
|
|
53
|
+
import { toId } from "./credit-profile.mjs";
|
|
54
|
+
import { usdgText } from "./work-types.mjs";
|
|
55
|
+
|
|
56
|
+
/* ---- the contract ---- */
|
|
57
|
+
|
|
58
|
+
/** The constructor: the ERC-8004 registry, USDG, pool v2, pool v1 (zero allowed), AgentMarketV2, AgentMarket v1 (V2's
|
|
59
|
+
* previous, zero allowed) and the guardian (the Safe: pause of offerRent, rent and extend only). */
|
|
60
|
+
export const LEASE_CONSTRUCTOR = "constructor(address registry, address usdg, address poolV2, address poolV1, address market, address previous, address guardian)";
|
|
61
|
+
|
|
62
|
+
const OFFER_TUPLE = "tuple(address owner, uint96 dayPrice, address renter, uint8 minDays, uint8 maxDays, uint64 expiry, uint64 soldAt, uint16 feeBps, uint96 minFee)";
|
|
63
|
+
const LEASE_TUPLE = "tuple(address renter, uint64 start, uint8 term, uint8 paidDays, uint8 maxDays, address holder, uint96 dayPrice, address owner, uint64 settledAt, uint16 feeBps, uint96 minFee)";
|
|
64
|
+
/** The fields of offerOf and leaseOf, in the structs' order (IAgentLease.Offer, IAgentLease.Lease). */
|
|
65
|
+
export const OFFER_FIELDS = Object.freeze(["owner", "dayPrice", "renter", "minDays", "maxDays", "expiry", "soldAt", "feeBps", "minFee"]);
|
|
66
|
+
export const LEASE_FIELDS = Object.freeze(["renter", "start", "term", "paidDays", "maxDays", "holder", "dayPrice", "owner", "settledAt", "feeBps", "minFee"]);
|
|
67
|
+
|
|
68
|
+
/** The calls and views. userOf and userExpires take EIP-4907's names and meaning (the renter and the end while the
|
|
69
|
+
* lease runs and the agent has an owner, else zero); the contract does not claim ERC-4907 and logs no UpdateUser
|
|
70
|
+
* (owner question F10). paused() is GuardianPause's. */
|
|
71
|
+
export const LEASE_FUNCTIONS = Object.freeze([
|
|
72
|
+
"function offerRent(uint256 id, uint256 dayPrice, uint8 minDays, uint8 maxDays, address renter, uint64 expiry)",
|
|
73
|
+
"function cancelOffer(uint256 id)",
|
|
74
|
+
"function rent(uint256 id, uint256 days_, uint256 maxTotal, bytes32 recordHash, bytes32 uriHash) returns (uint64 until)",
|
|
75
|
+
"function extend(uint256 id, uint256 days_, uint256 maxTotal, bytes32 recordHash, bytes32 uriHash) returns (uint64 until)",
|
|
76
|
+
"function claim(uint256 id) returns (uint256 paid)",
|
|
77
|
+
"function endLease(uint256 id, uint256 minRefund) returns (uint256 refund)",
|
|
78
|
+
"function withdraw(address account) returns (uint256 amount)",
|
|
79
|
+
"function userOf(uint256 id) view returns (address)",
|
|
80
|
+
"function userExpires(uint256 id) view returns (uint256)",
|
|
81
|
+
`function leaseOf(uint256 id) view returns (${LEASE_TUPLE})`,
|
|
82
|
+
`function offerOf(uint256 id) view returns (${OFFER_TUPLE})`,
|
|
83
|
+
"function quote(uint256 id, uint256 days_) view returns (uint256 total, uint256 fee)",
|
|
84
|
+
"function claimable(uint256 id) view returns (uint256)",
|
|
85
|
+
"function refundsOf(uint256 id) view returns (uint256 byRenter, uint256 byOwner)",
|
|
86
|
+
"function owed(address account) view returns (uint256)",
|
|
87
|
+
"function paused() view returns (bool)",
|
|
88
|
+
"function market() view returns (address)",
|
|
89
|
+
"function previous() view returns (address)",
|
|
90
|
+
"function MAX_DAYS() view returns (uint256)",
|
|
91
|
+
"function MIN_RENT() view returns (uint256)",
|
|
92
|
+
]);
|
|
93
|
+
|
|
94
|
+
/** The events (docs/AGENT-LEASE.md, "Lease events"), in the interface's order. Rented.fee is the fee the whole term
|
|
95
|
+
* carries, taken from its payouts: none of the rent moves on at `rent` (a rent that closes a lease which ran out
|
|
96
|
+
* unclaimed logs that lease's payout first, RentPaid and FeeTaken, then Rented). Extended moves a lease's end.
|
|
97
|
+
* RentPaid names who a payout went to, net of its days' fee; FeeTaken follows with that payout's fee and the market's
|
|
98
|
+
* feeTo it went to; RentHeld follows a payout USDG refused, which waits in owed. LeaseEnded is an early end, or the end
|
|
99
|
+
* of a broken agent's lease (also after its date): a sound lease that runs to its date logs nothing then. */
|
|
100
|
+
export const LEASE_EVENTS = Object.freeze([
|
|
101
|
+
"event RentOffered(uint256 indexed agentId, address indexed owner, address indexed renter, uint256 dayPrice, uint8 minDays, uint8 maxDays, uint64 expiry)",
|
|
102
|
+
"event RentOfferCancelled(uint256 indexed agentId, address indexed by)",
|
|
103
|
+
"event Rented(uint256 indexed agentId, address indexed owner, address indexed renter, uint64 start, uint64 until, uint256 total, uint256 fee)",
|
|
104
|
+
"event Extended(uint256 indexed agentId, address indexed owner, address indexed renter, uint64 until, uint256 total)",
|
|
105
|
+
"event RentPaid(uint256 indexed agentId, address indexed to, uint256 amount)",
|
|
106
|
+
"event FeeTaken(uint256 indexed agentId, address indexed to, uint256 amount)",
|
|
107
|
+
"event LeaseEnded(uint256 indexed agentId, address indexed renter, address indexed by, uint256 refund)",
|
|
108
|
+
"event RentHeld(address indexed to, uint256 amount)",
|
|
109
|
+
"event Withdrawn(address indexed to, uint256 amount)",
|
|
110
|
+
]);
|
|
111
|
+
|
|
112
|
+
/** The errors: the lease's own, then the ones with the market's signatures (one error map serves both), then
|
|
113
|
+
* GuardianPause's IsPaused. */
|
|
114
|
+
export const LEASE_ERRORS = Object.freeze([
|
|
115
|
+
"error NoOffer(uint256 id)",
|
|
116
|
+
"error OfferExpired(uint256 id, uint64 expiry)",
|
|
117
|
+
"error OfferGone(uint256 id)",
|
|
118
|
+
"error Leased(uint256 id, uint64 until)",
|
|
119
|
+
"error NotForYou(uint256 id)",
|
|
120
|
+
"error SelfRent()",
|
|
121
|
+
"error RenterIsWallet(uint256 id)",
|
|
122
|
+
"error RenterControls(uint256 id)",
|
|
123
|
+
"error Listed(uint256 id, address market)",
|
|
124
|
+
"error BadDays()",
|
|
125
|
+
"error DayBelowFee(uint256 dayPrice, uint256 fee)",
|
|
126
|
+
"error NoLease(uint256 id)",
|
|
127
|
+
"error CannotEnd(uint256 id, address caller)",
|
|
128
|
+
"error NothingOwed(address account)",
|
|
129
|
+
"error PayOutOfGas()",
|
|
130
|
+
"error NotRenter(uint256 id, address caller)",
|
|
131
|
+
"error ChangedHands(uint256 id)",
|
|
132
|
+
"error RefundBelow(uint256 refund, uint256 minRefund)",
|
|
133
|
+
"error RegistryFailed(uint256 id)",
|
|
134
|
+
"error NotOwner(uint256 id, address seller)",
|
|
135
|
+
"error Custodian(address account)",
|
|
136
|
+
"error Refused(address account)",
|
|
137
|
+
"error Marked(address account)",
|
|
138
|
+
"error IsRoot(uint256 id, address pool)",
|
|
139
|
+
"error AgentDefaulted(uint256 id, address pool)",
|
|
140
|
+
"error RecordChanged(uint256 id)",
|
|
141
|
+
"error UriChanged(uint256 id)",
|
|
142
|
+
"error PriceTooLow(uint256 price)",
|
|
143
|
+
"error PriceAbove(uint256 price, uint256 maxPrice)",
|
|
144
|
+
"error BadExpiry(uint64 expiry)",
|
|
145
|
+
"error CannotCancel(uint256 id, address caller)",
|
|
146
|
+
"error IsPaused(uint64 until)",
|
|
147
|
+
]);
|
|
148
|
+
|
|
149
|
+
export const LEASE_ABI = Object.freeze([LEASE_CONSTRUCTOR, ...LEASE_FUNCTIONS, ...LEASE_EVENTS, ...LEASE_ERRORS]);
|
|
150
|
+
export const LEASE_IFACE = new ethers.Interface(LEASE_ABI);
|
|
151
|
+
/** Each event's topic0. */
|
|
152
|
+
export const LEASE_TOPICS = Object.freeze(Object.fromEntries(LEASE_EVENTS.map((e) => {
|
|
153
|
+
const f = ethers.EventFragment.from(e);
|
|
154
|
+
return [f.name, LEASE_IFACE.getEvent(f.name).topicHash];
|
|
155
|
+
})));
|
|
156
|
+
|
|
157
|
+
/** The market's own calls a lease's client reads and sends, on the lease's market() (V2) and previous() (v1), with the
|
|
158
|
+
* market's signatures (src/interfaces/IAgentMarket.sol, sdk/market-abi.mjs): listingOf(id), since a listing that
|
|
159
|
+
* stands on either bars rent and extend, whoever listed it; and cancel(id), which anyone may send for a listing whose
|
|
160
|
+
* seller no longer holds the agent (rentCalls and extendCalls send it first). Not the lease's: no lease call. */
|
|
161
|
+
export const LEASE_MARKET_FUNCTIONS = Object.freeze([
|
|
162
|
+
"function listingOf(uint256 id) view returns (tuple(address seller, uint256 price, uint64 expiry, uint256 nonce, bytes32 uriHash, uint256 loansRepaid) listing)",
|
|
163
|
+
"function cancel(uint256 id)",
|
|
164
|
+
]);
|
|
165
|
+
const MARKET_IFACE = new ethers.Interface(LEASE_MARKET_FUNCTIONS);
|
|
166
|
+
|
|
167
|
+
/** What each refusal means for the sheets (the kinds Go mode's and the board's words use). */
|
|
168
|
+
export const LEASE_ERROR_KINDS = Object.freeze({
|
|
169
|
+
NoOffer: "noOffer", OfferExpired: "gone", OfferGone: "gone", Leased: "leased", NotForYou: "notForYou", SelfRent: "self",
|
|
170
|
+
RenterIsWallet: "wallet", RenterControls: "controls", Listed: "listed", BadDays: "days", DayBelowFee: "low",
|
|
171
|
+
NoLease: "noLease", CannotEnd: "notYours", NothingOwed: "nothingOwed", PayOutOfGas: "gas", NotRenter: "notYours",
|
|
172
|
+
ChangedHands: "changedHands", RefundBelow: "refundBelow", RegistryFailed: "registry", NotOwner: "notYours",
|
|
173
|
+
Custodian: "cantRent", Refused: "cantRent", Marked: "marked", IsRoot: "cantRent", AgentDefaulted: "cantRent",
|
|
174
|
+
RecordChanged: "record", UriChanged: "record", PriceTooLow: "low", PriceAbove: "price", BadExpiry: "expiry",
|
|
175
|
+
CannotCancel: "notYours", IsPaused: "paused",
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
/** The kind of a lease call's revert data ("0x..."), or null when it is none of the lease's errors. */
|
|
179
|
+
export function leaseRefusal(data) {
|
|
180
|
+
if (typeof data !== "string" || !/^0x[0-9a-fA-F]{8}/.test(data)) return null;
|
|
181
|
+
try {
|
|
182
|
+
const e = LEASE_IFACE.parseError(data);
|
|
183
|
+
return e ? { kind: LEASE_ERROR_KINDS[e.name], name: e.name } : null;
|
|
184
|
+
} catch (_) { return null; }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/* ---- the rules and the money ---- */
|
|
188
|
+
|
|
189
|
+
const DAY = 86_400;
|
|
190
|
+
/** The contract's rules, and Go mode's cap on one lease, added days included (goMax, the gas gate's: 600 USDG). */
|
|
191
|
+
export const LEASE_RULES = Object.freeze({
|
|
192
|
+
minRent: 5_000_000n, // 5 USDG in all at the offer's shortest term, as the market's MIN_PRICE
|
|
193
|
+
maxDays: 90, // MAX_DAYS: a lease runs 1 to 90 days, added days included (the owner's answer of 2026-10-31)
|
|
194
|
+
dayS: DAY,
|
|
195
|
+
maxOfferS: 30 * DAY, // MAX_OFFER: an offer stands 30 days at most
|
|
196
|
+
goMax: 600_000_000n,
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
const uint = (v, what) => toId(v, what);
|
|
200
|
+
function daysOf(v, what = "days") {
|
|
201
|
+
if (!Number.isSafeInteger(v) || v < 1 || v > LEASE_RULES.maxDays) throw new Error(`${what} is a whole number from 1 to ${LEASE_RULES.maxDays}`);
|
|
202
|
+
return v;
|
|
203
|
+
}
|
|
204
|
+
const refusal = (message, kind) => Object.assign(new Error(message), { kind });
|
|
205
|
+
|
|
206
|
+
/** The market's fee rule on `amount`: max(amount x feeBps / 10,000 rounded down, minFee). The fee is the market's
|
|
207
|
+
* feeBps and minFee read live (or a lease's pin): there is no default. */
|
|
208
|
+
export function feeOn(amount, { feeBps, minFee } = {}) {
|
|
209
|
+
if (feeBps == null || minFee == null) throw new Error("the fee is read live from the market: pass feeBps and minFee");
|
|
210
|
+
const a = uint(amount, "amount"), bps = uint(feeBps, "feeBps"), min = uint(minFee, "minFee");
|
|
211
|
+
const pct = (a * bps) / 10_000n;
|
|
212
|
+
return pct > min ? pct : min;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The fee pin a rent gives its lease, as the contract sets it: the lower rate and, on its own, the lower minimum of
|
|
216
|
+
* the offer's (offerOf's feeBps and minFee: the market's at the offer) and the market's now (read live).
|
|
217
|
+
* { feeBps, minFee } */
|
|
218
|
+
export function pinOf(offer, market) {
|
|
219
|
+
if (!offer || !market) throw new Error("pinOf takes the offer (offerOf) and the market's fee now");
|
|
220
|
+
const ob = uint(offer.feeBps, "the offer's feeBps"), mb = uint(market.feeBps, "the market's feeBps");
|
|
221
|
+
const om = uint(offer.minFee, "the offer's minFee"), mm = uint(market.minFee, "the market's minFee");
|
|
222
|
+
return { feeBps: Number(ob < mb ? ob : mb), minFee: om < mm ? om : mm };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* What `rent` takes, as the contract's quote, rent and payouts compute it: { total, fee, firstDay, held } in USDG
|
|
227
|
+
* units. `total` is dayPrice x days, all paid into the lease (`held`); none of it goes to the owner or the fee then.
|
|
228
|
+
* `fee` is F(days), the fee the whole term carries, taken from its payouts, at the lease's pin (pinOf: the offer's fee,
|
|
229
|
+
* offerFeeBps and offerMinFee, default the market's; and the market's now, feeBps and minFee, read live); `firstDay`
|
|
230
|
+
* what day 1 pays its owner when it ends: the day price less F(1). A free lease takes nothing.
|
|
231
|
+
*/
|
|
232
|
+
export function rentQuote({ dayPrice, days, feeBps, minFee, offerFeeBps = feeBps, offerMinFee = minFee }) {
|
|
233
|
+
if (feeBps == null || minFee == null) throw new Error("rentQuote takes the market's fee now (feeBps, minFee), read live");
|
|
234
|
+
const p = uint(dayPrice, "dayPrice"), d = daysOf(days);
|
|
235
|
+
const total = p * BigInt(d);
|
|
236
|
+
if (total === 0n) return { total: 0n, fee: 0n, firstDay: 0n, held: 0n };
|
|
237
|
+
const pin = pinOf({ feeBps: offerFeeBps, minFee: offerMinFee }, { feeBps, minFee });
|
|
238
|
+
const fee = feeOn(total, pin), f1 = feeOn(p, pin);
|
|
239
|
+
if (fee >= p) throw new Error("the fee is not under a day's rent: no such offer can stand");
|
|
240
|
+
return { total, fee, firstDay: p - f1, held: total };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Why `offerRent` would refuse these terms, leaving the fee aside: "days", "free" or "low" (offerProblem). */
|
|
244
|
+
function offerShape({ dayPrice, minDays, maxDays, renter }) {
|
|
245
|
+
if (!Number.isSafeInteger(minDays) || !Number.isSafeInteger(maxDays) || minDays < 1 || minDays > maxDays || maxDays > LEASE_RULES.maxDays) return "days";
|
|
246
|
+
const p = uint(dayPrice, "dayPrice");
|
|
247
|
+
if (p === 0n) return renter ? null : "free";
|
|
248
|
+
if (p * BigInt(minDays) < LEASE_RULES.minRent) return "low";
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Why `offerRent` would refuse these terms, or null: "days" (1 <= minDays <= maxDays <= 90), "free" (a day price of 0
|
|
254
|
+
* with no named renter), "low" (under 5 USDG in all at minDays), "fee" (a day not above the fee on the longest term at
|
|
255
|
+
* the market's fee now: DayBelowFee). `feeBps` and `minFee` are the market's, read live; they have no default.
|
|
256
|
+
*/
|
|
257
|
+
export function offerProblem({ dayPrice, minDays, maxDays, renter = null, feeBps, minFee }) {
|
|
258
|
+
if (feeBps == null || minFee == null) throw new Error("offerProblem takes the market's fee now (feeBps, minFee), read live");
|
|
259
|
+
const shape = offerShape({ dayPrice, minDays, maxDays, renter });
|
|
260
|
+
if (shape) return shape;
|
|
261
|
+
const p = uint(dayPrice, "dayPrice");
|
|
262
|
+
if (p !== 0n && p <= feeOn(p * BigInt(maxDays), { feeBps, minFee })) return "fee";
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** A lease as leaseOf gives it ({ renter, start, term, paidDays, maxDays, holder, dayPrice, owner, settledAt, feeBps,
|
|
267
|
+
* minFee }), with numbers or bigints. Only renter, start and term are needed to show it; the money needs the rest. */
|
|
268
|
+
function leaseOf(l) {
|
|
269
|
+
if (!l || l.renter == null) throw new Error("a lease is leaseOf's tuple");
|
|
270
|
+
const term = Number(l.term);
|
|
271
|
+
return {
|
|
272
|
+
renter: String(l.renter),
|
|
273
|
+
start: Number(l.start),
|
|
274
|
+
term,
|
|
275
|
+
paidDays: Number(l.paidDays ?? 0),
|
|
276
|
+
maxDays: Number(l.maxDays ?? term),
|
|
277
|
+
holder: l.holder == null ? null : String(l.holder),
|
|
278
|
+
dayPrice: uint(l.dayPrice ?? 0, "dayPrice"),
|
|
279
|
+
owner: l.owner == null ? null : String(l.owner),
|
|
280
|
+
settledAt: Number(l.settledAt ?? l.start),
|
|
281
|
+
feeBps: l.feeBps == null ? null : Number(l.feeBps),
|
|
282
|
+
minFee: l.minFee == null ? null : uint(l.minFee, "minFee"),
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
const none = (l) => BigInt(l.renter) === 0n;
|
|
286
|
+
const ZERO = ethers.ZeroAddress;
|
|
287
|
+
/** An address as a lower case key; null or undefined: the zero address (no owner). */
|
|
288
|
+
function key(a, what) {
|
|
289
|
+
if (a == null) return ZERO;
|
|
290
|
+
try { return ethers.getAddress(String(a)).toLowerCase(); } catch (_) { throw new Error(`${what} must be an address`); }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** The lease's end: start + term days (seconds). */
|
|
294
|
+
export const untilOf = (lease) => { const l = leaseOf(lease); return l.start + l.term * DAY; };
|
|
295
|
+
/** True while the lease runs (nowS < its end). */
|
|
296
|
+
export const isActive = (lease, nowS) => { const l = leaseOf(lease); return !none(l) && nowS < untilOf(l); };
|
|
297
|
+
/** The days of the lease that have ended by `nowS`: day k (0-based) ends at start + (k+1) days; all of them from its
|
|
298
|
+
* date on. */
|
|
299
|
+
export function daysEnded(lease, nowS) {
|
|
300
|
+
const l = leaseOf(lease);
|
|
301
|
+
if (nowS < l.start) return 0;
|
|
302
|
+
return Math.min(l.term, Math.floor((nowS - l.start) / DAY));
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* F(k): the fee the first `k` days of a lease carry in all, at its pin (leaseOf's feeBps and minFee): max(k x dayPrice
|
|
307
|
+
* x feeBps / 10,000 rounded down, minFee); 0 for no day and for a free lease. After a payout the fee taken on a lease in
|
|
308
|
+
* all is F(paidDays), so day j (0-based) carries F(j+1) - F(j), however the payouts are grouped.
|
|
309
|
+
*/
|
|
310
|
+
export function leaseFee(lease, k) {
|
|
311
|
+
const l = leaseOf(lease);
|
|
312
|
+
if (!Number.isSafeInteger(k) || k < 0 || k > LEASE_RULES.maxDays) throw new Error(`k is a whole number of days from 0 to ${LEASE_RULES.maxDays}`);
|
|
313
|
+
if (k === 0 || l.dayPrice === 0n) return 0n;
|
|
314
|
+
if (l.feeBps == null || l.minFee == null) throw new Error("a lease's fee pin (feeBps, minFee) is leaseOf's: read it with the lease");
|
|
315
|
+
return feeOn(BigInt(k) * l.dayPrice, { feeBps: l.feeBps, minFee: l.minFee });
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The contract's _settle: days `paidDays` to `to` of `l`, split between the holder at the last payout and the owner
|
|
319
|
+
* now (zero: none), each part net of its days' share of the fee. */
|
|
320
|
+
function settle(l, { holder, ownerNow, soldAt = 0, settledAt }, to) {
|
|
321
|
+
const from = l.paidDays;
|
|
322
|
+
if (to <= from) return { toHolder: 0n, toOwner: 0n, fee: 0n, paidDays: from };
|
|
323
|
+
const h = key(holder, "the holder"), o = key(ownerNow, "the owner now");
|
|
324
|
+
let split = to;
|
|
325
|
+
if (o !== h) { // a change of hands since the last payout, or no owner any more
|
|
326
|
+
split = from;
|
|
327
|
+
const sold = Number(soldAt);
|
|
328
|
+
if (sold > Number(settledAt)) split = Math.min(Math.max(Math.floor((sold - l.start) / DAY), from), to);
|
|
329
|
+
}
|
|
330
|
+
const paidTo = o === ZERO ? split : to; // with no owner the days after the split are not paid
|
|
331
|
+
const f0 = leaseFee(l, from), f1 = leaseFee(l, split), f2 = leaseFee(l, paidTo);
|
|
332
|
+
return {
|
|
333
|
+
toHolder: BigInt(split - from) * l.dayPrice - (f1 - f0),
|
|
334
|
+
toOwner: BigInt(paidTo - split) * l.dayPrice - (f2 - f1),
|
|
335
|
+
fee: f2 - f0,
|
|
336
|
+
paidDays: paidTo,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** The holder, owner, last sale and last payout a split reads: `holder` defaults to the lease's (leaseOf's holder),
|
|
341
|
+
* `ownerNow` to the holder (no change of hands; null or zero: no owner), `settledAt` to the lease's. */
|
|
342
|
+
function splitAt(l, { holder, ownerNow, soldAt = 0, settledAt }, what) {
|
|
343
|
+
const h = holder ?? l.holder;
|
|
344
|
+
if (h == null) throw new Error(`${what} takes the lease's holder (leaseOf's holder)`);
|
|
345
|
+
return { holder: h, ownerNow: ownerNow === undefined ? h : ownerNow, soldAt, settledAt: settledAt ?? l.settledAt };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Who a claim at `nowS` pays, as the contract splits it: { toHolder, toOwner, fee, paidDays } in USDG units (paidDays
|
|
350
|
+
* the lease's after the claim). The days ended and not paid are split at the market's last sale since the last payout:
|
|
351
|
+
* `holder` (the lease's holder at its last payout, `settledAt`) gets the days that ended by it (`soldAt`, lastSoldAt
|
|
352
|
+
* now; rounded down), `ownerNow` the rest; with a new owner and no sale since, the owner now gets them all. That is
|
|
353
|
+
* each day to whoever held the agent when it ended for one market sale since the last payout (a V2 buy or acceptBid,
|
|
354
|
+
* or a v1 sale), and only then: a plain transfer with no sale since gives every unpaid day to its receiver, and with
|
|
355
|
+
* two changes of hands the middle holder is paid nothing (its days go to `holder` when the later change is a market
|
|
356
|
+
* sale, to `ownerNow` when it is a plain transfer). With no owner now (null or zero: burnt, or held by the lease), only
|
|
357
|
+
* the holder's days are paid. Each part is net of its days' own fee; `fee` is their sum, to the market's feeTo.
|
|
358
|
+
*/
|
|
359
|
+
export function claimSplit({ lease, holder, ownerNow, soldAt = 0, settledAt, nowS }) {
|
|
360
|
+
const l = leaseOf(lease);
|
|
361
|
+
if (none(l)) return { toHolder: 0n, toOwner: 0n, fee: 0n, paidDays: 0 };
|
|
362
|
+
return settle(l, splitAt(l, { holder, ownerNow, soldAt, settledAt }, "claimSplit"), daysEnded(l, nowS));
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** What claim(id) pays out now, in all, net of the fee (the contract's claimable): the days ended and not paid, each
|
|
366
|
+
* less its own fee. Without `ownerNow` the lease's holder still holds the agent; with it (and `soldAt`) the days are
|
|
367
|
+
* split as claimSplit splits them. */
|
|
368
|
+
export function claimableOf(lease, nowS, { ownerNow, soldAt = 0 } = {}) {
|
|
369
|
+
const l = leaseOf(lease);
|
|
370
|
+
if (none(l)) return 0n;
|
|
371
|
+
const holder = l.holder ?? (ownerNow === undefined ? "0x0000000000000000000000000000000000000001" : null); // one holder all along
|
|
372
|
+
const s = claimSplit({ lease: l, holder, ownerNow, soldAt, nowS });
|
|
373
|
+
return s.toHolder + s.toOwner;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* What an end at `nowS` sends back to the renter (the contract's refundsOf): { byRenter, byOwner } in USDG units. An
|
|
378
|
+
* end first pays the days that ended, so this, not leaseOf's (term - paidDays) x dayPrice (what the lease holds), is
|
|
379
|
+
* the refund. While a sound lease runs a day is under way: the renter's own end keeps it paid (byRenter, the days after
|
|
380
|
+
* it), the owner's end sends it back too (byOwner); both are 0 once the lease is over. A renter that also holds the
|
|
381
|
+
* agent ends as the renter: its figure is byRenter, so a client names minRefund as account == renter ? byRenter :
|
|
382
|
+
* byOwner. On a broken agent (`broken`, with the split's `ownerNow` and `soldAt` as brokenEnd takes them) every end
|
|
383
|
+
* sends the day under way back, whoever ends: both are brokenEnd's refund.
|
|
384
|
+
*/
|
|
385
|
+
export function refundsOf(lease, nowS, { broken = false, ...at } = {}) {
|
|
386
|
+
const l = leaseOf(lease);
|
|
387
|
+
if (none(l)) return { byRenter: 0n, byOwner: 0n };
|
|
388
|
+
if (broken) { const r = brokenEnd({ lease: l, ...at, nowS }).refund; return { byRenter: r, byOwner: r }; }
|
|
389
|
+
if (nowS >= untilOf(l)) return { byRenter: 0n, byOwner: 0n };
|
|
390
|
+
const e = daysEnded(l, nowS);
|
|
391
|
+
return { byRenter: BigInt(l.term - e - 1) * l.dayPrice, byOwner: BigInt(l.term - e) * l.dayPrice };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* What an early end of a sound lease does at `nowS` (the contract's endLease while it runs): { toHolder, toOwner, fee,
|
|
396
|
+
* refund } in USDG units. `by` "renter": the days ended and the day under way go to their holders; "owner" (the agent's
|
|
397
|
+
* owner now, a buyer or a bid's maker included): only the days ended. A renter that also holds the agent ends as the
|
|
398
|
+
* renter ("renter"). The days are paid first, split as claimSplit splits them; then every day not paid goes back to
|
|
399
|
+
* the renter in full. A broken agent's end is brokenEnd's, whoever ends.
|
|
400
|
+
*/
|
|
401
|
+
export function earlyEnd({ lease, by, holder, ownerNow, soldAt = 0, settledAt, nowS }) {
|
|
402
|
+
const l = leaseOf(lease);
|
|
403
|
+
if (none(l) || nowS >= untilOf(l)) throw refusal("only a running lease ends early", "noLease");
|
|
404
|
+
if (by !== "renter" && by !== "owner") throw new Error('by is "renter" or "owner"');
|
|
405
|
+
const at = splitAt(l, { holder, ownerNow, soldAt, settledAt }, "earlyEnd");
|
|
406
|
+
if (key(at.ownerNow, "the owner now") === ZERO) throw new Error("an agent with no owner is broken: its end is brokenEnd's");
|
|
407
|
+
const s = settle(l, at, daysEnded(l, nowS) + (by === "renter" ? 1 : 0));
|
|
408
|
+
return { toHolder: s.toHolder, toOwner: s.toOwner, fee: s.fee, refund: BigInt(l.term - s.paidDays) * l.dayPrice };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* What the end of a broken agent's lease does at `nowS` (the contract's claim or endLease by anyone then, before the
|
|
413
|
+
* lease's date or after): { toHolder, toOwner, fee, refund } in USDG units, the same whoever ends, the renter
|
|
414
|
+
* included: the day under way always comes back. With an owner (`ownerNow`, by default the holder: the agent defaulted
|
|
415
|
+
* on pool v2 or v1), every day ended goes to its holders as a claim pays it, and the day under way and the days not
|
|
416
|
+
* begun go back to the renter. With none (`ownerNow` null or zero: burnt, or held by the lease), the holder at the last
|
|
417
|
+
* payout gets the days that ended by a market sale since (`soldAt`), and every other day not paid goes back.
|
|
418
|
+
*/
|
|
419
|
+
export function brokenEnd({ lease, holder, ownerNow, soldAt = 0, settledAt, nowS }) {
|
|
420
|
+
const l = leaseOf(lease);
|
|
421
|
+
if (none(l)) return { toHolder: 0n, toOwner: 0n, fee: 0n, refund: 0n };
|
|
422
|
+
const s = settle(l, splitAt(l, { holder, ownerNow, soldAt, settledAt }, "brokenEnd"), daysEnded(l, nowS));
|
|
423
|
+
return { toHolder: s.toHolder, toOwner: s.toOwner, fee: s.fee, refund: BigInt(l.term - s.paidDays) * l.dayPrice };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* What extend(id, days) takes now, from leaseOf's lease: { total, until, room }. `total` is the lease's day price x
|
|
428
|
+
* days, paid into the lease (no fee on top: the added days carry their share when they are paid out); `until` the
|
|
429
|
+
* lease's new end; `room` the most days it can take now (the rented offer's maxDays less its term). Throws as extend
|
|
430
|
+
* reverts: once the lease is over (kind "noLease"), and for days outside 1 to room (kind "max" past room, "days" for
|
|
431
|
+
* fewer than 1). The chain also refuses an extension once the agent changed hands or sold since the rent
|
|
432
|
+
* (ChangedHands), while a listing of it stands on V2 or v1, whoever listed it (extendCalls cancels one whose seller no
|
|
433
|
+
* longer holds the agent first), and on rent's checks of the agent and both accounts.
|
|
434
|
+
*/
|
|
435
|
+
export function extendQuote({ lease, days, nowS }) {
|
|
436
|
+
const l = leaseOf(lease);
|
|
437
|
+
if (none(l) || nowS >= untilOf(l)) throw refusal("the lease is over: no day can be added", "noLease");
|
|
438
|
+
const room = Math.max(l.maxDays - l.term, 0);
|
|
439
|
+
if (!Number.isSafeInteger(days) || days < 1) throw refusal("days is a whole number, at least 1", "days");
|
|
440
|
+
if (days > room) throw refusal(room ? `the lease can take ${room} more days at most` : "the lease is at its longest term", "max");
|
|
441
|
+
return { total: BigInt(days) * l.dayPrice, until: l.start + (l.term + days) * DAY, room };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/* ---- the words (spec 13, with the owner's answers of 2026-10-30 and 2026-10-31) ---- */
|
|
445
|
+
|
|
446
|
+
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
447
|
+
const dayText = (s) => { const d = new Date(Number(s) * 1000); return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}`; };
|
|
448
|
+
const shortAddr = (a) => `${a.slice(0, 6)}..${a.slice(-4)}`;
|
|
449
|
+
const noCents = (text) => text.replace(/\.00$/, "");
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* The words of renting, one set for every surface (the board, Go mode and the MCP translate or show them). None names a
|
|
453
|
+
* past lease's price or who ended a lease, and none says the owner vouches for the renter. `end` is the owner's End
|
|
454
|
+
* lease (and anyone's on a broken agent); `endYou` the renter's on a sound agent, also when the renter holds the agent,
|
|
455
|
+
* since it ends as the renter (account == renter); `endYouBroken` the renter's on a broken agent, whose every end sends
|
|
456
|
+
* the current day back. Those three are for a lease that runs: a broken agent's lease ended after its date has no day
|
|
457
|
+
* under way, and takes `endAfter` (the owner's or anyone's) and `endYouAfter` (the renter's). `errors.listed` is the
|
|
458
|
+
* owner's own listing, which rentCalls and extendCalls refuse; the chain's Listed maps there too (a stale listing met
|
|
459
|
+
* in a race, after the reads: read again, and the builders cancel it first).
|
|
460
|
+
*/
|
|
461
|
+
export const LEASE_WORDS = Object.freeze({
|
|
462
|
+
labels: Object.freeze({ forRent: "For rent", rented: "Rented", dayPrice: "Day price", days: "Days", runYou: "Agents you run", rentedOut: "Rented out", past: "Past leases" }),
|
|
463
|
+
buttons: Object.freeze({ rent: "Rent", rentOut: "Rent it out", cancel: "Cancel offer", extend: "Add days", end: "End lease", claim: "Collect rent", withdraw: "Withdraw" }),
|
|
464
|
+
pill: "{price} USDG a day",
|
|
465
|
+
runBy: "Run by {addr} until {date}",
|
|
466
|
+
offer: "{price} USDG a day, for {min} to {max} days.",
|
|
467
|
+
offerTo: "Offered to {addr}.",
|
|
468
|
+
box: Object.freeze([
|
|
469
|
+
"You sell its work and take paid jobs under its name. Clients pay your own address.",
|
|
470
|
+
"You can't borrow on its line or change its file. Its record stays with the agent.",
|
|
471
|
+
"You pay the whole lease now, and its owner is paid as each day ends. If you end it early, every day after the current one comes back to you in full. If its owner ends it, the current day comes back too.",
|
|
472
|
+
]),
|
|
473
|
+
sheet: Object.freeze({
|
|
474
|
+
total: "{total} USDG for {days} days of #{id}. It's yours to run until {date}. Each day goes to its owner when it ends, and the fee comes out of the owner's rent, never out of what comes back to you.",
|
|
475
|
+
loans: "Its owner can still borrow on its line. If a loan isn't repaid, you or anyone can end the lease, and the current day and every day after it come back to you.",
|
|
476
|
+
servers: "Its owner's own servers may keep running outside Priors.",
|
|
477
|
+
sale: "If #{id} changes hands, the lease goes on until {date}, but no days can be added. Each change of hands on Priors collects the rent first, so each day goes to whoever held #{id} when it ended.",
|
|
478
|
+
hidden: "If Priors stops showing your offers for #{id}, nothing is paid back. You can end the lease and get the days not begun.",
|
|
479
|
+
}),
|
|
480
|
+
sell: "It's rented until {date}. A buyer gets it with the lease and the rent of each day that ends after the sale. A sale here collects the rent due to you first.",
|
|
481
|
+
rentOut: "Someone pays {price} USDG a day to sell #{id}'s work under its name. They can't borrow on its line or change its file. Each day's rent comes to you when the day ends, less the fee. You can end the lease early at no cost to you, and the renter then gets back the current day and the days after it.",
|
|
482
|
+
end: "The lease ends now. The renter gets back {refund} USDG for {n} days, the current day included.",
|
|
483
|
+
endYou: "The lease ends now. You get back {refund} USDG for the {n} days after the current one, and the current day goes to its owner.",
|
|
484
|
+
endYouBroken: "The lease ends now. You get back {refund} USDG for {n} days, the current day included.",
|
|
485
|
+
endAfter: "The lease ends now. The renter gets back {refund} USDG for {n} days.",
|
|
486
|
+
endYouAfter: "The lease ends now. You get back {refund} USDG for {n} days.",
|
|
487
|
+
errors: Object.freeze({
|
|
488
|
+
leased: "This agent is rented until {date}. You can rent it after that.",
|
|
489
|
+
notForYou: "This offer is for another address. Ask its owner for one.",
|
|
490
|
+
gone: "This offer is closed. Its owner can make a new one.",
|
|
491
|
+
listed: "This agent is listed for sale. You can rent it or add days if the listing is taken down or runs out.",
|
|
492
|
+
self: "You hold this agent. Use Rent it out to set a price.",
|
|
493
|
+
wallet: "This address is the agent's payment wallet. Rent from another address.",
|
|
494
|
+
controls: "This address can borrow for this agent. Rent from another address.",
|
|
495
|
+
marked: "This address has a defaulted loan on Priors, so it can't rent here. Use another address.",
|
|
496
|
+
record: "Its record changed since you looked. Read it again, then rent.",
|
|
497
|
+
price: "The price changed since you looked. Read the offer again, then rent.",
|
|
498
|
+
short: "You have {cash} USDG. Add {short} more, then rent.",
|
|
499
|
+
over: "Go mode rents up to 600 USDG a lease, added days included. Choose fewer days.",
|
|
500
|
+
low: "A paid lease costs 5 USDG or more in all, and a day costs more than the fee. Raise the day price.",
|
|
501
|
+
cantRent: "This agent can't be rented here. Choose another agent.",
|
|
502
|
+
paused: "Renting is paused for now. Ending a lease still works.",
|
|
503
|
+
changedHands: "This agent changed hands since you rented it, so no days can be added. Its new owner can offer it again once this lease ends.",
|
|
504
|
+
max: "This lease can't run longer than its owner offers, {max} days in all. Add fewer days, or rent it again once it ends.",
|
|
505
|
+
notRenter: "Only the address that rented this agent can add days. Use that address.",
|
|
506
|
+
refundBelow: "A day ended while this was being sent, so less would come back than you saw. Read the lease again, then end it.",
|
|
507
|
+
registry: "The agent registry didn't answer, so nothing moved. Try again in a moment.",
|
|
508
|
+
}),
|
|
509
|
+
bell: Object.freeze({
|
|
510
|
+
rented: "#{id} is rented until {date}.",
|
|
511
|
+
extended: "#{id}'s lease now runs until {date}.",
|
|
512
|
+
ending: "Your lease on #{id} ends within a day, on {date}.",
|
|
513
|
+
endedEarly: "Your lease on #{id} ended early. {refund} USDG came back to you.",
|
|
514
|
+
collect: "{amount} USDG of rent to collect on #{id}.",
|
|
515
|
+
defaulted: "#{id} defaulted, so you can end its lease. The current day and every day after it come back to you.",
|
|
516
|
+
}),
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
const fill = (t, v) => t.replace(/\{(\w+)\}/g, (m, k) => (k in v ? String(v[k]) : m));
|
|
520
|
+
|
|
521
|
+
/** An address, checksummed or lower case, never zero; lower case. */
|
|
522
|
+
function addressOf(a, what) {
|
|
523
|
+
let x;
|
|
524
|
+
try { x = ethers.getAddress(a); } catch (_) { throw new Error(`${what} must be an address`); }
|
|
525
|
+
if (x === ethers.ZeroAddress) throw new Error(`${what} must not be the zero address`);
|
|
526
|
+
return x.toLowerCase();
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** A running lease as every surface shows it: { by, since, until, words: "Run by 0x12..ab until 30 Nov" }. No price.
|
|
530
|
+
* Null when there is none, or it is over at `nowS`. */
|
|
531
|
+
export function leaseView(item, { nowS = Math.floor(Date.now() / 1000) } = {}) {
|
|
532
|
+
if (!item || item.renter == null || BigInt(item.renter) === 0n) return null;
|
|
533
|
+
const l = leaseOf(item);
|
|
534
|
+
if (!isActive(l, nowS)) return null;
|
|
535
|
+
const by = addressOf(l.renter, "the renter"), until = untilOf(l);
|
|
536
|
+
return { by, since: l.start, until, words: fill(LEASE_WORDS.runBy, { addr: shortAddr(by), date: dayText(until) }) };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** A standing offer as the For rent box shows it: { dayPrice: "2.00", minDays, maxDays, for, until, pill, words }. Null
|
|
540
|
+
* for none. `for` is the named renter (lower case), or null for anyone. */
|
|
541
|
+
export function offerView(item) {
|
|
542
|
+
if (!item || item.owner == null || BigInt(item.owner) === 0n) return null;
|
|
543
|
+
const p = uint(item.dayPrice, "dayPrice"), min = daysOf(Number(item.minDays), "minDays"), max = daysOf(Number(item.maxDays), "maxDays");
|
|
544
|
+
const forWho = item.renter && BigInt(item.renter) !== 0n ? addressOf(item.renter, "the renter") : null;
|
|
545
|
+
const price = noCents(usdgText(p));
|
|
546
|
+
const words = [fill(LEASE_WORDS.offer, { price, min, max })];
|
|
547
|
+
if (forWho) words.push(fill(LEASE_WORDS.offerTo, { addr: shortAddr(forWho) }));
|
|
548
|
+
return { dayPrice: usdgText(p), minDays: min, maxDays: max, for: forWho, until: Number(item.expiry), pill: fill(LEASE_WORDS.pill, { price }), words };
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/* ---- the calls, for agents and scripts ---- */
|
|
552
|
+
|
|
553
|
+
const USDG_IFACE = new ethers.Interface(["function approve(address spender, uint256 amount) returns (bool)"]);
|
|
554
|
+
const bytes32Of = (v, what) => { if (!/^0x[0-9a-fA-F]{64}$/.test(String(v))) throw new Error(`${what} is a 32-byte hex value`); return String(v).toLowerCase(); };
|
|
555
|
+
const call = (to, fn, args) => ({ to, data: LEASE_IFACE.encodeFunctionData(fn, args) });
|
|
556
|
+
|
|
557
|
+
/** offerRent: the owner's offer. `renter` null for anyone; `dayPrice` 0 only with a renter. With the market's fee read
|
|
558
|
+
* live (`feeBps` and `minFee`) it also refuses a day not above the fee on the longest term. [{ to, data }] */
|
|
559
|
+
export function offerCalls({ lease, id, dayPrice, minDays, maxDays, renter = null, expiry, feeBps, minFee }) {
|
|
560
|
+
const to = addressOf(lease, "the lease");
|
|
561
|
+
const who = renter ? addressOf(renter, "the renter") : ethers.ZeroAddress;
|
|
562
|
+
const terms = { dayPrice, minDays, maxDays, renter: renter ? who : null };
|
|
563
|
+
const problem = feeBps == null && minFee == null ? offerShape(terms) : offerProblem({ ...terms, feeBps, minFee });
|
|
564
|
+
if (problem) throw new Error(`the offer is refused: ${problem}`);
|
|
565
|
+
return [call(to, "offerRent", [uint(id, "id"), uint(dayPrice, "dayPrice"), minDays, maxDays, who, uint(expiry, "expiry")])];
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** cancelOffer. [{ to, data }] */
|
|
569
|
+
export const cancelOfferCalls = ({ lease, id }) => [call(addressOf(lease, "the lease"), "cancelOffer", [uint(id, "id")])];
|
|
570
|
+
|
|
571
|
+
/** A market's listingOf(id) as read: { seller (lower case; zero for none), expiry }. */
|
|
572
|
+
function listingRead(l, what) {
|
|
573
|
+
if (l == null || l.seller == null) throw new Error(`${what} is the market's listingOf(id), read just before (its seller the zero address for none)`);
|
|
574
|
+
let seller;
|
|
575
|
+
try { seller = ethers.getAddress(String(l.seller)).toLowerCase(); } catch (_) { throw new Error(`${what}'s seller must be an address`); }
|
|
576
|
+
if (seller !== ZERO && l.expiry == null) throw new Error(`${what} takes listingOf's expiry`);
|
|
577
|
+
return { seller, expiry: seller === ZERO ? 0 : Number(l.expiry) };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** What a rent or an extension of agent `id` sends before its own calls, for the listings that would bar it (the
|
|
581
|
+
* contract's Listed): a market's cancel(id) for each listing not expired at `nowS` whose seller no longer holds the
|
|
582
|
+
* agent, V2's before v1's. One by the owner now refuses (kind "listed"). [{ to, data }, ...] */
|
|
583
|
+
function unlistCalls({ id, ownerNow, market, listing, previous, prevListing, nowS }) {
|
|
584
|
+
const owner = addressOf(ownerNow, "ownerNow (the agent's owner now)");
|
|
585
|
+
if (!Number.isSafeInteger(nowS) || nowS < 0) throw new Error("nowS is the time the listings were read, in seconds");
|
|
586
|
+
if (previous === undefined) throw new Error("previous is the lease's previous() (the zero address for none)");
|
|
587
|
+
const markets = [[addressOf(market, "the market"), listingRead(listing, "listing")]];
|
|
588
|
+
const prev = key(previous, "previous");
|
|
589
|
+
if (prev !== ZERO) markets.push([prev, listingRead(prevListing, "prevListing")]);
|
|
590
|
+
const calls = [];
|
|
591
|
+
for (const [m, l] of markets) {
|
|
592
|
+
if (l.seller === ZERO || nowS >= l.expiry) continue; // none, or expired: it bars nothing
|
|
593
|
+
if (l.seller === owner) throw refusal(`#${id} is listed by its owner on ${m}: no lease starts or grows while that listing stands`, "listed");
|
|
594
|
+
calls.push({ to: m, data: MARKET_IFACE.encodeFunctionData("cancel", [id]) });
|
|
595
|
+
}
|
|
596
|
+
return calls;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* rent or extend, as the calls of one operation: first, for each listing of agent `id` that stands at `nowS` (not
|
|
601
|
+
* expired) on the lease's market (V2) or its previous (v1) while its seller no longer holds the agent, that market's
|
|
602
|
+
* cancel(id), which anyone may send (V2's before v1's); then USDG approve(lease, total) exactly (none when nothing is
|
|
603
|
+
* paid); then the call with maxTotal = total and the pins read. Any listing that stands bars both calls, whoever listed
|
|
604
|
+
* it (Listed): one by an earlier holder is buyable again once the agent goes back to it, and a buyer in flight would
|
|
605
|
+
* meet a new or a longer lease. One by the owner now refuses here (kind "listed"): only the owner can take it down
|
|
606
|
+
* before its expiry. The reads, just before: `ownerNow` (the registry's ownerOf(id)), `market` and `previous` (the
|
|
607
|
+
* lease's market() and previous(), the zero address for none), `listing` and `prevListing` (listingOf(id) on each: its
|
|
608
|
+
* seller, the zero address for none, and its expiry), and `nowS`, their time. A cancel that lands first (by its seller
|
|
609
|
+
* or anyone) makes this one revert NoListing: read again, and the next operation goes without it.
|
|
610
|
+
*/
|
|
611
|
+
function paidCalls(fn, { lease, usdg, id, days, total, recordHash, uriHash, ownerNow, market, listing, previous, prevListing, nowS }) {
|
|
612
|
+
const to = addressOf(lease, "the lease"), t = uint(total, "total"), i = uint(id, "id");
|
|
613
|
+
const calls = unlistCalls({ id: i, ownerNow, market, listing, previous, prevListing, nowS });
|
|
614
|
+
if (t > 0n) calls.push({ to: addressOf(usdg, "USDG"), data: USDG_IFACE.encodeFunctionData("approve", [to, t]) });
|
|
615
|
+
calls.push(call(to, fn, [i, BigInt(daysOf(days)), t, bytes32Of(recordHash, "recordHash"), bytes32Of(uriHash, "uriHash")]));
|
|
616
|
+
return calls;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** rent: a stale listing's cancel first (paidCalls), USDG approve(lease, total) exactly, then rent with maxTotal =
|
|
620
|
+
* total and the pins read (no approval for a free lease). [{ to, data }, ...] */
|
|
621
|
+
export const rentCalls = (args) => paidCalls("rent", args);
|
|
622
|
+
|
|
623
|
+
/** extend: a stale listing's cancel first (paidCalls), USDG approve(lease, total) exactly (extendQuote's total), then
|
|
624
|
+
* extend with maxTotal = total and the pins read; the renter only (no approval for a free lease).
|
|
625
|
+
* [{ to, data }, ...] */
|
|
626
|
+
export const extendCalls = (args) => paidCalls("extend", args);
|
|
627
|
+
|
|
628
|
+
/** claim. [{ to, data }] */
|
|
629
|
+
export const claimCalls = ({ lease, id }) => [call(addressOf(lease, "the lease"), "claim", [uint(id, "id")])];
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* What a change of hands of agent `id` sends around its own calls, in the same operation (the client rule,
|
|
633
|
+
* docs/AGENT-LEASE.md): { before, after }. While a lease is stored (`leased`: leaseOf names a renter, running or ended
|
|
634
|
+
* and not yet paid out), claim(id) before, so every day ended until now goes to whoever held the agent when it ended,
|
|
635
|
+
* and claim(id) after, so the new holder is recorded at once and a later change of hands elsewhere can't take its
|
|
636
|
+
* days (claim on an agent with nothing stored returns 0, so the second never fails). For a move outside the market
|
|
637
|
+
* (`plain`), cancelOffer(id) before while an offer stands (`offered`), as a round trip by plain transfers would bring
|
|
638
|
+
* it back. Go mode's Buy ([...before, approve, buy, ...after]), Accept and transfer, the board's wallet paths and
|
|
639
|
+
* @priors/mcp's market_buy and market_accept wrap their own calls in these; Go mode's Sell sends `before` ahead of its
|
|
640
|
+
* listing.
|
|
641
|
+
*/
|
|
642
|
+
export function handoverCalls({ lease, id, leased = false, offered = false, plain = false }) {
|
|
643
|
+
const before = [], after = [];
|
|
644
|
+
if (leased) before.push(...claimCalls({ lease, id }));
|
|
645
|
+
if (plain && offered) before.push(...cancelOfferCalls({ lease, id }));
|
|
646
|
+
if (leased) after.push(...claimCalls({ lease, id }));
|
|
647
|
+
return { before, after };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** endLease, with the least refund the caller takes (`minRefund`, refundsOf's figure read just before, never leaseOf's:
|
|
651
|
+
* account == renter ? byRenter : byOwner, since a renter that also holds the agent ends as the renter; 0 to take
|
|
652
|
+
* whatever it is). [{ to, data }] */
|
|
653
|
+
export const endCalls = ({ lease, id, minRefund }) => [call(addressOf(lease, "the lease"), "endLease", [uint(id, "id"), uint(minRefund, "minRefund")])];
|
|
654
|
+
|
|
655
|
+
/** withdraw: sends `account` what USDG refused it (owed); anyone may send it, and it pays that account only. [{ to, data }] */
|
|
656
|
+
export const withdrawCalls = ({ lease, account }) => [call(addressOf(lease, "the lease"), "withdraw", [addressOf(account, "the account")])];
|