> 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/sdk-earn.md).

# Earn with gage-sdk

Earn with gage-sdk: deposit into and withdraw from a partner vault, exit now through the exit desk, collect, and create and manage a vault of your own, from your own app or agent.

Only partner vaults lend on gage: a wallet or a contract lends by depositing into one, never by funding a loan itself. Every loan a partner vault funds has a fixed cost and no liquidation: it is never closed early because a price moves, and if it is not repaid by the end of its term the vault keeps the collateral and nothing else is taken. **You may end up holding the collateral instead of USDG.** See [Partner vaults](https://docs.gage.cash/earn/partner-vaults.md).

## Deposit

Anyone can create a partner vault, and the list comes in address order: neither a vault's place in it nor its name says who runs it or on what rules. Choose by its manager and its rules, then name that vault (`chosen`, its address).

```ts
const { vaults } = await gage.earnVaults();
const vault = vaults.find((v) => v.vault.toLowerCase() === chosen.toLowerCase());
// A vault that lends USDG names its figures in USDG; one that lends another asset names them in that asset.
if (!vault?.lends || !("totalAssetsUSDG" in vault)) throw new Error("That vault takes no USDG deposits now");
return gage.run({ action: "earn_deposit", vault: vault.vault, amount: parseUnits(usdg, 6).toString() }, signer);
```

`earn_deposit` takes `amount` in the vault's own asset (USDG, or the stock token of a stock token's vault), approves exactly that, and deposits for at least what it buys now less `maxSlippageBps`. You may end up holding the collateral instead of USDG.

While a loan past its end is not booked, a vault takes no deposit or withdrawal: the plan settles those loans first (anyone may, and gage's keeper does each pass) and answers `again: true`; `run()` plans the deposit again once the settle is mined. Booking a loan unpaid at its end writes it off, which lowers the share price.

## Withdraw

```ts
const withdrawn = await gage.run({ action: "earn_redeem", vault }, signer);
```

`earn_redeem` withdraws `shares`, or everything the vault can pay the wallet now. A vault pays withdrawals from its free cash; what it has lent comes back as its loans repay or end. `vaultFreeCash({ vault })` says what it can pay now, and what comes back by day, if the loans are repaid. Where free cash is what limits it, the withdrawal stays a basis point under it, as a share's value grows while the transaction is on its way.

## Exit now

A holder whose balance is more than the vault can pay now need not wait: `earn_exit_now` sells one of the vault's loans for them through the chain's exit desk, as Exit now on gage.cash does. Preview it first:

```ts
const plan = await gage.prepare({ action: "earn_exit_now", wallet, vault });
return { holding, exit: holding.exit ?? null, summary: plan.summary, preview: plan.preview ?? null, next: plan.next?.label ?? null, notes: plan.notes };
```

* Your shares are committed at the desk, which lists one of the vault's loans: over ten minutes its price falls from book value plus 99% of what the loan has still to earn, no further than your own share of that loan can pay the buyer's discount, which you pay. A small share sets a high floor, so the listing may not sell. Your shares stay yours until a sale.
* The first vault that buys the loan pays you at today's share value, in the sale's own transaction; the desk owes it to you until you collect it (`earn_exit_collect`, or `collect`). A listing that ends unsold leaves the next one to list (`earn_exit_list`); `earn_exit_cancel` withdraws the exit before a sale. A request lasts 24 hours.
* You leave at today's share value. What you give up is your share of what the vault's loans have still to earn, if they are repaid, plus any discount the sale takes from your share of the sold loan. The plan's `preview` says about how much, what you receive and the steps in time. Like a withdrawal, exit now avoids losses on loans that default after you leave; the holders who stay bear them.
* `portfolio(wallet)` gives each holding's open exit and its stage, and what the desk owes the wallet (`exitOwed`).

```ts
const { exitOwed } = await gage.portfolio(signer.address);
if (!exitOwed?.some((x) => BigInt(x.amount) > 0n)) return null;
return gage.run({ action: "earn_exit_collect" }, signer);
```

A rehypo pool's LP exits the same way through the pool's source for a token: `rehypo_exit_now { source }`. The buyer's discount comes out of the source's share, which belongs to the pool's LPs who stay. See [Lender AMM](https://docs.gage.cash/developers/lender-amm.md).

## Collect

`collect` gathers what is ready for the wallet: vault earnings, collateral the vaults recovered from loans written off and backing added to them, the sGAGE of partner vaults, and what exit sales paid, at most twenty claims at a time. A claim that would revert now is left out, and its note says so. A written-off loan's collateral reaches its pocket once the vault's `recover` is called, which gage's keeper does each pass and anyone may.

## Create a vault

Anyone may create a partner vault: one asset, tokens of one universe, a free name. Creating and managing one take gage-sdk 0.8.0 or later.

```ts
const made = await gage.run({ action: "create_vault", name, term: 604_800, feeBps: 1_000, maxLoan: parseUnits(largestLoan, 6).toString() }, signer);
return { status: made.status, vault: made.vault ?? null, sent: made.sent.map((s) => s.hash) };
```

`create_vault` makes the signer its manager for good, and `run` answers the new vault's address. Left out, a vault lends USDG against every stock and commodity gage admits, keeps no cash free, pays a priority fee of at most 20% of each loan's return, funds Loan grade B and up, and buys no running loan. The input names otherwise: `asset`, `universe` (`ecosystem` for meme and utility coins), `collateral`, `cashKeptFreeBps`, `priorityFeeBps`, `minRateGrade`, `buyLoans`, and `buysOnly` for a vault that buys running loans alone.

For a Safe, `createVault` answers the call, simulated from the Safe now, and the same as a Safe{Wallet} Transaction Builder file, and signs nothing; its owners load the file and sign there:

```ts
const { calls, safeBatch, collateral, notes } = await gage.createVault({ curator: safe, name, term: 604_800, feeBps: 1_000, maxLoan: "1500000000" });
```

A vault for a DEX's pool has its own guide: [Create your pool vaults](https://docs.gage.cash/developers/pool-vaults.md).

## Manage a vault

`vault_manage` carries a vault's manager's calls, as Manage on gage.cash sends them, each field one transaction, read from the chain alone: `name`, `paused`, `fillersOpen` (gage's automatic funding), `priorityFeeBps`, `feeRecipient`, the limits (`maxLoan`, `maxPerTokenBps`, `cashKeptFreeBps`, `minRateGrade`, `stockBps`, `memeBps`, `ecosystemBps`, `commodityBps`), `buyLoans`, `addTokens`, `removeTokens`, `applyTokens`, `dropTokens`, `apply`, `drop`, `listLoan` and `cancelListing`.

The name, pause, automatic funding, priority fee ceiling and fee recipient apply at once. Among the limits, buying and tokens, a change that tightens the vault applies at once, and one that loosens it waits three hours, so depositors see it coming, then `apply` makes it so; anyone may, and `drop` takes it back. What the vault has already is left out, so it can be prepared again after each transaction until `status` is `done`.

A manager cannot withdraw depositors' assets. Two calls move money all the same, and the plan says how much of it. A new `feeRecipient` takes the fees not yet claimed too. A running loan listed for sale falls in about five minutes from book value plus 99% of what it has still to earn to book value plus 50% of it, and stays there until the listing ends: what a sale gives up, the vault's depositors bear.

`vaultOnChain({ vault })` reads what it is set to now and what waits:

```ts
const { settings, waiting } = await gage.vaultOnChain({ vault });
```

## With gage's index off

Leaving goes on while gage's index gives no answer. `earn_redeem` and the exits read the vault itself, and a settlement due is booked first from the records its factory's exit desk names; where none names them, it refuses `SETTLEMENT_DUE` (`retryable`) until the index answers. A deposit still needs the index.

`vaultOnChain({ vault, wallet })` reads one vault from the chain alone, and what it can pay the wallet now, with the call that withdraws that and its gas.

```ts
const { holder, settlementDue } = await gage.vaultOnChain({ vault, wallet });
return { settlementDue, payableNow: holder?.payableNow ?? "0", call: holder?.withdraw ?? null };
```


---

# 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/sdk-earn.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.
