SDK/Reference

Rules and policy

PREVIEW

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#

TypeScript
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#

TypeScript
export type LoanState =
  "open" | "repaid" | "liquidated" | "written-off" | "refinancing" | "claimed" | "defaulted";

LoanView#

TypeScript
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#

TypeScript
export type Memory = { offers: string[]; caps: string[]; fallbacks: { offerId: string; amount: bigint }[] };

Fill#

TypeScript
export type Fill = { offer: OfferView; amount: bigint; ltvBps: number };

emptyMemory#

TypeScript
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.

TypeScript
export const REPOST_COOLDOWN_MS = 60_000;

RepostMemo#

TypeScript
export type RepostMemo = { lastRepostMs: number | null };

StandingRead#

TypeScript
export type StandingRead = { mine: OfferView[]; lastId: string; nowMs: number; headroom: bigint | null };

Unusable#

TypeScript
export type Unusable = "at-cap" | "expired" | "cancelled";

RepostMove#

TypeScript
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.

TypeScript
export function ltvBps(debt: bigint, value: bigint): number

withinMandate#

TypeScript
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).

TypeScript
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#

TypeScript
export type DrawAsk = {
  amount: bigint;
  ltvBps: number;
  rateBps: number;
  termMs: number;
  taker: string;
  viaSealedRoom: boolean;
  nowMs: number;
};

DrawFault#

TypeScript
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#

TypeScript
export const TAKER_ANY = 0;

TAKER_LIST#

TypeScript
export const TAKER_LIST = 1;

TAKER_SEALED_ROOM#

TypeScript
export const TAKER_SEALED_ROOM = 2;

TakerKind#

treasury.move:50-52; assert_mandate (:743) refuses any other value.

TypeScript
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.

TypeScript
export const MAX_TAKERS = 64;

drawFault#

treasury::draw (treasury.move:332-341, assert_duration :520, assert_taker :524) in its order: the first refusal.

TypeScript
export function drawFault(m: MandateView | null, a: DrawAsk): DrawFault | null

repayDue#

An offer loan inside its repay lead; 0 = off, and a pool loan (maturity 0) has none.

TypeScript
export function repayDue(repayLeadMs: number, maturityMs: number, nowMs: number): boolean

borrowsOnce#

A repay-before-maturity or hosted borrower takes one loan: any loan it ever opened (refinances too) ends borrowing.

TypeScript
export function borrowsOnce(s: Pick<BorrowStrategy, "repayLeadMs" | "hosted">, opened: number): boolean

pastRepayBy#

Hosted: every open loan is repaid by repayByMs, whatever its kind (a pool loan has no maturity of its own).

TypeScript
export function pastRepayBy(h: HostedRules | null, nowMs: number): boolean

MIN_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.

TypeScript
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).

TypeScript
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#

TypeScript
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.

TypeScript
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.

TypeScript
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.

TypeScript
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.

TypeScript
export function termFault(
  s: { hosted: HostedRules | null },
  termMs: number,
  nowMs: number,
): "too-short" | "too-late" | null

refisLeft#

Hosted: refinances left; every loan it opened after its first is one.

TypeScript
export function refisLeft(h: HostedRules | null, opened: number): boolean

CLOSED_WITH_SURPLUS#

A loan closed against the borrower that may still hold collateral for the deed (loan.move claim).

TypeScript
export const CLOSED_WITH_SURPLUS: readonly LoanState[] = ["liquidated", "written-off", "defaulted"];

CapLimits#

TypeScript
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).

TypeScript
export function capRoom(l: CapLimits | null, nowMs: number): bigint

TOP_UP_TRIGGER_GAP_BPS#

TypeScript
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.

TypeScript
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.

TypeScript
export function allowedFills(
  s: BorrowStrategy,
  offers: OfferView[],
  value: bigint,
  marketLtvBps: number,
  nowMs: number,
  memory: Memory,
  wanted: bigint,
): Fill[]

chooseFill#

TypeScript
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.

TypeScript
export function chooseRefinance(
  s: BorrowStrategy,
  loan: LoanView,
  offers: OfferView[],
  value: bigint,
  marketLtvBps: number,
  nowMs: number,
  owed: bigint,
  memory: Memory,
): Fill | null

repostMove#

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.

TypeScript
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.

TypeScript
export function offerLife(expiryMs: number, nowMs: number, capEndMs: number): number | null

undercutTerms#

The refinancer's offer: under the dearest loan above its watch line, never under its mandate floor.

TypeScript
export function undercutTerms(p: LenderPolicy, loans: LoanView[], ownTreasury: string): OfferTerms | null

From policy.ts#

Exported by index.ts.

Decimals#

TypeScript
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.

TypeScript
export type Venue = { marketLtvBps: number; capLifetimeMs: number; nowMs?: number };

Judge#

TypeScript
export type Judge = "rules" | "llm";

OfferTerms#

TypeScript
export type OfferTerms = {
  rateBps: number;
  maxLtvBps: number;
  minFill: bigint;
  maxFill: bigint;
  size: bigint;
  expiryMs: number;
  termMs: number;
};

Mandate#

TypeScript
export type Mandate = {
  totalCap: bigint;
  minFill: bigint;
  maxFill: bigint;
  minRateBps: number;
  maxLtvBps: number;
  maxTermMs: number;
};

SpendLimits#

TypeScript
export type SpendLimits = { perTx: bigint; perDay: bigint };

Probe#

TypeScript
export type Probe =
  | { gate: "G14"; kind: "post-over-ltv"; maxLtvBps: number }
  | { gate: "G14"; kind: "post-under-floor"; rateBps: number };

LenderStrategy#

TypeScript
export type LenderStrategy =
  | { kind: "post"; offer: OfferTerms }
  | { kind: "undercut"; watchAboveBps: number; undercutBps: number; offer: OfferTerms };

BorrowStrategy#

TypeScript
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.

TypeScript
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#

TypeScript
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#

TypeScript
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.

TypeScript
export type BorrowerPolicy = Base & {
  role: "borrower";
  spend: SpendLimits;
  strategy: BorrowStrategy;
  cash: SpendLimits | null;
};

LiquidatorPolicy#

TypeScript
export type LiquidatorPolicy = Base & {
  role: "liquidator";
  spend: SpendLimits;
  strategy: { buffer: bigint };
};

Policy#

TypeScript
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.

TypeScript
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.

TypeScript
export function termsFault(m: Mandate, t: OfferTerms): string | null

EXPIRY_MARGIN_MS#

Before a lender can claim (GRACE after maturity) and before the agent's cash cap ends (treasury.move:217).

TypeScript
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.

TypeScript
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.

TypeScript
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).

TypeScript
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.

TypeScript
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).

TypeScript
export function repayBound(a: {
  amount: bigint;
  refiBuffer: bigint;
  maxRefis: number;
  rateBoundBps: number;
  lifeMs: number;
}): { principal: bigint; interest: bigint; maxOwed: bigint } | null

parsePolicy#

A policy file, or the reason the agent refuses to start with it.

TypeScript
export function parsePolicy(raw: unknown, d: Decimals, v: Venue): Policy | string