@priors/mcp 0.15.0 → 0.17.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 +80 -2
- package/README.md +58 -27
- package/deployments/4663.agent-lease.json +46 -0
- package/package.json +2 -2
- package/src/agent-lease.mjs +6 -7
- package/src/key-file.mjs +37 -12
- package/src/market-plan.mjs +25 -4
- package/src/market-tools.mjs +45 -14
- package/src/pt-onestep-core.cjs +128 -0
- package/src/rialto.mjs +217 -0
- package/src/server.mjs +169 -10
- package/src/stock-tools.mjs +63 -10
- package/src/stock-trade.mjs +200 -11
- package/src/work-types.mjs +11 -4
package/src/market-plan.mjs
CHANGED
|
@@ -34,6 +34,7 @@ import { ethers } from "ethers";
|
|
|
34
34
|
import { MARKET_IFACE, LISTING_RULES, feeOf } from "./market-abi.mjs";
|
|
35
35
|
import { BID_RULES, BID_WORDS, spenderOf, idsRootOf, listOf, inRoot, reserveCall, bidCall, bidAnyCall, cancelBidCall, acceptCall } from "./market-bids.mjs";
|
|
36
36
|
import { LEASE_IFACE, LEASE_WORDS, handoverCalls } from "./agent-lease.mjs";
|
|
37
|
+
import { BUILDER_WORDS } from "./market-builders.mjs";
|
|
37
38
|
|
|
38
39
|
/* ---- small helpers ---- */
|
|
39
40
|
|
|
@@ -81,6 +82,7 @@ export const READS = Object.freeze({
|
|
|
81
82
|
// the builder share, on a V2 that has it (the P5 spec, 2.2 and 2.3)
|
|
82
83
|
"function MAX_BUILDER_BPS() view returns (uint256)", "function builderOf(uint256 id) view returns (tuple(address to, uint16 bps))",
|
|
83
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)",
|
|
84
86
|
]),
|
|
85
87
|
spender: new ethers.Interface(["function market() view returns (address)"]),
|
|
86
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)"]),
|
|
@@ -206,7 +208,7 @@ export function agentReads({ addr, id, shares = false }) {
|
|
|
206
208
|
add("bondV2", a.inviteBondV2, "bondV2", "bonds", [i]);
|
|
207
209
|
add("bondAmount", a.inviteBondV2, "bondV2", "amount");
|
|
208
210
|
add("soldAt", a.market, "market", "lastSoldAt", [i]);
|
|
209
|
-
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]); }
|
|
210
212
|
add("lease", a.lease, "lease", "leaseOf", [i]);
|
|
211
213
|
return out;
|
|
212
214
|
}
|
|
@@ -368,6 +370,17 @@ function builderIn(c, shares) {
|
|
|
368
370
|
if (big(b.bps) > 500n) return { error: "unread" };
|
|
369
371
|
return { builder: { to: lc(b.to), bps: big(b.bps) } };
|
|
370
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
|
+
|
|
371
384
|
/**
|
|
372
385
|
* The claims on the lease around a change of hands of the agent `c` read (the client rule, docs/AGENT-LEASE.md), where
|
|
373
386
|
* the package records AgentLease (addr.lease): while leaseOf names a renter (a lease that runs, or one that ended and
|
|
@@ -646,8 +659,9 @@ export function cancelBidPlan(c, { me, now, bidIds, myBids = [] }) {
|
|
|
646
659
|
* Accepting bid `bidId` for agent `id` held by `me` (web/board-wallet-bids-core.js walletAcceptPlan): the bid, its
|
|
647
660
|
* target or list (`proof`, checked with inRoot, never trusted), the maker as a buyer, the sale's rules with `me` as the
|
|
648
661
|
* seller, the maker's pins, the net. { error } ("unread", "gone", "notInBid", "taken", "selfAccept", "maker",
|
|
649
|
-
* "unfunded", "paused", saleChecks' kinds, "repaid" (`n`, `m`), "lineBelow" (`line`), "card", "
|
|
650
|
-
* the
|
|
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
|
|
651
665
|
* ("cancelOldPrev", "cancelOld", "bondApprove", "bond", "approve", "accept", in acceptCalls' order; "claimBefore" first
|
|
652
666
|
* and "claimAfter" last while a lease is stored, with `leased`, as buyPlan's), price, maker, proof, fee, share, net
|
|
653
667
|
* (minNet: exact at the read block; a fee changes only after the market's 48 h, and a share only lower), bond, pins }.
|
|
@@ -673,6 +687,11 @@ export function acceptPlan(c, { addr, me, now, bidId, id, proof = [], shares = f
|
|
|
673
687
|
if (BigInt(b.uriHash) !== 0n && lc(ethers.keccak256(ethers.toUtf8Bytes(c.uri))) !== lc(b.uriHash)) return { error: "card" };
|
|
674
688
|
const bi = builderIn(c, shares);
|
|
675
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" };
|
|
676
695
|
const { fee, share, net } = netOf(big(b.price), { ...feesOf(c), builder: bi.builder, seller: me });
|
|
677
696
|
if (net < 1n) return { error: "noNet", price: big(b.price), fee };
|
|
678
697
|
const approved = same(c.approved, addr.market), mine = ownListing(c.listing, me, now);
|
|
@@ -745,7 +764,7 @@ export const MARKET_ERRORS = Object.freeze({
|
|
|
745
764
|
// the builder share (the P5 spec, 2.8), once V2 has it: a seller or a buyer never sets one here (BuildersOff: setBuilder
|
|
746
765
|
// before the owner turned shares on)
|
|
747
766
|
"NotBuilder(uint256,address)": "failed", "BuilderTaken(uint256)": "failed", "AlreadySold(uint256)": "failed", "BadShare(uint256)": "failed", "BadBuilder(address)": "failed",
|
|
748
|
-
"PayOutOfGas()": "failed", "BuildersOff()": "failed",
|
|
767
|
+
"PayOutOfGas()": "failed", "BuildersOff()": "failed", "BuilderAfterBid(uint256,uint256)": "afterBid",
|
|
749
768
|
// the pause
|
|
750
769
|
"IsPaused(uint64)": "paused", "NotGuardian(address)": "failed", "NotTimelock(address)": "failed", "PauseRefused(uint64)": "failed", "BadPause(uint64)": "failed", "ZeroAddress()": "failed",
|
|
751
770
|
// BidSpender: its pull is the market's alone
|
|
@@ -801,6 +820,7 @@ export const PLAN_WORDS = Object.freeze({
|
|
|
801
820
|
record: "#{id} has {m} repaid loan{s}. This server buys and bids only on agents with {n} or more.",
|
|
802
821
|
// money
|
|
803
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.",
|
|
804
824
|
short: "This wallet holds {cash} USDG. Add {short} USDG, then try again.",
|
|
805
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.",
|
|
806
826
|
noEth: "This wallet holds no ETH on Robinhood Chain for gas. Add a little ETH, then try again.",
|
|
@@ -840,6 +860,7 @@ export const PLAN_WORDS = Object.freeze({
|
|
|
840
860
|
notMaker: "Bid #{bidId} isn't this wallet's. Only its maker can cancel it.",
|
|
841
861
|
bidGone: "Bid #{bidId} isn't open now. It was cancelled, taken or ran out, or there is no such bid.",
|
|
842
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,
|
|
843
864
|
tooMany: "market_cancel_bid cancels at most 10 bids a call. Cancel the rest in another call.",
|
|
844
865
|
count: "A bid on an origin takes 1 to {max} agents here. Pick a count in that range.",
|
|
845
866
|
noBids: "This wallet has no open bid to cancel.",
|
package/src/market-tools.mjs
CHANGED
|
@@ -162,6 +162,8 @@ export function marketInstructions(s, kind) {
|
|
|
162
162
|
export function registerMarketTools(ctx) {
|
|
163
163
|
const { tool, serial, needWallet, wallet, provider, fetchImpl, credit, locked, stateDir, withinTime, ToolError, callBudgetMs, settings: S, record: REC, addresses } = ctx;
|
|
164
164
|
const pollMs = ctx.pollMs ?? 1000;
|
|
165
|
+
// the USDG payments signed and not settled yet still need (pay_url's, as stock_buy and save keep it back)
|
|
166
|
+
const heldForPayments = typeof ctx.heldForPayments === "function" ? ctx.heldForPayments : () => 0n;
|
|
165
167
|
const fail = (t) => new ToolError(t);
|
|
166
168
|
/** A kind's words, with a value the refusal didn't carry: the sentence that names it dropped, or the step's own. */
|
|
167
169
|
const words = (kind, vars, role) => {
|
|
@@ -532,8 +534,11 @@ export function registerMarketTools(ctx) {
|
|
|
532
534
|
// the steps that take USDG from the wallet or raise what its bids may take: keep back is checked again before each
|
|
533
535
|
const TAKES = new Set(["buy", "bid", "bidAny", "approveReserve", "bond"]);
|
|
534
536
|
const ledger = wallet ? dailyLedger({ stateDir: join(stateDir, "market"), owners: ledgerOwners(String(S.agentId), wallet.address), caps: { signed: S.dayCap, borrowed: null } }) : null;
|
|
535
|
-
/** 6. What the agent's open loans owe stays in the wallet (its savings count): `out` is what this call takes.
|
|
536
|
-
|
|
537
|
+
/** 6. What the agent's open loans owe stays in the wallet (its savings count): `out` is what this call takes. USDG
|
|
538
|
+
* this wallet's open bids can still take (what it approved to the bids' spender, c.reserve) and USDG payments signed
|
|
539
|
+
* and not settled yet still need are not there to repay them (GHSA-m2h8-m55f-9j66): `bids` false for a bid, whose
|
|
540
|
+
* `out` already is the reserve of all its open bids. */
|
|
541
|
+
async function keepBack(c, out, T, bids = true) {
|
|
537
542
|
const a = c.selfAgent;
|
|
538
543
|
if (a == null) throw refuse("unread");
|
|
539
544
|
if (BigInt(a.activeLoans) === 0n) return;
|
|
@@ -544,8 +549,12 @@ export function registerMarketTools(ctx) {
|
|
|
544
549
|
} catch (_) { throw refuse("unread"); }
|
|
545
550
|
let saved = 0n;
|
|
546
551
|
try { if (typeof credit.savedOf === "function") saved = BigInt(await withinTime(credit.savedOf(wallet.address), Math.min(5000, T.left()))); } catch (_) { saved = 0n; }
|
|
547
|
-
|
|
548
|
-
|
|
552
|
+
let held = 0n;
|
|
553
|
+
try { held = BigInt(heldForPayments() || 0n); } catch (_) { held = 0n; }
|
|
554
|
+
if (bids && c.reserve != null) held += BigInt(c.reserve);
|
|
555
|
+
const left = BigInt(c.cash) + saved - out - held;
|
|
556
|
+
const vars = { self: S.agentId, owed, due: due ? M.dayText(due) : "soon", left: left > 0n ? left : 0n, held };
|
|
557
|
+
if (left < owed) throw refuse(held > 0n ? "keepBackHeld" : "keepBack", vars);
|
|
549
558
|
}
|
|
550
559
|
/** 7. The day's count, reserved before anything is sent (the market's own ledger). */
|
|
551
560
|
function reserveDay(want) {
|
|
@@ -586,7 +595,7 @@ export function registerMarketTools(ctx) {
|
|
|
586
595
|
if (plan.error) throw refuse(plan.error, varsOf(plan, o), o.role);
|
|
587
596
|
if (o.check) o.check(plan, s, rec);
|
|
588
597
|
const out = o.keep ? o.keep(plan) : null;
|
|
589
|
-
if (out != null) await keepBack(s.c, out, T);
|
|
598
|
+
if (out != null) await keepBack(s.c, out, T, o.role !== "bid");
|
|
590
599
|
const stepsAll = plan.steps;
|
|
591
600
|
const calls = stepsAll.map((st) => ({ step: st, ...M.stepCalls(st, { addr: k.addr, id: o.id, now: s.now, ...plan }), what: stageWords(st, o.id, plan) }));
|
|
592
601
|
if (o.dry) {
|
|
@@ -594,7 +603,11 @@ export function registerMarketTools(ctx) {
|
|
|
594
603
|
structured: { tool: o.name, dryRun: true, agentId: o.id == null ? null : String(o.id), calls: calls.map((c) => ({ step: c.step, to: lc(c.to), data: c.data })) } };
|
|
595
604
|
}
|
|
596
605
|
const day = reserveDay(o.day ? o.day(plan) : 0n);
|
|
597
|
-
|
|
606
|
+
// what the steps sent count (o.counted), and the step being sent with the plan it was sent on: a step whose answer
|
|
607
|
+
// is lost may still land, so it adds what it alone counts (an approval nothing, a buy its price); the steps mined
|
|
608
|
+
// before it stay counted (GHSA-m2h8-m55f-9j66, GHSA-pg36-8pmq-5p4v: a later plan of the same call, read once the bond
|
|
609
|
+
// was mined, carries no bond, so its day was no measure of what the call spent)
|
|
610
|
+
let counted = 0n, inFlight = null;
|
|
598
611
|
try {
|
|
599
612
|
await gasCheck(stepsAll, calls[0], T);
|
|
600
613
|
const opBase = { tool: o.name, key, at: nowS(), plan: stepsAll, id: o.id == null ? null : String(o.id), by: SESSION };
|
|
@@ -624,21 +637,24 @@ export function registerMarketTools(ctx) {
|
|
|
624
637
|
// that left the wallet since the first read (another session's pay_url, an autopay pull) counts
|
|
625
638
|
const out2 = sent.length && o.keep && TAKES.has(step) ? o.keep(plan) : null;
|
|
626
639
|
if (out2 != null) {
|
|
627
|
-
try { await keepBack(s.c, out2, T); } catch (e) {
|
|
640
|
+
try { await keepBack(s.c, out2, T, o.role !== "bid"); } catch (e) {
|
|
628
641
|
throw fail(`Sent ${sentWords(sent, o)}, then stopped. ${e instanceof ToolError ? e.message.replace(/ Nothing was signed or sent\.$/, "") : M.planWords("unread")} ${NOTHING_MORE}${standing(sent[sent.length - 1].step)}`);
|
|
629
642
|
}
|
|
630
643
|
}
|
|
631
644
|
const call = M.stepCalls(step, { addr: k.addr, id: o.id, now: s.now, ...plan });
|
|
632
645
|
let r;
|
|
646
|
+
inFlight = { step, plan };
|
|
633
647
|
try { r = await sendStep({ step, call, o: { id: o.id, vars: { ...o.vars, id: o.id }, ...plan }, rec, opBase, sent, T, role: o.role }); } catch (e) {
|
|
634
648
|
// a claim after that was sent and not seen yet stays in the record as any step does (TX_UNCONFIRMED)
|
|
635
649
|
if (!after || !(e instanceof ToolError) || /^TX_UNCONFIRMED/.test(e.message)) throw e;
|
|
650
|
+
inFlight = null;
|
|
636
651
|
missed = "failed";
|
|
637
652
|
// the record as the step left it (one mined and reverted is kept so), while its op is still this call's: the
|
|
638
653
|
// answer below is then kept for a retry; another session's op is never written over
|
|
639
654
|
try { const cur = readRec(); if (cur.op && cur.op.by === SESSION && cur.op.key === key && cur.op.at === opBase.at) rec = cur; } catch (_) { /* settled next time */ }
|
|
640
655
|
break;
|
|
641
656
|
}
|
|
657
|
+
inFlight = null;
|
|
642
658
|
counted += o.counted ? o.counted(step, plan) : 0n;
|
|
643
659
|
rec = r.rec;
|
|
644
660
|
sent.push({ step, hash: r.hash, rc: r.rc, o: plan });
|
|
@@ -657,7 +673,7 @@ export function registerMarketTools(ctx) {
|
|
|
657
673
|
} catch (e) {
|
|
658
674
|
// what a step that was broadcast counts stays counted, its answer lost or not (a sent step may still land)
|
|
659
675
|
const unconfirmed = e instanceof ToolError && /^TX_UNCONFIRMED/.test(e.message);
|
|
660
|
-
if (unconfirmed && o.counted) counted
|
|
676
|
+
if (unconfirmed && o.counted && inFlight) counted += o.counted(inFlight.step, inFlight.plan);
|
|
661
677
|
// a call that stopped with every step it sent settled leaves nothing in flight: the next call isn't held by it
|
|
662
678
|
if (!unconfirmed && rec && rec.op && rec.op.steps.every((x) => x.state !== "sent")) {
|
|
663
679
|
try { await writeRec({ op: null, done: rec.done, bids: rec.bids }, rec.rev); } catch (_) { /* settled next time */ }
|
|
@@ -777,6 +793,8 @@ export function registerMarketTools(ctx) {
|
|
|
777
793
|
for (const item of hubBids) {
|
|
778
794
|
const b = c.bids.get(String(item.bid));
|
|
779
795
|
if (!b || !isAddr(b.maker) || Number(b.expiry) <= s.now || (item.by && !same(item.by, b.maker))) continue;
|
|
796
|
+
// a bid made before the agent's builder share was set: no accept can take it (BuilderAfterBid)
|
|
797
|
+
if (M.takesBid(c, String(item.bid), k.shares) === false) continue;
|
|
780
798
|
const mk = c.makers.get(lc(b.maker)) || {};
|
|
781
799
|
if (mk.cash == null || mk.reserve == null || BigInt(mk.cash) < BigInt(b.price) || BigInt(mk.reserve) < BigInt(b.price)) continue;
|
|
782
800
|
let proof = [];
|
|
@@ -989,7 +1007,7 @@ export function registerMarketTools(ctx) {
|
|
|
989
1007
|
/* ---- market_cancel_bid ---- */
|
|
990
1008
|
tool("market_cancel_bid", {
|
|
991
1009
|
title: "Cancel a bid",
|
|
992
|
-
description: "Cancel this wallet's bid bid_id on Priors' agent market, or with all: true every open bid of this wallet (the ones this server made and the ones Priors' hub shows, at most 10 a call), then set the bids' approval down to what the bids left still take. Each cancel is its own transaction from this wallet; never paused. dry_run: true lists the transactions without sending. Needs ETH for gas.",
|
|
1010
|
+
description: "Cancel this wallet's bid bid_id on Priors' agent market, or with all: true every open bid of this wallet (the ones this server made and the ones Priors' hub shows, at most 10 a call), then set the bids' approval down to what the bids left still take (left as it is while Priors' hub doesn't answer, since bids made elsewhere can't be counted then; with all: true and no open bid, an approval left standing is set to 0). Each cancel is its own transaction from this wallet; never paused. dry_run: true lists the transactions without sending. Needs ETH for gas.",
|
|
993
1011
|
inputSchema: { bid_id: z.number().int().positive().optional().describe("The bid to cancel."), all: z.boolean().optional().describe("true: every open bid of this wallet, at most 10 a call."), dry_run: dryRun },
|
|
994
1012
|
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
995
1013
|
}, serial(async ({ bid_id, all = false, dry_run = false }, deadline) => {
|
|
@@ -997,28 +1015,41 @@ export function registerMarketTools(ctx) {
|
|
|
997
1015
|
if ((bid_id == null) === !all) throw fail(`Give bid_id, or all: true. ${NOTHING}`);
|
|
998
1016
|
const me = lc(wallet.address);
|
|
999
1017
|
let targets = bid_id != null ? [String(bid_id)] : null;
|
|
1018
|
+
// the hub's list of this wallet's bids not read (once in a call, for the whole call): bids made elsewhere (Go mode,
|
|
1019
|
+
// the board, another machine) are then unknown, so the bids' approval is never set down, which would leave them
|
|
1020
|
+
// unfunded (GHSA-m2h8-m55f-9j66)
|
|
1021
|
+
let hubDown = false;
|
|
1022
|
+
const keptWords = (x) => `Priors' hub didn't answer, so bids this wallet made elsewhere can't be counted: the bids' approval was left at ${amt(x)} USDG.`;
|
|
1000
1023
|
return execute({
|
|
1001
1024
|
name: "market_cancel_bid", role: "cancelBid", args: { bid_id, all }, id: null, me, dry: dry_run, vars: { bidId: bid_id == null ? null : String(bid_id) }, replay: false,
|
|
1002
|
-
read: async (rec, k, T) => { const b = await myBids(rec, T); return { me, bidIds: [...new Set([...b.ids, ...(targets || [])])] }; },
|
|
1025
|
+
read: async (rec, k, T) => { const b = await myBids(rec, T); hubDown = hubDown || b.hubDown; return { me, bidIds: [...new Set([...b.ids, ...(targets || [])])] }; },
|
|
1003
1026
|
plan: (s, k, first, T, sent = []) => {
|
|
1004
1027
|
const done = sent.filter((x) => x.step.startsWith("cancelBid:")).map((x) => x.step.slice(10));
|
|
1005
1028
|
const mine = [...s.c.bids.keys()];
|
|
1006
1029
|
if (!targets) {
|
|
1007
1030
|
targets = mine.filter((b) => { const x = s.c.bids.get(b); return x && same(x.maker, me) && Number(x.expiry) > s.now; }).sort((a, b) => Number(BigInt(a) - BigInt(b))).slice(0, 10);
|
|
1031
|
+
// no open bid, and an approval left standing (bids that ran out or were taken): set down to 0, the hub's list read
|
|
1032
|
+
if (!targets.length && !hubDown && s.c.reserve != null && BigInt(s.c.reserve) > 0n) return { steps: ["approveReserve"], reserve: 0n, reserveAfter: 0n, trimOnly: true, pins: { reserveAfter: "0" } };
|
|
1008
1033
|
if (!targets.length) return { error: "noBids" };
|
|
1009
1034
|
}
|
|
1010
1035
|
const left = targets.filter((b) => !done.includes(b));
|
|
1011
1036
|
if (!left.length) {
|
|
1012
1037
|
const reserveAfter = first ? first.reserveAfter : 0n;
|
|
1013
|
-
return { steps: s.c.reserve != null && BigInt(s.c.reserve) > reserveAfter ? ["approveReserve"] : [], reserve: reserveAfter, reserveAfter, pins: first.pins };
|
|
1038
|
+
return { steps: s.c.reserve != null && BigInt(s.c.reserve) > reserveAfter ? ["approveReserve"] : [], reserve: reserveAfter, reserveAfter, kept: first.kept, pins: first.pins };
|
|
1014
1039
|
}
|
|
1015
1040
|
const p = M.cancelBidPlan(s.c, { me, now: s.now, bidIds: left, myBids: mine });
|
|
1016
|
-
|
|
1041
|
+
if (p.error) return { ...p, bidId: p.bidId ? BigInt(p.bidId) : null };
|
|
1042
|
+
if (hubDown && s.c.reserve != null) {
|
|
1043
|
+
const r = BigInt(s.c.reserve);
|
|
1044
|
+
return { ...p, steps: p.steps.filter((x) => x !== "approveReserve"), reserveAfter: r, reserve: r, kept: true, pins: { reserveAfter: String(r) } };
|
|
1045
|
+
}
|
|
1046
|
+
return { ...p, pins: { reserveAfter: String(p.reserveAfter) } };
|
|
1017
1047
|
},
|
|
1018
|
-
facts: (p) => [`Cancels ${p.steps.filter((x) => x.startsWith("cancelBid:")).map((x) => `bid #${x.slice(10)}`).join(", ")}.${p.steps.includes("approveReserve") ? ` Then sets the bids' approval down to ${amt(p.reserveAfter)} USDG.` : ""}`],
|
|
1048
|
+
facts: (p) => [p.trimOnly ? `No open bid to cancel. Sets the bids' approval down to 0 USDG.` : `Cancels ${p.steps.filter((x) => x.startsWith("cancelBid:")).map((x) => `bid #${x.slice(10)}`).join(", ")}.${p.steps.includes("approveReserve") ? ` Then sets the bids' approval down to ${amt(p.reserveAfter)} USDG.` : ""}${p.kept ? ` ${keptWords(p.reserveAfter)}` : ""}`],
|
|
1019
1049
|
done: async ({ sent, plan, events, k, T }) => {
|
|
1020
1050
|
const txs = sent.map((x) => x.hash), cancelled = sent.filter((x) => x.step.startsWith("cancelBid:")).map((x) => x.step.slice(10));
|
|
1021
|
-
return { text: `
|
|
1051
|
+
if (plan.trimOnly) return { text: `No open bid to cancel; set the bids' approval down to 0 USDG. Tx ${txs.join(", ")}.`, structured: { tool: "market_cancel_bid", txs, cancelled, reserve: amt(0n) } };
|
|
1052
|
+
return { text: `Cancelled bid${cancelled.length > 1 ? "s" : ""} #${cancelled.join(", #")}. Tx ${txs.join(", ")}. ${plan.kept ? keptWords(plan.reserveAfter) : reserveLine(plan.reserveAfter).replace(/\.$/, " now.")}`, structured: { tool: "market_cancel_bid", txs, cancelled, reserve: amt(plan.reserveAfter), ...(plan.kept ? { hubDown: true } : {}) } };
|
|
1022
1053
|
},
|
|
1023
1054
|
}, deadline);
|
|
1024
1055
|
}));
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/* PT one step (SITE_PT_ONESTEP=on; docs/PT-USDG.md, "One step: buy and back a line"): USDG to PT-USDG to an open line
|
|
2
|
+
on the stock vault, as one batch. The plan of it (the least PT the buy takes, from a fresh quote less the slippage, and
|
|
3
|
+
what goes behind the line) and its four calls, built the same way for Go mode (web/account-pt-onestep.js: one
|
|
4
|
+
sponsored operation) and for agents (@priors/mcp's pt_buy_and_deposit: packages/mcp/src/pt-onestep-core.cjs is this
|
|
5
|
+
file, byte for byte, its four calls sent from the agent's own wallet):
|
|
6
|
+
1. USDG.approve(router, usdgIn) exactly what the buy takes
|
|
7
|
+
2. router.swapExactTokenForPt(account, market, minPtOut, ...) USDG in, the PT paid to the account itself
|
|
8
|
+
3. PT.approve(stockVault, deposit) exactly what the open takes
|
|
9
|
+
4. stockVault.open(agentId, PT, deposit, consent, sig) the account's own consent, for that agent, naming
|
|
10
|
+
the vault's root
|
|
11
|
+
deposit is the buy's minPtOut, plus the PT the account already holds when the caller includes it: the router pays at
|
|
12
|
+
least minPtOut or the whole batch reverts, so the open never asks for more PT than the account has. The buy is the one
|
|
13
|
+
shape the gas gate sponsors (sdk/pendle-pt.mjs buildBuy and checkRouterCall), and the approval and the open are the
|
|
14
|
+
account bundle's own deposit (web-src/priors-app.mjs openStockLine), byte for byte (scripts/test-pt-onestep.mjs).
|
|
15
|
+
|
|
16
|
+
Pure: no DOM, no chain, no library; no address of its own (the caller's `conf` names the router, USDG, the market, the
|
|
17
|
+
PT and the vault). The caller brings `encode(to, sig, args) -> { to, data }` (Go mode: the bundle's
|
|
18
|
+
PriorsApp.encodeCall; the MCP: viem's encodeFunctionData) and the reads. Amounts are 6-decimal bigints; times seconds.
|
|
19
|
+
|
|
20
|
+
window.PriorsPtOnestepCore (a page) / module.exports (node):
|
|
21
|
+
LIMITS { minUsdg (1 USDG), maxQuoteAgeS (60), slippageBps (100, the default), maxSlippageBps (300) }
|
|
22
|
+
SIG the four functions' signatures, structs spelled out
|
|
23
|
+
plan(o) o { conf, usdgIn, rate (USDG per PT, 1e18 = par), rateAt (when it was read), now, slippageBps?,
|
|
24
|
+
held? (the account's PT), includeHeld? (default true) } -> { usdgIn, rate, expectedPt, minPtOut,
|
|
25
|
+
held, deposit, slippageBps, quotedAt }, frozen; or throws an Error whose .code is "amount" | "min"
|
|
26
|
+
| "cap" | "slippage" | "redeem-only" | "matured" | "rate" | "stale" | "held"
|
|
27
|
+
confirm(shown, fresh) `fresh` (a plan made at the tap) when it gives at least what `shown` said: the same USDG, a
|
|
28
|
+
least PT and a deposit no smaller; else throws .code "moved"
|
|
29
|
+
calls(encode, p, o) plan `p`'s four calls, each { to, data, what }, for o { conf, account, agentId, root (the
|
|
30
|
+
vault's agentId), consent, sig }; throws .code "consent" (not the account's own, for that agent,
|
|
31
|
+
naming that root) or "amount" (nothing to deposit)
|
|
32
|
+
lineOf(o) o { value, ltvBps, maxLine? }: the line the vault opens on a deposit worth `value`
|
|
33
|
+
usdgForLine(o) o { line, value1 (the vault's value of one whole PT), ltvBps, held, rate, slippageBps? }: the
|
|
34
|
+
least USDG whose buy, with `held`, reaches a `line` (0n when `held` already does) */
|
|
35
|
+
(function () {
|
|
36
|
+
"use strict";
|
|
37
|
+
const E18 = 10n ** 18n, BPS = 10_000n, UNIT = 1_000_000n;
|
|
38
|
+
const ZERO = "0x0000000000000000000000000000000000000000";
|
|
39
|
+
const LIMITS = Object.freeze({ minUsdg: UNIT, maxQuoteAgeS: 60, slippageBps: 100, maxSlippageBps: 300 });
|
|
40
|
+
// the router's buy (sdk/pendle-pt.mjs ROUTER_ABI, Pendle's IPAllActionTypeV3 structs spelled out), the ERC-20 approval
|
|
41
|
+
// and the vault's open (web-src/priors-app.mjs ABI.vault, CreditPoolV2.Consent spelled out)
|
|
42
|
+
const SWAP_DATA = "(uint8 swapType, address extRouter, bytes extCalldata, bool needScale)";
|
|
43
|
+
const ORDER = "(uint256 salt, uint256 expiry, uint256 nonce, uint8 orderType, address token, address YT, address maker, address receiver, uint256 makingAmount, uint256 lnImpliedRate, uint256 failSafeRate, bytes permit)";
|
|
44
|
+
const FILL = "(" + ORDER + " order, bytes signature, uint256 makingAmount)";
|
|
45
|
+
const LIMIT = "(address limitRouter, uint256 epsSkipMarket, " + FILL + "[] normalFills, " + FILL + "[] flashFills, bytes optData)";
|
|
46
|
+
const TOKEN_IN = "(address tokenIn, uint256 netTokenIn, address tokenMintSy, address pendleSwap, " + SWAP_DATA + " swapData)";
|
|
47
|
+
const APPROX = "(uint256 guessMin, uint256 guessMax, uint256 guessOffchain, uint256 maxIteration, uint256 eps)";
|
|
48
|
+
const CONSENT = "(uint256 agentId, uint256 sponsorId, address owner, uint256 maxPremiumBps, uint256 nonce, uint256 deadline)";
|
|
49
|
+
const SIG = Object.freeze({
|
|
50
|
+
approve: "function approve(address spender, uint256 amount) returns (bool)",
|
|
51
|
+
buy: "function swapExactTokenForPt(address receiver, address market, uint256 minPtOut, " + APPROX + " guessPtOut, " + TOKEN_IN + " input, " + LIMIT + " limit) payable returns (uint256 netPtOut, uint256 netSyFee, uint256 netSyInterm)",
|
|
52
|
+
open: "function open(uint256 id, address token, uint256 amount, " + CONSENT + " c, bytes sig) returns (uint256)",
|
|
53
|
+
});
|
|
54
|
+
const NONE_SWAP = () => ({ swapType: 0, extRouter: ZERO, extCalldata: "0x", needScale: false });
|
|
55
|
+
const NO_LIMIT = () => ({ limitRouter: ZERO, epsSkipMarket: 0n, normalFills: [], flashFills: [], optData: "0x" });
|
|
56
|
+
// Pendle's on-chain search of the PT amount, no off-chain guess (sdk/pendle-pt.mjs DEFAULT_APPROX)
|
|
57
|
+
const APPROX_ALL = () => ({ guessMin: 0n, guessMax: (1n << 256n) - 1n, guessOffchain: 0n, maxIteration: 256n, eps: 10n ** 14n });
|
|
58
|
+
|
|
59
|
+
const no = (code, message) => Object.assign(new Error(message || code), { code });
|
|
60
|
+
const isBig = (v) => typeof v === "bigint";
|
|
61
|
+
const same = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
|
|
62
|
+
// 6-decimal units in plain digits, trailing zeros dropped (12_500_000n -> "12.5"), for the calls' own words
|
|
63
|
+
const fmt6 = (u) => { const s = String(u), neg = s.startsWith("-"), d = (neg ? s.slice(1) : s).padStart(7, "0"); const f = d.slice(-6).replace(/0+$/, ""); return (neg ? "-" : "") + d.slice(0, -6) + (f ? "." + f : ""); };
|
|
64
|
+
|
|
65
|
+
/** The buy and the deposit, from a quote read at `rateAt`; throws why it can't be done now (see the header). */
|
|
66
|
+
function plan({ conf, usdgIn, rate, rateAt, now, slippageBps, held = 0n, includeHeld = true }) {
|
|
67
|
+
if (!isBig(usdgIn) || usdgIn <= 0n) throw no("amount", "a buy needs an amount of USDG");
|
|
68
|
+
if (usdgIn < LIMITS.minUsdg) throw no("min", "the smallest buy is 1 USDG");
|
|
69
|
+
if (usdgIn > BigInt(conf.maxUsdgPerOp)) throw no("cap", "above the most one sponsored trade takes");
|
|
70
|
+
const slip = slippageBps == null ? LIMITS.slippageBps : slippageBps;
|
|
71
|
+
if (!Number.isInteger(slip) || slip < 0 || slip > LIMITS.maxSlippageBps) throw no("slippage", "a slippage of 0 to 300 bps");
|
|
72
|
+
if (conf.active === false) throw no("redeem-only", "the market is redeem-only");
|
|
73
|
+
if (!(now < Number(conf.expiry))) throw no("matured", "the market has matured");
|
|
74
|
+
// a rate above par is no PT's before maturity: a misread one would name a minimum below the market
|
|
75
|
+
if (!isBig(rate) || rate <= 0n || rate > E18) throw no("rate", "no usable quote");
|
|
76
|
+
if (!Number.isFinite(rateAt) || now - rateAt > LIMITS.maxQuoteAgeS || rateAt - now > 30) throw no("stale", "the quote is not fresh");
|
|
77
|
+
if (!isBig(held) || held < 0n) throw no("held", "the balance is not one");
|
|
78
|
+
const expectedPt = (usdgIn * E18) / rate;
|
|
79
|
+
const minPtOut = (expectedPt * (BPS - BigInt(slip))) / BPS;
|
|
80
|
+
if (minPtOut <= 0n) throw no("amount", "too small to name a least PT out");
|
|
81
|
+
const used = includeHeld ? held : 0n;
|
|
82
|
+
return Object.freeze({ usdgIn, rate, expectedPt, minPtOut, held: used, deposit: minPtOut + used, slippageBps: slip, quotedAt: rateAt });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The plan made at the tap, when it gives at least what the screen said; else "moved". */
|
|
86
|
+
function confirm(shown, fresh) {
|
|
87
|
+
if (!shown || !fresh || fresh.usdgIn !== shown.usdgIn || fresh.minPtOut < shown.minPtOut || fresh.deposit < shown.deposit) throw no("moved", "the price or the balance moved");
|
|
88
|
+
return fresh;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Plan `p`'s four calls, in order, for the account's own consent. */
|
|
92
|
+
function calls(encode, p, { conf, account, agentId, root, consent, sig }) {
|
|
93
|
+
const id = BigInt(agentId);
|
|
94
|
+
if (!consent || !same(consent.owner, account) || BigInt(consent.agentId) !== id || root == null || BigInt(consent.sponsorId) !== BigInt(root)) throw no("consent", "the consent must be the account's own, for this agent, naming the vault's root");
|
|
95
|
+
if (!isBig(p.deposit) || p.deposit <= 0n || !isBig(p.minPtOut) || p.minPtOut <= 0n) throw no("amount", "nothing to deposit");
|
|
96
|
+
const c = { agentId: id, sponsorId: BigInt(consent.sponsorId), owner: consent.owner, maxPremiumBps: BigInt(consent.maxPremiumBps), nonce: BigInt(consent.nonce), deadline: BigInt(consent.deadline) };
|
|
97
|
+
const what = (x, w) => Object.assign({}, x, { what: w });
|
|
98
|
+
return [
|
|
99
|
+
what(encode(conf.usdg, SIG.approve, [conf.router, p.usdgIn]), `approve ${fmt6(p.usdgIn)} USDG to Pendle's router`),
|
|
100
|
+
what(encode(conf.router, SIG.buy, [account, conf.market, p.minPtOut, APPROX_ALL(), { tokenIn: conf.usdg, netTokenIn: p.usdgIn, tokenMintSy: conf.usdg, pendleSwap: ZERO, swapData: NONE_SWAP() }, NO_LIMIT()]), `buy at least ${fmt6(p.minPtOut)} PT-USDG with ${fmt6(p.usdgIn)} USDG`),
|
|
101
|
+
what(encode(conf.pt, SIG.approve, [conf.stockVault, p.deposit]), `approve ${fmt6(p.deposit)} PT-USDG to the stock vault`),
|
|
102
|
+
what(encode(conf.stockVault, SIG.open, [id, conf.pt, p.deposit, c, sig]), `deposit ${fmt6(p.deposit)} PT-USDG and open agent #${id}'s line`),
|
|
103
|
+
];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The line on a deposit worth `value` (StockVault.open: value × ltvOf / 10,000, at most maxLine). */
|
|
107
|
+
function lineOf({ value, ltvBps, maxLine }) {
|
|
108
|
+
const line = (BigInt(value) * BigInt(ltvBps)) / BPS;
|
|
109
|
+
return maxLine != null && line > BigInt(maxLine) ? BigInt(maxLine) : line;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The least USDG whose buy (its least PT out, at `rate` less the slippage), with `held`, reaches `line`. */
|
|
113
|
+
function usdgForLine({ line, value1, ltvBps, held = 0n, rate, slippageBps }) {
|
|
114
|
+
const slip = BigInt(slippageBps == null ? LIMITS.slippageBps : slippageBps);
|
|
115
|
+
// the PT whose value reaches the line: value(d) = d × value1 / 1e6, line = value × ltv / 1e4 (each rounded down)
|
|
116
|
+
const need = (BigInt(line) * BPS * UNIT + BigInt(ltvBps) * BigInt(value1) - 1n) / (BigInt(ltvBps) * BigInt(value1)) + 1n;
|
|
117
|
+
const buy = need > held ? need - held : 0n;
|
|
118
|
+
if (buy === 0n) return 0n;
|
|
119
|
+
// the USDG whose least PT out is at least `buy`: min = (usdg × 1e18 / rate) × (1e4 - slip) / 1e4
|
|
120
|
+
let usdg = (buy * BPS * BigInt(rate) + (BPS - slip) * E18 - 1n) / ((BPS - slip) * E18);
|
|
121
|
+
while ((((usdg * E18) / BigInt(rate)) * (BPS - slip)) / BPS < buy) usdg += 1n;
|
|
122
|
+
return usdg;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const api = { LIMITS, SIG, plan, confirm, calls, lineOf, usdgForLine };
|
|
126
|
+
if (typeof window !== "undefined") window.PriorsPtOnestepCore = api;
|
|
127
|
+
if (typeof module === "object" && module && module.exports) module.exports = api;
|
|
128
|
+
})();
|
package/src/rialto.mjs
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// Rialto's Quote API for the stock tokens (docs.rialto.xyz, "Quote API Overview"; the guide
|
|
2
|
+
// github.com/rialto-plds/rialto-api-docs RIALTO_SWAP_API.md, read 2026-11-02): a quote checked before anything of it is
|
|
3
|
+
// used, the choice between it and the pinned pool's quote (sdk/stock-zap.mjs), and the two calls it then takes. Pure:
|
|
4
|
+
// no network, no key. The key lives only in the gas gate (gas-worker/rialto.mjs): Rialto's own rule is that a partner
|
|
5
|
+
// key never reaches a page, an app, a repository or a log.
|
|
6
|
+
//
|
|
7
|
+
// GET /quote?sell_token&buy_token&sell_amount&taker&slippage_bps (API key, Bearer) answers the best route Rialto finds
|
|
8
|
+
// (its propAMMs, internal liquidity and AMMs) and a ready transaction for its RialtoRouter. Priors asks it only in
|
|
9
|
+
// `allowance` settlement: the taker approves the router for exactly the amount sold, then sends the router transaction
|
|
10
|
+
// unchanged. That is the mode Rialto gives a smart account (Go mode's Alchemy Modular Account v2) anyway, and it keeps
|
|
11
|
+
// both of Priors' paths at "an exact approval, then the one swap" (docs/STOCK-ZAP-SPEC.md 6). Priors charges no fee on
|
|
12
|
+
// a Rialto trade (the owner, 2026-11-02): the request never carries swap_fee_bps, and a quote naming an integrator fee
|
|
13
|
+
// is refused.
|
|
14
|
+
//
|
|
15
|
+
// The router is never taken from the quote alone: Rialto's Router Registry names the active one (feature 2, the
|
|
16
|
+
// taker-submitted swap; `ownerOf(2)` reverts while the feature is paused), and checkQuote takes only a quote whose
|
|
17
|
+
// transaction goes to it. Nor is the transaction's data: the router's swap carries its own tokens, amount, minimum,
|
|
18
|
+
// recipient and deadline, so checkQuote decodes it (checkSwap) and takes it only when it is the trade it checked, paid
|
|
19
|
+
// to the taker, with at least the quote's minimum (GHSA-cqcw-9qjc-5qc7, reported by @hey-research-lab: @priors/mcp
|
|
20
|
+
// 0.16.0 checked the JSON alone and sent the data as it came, so an answer could pay another address or drop the
|
|
21
|
+
// minimum).
|
|
22
|
+
//
|
|
23
|
+
// RIALTO_REGISTRY, RIALTO_FEATURE, REGISTRY_ABI the registry that names Rialto's router (Rialto's API address is the
|
|
24
|
+
// gate's alone, gas-worker/rialto.mjs: this file ships in @priors/mcp, which never calls Rialto)
|
|
25
|
+
// quoteQuery(o) the /quote query for a trade (URLSearchParams string), in allowance settlement, with no fee
|
|
26
|
+
// checkQuote(body, o) a quote checked against the trade asked for -> frozen terms, or throws RialtoError with the reason
|
|
27
|
+
// decodeSwap(data) the router's swap call read: { sellToken, buyToken, sellAmount, minBuyAmount, recipient, deadline,
|
|
28
|
+
// feeRecipient, srcBps, dstBps }, or throws RialtoError
|
|
29
|
+
// checkSwap(data, o) that call taken only as the trade checked (checkQuote's last check), or throws RialtoError
|
|
30
|
+
// chooseRoute(o) "rialto" when its quote gives more of the bought token than the pinned pool's, else "pinned"
|
|
31
|
+
// rialtoCalls(terms) the two calls: the exact approval of the sold token to the router, then Rialto's transaction
|
|
32
|
+
// wireTerms / readWire terms to JSON (amounts as digits) and back, checked again
|
|
33
|
+
import { encodeFunctionData, formatUnits, getAddress, isAddress, keccak256, parseAbi } from "viem";
|
|
34
|
+
|
|
35
|
+
export const RIALTO_CHAIN_ID = 4663;
|
|
36
|
+
/** Rialto's Router Registry on Robinhood Chain (the guide's "Registry deployments"), and the feature id of the
|
|
37
|
+
* taker-submitted swap: `ownerOf(2)` is the router a quote's transaction must go to. */
|
|
38
|
+
export const RIALTO_REGISTRY = "0x71a120CbBf3Ce7cD910a3c50fF77aFc62735687E";
|
|
39
|
+
export const RIALTO_FEATURE = 2;
|
|
40
|
+
export const REGISTRY_ABI = parseAbi(["function ownerOf(uint256 featureId) view returns (address)"]);
|
|
41
|
+
const APPROVE_ABI = parseAbi(["function approve(address spender, uint256 amount) returns (bool)"]);
|
|
42
|
+
/** The most slippage Priors lets a trade take (docs/STOCK-ZAP-SPEC.md 6: 2%), and how long the gate keeps a quote's
|
|
43
|
+
* transaction for the account it quoted (Rialto: quotes "can go stale quickly"). */
|
|
44
|
+
export const MAX_SLIPPAGE_BPS = 200;
|
|
45
|
+
export const QUOTE_TTL_S = 90;
|
|
46
|
+
/**
|
|
47
|
+
* The router's swap in allowance settlement, as its calldata carries it. Rialto publishes no ABI for it; the layout is
|
|
48
|
+
* read from live transactions to the registry's router 0xb63cEcf4...b8b3 (whose code dispatches on the selector):
|
|
49
|
+
* Priors' own of 2026-11-02, an agent's buy and sale (0x595201f3...c7f9, 0xf0f99abb...8dda, scripts/fixtures/
|
|
50
|
+
* rialto-swaps-4663.json) and a Go mode buy (0xca316226...a6d5), each word read against its quote. The selector, then
|
|
51
|
+
* eleven static words and the offset of the route's actions, 0x180 (twelve words):
|
|
52
|
+
* 0 sellToken, 1 buyToken, 2 sellAmount, 3 minBuyAmount, 4 recipient, 5 deadline (unix s, about 5 minutes on),
|
|
53
|
+
* 6 feeRecipient, 7 srcBps, 8 dstBps, 9 referralCode, 10 quoteId, 11 0x180
|
|
54
|
+
* (words 4 to 10 in the order of the guide's RialtoSwap witness, which binds a Permit2 quote to the same fields). The
|
|
55
|
+
* minimum is the router's own check on what the recipient receives, after Rialto's fee: the guide's min_buy_amount is
|
|
56
|
+
* "encoded into tx.data". Any other selector or shape is refused, so a router upgrade that changes it falls back to the
|
|
57
|
+
* pinned pool until this is read again.
|
|
58
|
+
*/
|
|
59
|
+
export const SWAP_SELECTOR = "0x77963966";
|
|
60
|
+
const SWAP_WORDS = 12, ACTIONS_AT = 0x180n;
|
|
61
|
+
/** The latest deadline a quote's transaction may carry, from now (Rialto's is about 5 minutes on). */
|
|
62
|
+
export const MAX_DEADLINE_S = 1800;
|
|
63
|
+
|
|
64
|
+
export class RialtoError extends Error {
|
|
65
|
+
constructor(message, o = {}) { super(message); this.name = "RialtoError"; Object.assign(this, o); }
|
|
66
|
+
}
|
|
67
|
+
const fail = (m, o) => { throw new RialtoError(m, o); };
|
|
68
|
+
const HEX = /^0x(?:[0-9a-fA-F]{2})+$/;
|
|
69
|
+
const DIGITS = /^(0|[1-9]\d*)$/;
|
|
70
|
+
const same = (a, b) => { try { return getAddress(a) === getAddress(b); } catch (_) { return false; } };
|
|
71
|
+
const addr = (v, what) => (typeof v === "string" && isAddress(v, { strict: false }) && !/^0x0{40}$/i.test(v) ? getAddress(v) : fail(`${what}: not an address`));
|
|
72
|
+
const big = (v, what) => {
|
|
73
|
+
if (typeof v === "bigint" && v >= 0n) return v;
|
|
74
|
+
if (typeof v === "number" && Number.isSafeInteger(v) && v >= 0) return BigInt(v);
|
|
75
|
+
if (typeof v === "string" && DIGITS.test(v)) return BigInt(v);
|
|
76
|
+
return fail(`${what}: not an amount`);
|
|
77
|
+
};
|
|
78
|
+
const bps = (v) => (Number.isInteger(v) && v >= 1 && v <= MAX_SLIPPAGE_BPS ? v : fail(`slippage: from 1 to ${MAX_SLIPPAGE_BPS} basis points`));
|
|
79
|
+
|
|
80
|
+
/** The /quote query for selling `sellAmount` (base units, `sellDecimals`) of `sellToken` for `buyToken`, paid to
|
|
81
|
+
* `taker`, at most `slippageBps` off: Rialto takes the amount as a decimal and addresses only (no symbols), and is
|
|
82
|
+
* asked for allowance settlement on Robinhood Chain. No swap_fee_bps, ever: Priors takes no fee. */
|
|
83
|
+
export function quoteQuery({ sellToken, buyToken, sellAmount, sellDecimals, taker, slippageBps }) {
|
|
84
|
+
const s = addr(sellToken, "sell token"), b = addr(buyToken, "buy token"), t = addr(taker, "taker");
|
|
85
|
+
if (same(s, b)) fail("the same token on both sides");
|
|
86
|
+
const amount = big(sellAmount, "sell amount");
|
|
87
|
+
if (amount === 0n) fail("sell amount: not an amount");
|
|
88
|
+
if (!Number.isInteger(sellDecimals) || sellDecimals < 0 || sellDecimals > 36) fail("sell token: no decimals");
|
|
89
|
+
return new URLSearchParams({
|
|
90
|
+
sell_token: s, buy_token: b, sell_amount: formatUnits(amount, sellDecimals), taker: t,
|
|
91
|
+
slippage_bps: String(bps(slippageBps)), settlement: "allowance", chain_id: String(RIALTO_CHAIN_ID),
|
|
92
|
+
}).toString();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A /quote answer `body` taken only when it is the trade asked for: on Robinhood Chain, allowance settlement (no
|
|
97
|
+
* Permit2 payload, no signature offset), the transaction to `router` (the registry's ownerOf(2)) with no value, the
|
|
98
|
+
* tokens and the raw sell amount asked, paid to `taker`, an output above 0 with a minimum within `slippageBps` of it,
|
|
99
|
+
* no integrator fee, and the taker holding enough (issues.balance). An approval Rialto asks for (issues.allowance) must
|
|
100
|
+
* be to the router itself. Last, the transaction's data itself (checkSwap): the router's swap of those tokens and that
|
|
101
|
+
* amount, paid to `taker`, its minimum at least the quote's and not above its output, its deadline after `now` (unix s,
|
|
102
|
+
* the clock's by default) and at most MAX_DEADLINE_S on. -> frozen terms: { quoteId, router, spender, data, sellToken,
|
|
103
|
+
* buyToken, sellAmount, buyAmount, minBuyAmount (the transaction's own minimum, what the router enforces), gas, feeBps,
|
|
104
|
+
* legs }. Throws RialtoError (balance: true when the taker holds too little).
|
|
105
|
+
*/
|
|
106
|
+
export function checkQuote(body, { sellToken, buyToken, sellAmount, taker, router, slippageBps, now = Math.floor(Date.now() / 1000) }) {
|
|
107
|
+
if (!body || typeof body !== "object") fail("Rialto's quote: not a quote");
|
|
108
|
+
const want = { sell: addr(sellToken, "sell token"), buy: addr(buyToken, "buy token"), taker: addr(taker, "taker"), router: addr(router, "router") };
|
|
109
|
+
const amount = big(sellAmount, "sell amount"), slip = bps(slippageBps);
|
|
110
|
+
if (Number(body.chain_id) !== RIALTO_CHAIN_ID) fail("Rialto's quote: another chain");
|
|
111
|
+
if (body.settlement !== "allowance") fail("Rialto's quote: not allowance settlement");
|
|
112
|
+
const tx = body.tx;
|
|
113
|
+
if (!tx || typeof tx !== "object") fail("Rialto's quote: no transaction");
|
|
114
|
+
if (body.permit2 != null || tx.signature_offset != null) fail("Rialto's quote: a Permit2 payload in allowance settlement");
|
|
115
|
+
if (!same(tx.to, want.router)) fail("Rialto's quote: its transaction is not to Rialto's registered router");
|
|
116
|
+
if (big(tx.value ?? "0", "value") !== 0n) fail("Rialto's quote: its transaction sends ETH");
|
|
117
|
+
if (typeof tx.data !== "string" || !HEX.test(tx.data) || tx.data.length < 10) fail("Rialto's quote: no transaction data");
|
|
118
|
+
if (!same(body.sell_token, want.sell) || !same(body.buy_token, want.buy)) fail("Rialto's quote: other tokens");
|
|
119
|
+
if (big(body.sell_amount, "sell amount") !== amount) fail("Rialto's quote: another amount");
|
|
120
|
+
if (!same(body.taker, want.taker)) fail("Rialto's quote: another taker");
|
|
121
|
+
if (body.integrator_fee != null) fail("Rialto's quote: an integrator fee");
|
|
122
|
+
const buyAmount = big(body.buy_amount, "buy amount"), minBuyAmount = big(body.min_buy_amount, "minimum");
|
|
123
|
+
if (buyAmount === 0n || minBuyAmount === 0n) fail("Rialto's quote: nothing out");
|
|
124
|
+
if (minBuyAmount > buyAmount) fail("Rialto's quote: a minimum above its output");
|
|
125
|
+
// Rialto rounds the minimum down (min = floor(buy * (10000 - slippage) / 10000), read 2026-11-02 on a live quote)
|
|
126
|
+
if (minBuyAmount < (buyAmount * BigInt(10000 - slip)) / 10000n) fail("Rialto's quote: a minimum below the slippage asked");
|
|
127
|
+
const issues = body.issues && typeof body.issues === "object" ? body.issues : {};
|
|
128
|
+
if (issues.balance != null) fail("not enough of the sold token for that amount", { balance: true });
|
|
129
|
+
if (issues.allowance != null && !same(issues.allowance.spender, want.router)) fail("Rialto's quote: an approval to another spender");
|
|
130
|
+
if (typeof body.quote_id !== "string" || !/^[0-9a-fA-F-]{8,64}$/.test(body.quote_id)) fail("Rialto's quote: no quote id");
|
|
131
|
+
const feeBps = Number(body.platform_fee && body.platform_fee.total_bps);
|
|
132
|
+
const swap = checkSwap(tx.data, { sellToken: want.sell, buyToken: want.buy, sellAmount: amount, taker: want.taker, minBuyAmount, buyAmount, now });
|
|
133
|
+
return Object.freeze({
|
|
134
|
+
quoteId: body.quote_id, router: want.router, spender: want.router, data: tx.data.toLowerCase(),
|
|
135
|
+
sellToken: want.sell, buyToken: want.buy, taker: want.taker, sellAmount: amount, buyAmount, minBuyAmount: swap.minBuyAmount,
|
|
136
|
+
gas: Number.isSafeInteger(tx.estimated_gas) ? tx.estimated_gas : null,
|
|
137
|
+
feeBps: Number.isFinite(feeBps) ? feeBps : null,
|
|
138
|
+
legs: Array.isArray(body.route && body.route.legs) ? body.route.legs.length : null,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The router's swap call `data` read (SWAP_SELECTOR's layout, above): { sellToken, buyToken, sellAmount, minBuyAmount,
|
|
143
|
+
* recipient, deadline (bigints for the amounts and the deadline), feeRecipient, srcBps, dstBps }. Throws RialtoError
|
|
144
|
+
* for any other call: another selector, a head that is not twelve whole words with the actions at 0x180, an address
|
|
145
|
+
* word with its upper bytes set, a fee word over uint16. */
|
|
146
|
+
export function decodeSwap(data) {
|
|
147
|
+
if (typeof data !== "string" || !HEX.test(data)) fail("Rialto's quote: no transaction data");
|
|
148
|
+
const d = data.toLowerCase(), words = (d.length - 10) / 64;
|
|
149
|
+
if (d.slice(0, 10) !== SWAP_SELECTOR || !Number.isInteger(words) || words <= SWAP_WORDS) fail("Rialto's quote: its transaction is not Rialto's swap");
|
|
150
|
+
const word = (i) => d.slice(10 + 64 * i, 74 + 64 * i), uint = (i) => BigInt("0x" + word(i));
|
|
151
|
+
const address = (i, what) => (/^0{24}/.test(word(i)) ? getAddress("0x" + word(i).slice(24)) : fail(`Rialto's quote: its transaction's ${what} is not an address`));
|
|
152
|
+
if (uint(11) !== ACTIONS_AT) fail("Rialto's quote: its transaction is not Rialto's swap");
|
|
153
|
+
const bpsOf = (i) => (uint(i) <= 0xffffn ? Number(uint(i)) : fail("Rialto's quote: its transaction is not Rialto's swap"));
|
|
154
|
+
return Object.freeze({
|
|
155
|
+
sellToken: address(0, "sell token"), buyToken: address(1, "buy token"), sellAmount: uint(2), minBuyAmount: uint(3),
|
|
156
|
+
recipient: address(4, "recipient"), deadline: uint(5), feeRecipient: address(6, "fee recipient"), srcBps: bpsOf(7), dstBps: bpsOf(8),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The router's swap call `data` taken only as the trade checked: `sellAmount` of `sellToken` for `buyToken`, paid to
|
|
161
|
+
* `taker`, a minimum at least `minBuyAmount` (and not above `buyAmount` when given), a deadline after `now` (unix s)
|
|
162
|
+
* and at most MAX_DEADLINE_S after it. -> decodeSwap's fields, or throws RialtoError with the reason. */
|
|
163
|
+
export function checkSwap(data, { sellToken, buyToken, sellAmount, taker, minBuyAmount, buyAmount = null, now }) {
|
|
164
|
+
const s = decodeSwap(data);
|
|
165
|
+
if (!same(s.sellToken, sellToken) || !same(s.buyToken, buyToken)) fail("Rialto's quote: its transaction swaps other tokens");
|
|
166
|
+
if (s.sellAmount !== big(sellAmount, "sell amount")) fail("Rialto's quote: its transaction sells another amount");
|
|
167
|
+
if (!same(s.recipient, taker)) fail("Rialto's quote: its transaction pays another address");
|
|
168
|
+
if (s.minBuyAmount < big(minBuyAmount, "minimum")) fail("Rialto's quote: its transaction's minimum is below the quote's");
|
|
169
|
+
if (buyAmount != null && s.minBuyAmount > big(buyAmount, "buy amount")) fail("Rialto's quote: its transaction's minimum is above its output");
|
|
170
|
+
const t = big(now, "now");
|
|
171
|
+
if (s.deadline <= t) fail("Rialto's quote: its transaction's deadline has passed");
|
|
172
|
+
if (s.deadline > t + BigInt(MAX_DEADLINE_S)) fail("Rialto's quote: its transaction's deadline is too far off");
|
|
173
|
+
return s;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** The route a trade takes: "rialto" only when Rialto's terms give strictly more of the bought token than the pinned
|
|
177
|
+
* pool's quote (`pinnedOut`, base units, null when no pinned pool serves the token), else "pinned" (null when neither
|
|
178
|
+
* can: no pinned pool and no Rialto quote). Equal goes to the pinned pool, today's path. */
|
|
179
|
+
export function chooseRoute({ pinnedOut = null, rialto = null }) {
|
|
180
|
+
const p = pinnedOut == null ? null : big(pinnedOut, "pinned output");
|
|
181
|
+
if (rialto && rialto.buyAmount > 0n && (p == null || rialto.buyAmount > p)) return { route: "rialto", out: rialto.buyAmount, min: rialto.minBuyAmount };
|
|
182
|
+
if (p == null || p === 0n) return { route: null, out: null, min: null };
|
|
183
|
+
return { route: "pinned", out: p, min: null };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** The two calls of a Rialto trade from the account: the sold token approved to the router for exactly the amount, then
|
|
187
|
+
* Rialto's transaction, unchanged (checkQuote took it only as the router's swap of these terms, checkSwap). */
|
|
188
|
+
export function rialtoCalls(terms) {
|
|
189
|
+
return [
|
|
190
|
+
{ to: terms.sellToken, data: encodeFunctionData({ abi: APPROVE_ABI, functionName: "approve", args: [terms.spender, terms.sellAmount] }), value: 0n },
|
|
191
|
+
{ to: terms.router, data: terms.data, value: 0n },
|
|
192
|
+
];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** keccak256 of a quote's transaction data: what the gate keeps to know the call it sponsors is the one it quoted. */
|
|
196
|
+
export const dataHashOf = (data) => keccak256(data);
|
|
197
|
+
|
|
198
|
+
/** Terms as JSON (amounts as digits). */
|
|
199
|
+
export function wireTerms(t) {
|
|
200
|
+
return { quoteId: t.quoteId, router: t.router, spender: t.spender, data: t.data, sellToken: t.sellToken, buyToken: t.buyToken, taker: t.taker,
|
|
201
|
+
sellAmount: String(t.sellAmount), buyAmount: String(t.buyAmount), minBuyAmount: String(t.minBuyAmount), gas: t.gas, feeBps: t.feeBps, legs: t.legs };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** wireTerms' JSON read back and checked: the same shape, addresses and digits, or throws RialtoError. */
|
|
205
|
+
export function readWire(w) {
|
|
206
|
+
if (!w || typeof w !== "object") fail("not a quote");
|
|
207
|
+
if (typeof w.data !== "string" || !HEX.test(w.data) || w.data.length < 10) fail("Rialto's quote: no transaction data");
|
|
208
|
+
if (!same(w.router, w.spender)) fail("Rialto's quote: an approval to another spender");
|
|
209
|
+
const buyAmount = big(w.buyAmount, "buy amount"), minBuyAmount = big(w.minBuyAmount, "minimum");
|
|
210
|
+
if (minBuyAmount === 0n || minBuyAmount > buyAmount) fail("Rialto's quote: a minimum above its output");
|
|
211
|
+
return Object.freeze({
|
|
212
|
+
quoteId: String(w.quoteId || ""), router: addr(w.router, "router"), spender: addr(w.spender, "spender"), data: w.data.toLowerCase(),
|
|
213
|
+
sellToken: addr(w.sellToken, "sell token"), buyToken: addr(w.buyToken, "buy token"), taker: addr(w.taker, "taker"), sellAmount: big(w.sellAmount, "sell amount"),
|
|
214
|
+
buyAmount, minBuyAmount, gas: Number.isSafeInteger(w.gas) ? w.gas : null, feeBps: Number.isFinite(w.feeBps) ? w.feeBps : null,
|
|
215
|
+
legs: Number.isSafeInteger(w.legs) ? w.legs : null,
|
|
216
|
+
});
|
|
217
|
+
}
|