> For the complete documentation index, see [llms.txt](https://docs.gage.cash/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gage.cash/developers/contracts.md).

# Contracts

Mainnet contract interfaces, fee routes, reward accounting and owner-controlled settings.

Gage contracts use Solidity 0.8.28 and Foundry. The vault contracts, the legacy DealVault, the native engines (the Intent core and each lend asset's core included), the fill routers and the Earn strategies, have no owner or upgrade function. Since block 62,622,930 (14 September 2026) the Safe `0x30e8E13E62DFcd063AF763aB29501FeE74C4918e` owns the registries, FeeSink, Emissions, FeeFloor, DealFeeRouter and the Earn factory, and from their deployment each IntentFactory, the cash-out, loop, private borrow and rollover routers and the admin role of the Intent core's adapter; gage's keeper `0xf373e8c4C0842CE2A9F675f206BF326A99fa809E` owns DealRewards; the deployer wallet `0x86514e45293fcf111ED8A6bDA7c8bca4A64Dd9E5` keeps the earlier adapters' admin role and the Earn curator. See [Contract addresses](https://docs.gage.cash/protocol/addresses.md) for the 17 launch contracts, the extension markets (Meme / USDG LP, PONS / WETH LP, Borrow LP Zap, CASHCAT / USDG zap), the native engines with their adapters, the Earn factory and strategies, and verified source links, the [Bounty target inventory](https://docs.gage.cash/protocol/bounty-targets.md) for every partner lending contract, and [Status](https://docs.gage.cash/protocol/status.md) for authority details. Interfaces below are a guide; use each deployed contract’s matched source and ABI for integration.

## Native engines (GageV2Vault)

Five engines are published in the manifest's `nativeV2.engines` (`https://gage.cash/api/deployment`): `0x2265…` (grace 172,800 s), `0x0856…` (grace 172,800 s, lender sales), V3 `0xfee799ade96229c2c128bc5ed9e55f8d9d01a7e9` (grace 0, lender sales), the Intent core of 15 October 2026 `0x856e4232469b957150cb29a8ce9b60059449e87e` (grace 0) and the current Intent core `0x0086ec1540719d4199432797e2b6068e6ae5a0e5` (grace 0, since 4 November 2026, the manifest's `intentV1.core`), where new loans are listed. The four earlier engines take no new listings and settle the loans they hold. Each has its own registry, rewards ledger, cash-out router and an adapter (`0x647d…` for the first two, `0x2166…` for V3, `0x7896…` for the Intent core of 15 October, `0x6c96…` for the current one); the first three also have entry and zap routers. Each lend asset's core (`intentV1Assets`) runs the Intent core's code and is not listed there, since its amounts are in its own asset. A loan is sold in `UNITS = 4` quarters: `list(...)` opens funding, `fund(id, units)` buys whole quarters, the loan activates when all four are sold, and `cancelFunding(id)` closes an unfilled listing so the quarters are refunded. On the Intent cores only partner vaults fund, through the fill router, all four quarters in one transaction. `MAX_FUNDING_WINDOW` is 7 days; the app sets 24 hours. Repayment closes and `finalizeDefault(id)` opens at `fundedAt + term + GRACE`; on V3 and the Intent cores that is the end of the term. States: FUNDING, ACTIVE, REPAID, DEFAULTED, CANCELLED. Views: `getLoan(id)`, `loanCount()`. Immutables: `USDG` (a lend asset's core reports its asset here), `SGAGE`, `REGISTRY`, `VALIDATOR` (the three earlier engines; the token-only Intent cores have none), `REWARDS`, `BRIDGE` (the adapter), `ACCOUNT_IMPLEMENTATION`, `FEE_RECIPIENT` and `GRACE` (at most `MAX_GRACE`, 7 days). The engine's registry caps the trade fee at `MAX_TRADE_FEE_BPS` = 200. On the current Intent core's registry a token has a minimum, and ten Stock Tokens also have a per-loan and an open cap; a lend asset's registry may cap a token too (HIMS's BONER).

## Partner lending (Intent V1)

The manifest's `intentV1` names the USDG generation: `core`, `factory`, `fillRouter`, `quoteVerifier`, `loopRouter`, `privateRouter`, `rolloverRouter` and `reserve`. Each lend asset has a generation of its own under `intentV1Assets.<SYMBOL>` (GLD, NVDA and HIMS today), with its own core, registry, factory, fill router, quote verifier, cash-out router, grade registry and rollover router; its loans are paid out and repaid in that asset. A stablecoin generation the GenerationDeployer builds (frxUSD since 5 November 2026) is not named in the manifest: gage's services find it from the deployer's `GenerationDeployed` events (see [Lend generations with gage-sdk](https://docs.gage.cash/developers/sdk-lend-generations.md)). A generation a newer one replaces moves to `intentV1Previous` or `intentV1AssetsPrevious` and is withdraw-only: its factory's `fillRouter()` is zero and its registry pauses new deals. `rolloverExecutor` is the keeper wallet that runs standing roll instructions.

* **`IntentFactory`** creates every partner vault from one fixed creation code (`VAULT_INIT_HASH`); `count()` and `vaults(i)`, or `isVault(address)`, enumerate them. Any address can call `create` and manage the vault it creates (`openCreation` is true since 5 November 2026); `isCreator` names the creators its owner admitted before.
* **`IntentVault`**, a partner vault: `deposit(assets, minShares)` takes at least one whole unit of its asset, `redeem(shares, minAssets)` pays up to `freeLiquidity()`, the permissionless `settle(ids)` books each loan's outcome, and `claimPocket(pocketId)` and `claimRewards()` pay out recovered collateral and sGAGE. `totalAssets()` counts a loan past its end at its full value, principal and whole return after fees, until `settle` books it; from the end of its term, deposits, redemptions and fills revert (`SettlementDue`) until then. Its manager's mandate tightens at once and loosens after three hours; a pause never blocks redemptions. Vaults of the current factories (since 4 November 2026 for USDG, 5 November for GLD, NVDA, HIMS and frxUSD) are also standard ERC-4626: `deposit(assets, receiver)`, `mint`, `withdraw`, `redeem(shares, receiver, owner)`, `asset()`, `totalAssets()`, the conversions and the `max*` and `preview*` views, with 18-decimal shares (`gSHARE`). The deviations: an entry takes at least one whole unit of the asset; the maxima read zero while a settlement is due; a positive maximum can still revert `RewardsPending`; the maxima ignore USDG's pause and freezes; pricing reverts if the reserve's `convertToAssets` does while the vault holds reserve shares; and `maxWithdraw` keeps a raw unit back while other shares remain, so `redeem(maxRedeem(owner), …)` is the way to empty a holding. Vaults of the earlier, withdraw-only factories have only the slippage-held `deposit(assets, minShares)` and `redeem(shares, minAssets)`.
* **`IntentFillRouter`** executes a fill plan the rates service signs and `IntentQuoteVerifier` checks: one transaction funds a listing whole from one or more vaults, and the execution fee goes to the protocol's fee recipient. gage's filler `0xCB14554904b86b3472F960740aE377b5b711A659` is the only wallet a factory admits as a filler; the rollover, loop and private borrow routers are admitted too, and fill inside their own transactions.
* **`LoopRouter`** (the USDG generation's; NVDA has its own, which its put router uses) buys more of the pledged token through admitted Uniswap pools or KyberSwap, then lists, funds and pays out one loan, in one transaction.
* **`RolloverRouter`**: `roll(...)` repays a running loan with PoolManager flash liquidity, lists the same collateral for the same borrower (`listFor`) and funds the new loan on signed plans, in one transaction. `setAutoRoll(loanId, executor, term, window, maxCost, maxTopUp, rollsLeft, withRewards, until)` stores a standing instruction the named executor runs with `rollFor`, inside limits the router checks: the same principal and term, a cost ceiling in the loan's asset to the unit, the last `window` of the loan (at most one day and an eighth of the term), a number of rolls and a date. `cancelAutoRoll(loanId)` ends it. Its owner can only pause it.
* **`PrivateBorrowRouter`** (USDG core) withdraws a piece of a screened deposit from a Privacy Pool, lists it for the borrower its proof names and funds the loan, in one transaction; memecoins and Robinhood Chain ecosystem tokens only.
* **`GageV2CashoutRouter.cashOutVia`** sells a running loan's whole collateral through a KyberSwap router its owner admits, repays the loan and pays the rest to the recipient, less the 0.5% platform fee.

## Lender sales on supported V2 engines

Check the published engine's `lenderSales` capability before calling these functions. Older V2 engines do not implement them; their original methods and exits remain valid.

* `setLenderAsk(id, slots, price, deadline, maxFeeBps)` posts one fixed-price bundle per seller and loan. `slots` is a nonzero four-bit mask of exact owned quarters; the price buys all selected quarters together.
* `getLenderAsks(id)` returns up to four asks, once per seller. Ignore zero prices and expired deadlines. `getLenderAsk(id, seller)` returns the stored individual ask.
* `buyLender(id, purchase)` binds the seller, recipient, exact slots, price, nonce, maximum fee and minimum remaining reward allocation. Approve the full USDG price to that engine first. The remaining allocation is an upper bound on future rewards; early closure can reduce actual earnings.
* `cancelLenderAsk(id)` invalidates the seller's stored ask. The engine rejects purchases after repayment or default finalization, including offers still present in storage.

Sales checkpoint earned rewards before changing quarter ownership. Repayment and default recovery follow the updated quarters; previous owners retain their earned reward claims. Sale proceeds use `cashCredit` and `withdrawUSDG`, and fees use the existing floor route. Index `LenderAskPosted`, `LenderAskCancelled` and `LenderSold`; retain former sellers as position participants.

## Extension markets (`DealVaultV2`)

`DealVaultV2` implements the same deal and withdrawal interfaces for independently allowlisted LP markets. The manifest's `vaultMarkets` lists four: Meme / USDG LP, PONS / WETH LP, Borrow LP Zap and CASHCAT / USDG zap, each with its own vault, registry and ETH entry router. Its admission adapter rejects direct ERC20 collateral and unsupported pair classes. Resolve a deal by both vault address and deal ID; numeric IDs may overlap.

The public manifest (`https://gage.cash/api/deployment`) lists each extension’s contracts. The UI combines their LPs into the shared picker, lending list and open-positions feed while scoping approvals and transactions to the selected vault. Deal rewards are disabled for the extension vaults; never register their IDs with the original DealRewards. `LPFeeForwarder.forward()` moves accrued USDG deal fees into the existing DealFeeRouter and shares its keeper and batching policy.

## DealVault (legacy)

The original vault, exits-only today: its ERC-20 allowlist holds only the adapters' receipts, and new listings go to the Intent core. Every V1 deal, escrowed asset and internal balance lives here.

```solidity
// Deals
function list(Collateral calldata c, uint128 cap, uint32 term, uint40 listingExpiry, uint128 minPrice)
    external returns (uint256 dealId);
function cancel(uint256 dealId) external;
function fund(uint256 dealId, address lender) external returns (uint256 bidId);   // pulls exactly minPrice, settles at once
function reclaim(uint256 dealId) external;                                          // borrower pays exactly cap
function claim(uint256 dealId) external;                                            // lender, once now >= expiry + GRACE

// Offers (dormant in v1)
function bid(uint256 dealId, uint128 price, uint40 bidExpiry, address lender) external returns (uint256 bidId);
function withdrawBid(uint256 bidId) external;
function accept(uint256 dealId, uint256 bidId) external;

// Balances: pull, never push
function withdrawUSDG() external;
function withdrawERC20(address token) external;
function withdrawPosition(uint256 tokenId) external;
function withdrawCollateral(uint256 dealId) external;   // dispatcher for the deal page

// Views
function getDeal(uint256 dealId) external view returns (Deal memory);
function getBid(uint256 bidId) external view returns (Bid memory);
function claimableAt(uint256 dealId) external view returns (uint40);
function balanceUSDG(address account) external view returns (uint256);
function balanceERC20(address account, address token) external view returns (uint256);
function owedNFT(address account, uint256 tokenId) external view returns (bool);
function openRaw(address token) external view returns (uint256);
function dealCount() external view returns (uint256);
function bidCount() external view returns (uint256);
function GRACE() external view returns (uint48);
```

| Constant             | Value    |
| -------------------- | -------- |
| `MIN_GRACE`          | 24 hours |
| `MAX_LISTING_EXPIRY` | 7 days   |
| `MAX_FEE_BPS`        | 200      |

Immutables: `USDG`, `REGISTRY`, `FEE_SINK`, `POSITION_MANAGER`, `GRACE`. `GRACE` is fixed per deployment: 48 hours on this vault and on the two earliest native engines, 0 on V3 and the Intent cores, where repayment reverts with `Deadline` from `fundedAt + term` and `finalizeDefault` opens in that same second. Read the published engine entry rather than hard-coding a window.

**Events.** `Listed`, `BidPlaced`, `BidWithdrawn`, `Funded(dealId, bidId, lender, price, fee, fundedAt, expiry)`, `Reclaimed`, `Claimed`, `Cancelled`, `Withdrawn(account, asset, amount)`. Every table the indexer holds is rebuilt from these alone. `fund` emits `BidPlaced` then `Funded` for a synthetic accepted offer, so one accounting path serves both flows.

**Rules.** Custom errors, never revert strings. A `lender` other than the caller is accepted only from a registry-allowlisted router. The ERC-721 receiver accepts exactly the token an in-flight `list` expects, from the PositionManager only, and consumes the expectation. Timestamps only; deadlines are exclusive.

## CollateralRegistry

Owner: the Safe `0x30e8E13E62DFcd063AF763aB29501FeE74C4918e` since block 62,622,930 (14 September 2026), by two-step transfer; each native engine's registry is owned the same way. Pool allowlisting can grow after launch. `setPoolRemovalHook(poolId, hook, codeHash)` pins the reviewed removal-hook runtime for an individual pool; token and pool eligibility are separate settings.

```solidity
function setERC20Allowed(address token, bool ok, Lane lane, uint128 minAmount, uint128 maxDealRaw, uint128 maxOpenRaw) external;
function setPoolAllowed(bytes32 poolId, bool ok, uint128 minLiquidity) external;
function setTerms(uint32[] calldata terms) external;        // at most MAX_TERMS, each MIN_TERM..MAX_TERM
function setFee(uint16 bps) external;                       // <= MAX_FEE_BPS
function setInRangeRequired(bool required) external;
function pauseNewDeals(bool paused) external;               // list, bid, accept, fund only
function setRouter(address router, bool ok) external;
function setMemePairs(uint8 mask) external;                 // STOCK = 1, USDG = 2, ETH = 4

function getERC20Config(address token) external view returns (ERC20Config memory);
function getPoolConfig(bytes32 poolId) external view returns (PoolConfig memory);
function isTermAllowed(uint32 term) external view returns (bool);
function allowedTerms() external view returns (uint32[] memory);
function feeBps() external view returns (uint16);
function inRangeRequired() external view returns (bool);
function newDealsPaused() external view returns (bool);
function isRouter(address account) external view returns (bool);
function memePairMask() external view returns (uint8);
```

| Constant                | Value           |
| ----------------------- | --------------- |
| `MAX_FEE_BPS`           | 200             |
| `MIN_TERM` / `MAX_TERM` | 1 day / 30 days |
| `MAX_TERMS`             | 8               |

`Lane` is STOCK, ETH or MEME and is emitted in `ERC20Set` for the indexer. The vault never reads it.

## FeeSink and DealFeeRouter

FeeSink pulls USDG fees credited by DealVault with `collect()` and sends them to the configured destination with `sweep()`. The owner can change route, treasury and destination. Mainnet uses the historical `BUYBACK` route enum with `buyback()` pointing to **DealFeeRouter**, not the legacy Buyback implementation.

`DealFeeRouter.process(clipUSDG)` opens a batch at `threshold()`, converts USDG → ETH → GAGE, and calls `FeeFloor.depositGAGE`. It has no operations deduction, immediate sGAGE purchase/burn or caller bounty. `availableUSDG()` includes the router balance, FeeSink balance and vault credit. `batchRemaining()`, `totalUSDGProcessed()` and `totalGAGEAdded()` expose execution progress. `setThreshold` is owner-only, bounded to 10–10,000 USDG. The launch threshold is 100 USDG.

## EntryRouter

Stateless. `fundWithETH(dealId, commands, inputs, deadline)` swaps ETH to USDG through the Universal Router, then funds the deal with the caller as lender. Surplus USDG is credited to the caller's vault balance. `bidWithETH` is the dormant offer variant.

## sGAGE

ERC-20 with `burn(amount)`. The constructor mints `TOTAL_SUPPLY_AT_MINT` (5,000,000,000) once: 4.0B to Emissions, 1.0B for the seed. No mint function exists afterwards.

## Drip

Locked balances keyed by a drip id. `claim(dripId)` and `claimMany(dripIds)` transfer what has unlocked since the last claim. Unlocked at time `t` is `total × e² ÷ L²` with `e = min(t − start, L)`. Grantors are DealRewards and LPRewards only, set once. `totalLocked()` is the sum outstanding.

## Emissions

Holds the 4.0B reserve and the 52-week table. `WEEKS()`, `EPOCH()`, `RESERVE()`, `weekly(epoch)`, `prefixSum(epoch)`, `launchAt()`, `currentEpoch()`, `epochStart(epoch)`, `epochOf(timestamp)`, `dealShareBps(epoch)`, `term21ShareBps(epoch)`, `liquidityBudget(epoch)`, `dealBudget(epoch, term)`. `release(epoch)` and `rollover(epoch)` are permissionless; `finalize()` burns the remainder after week 52. Cumulative transfers out are bounded by the table's prefix sums. The owner retains `setShares(epoch, dealShareBps, term21ShareBps)` for allowed epoch share updates within its contract constraints.

## DealRewards

`register(dealId)` is permissionless: reads the funded deal from the vault, derives the epoch from `fundedAt`, computes `fee × rate[term]` capped at `MAX_REWARD_SHARE_BPS` (80%) of the fee at the posted price, reserves it from the term's budget, and grants two drips of length `term` starting at `fundedAt`. `quote(term, fee)` previews a reward. `epochRates(epoch)` and `effectiveRates(epoch)` expose the posted and carried-forward rates. `setEpochRates` is owner-only (gage's keeper, which posts the weekly rates), for the current or a future epoch only.

## LPHook

A v4 hook on the GAGE/sGAGE pool with `afterAddLiquidity` and `afterRemoveLiquidity` permissions and no others. When the sender is the PositionManager it calls `LPRewards.onLiquidityChange(tokenId)` inside a `try` with a fixed gas stipend and emits `RecordFailed` on any failure. It never reverts and never returns a delta.

## LPRewards

`checkpoint(tokenId)` and `checkpointMany` are permissionless. `collect(tokenId)` by the position's owner moves earned emissions into a 7-day drip. Views: `earned(tokenId)`, `positionState(tokenId)`, `valueInGAGE(tokenId)`, `totalWeight()`, `poolKey()`, `seedTokenId()`. `notifyEmissions` and `notifyLump` are called by Emissions. The seed and the floor bands carry zero weight.

## CreatorFeeSplitter / FeeFloor

The deployed implementation is **FeeFloor**. `claim()` pulls available Pons creator fees; `claimAndSplit(clipETH)` claims and executes a clip. `split()` and `split(clipETH)` split processed ETH 50:50 between the fixed operations wallet and buying GAGE for floor bands, with no caller bounty. The threshold is measured in USDG equivalent on the gross ETH balance; the owner can adjust it within 10–10,000 USDG.

`depositGAGE(amount)` adds GAGE supplied by DealFeeRouter or another caller directly to the floor, without an operations deduction. `bandNow()`, `floorCount()`, `floorTokenIds(i)`, `bands(tokenId)` and `floorBacking()` describe the positions. `collect(tokenId)` burns collected sGAGE fees and keeps GAGE fees; `sweep(tokenId)` removes a fully converted band and burns its sGAGE. There is no owner withdrawal of floor principal or NFTs.

## ReinvestRouter

Stateless. `reinvestMatch(...)` and `reinvestZap(...)` mint a new GAGE/sGAGE position to the caller; `increaseMatch(...)` and `increaseZap(...)` add to one the caller owns, which needs the caller's NFT approval to the router. Pulls sGAGE with a plain approval. Ends every transaction holding nothing.

## CompoundingSeedBootstrap and CompoundingSeedTimelock

CompoundingSeedBootstrap atomically minted and locked the seed NFT. The resulting CompoundingSeedTimelock holds **NFT 2126377**, with `releaseAt()` fixed at **1820345126** (7 September 2027, 19:25:26 UTC).

`previewCompound()` estimates available fees and additional liquidity. `compound(referenceSqrtPriceX96, minLiquidity, deadline)` is callable only by the fixed `TREASURY` wallet, which has not called it since October 2026, so fees accrue in the position uncollected. It collects fees into the lock and increases the same position, retaining unmatched balances for later. It neither sends those fees to operations nor extends the lock. `release()` sends the NFT and remaining token balances to `TREASURY` at or after the deadline. The older SeedTimelock contract with `collectFees()` is not this deployment.

## Earn (third design)

`EarnFactory` (`0x124d74D5626D392E937c3410c0325eA464700682`, owned by the Safe) creates strategies with `create(mandate)`; creation is owner-only while `publicCreation` is false. It holds `PROTOCOL_SHARE_BPS` and `protocolRecipient` (`setProtocolRecipient`, owner-only), which every strategy reads at `claimFees`. `EarnVault` is one pooled share class (`MANDATE_VERSION` 3; shares are not transferable) that lends USDG through one zero-grace engine: the constructor reverts unless the core's `GRACE()` is 0. `deposit(assets, minShares)` needs at least `MIN_DEPOSIT`, one whole USDG; `redeem(shares, minAssets)` pays up to `freeLiquidity()` and reverts beyond it. `fund(id, units, maxReserveShares)` buys whole quarters of a listing from cash then the reserve, with at most `MAX_OPEN_LOANS` (128) open; `withdrawCommitment(id)` releases an unfilled commitment; `settle(ids)` is permissionless and books each outcome; `recover(id)` opens a written-off loan's side pockets, claimed with `claimPocket(pocketId)`; `claimRewards()` takes the holder's sGAGE. The fee is `feeBps` (at most `MAX_FEE_BPS`, 5000) of each loan's gross return, snapshotted at funding and split at settlement between the curator and the protocol recipient. Settings: `setLaneWeight`, `setAsset`, `setMaxTotalDeposits`, `setFee`, `setFeeRecipient`, `setPaused`; `investReserve` and `divestReserve` move idle cash between the strategy and the reserve. Two Gage-curated strategies hold earlier positions: Gage USDG Stocks `0x36b438761AA271d9852549F54E88283987977B7a` and Gage USDG Memes `0xc04a365061E5D3CF7f614cF353494294b0E3F0c9`. Both stopped taking deposits and funding new loans on 15 October 2026, when partner vaults took over lending; withdrawals, claims and settlement stay open.

## Source and ABIs

All 17 launch addresses, the extension contracts, the three earlier native engines and the adapter `0x2166…` have matched source records on Sourcify; links are in the [directory](https://docs.gage.cash/protocol/addresses.md). So do the USDG generation's Intent contracts: the core, its adapter, the factory, the quote verifier and the fill, cash-out, loop, private borrow and rollover routers. Source verification does not establish security. ABIs are the Foundry build outputs, one per contract and interface. The chain's Universal Router is a modified fork; anything that builds swap calldata for the entry router must target its ABI, which carries an extra `minHopPriceX36` field in the v4 swap struct.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.gage.cash/developers/contracts.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
