Rules and policy
The lending rule checks and the policy parser the agents use, mirrors of what the chain enforces. Exported whole from rules.ts and policy.ts.
Signatures below are copied from the source; descriptions are the source's own doc comments.
From rules.ts#
Exported by index.ts.
OfferView#
export type OfferView = {
id: string;
capId: string;
treasuryId: string;
rateBps: number;
maxLtvBps: number;
minFill: bigint;
maxFill: bigint;
size: bigint;
filled: bigint;
termMs: number;
expiresAtMs: number;
postedSeq: number;
};LoanState#
export type LoanState =
"open" | "repaid" | "liquidated" | "written-off" | "refinancing" | "claimed" | "defaulted";LoanView#
export type LoanView = {
id: string;
opener?: string;
rateBps: number;
principal: bigint;
lenderKind: "treasury" | "pool";
lenderId: string;
capId: string;
state: LoanState;
collateral: bigint;
openedSeq: number;
/** Fill time + term on an offer loan; 0 on a pool loan (open-ended). */
maturityMs?: number;
claimId?: string;
startS?: number;
indexAtOpen?: bigint;
};Memory#
export type Memory = { offers: string[]; caps: string[]; fallbacks: { offerId: string; amount: bigint }[] };Fill#
export type Fill = { offer: OfferView; amount: bigint; ltvBps: number };emptyMemory#
export const emptyMemory = (): Memory => …REPOST_COOLDOWN_MS#
The chain already stops overspending (the mandate's total cap, treasury/13), so re-posts have no lifetime limit; the cool-down only spaces them out to spare the sponsor's gas budget.
export const REPOST_COOLDOWN_MS = 60_000;RepostMemo#
export type RepostMemo = { lastRepostMs: number | null };StandingRead#
export type StandingRead = { mine: OfferView[]; lastId: string; nowMs: number; headroom: bigint | null };Unusable#
export type Unusable = "at-cap" | "expired" | "cancelled";RepostMove#
export type RepostMove =
| { kind: "keep" }
| { kind: "repost" | "wait" | "backoff"; why: Unusable }
| { kind: "give-up"; why: "revoked" };ltvBps#
market::ltv_bps (market.move:166-171): debt over value, rounded up, saturating.
export function ltvBps(debt: bigint, value: bigint): numberwithinMandate#
export function withinMandate(m: Mandate, t: OfferTerms): { ok: true } | { ok: false; reason: string }MandateView#
A lender's mandate as treasury.move holds it (LendMandate :83-93, limits_of :436, balance :416).
export type MandateView = {
totalCap: bigint;
outstanding: bigint;
minFill: bigint;
maxFill: bigint;
/** The mandate's LTV ceiling for the collateral, or null when that collateral is not in its set. */
collateralLtvBps: number | null;
minRateBps: number;
maxDurationMs: number;
takerKind: number;
takers: string[];
capExpiresAtMs: number;
funds: bigint;
};DrawAsk#
export type DrawAsk = {
amount: bigint;
ltvBps: number;
rateBps: number;
termMs: number;
taker: string;
viaSealedRoom: boolean;
nowMs: number;
};DrawFault#
export type DrawFault =
| "MANDATE_GONE"
| "CAP_EXPIRED"
| "OUTSIDE_MANDATE_FILLS"
| "OVER_MANDATE_CAP"
| "COLLATERAL_NOT_ALLOWED"
| "OVER_MANDATE_LTV"
| "RATE_BELOW_MANDATE"
| "TERM_OUTSIDE_MANDATE"
| "TAKER_NOT_ALLOWED"
| "LENDER_SHORT";TAKER_ANY#
export const TAKER_ANY = 0;TAKER_LIST#
export const TAKER_LIST = 1;TAKER_SEALED_ROOM#
export const TAKER_SEALED_ROOM = 2;TakerKind#
treasury.move:50-52; assert_mandate (:743) refuses any other value.
export type TakerKind = typeof TAKER_ANY | typeof TAKER_LIST | typeof TAKER_SEALED_ROOM;MAX_TAKERS#
treasury.move:48 MAX_TAKERS; assert_mandate (:745) pairs TAKER_LIST with 1 to 64 takers and the rest with none.
export const MAX_TAKERS = 64;drawFault#
treasury::draw (treasury.move:332-341, assert_duration :520, assert_taker :524) in its order: the first refusal.
export function drawFault(m: MandateView | null, a: DrawAsk): DrawFault | nullrepayDue#
An offer loan inside its repay lead; 0 = off, and a pool loan (maturity 0) has none.
export function repayDue(repayLeadMs: number, maturityMs: number, nowMs: number): booleanborrowsOnce#
A repay-before-maturity or hosted borrower takes one loan: any loan it ever opened (refinances too) ends borrowing.
export function borrowsOnce(s: Pick<BorrowStrategy, "repayLeadMs" | "hosted">, opened: number): booleanpastRepayBy#
Hosted: every open loan is repaid by repayByMs, whatever its kind (a pool loan has no maturity of its own).
export function pastRepayBy(h: HostedRules | null, nowMs: number): booleanMIN_HOSTED_TERM_MS#
Round-2 F1: the shortest offer a hosted borrower takes or refinances into. An outsider's 1 ms offer comes due at once and anyone may claim its default 300 s later (loan.move GRACE_MS); the agent ticks every 30 s and may be paused. A floor on the term, not on term minus repay lead: a loan due at once is repaid at once, with this long to retry.
export const MIN_HOSTED_TERM_MS = 6 * 3_600_000;BorrowRules#
treasury::BorrowMandate: the owner sets it on the SUI cap and every desk borrow, pool or refinance is held to it. poolId: the one pool it may borrow from, only for a pool-path borrower; null refuses every pool (treasury/27).
export type BorrowRules = {
maxRateBps: number;
minTermMs: number;
latestMaturityMs: number;
poolId: string | null;
/** What the agent may still borrow (treasury.move use_allowance); only the owner's next set restores it. */
allowance: bigint;
};U64_MAX#
export const U64_MAX = 2n ** 64n - 1n;borrowRules#
A hosted borrower may borrow its amount, plus one refinance buffer per refinance: a refinance uses up what it borrows over the old loan's debt (borrower.move refinance_*). Scenario borrowers have no allowance to keep.
export const borrowRules = (
s: Pick<BorrowStrategy, "maxRateBps" | "hosted" | "path" | "amount" | "refiBuffer">,
pool: string | null,
): BorrowRules => …withinAllowance#
Never ask for more than the allowance left; null (no rules read) leaves it to the chain.
export const withinAllowance = (wanted: bigint, remaining: bigint | null) => …refiExtra#
What a refinance uses of the allowance: its new principal over what the old loan owes, never below 0.
export const refiExtra = (amount: bigint, owed: bigint) => …termFault#
Why the chain's borrow rules refuse an offer of this term now: too short to repay in time, or due after repay-by.
export function termFault(
s: { hosted: HostedRules | null },
termMs: number,
nowMs: number,
): "too-short" | "too-late" | nullrefisLeft#
Hosted: refinances left; every loan it opened after its first is one.
export function refisLeft(h: HostedRules | null, opened: number): booleanCLOSED_WITH_SURPLUS#
A loan closed against the borrower that may still hold collateral for the deed (loan.move claim).
export const CLOSED_WITH_SURPLUS: readonly LoanState[] = ["liquidated", "written-off", "defaulted"];CapLimits#
export type CapLimits = { perTx: bigint; perDay: bigint; expiresAtMs: number; spent24h: bigint };capRoom#
What a cap lets its agent spend right now (treasury.move spend: expiry, per_tx, per_day over the window).
export function capRoom(l: CapLimits | null, nowMs: number): bigintTOP_UP_TRIGGER_GAP_BPS#
export const TOP_UP_TRIGGER_GAP_BPS = 1_000;topUpNeed#
SUI to add so the loan's LTV returns to targetBps (the market's borrow limit); 0 below the trigger.
export function topUpNeed(a: {
debt: bigint;
collateral: bigint;
value: bigint;
liqBps: number;
targetBps: number;
})allowedFills#
Every fill this borrower is allowed, cheapest first, then the one-time minimum retries; a judge picks among them.
export function allowedFills(
s: BorrowStrategy,
offers: OfferView[],
value: bigint,
marketLtvBps: number,
nowMs: number,
memory: Memory,
wanted: bigint,
): Fill[]chooseFill#
export const chooseFill = (...args: Parameters<typeof allowedFills>): Fill | null => …chooseRefinance#
principal + buffer, a fixed draw that must cover what is owed; finish_refi returns the change.
export function chooseRefinance(
s: BorrowStrategy,
loan: LoanView,
offers: OfferView[],
value: bigint,
marketLtvBps: number,
nowMs: number,
owed: bigint,
memory: Memory,
): Fill | nullrepostMove#
A lender whose offers can no longer take a minimum fill re-posts inside its mandate, or waits for a repayment when the mandate has no minimum fill left. Re-posts back off 1, 2, 4 turns and stop after MAX_REPOSTS, so an offer exhausted for gas (review A-M1) costs the lender a bounded number of posts.
export function repostMove(
t: OfferTerms,
r: StandingRead,
memo: RepostMemo,
cooldownMs: number,
): { move: RepostMove; memo: RepostMemo }offerLife#
treasury.move:307: an offer may not outlive its cap. null once the cap has no time left.
export function offerLife(expiryMs: number, nowMs: number, capEndMs: number): number | nullundercutTerms#
The refinancer's offer: under the dearest loan above its watch line, never under its mandate floor.
export function undercutTerms(p: LenderPolicy, loans: LoanView[], ownTreasury: string): OfferTerms | nullFrom policy.ts#
Exported by index.ts.
Decimals#
export type Decimals = { loan: number; collateral: number };Venue#
What the chain holds an offer to beyond the mandate: the cap's lifetime (treasury.move:307) and the market's LTV.
export type Venue = { marketLtvBps: number; capLifetimeMs: number; nowMs?: number };Judge#
export type Judge = "rules" | "llm";OfferTerms#
export type OfferTerms = {
rateBps: number;
maxLtvBps: number;
minFill: bigint;
maxFill: bigint;
size: bigint;
expiryMs: number;
termMs: number;
};Mandate#
export type Mandate = {
totalCap: bigint;
minFill: bigint;
maxFill: bigint;
minRateBps: number;
maxLtvBps: number;
maxTermMs: number;
};SpendLimits#
export type SpendLimits = { perTx: bigint; perDay: bigint };Probe#
export type Probe =
| { gate: "G14"; kind: "post-over-ltv"; maxLtvBps: number }
| { gate: "G14"; kind: "post-under-floor"; rateBps: number };LenderStrategy#
export type LenderStrategy =
| { kind: "post"; offer: OfferTerms }
| { kind: "undercut"; watchAboveBps: number; undercutBps: number; offer: OfferTerms };BorrowStrategy#
export type BorrowStrategy = {
path: "open-offer" | "pool" | "sealed-rfq";
fallback: "open-offer" | "none";
sizing: "fixed" | "max";
collateral: bigint;
amount: bigint;
minAmount: bigint;
maxRateBps: number;
ltvHeadroomBps: number;
refinance: boolean;
refiBuffer: bigint;
repayAtClose: boolean;
/** 0 = off. Otherwise the agent borrows once and repays this long before an offer loan's maturity. */
repayLeadMs: number;
room: { windowMs: number; settleWindowMs: number; termMs: number } | null;
/** Hosted borrowers (all three set together): every loan is repaid by repayByMs, at most once borrowed. */
hosted: HostedRules | null;
};HostedRules#
repayByMs: no loan past it (cap expiry minus EXPIRY_MARGIN_MS); rateBoundBps: the highest rate any of its loans can run at (its max rate, or the pool's curve top when it may hold a pool loan); maxRefis: refinances per life.
export type HostedRules = {
repayByMs: number;
rateBoundBps: number;
maxRefis: number;
autoTopUp: boolean;
/** Claims the surplus of a liquidated, written-off or defaulted loan back into the user's SUI treasury. */
autoClaim: boolean;
};LenderPolicy#
export type LenderPolicy = Base & {
role: "lender";
mandate: Mandate;
strategy: LenderStrategy;
probe: Probe | null;
/** The floor of the band a sealed bid is drawn from, never the bid itself: sealed.ts sealedRateBps. */
sealedBid: { floorBps: number } | null;
};PoolLenderPolicy#
export type PoolLenderPolicy = Base & {
role: "pool-lender";
spend: SpendLimits;
strategy: { amount: bigint };
};BorrowerPolicy#
cash: a hosted borrower's loan-coin cap; it must cover repayBound's maxOwed or the rules could block a repay.
export type BorrowerPolicy = Base & {
role: "borrower";
spend: SpendLimits;
strategy: BorrowStrategy;
cash: SpendLimits | null;
};LiquidatorPolicy#
export type LiquidatorPolicy = Base & {
role: "liquidator";
spend: SpendLimits;
strategy: { buffer: bigint };
};Policy#
export type Policy = LenderPolicy | PoolLenderPolicy | BorrowerPolicy | LiquidatorPolicy;MANDATE_MAX_RATE_BPS#
treasury.move assert_mandate: min_rate_bps < MAX_BPS * 10. The self-serve form checks the same constant.
export const MANDATE_MAX_RATE_BPS = 99_999;termsFault#
The off-chain mirror of treasury::assert_offer_terms (treasury.move:289-309) plus offer::post's size rule.
export function termsFault(m: Mandate, t: OfferTerms): string | nullEXPIRY_MARGIN_MS#
Before a lender can claim (GRACE after maturity) and before the agent's cash cap ends (treasury.move:217).
export const EXPIRY_MARGIN_MS = 3_600_000;REPAY_MARGIN_S#
Extra seconds in the cash-cap sizing bound (repayBound). Hosted pool repay uses executionDraw at the live curve.
export const REPAY_MARGIN_S = 600;repayDraw#
What the agent draws to repay (agents/agent.ts repayLoan): owed plus REPAY_MARGIN_S of interest, plus one unit.
export const repayDraw = (owed: bigint, rateBps: number) => …EXEC_MARGIN_S#
Seconds between the agent's read of what is owed and the repay landing (one sponsored transaction).
export const EXEC_MARGIN_S = 60;executionDraw#
Round-2 F1: what the chain can draw when the repay executes, rounded up; at 0% it is what is owed exactly. The agent repays whenever the cash covers this, so its own REPAY_MARGIN_S never blocks a fully funded loan.
export const executionDraw = (owed: bigint, rateBps: number) => …repayBound#
The most a hosted borrower's loan can owe at its repay, all refinances included. Principal grows by refiBuffer per refinance (rules.ts chooseRefinance); interest is simple on an offer loan (interest.move owed) and compounds per touch on a pool loan (interest.move grown), so with y = rate * time: growth <= e^y - 1 <= y + y^2 for y <= 1, each term rounded up, plus one unit per rounding step (owed rounds up once per loan).
export function repayBound(a: {
amount: bigint;
refiBuffer: bigint;
maxRefis: number;
rateBoundBps: number;
lifeMs: number;
}): { principal: bigint; interest: bigint; maxOwed: bigint } | nullparsePolicy#
A policy file, or the reason the agent refuses to start with it.
export function parsePolicy(raw: unknown, d: Decimals, v: Venue): Policy | string