> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kamino.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Kamino Vault Bot

> Run an automated bot service that rebalances Kamino vaults on a schedule and moves capital out of a reserve when its safety score drops below the vault's risk threshold

The Vault Bot is an open source service that automates vault operations. It invests idle capital, rebalances allocations using a chosen strategy, and attempts to exit reserves that show signs of risk. Risk checks and rebalances run on a schedule, so the vault responds without manual updates. The bot signs as the vault's Allocation Admin.

## How the Bot Works

The bot runs two loops with separate switches. Danger detection runs only in the allocation loop, so the invest loop alone never exits a risky reserve.

Loop
What it does
Signer

Invest loop`INVEST_LOOP`
Sends permissionless invest instructions that move capital toward the weights already on chain. It never changes weights.
Any wallet with SOL

Allocation loop`ALLOCATION_REBALANCE_LOOP`
Runs danger checks, then writes new weights from the strategy for each vault that is due, then invests.
Allocation Admin

The allocation loop works in rounds, called passes. Each pass starts with danger checks, and passes run at most `DANGER_PASS_INTERVAL_SECONDS` apart, 300 by default, so risk is checked about every five minutes. Each vault still rebalances on its own `rebalanceFrequencySeconds`, 3,600 by default.

> [!WARNING]
>
> Every strategy except `UNCHANGED` overwrites weights the curator sets by hand on the vault's next rebalance. To control weights directly, set them with `FIXED_WEIGHTS` in the allocation config and restart the allocation loop, or switch the vault to `UNCHANGED`. The allocation loop reads its config only at startup.

> [accordion] How the Invest Loop Works
>
> The invest loop builds its vault list from `INVEST_VAULTS`, the vaults owned by `INVEST_OWNERS`, and, with `INVEST_UI_VAULTS` on, the vaults listed in the Kamino app. If the app's list fails to load, it invests only the configured vaults for that pass. With `INVEST_UI_VAULTS` off and the other two empty, it invests every vault on chain. With `INVEST_UI_VAULTS` on, an empty app list and no other vaults set skips the pass instead. An address that holds no vault is skipped and logged.
>
> The loop skips any vault with an exit in progress or a blacklisted reserve, and sends no deposits to reserves the allocation loop has blocked, though withdrawals still go through. After the allocation worker restarts, it keeps the last blocked list until the next successful pass. A vault is invested only when the amount to move, the larger of its deposits and its withdrawals, is more than `MIN_INVEST_TOKENS` whole tokens, and both the bot's delay (`MIN_SECONDS_SINCE_LAST_INVEST`) and the program's own delay have passed.
>
> Before investing, the loop creates missing token accounts and keeps small token balances in the invest signer to cover rounding, buying them through KSwap or by wrapping SOL within both slippage limits. If the program rejects an invest for one reserve, the loop skips that reserve for the vault for `RESERVE_INVEST_COOLDOWN_MS` while the others continue. More than one invest process can run, but all of them must use the same safety file and the same `ALLOCATION_CONFIG_PATH`. The invest loop rereads that config before each normal invest.

> [accordion] How Rebalancing Works
>
> Between passes, the allocation loop sleeps for the shortest of `DANGER_PASS_INTERVAL_SECONDS`, any vault's `rebalanceFrequencySeconds`, and the next scheduled data refresh. The time a pass takes adds to the gap.
>
> For a vault that is due, the strategy computes target weights and the bot writes every change in one transaction. After it confirms, the bot waits five seconds, reloads the vault, and invests. It invests after every due rebalance, even when the weights did not change, and a failed update means no invest for that vault.
>
> The bot checks that the Allocation Admin wallet holds a small amount of each vault's token, because that wallet pays the rounding on the invests and emergency withdrawals it sends. Without it, those transactions fail and the bot logs an error. Blacklisted reserves get zero weight. Reserves blocked from new funds keep their weight but receive no deposits, and the bot can lower their cap to enforce that. It never changes cToken caps.

> [accordion] How Failures and Retries Work
>
> A failed rebalance is retried after one pass interval, then after twice as long for each failure in a row, up to the vault's rebalance frequency. A vault that fails to load is skipped for that pass. If no vault loads, the pass counts as failed and retries after 10 seconds. An empty `allocationsConfig` leaves the loop idle with a warning.
>
> If a vault's weight changes do not fit in one Solana transaction, the bot sends none, skips that vault's invest, and logs whether a vault lookup table would make them fit.
>
> The bot combines each vault's on-chain lookup table with Kamino's managed tables from `https://api.kamino.finance/luts/managed`. If the managed tables fail to load, it uses the on-chain table alone. If the on-chain table fails to load, that vault's operation fails. After a failed send, the bot drops any table that is being deactivated and refreshes the managed list, but does not resend the transaction. A send with an unknown outcome may need a manual check.

***

## Strategies

A strategy computes target weights for every vault in an allocation config entry. The bot only updates reserves the vault already holds. The Vault Admin adds every reserve a strategy can use before the bot runs.

Goal
Strategy
Note

A set split
`FIXED_WEIGHTS`
Weights are shares: 1 and 3 mean 25% and 75%. The list must name every healthy reserve.

An even split
`EQUAL`
Gives every reserve the same weight.

Highest APY
`MAX_YIELD`
Applies the optimum at once.

Highest APY, moved gradually
`MAX_YIELD_DRIPPING`
Closes 20% of the gap per due rebalance by default. Set with `drippingRatePercent`.

Highest APY with a floor
`MAX_YIELD_WITH_FIXED_RESERVES`
Keeps a minimum combined share in a named set of reserves.

Even yields
`MAX_YIELD_STABLE`
Narrows the spread between reserve yields.

Danger exits only
`UNCHANGED`
Keeps current weights and reports APY.

`driftRatePercent` moves other strategies part of the way toward their target on each due rebalance. Setting `driftRatePercent` on a `MAX_YIELD_DRIPPING` vault fails config loading. A `RANDOM` strategy also exists for testing only.

> [accordion] How Strategies Set Weights
>
> `EQUAL`, `FIXED_WEIGHTS`, and `RANDOM` scale their targets to the vault's current weight total, keep the vault's unallocated share, and leave blocked reserves' weights alone. With no unallocated share, the bot can multiply a small weight total by a whole number to reduce rounding. These three do not check how much each reserve can take or return, so on-chain caps can make a later invest fall short or fail.
>
> The max-yield strategies check each reserve's room for deposits and withdrawals. If no allocation fits, the vault keeps its current allocation, and normal investing can be blocked when the current target is unsafe. They search a coarse grid, then refine the best areas, and may use a coarser step than `GRID_SEARCH_RESOLUTION` for vaults with many reserves. A search that reaches `GRID_SEARCH_MAX_CANDIDATES` or `GRID_SEARCH_MAX_MS` keeps the current allocation for that pass. Raising `GRID_SEARCH_RESOLUTION` is the first thing to try before raising those limits.
>
> Farm rewards count toward yield when `includeReservesSupplyFarmRewardsApy` is on, and a vault whose farm data fails to load skips its rebalance for that pass. `MAX_YIELD_WITH_FIXED_RESERVES` and `MAX_YIELD_STABLE` treat `reservesAllocationPercentageBPS` as a minimum for the search, not a guarantee, because capacity limits can still change the result. `MAX_YIELD_STABLE` reports APY but does not use it to break ties.

> [accordion] How Drift Works
>
> With `driftRatePercent` set, a strategy moves that share of the gap per due rebalance instead of jumping to the target. `UNCHANGED` does not drift.
>
> `MAX_YIELD_DRIPPING` uses `drippingRatePercent` instead and ignores minimum allocations. With `enforceUtilizationCap` on, it moves from actual token holdings and limits each reserve's utilization change to `maxUtilizationChangeBps`. Otherwise it moves from configured weights.
>
> Drift does not start a vault whose healthy weight total is zero, and very small gaps send no update. Exits for danger always happen at once, without drift.

***

## Danger Detection

Each check returns a safety score between zero and one, and the scores multiply. A reserve is exited when its combined score falls strictly below the threshold for the vault's `riskAppetiteMode`. The bot does not check DEX liquidity, full deposit caps, sudden borrowing spikes, or governance changes. The [danger catalog](https://github.com/Kamino-Finance/kvault-bot/blob/2.0.1/investing-bot/src/danger/danger_triggers_catalog.md) is the source for the thresholds below.

Risk appetite: exits when the combined score is below

`PARANOID`
0.5

`SENSIBLE`Default
0.3

`YOLO`
0.1

Signal
What the bot does
Lasts

Catastrophice.g. unexpected minting
Sets the reserve's weight to zero, attempts withdrawals, and blacklists the reserve.
Until cleared

Temporary
Sets the reserve's weight to zero and attempts withdrawals. From that moment, no vault sends the reserve new funds for 2,700 s.
Until the vault holds none

Dominance`maxVaultDominanceBps`
When set, exits at any risk appetite once the vault's share of the reserve reaches the limit. Handled like a temporary signal.
Until the vault holds none

An exit keeps retrying on every pass until the vault holds no weight and no tokens in the reserve. If a market price the checks need is older than `MARKET_PRICE_MAX_AGE_SECONDS`, 300 by default, the bot skips normal rebalancing for that pass rather than act on stale data. Exits already in progress still retry.

> [accordion] Danger Checks
>
> | Check | What it watches | Type |
> | - | - | - |
> | Infinite mint | A token's supply jumping by more than 50% between readings | Catastrophic: blacklists on one event |
> | Exchange-rate anomaly | A reserve's exchange rate moving the wrong way, or receipt tokens with no liquidity behind them | Catastrophic: blacklists on one event |
> | Supply APY spike | Supply APY above 20% | Gradual: exits alone only when severe |
> | Exit liquidity | Available liquidity compared to the vault's position | Gradual: exits alone only when severe |
> | Oracle divergence | The oracle price compared to the KSwap market price | Gradual: exits alone only when severe |
> | Stale or zero oracle price | How old the oracle price is, and prices at or near zero | Gradual: exits alone only when severe |
> | Secondary-market depeg | Stablecoins drifting from 1 USD, and liquid staking tokens trading below SOL | Gradual: exits alone only when severe |
> | Market utilization | Borrowed compared to supplied, above 90% | Gradual: exits alone only when severe |
> | Dominant depositor | The vault's share of the reserve's supply | Red flag: adds to other signals |

> [accordion] Check Thresholds
>
> | Check | Score |
> | - | - |
> | Infinite mint | 0 when supply rises more than 50% between readings. |
> | Exchange-rate anomaly | 0 when the rate rises more than 0.1%, or receipt tokens have no liquidity behind them. |
> | Supply APY spike | 0 when supply APY is above 20%. |
> | Exit liquidity | Available liquidity as a share of the vault's position: 1 at full coverage, 0.5 at 65%, 0 at 30% or less. |
> | Oracle divergence | Gap between the oracle and KSwap prices: 1 up to 2%, about 0.39 at 5%, 0 from 10%. |
> | Stablecoin depeg | Gap from 1 USD in either direction, using whichever of the market and oracle prices is further: 1 up to 0.5%, 0 at 2%. Alone, it exits `PARANOID` at about 0.88%, `SENSIBLE` at 1.24%, and `YOLO` at 1.72%. |
> | Liquid staking token discount | Discount to SOL: 1 up to 1%, 0 at 10%. |
> | Market utilization | 1 up to 90%, 0.5 at 95%, 0.1 at 99%, 0 at 100%. |
> | Dominant depositor | The vault's share of the reserve's supply: 1 up to 10%, 0.7 at 50%, 0.3 from 90%. Alone, it exits only `PARANOID` vaults, above 70%. At or above `maxVaultDominanceBps`, the score is 0. |

> [accordion] Stale Price Scores
>
> | Oracle price age | Score | Risk modes that exit |
> | - | - | - |
> | Up to `MAX_STALE_PRICE_DURATION_SECONDS`, 1 hour by default | 1 | None |
> | Past 1×, up to 2× that limit | 0.4 | `PARANOID` |
> | Past 2×, up to 4× that limit | 0.2 | `PARANOID`, `SENSIBLE` |
> | Past 4× that limit | 0 | All |

> [accordion] How Exits Run
>
> To exit, the bot blacklists catastrophic reserves, starts the 2,700 second no-new-funds period for temporary ones, and records the exit in the safety file. It then sets the reserves' weights to zero two at a time, waits five seconds, reloads the vault, and withdraws from each reserve whose weight is now zero. If a batch fails, it retries one reserve at a time.
>
> Exit transactions are sent even if a test run of the transaction fails, so the bot does not wait while capital is at risk. After three failed exits for the same reserve in a vault, it only sends exits that pass the test run first. A successful exit or a restart resets this. Failures explained by an earlier skipped withdrawal, or caused by an instruction the bot adds such as a Jito tip, do not count toward the three.
>
> A temporary signal on a reserve the vault does not hold still starts the no-new-funds period. The two checks that look at the vault's own position, exit liquidity and dominant depositor, are skipped when the reserve already scores 0.

> [accordion] How Prices and Collateral Are Checked
>
> When a reserve's oracle price is stale, reads zero, or falls below one millionth of the KSwap market price, the bot first stops sending new deposits to the reserve. If the problem continues and the score falls below the vault's threshold, the bot moves the vault's capital out. A price that reaches the reserve's own oracle age limit also blocks new funds at once, separately from the bot's stale timer. A zero price that keeps refreshing blocks deposits but does not cause an exit just by lasting. A reserve without a valid oracle price setup gets no age check.
>
> Stablecoins are compared to 1 USD, except a fixed list of non-USD and yield-bearing stablecoins such as EURC, VGBP, vCHF, PRIME, and USD+, which still get the oracle divergence check. Liquid staking tokens are compared to SOL at one to one, not the stake pool's higher redemption rate. Both use Kamino's token flags feed. If that feed is down, the bot uses its last copy. With no copy, the pass fails.
>
> The bot also checks the collateral in each lending market the vault lends into: every reserve in that market with a positive loan-to-value or an elevation group, hidden ones included. An unexpected mint of a collateral token blacklists every reserve the vault holds in that market. A collateral price that stops updating or reads zero blocks new funds to those reserves, and the vault exits them once the price is old enough to cross the risk threshold. Each market is checked separately, even when a token appears in more than one.

> [accordion] What Happens When Data Fails
>
> The bot needs a fresh KSwap price for every token it checks, and asks again after one and two seconds. If a price is still missing or too old, or a required read fails, the bot makes no new decisions that pass but keeps working on exits already in progress.
>
> If only a market's reserve list or a collateral check cannot be read, the affected reserves get no new funds for that pass, with no exit. If the chain time cannot be read, or the pass runs past its time limit of the number of vaults × `RPC_REQUEST_TIMEOUT_MS` × 4, the pass stops.
>
> After three failed passes in a row, `/ready` reports the bot as not ready. A single vault that goes unchecked three passes in a row is logged on every pass but does not affect `/ready`.

***

## Keys and Permissions

The bot holds up to two keys. The Vault Admin can also sign allocation updates, but it carries authority the bot does not need, so it stays with the curator.

Signer
What it can do
Held by the bot

Invest signer`INVESTOR_SECRET_PATH`
Sends permissionless invest instructions.
Yes

Allocation Admin`ALLOCATION_ADMIN_SECRET_PATH`
Updates weights and caps of reserves already in the vault.
Yes

Vault Admin
Adds reserves and holds broader authority over the vault.
No

If the bot's key is neither a vault's Allocation Admin nor its Vault Admin, the bot skips that vault's rebalance and logs it, and emergency exits for that vault fail. Dry run does not check the key, so confirm it before going live.

***

## Restarts and Outages

The safety file at `DANGER_BLACKLIST_PATH` keeps the bot's long-lived state across restarts. Everything else lives in memory.

State
Where it lives
After a restart

Blacklists, pending exits, original caps
Safety file on disk
Kept

Cooldowns, failure counters, rebalance schedule
Memory
Reset

A restart rebalances every configured vault on its first pass, and resets the baselines the bot uses to detect unexpected minting.

If the bot stops, Kamino's sync crank keeps investing vaults toward their current weights. The weights stay frozen and no danger exits happen until the bot is running again.

> [accordion] Safety State
>
> | State | Applies to | Kept in | Ends when |
> | - | - | - | - |
> | Blacklist | A reserve, in all vaults | Safety file | It is cleared manually |
> | Pending exit | A vault and reserve | Safety file | The vault holds no weight and no tokens in the reserve |
> | Deposit freeze | A vault and reserve | Safety file and the on-chain cap | The reserve recovers and its cap is restored |
> | No-new-funds period | A reserve, in all vaults | Memory | `REINVEST_COOLDOWN_SECONDS` pass, or a restart |
> | Price or collateral block | A reserve, for one pass | Memory | A successful pass clears the cause |
> | Reserve invest cooldown | A vault and reserve | Memory | `RESERVE_INVEST_COOLDOWN_MS` pass, or a restart |
> | Failed exit count | A vault and reserve | Memory | A successful exit, or a restart |
> | Check baselines | A reserve | Memory | A restart. Mint baselines also expire after 24 hours. |
> | Zero price timer | A reserve | Memory | A normal price, removal of the oracle price, or a restart |

> [accordion] How the Safety File Works
>
> The safety file holds three lists: `blacklistedReserves`, `pendingEvacuations`, and `depositFreezes`. The repository's `danger_blacklist_example.json` shows the blacklist format, and the other two lists appear once the bot writes them. The bot writes the file under a lock file next to it and replaces it in one step, so a crash never leaves it half written. A missing or blank file counts as empty if its folder exists. An unreadable or invalid file stops the danger checks and the invest loop until it is fixed.
>
> A pending exit is retried on every pass, even after the signal recovers, and blocks the vault's strategy and the invest loop until the vault holds nothing in the reserve.
>
> When the bot lowers a cap to block deposits, it records the original cap before sending the change. Once the reserve recovers, it restores that cap, but only if the cap is still the one the bot set. If someone else changed the cap, the bot leaves it and drops the record. While a cap change the bot sent can still land, it keeps the freeze in place. Records also clear when a reserve leaves the vault, and failed cap updates retry on the next pass.

***

## Set Up the Bot

The steps below install the bot, test it with a dry run, and take it live. Settings and defaults on this page are for kvault-bot v2.0.1. Newer releases are documented in the [README](https://github.com/Kamino-Finance/kvault-bot#readme).

Before starting, the bot requires:

* Node.js, which Kamino runs on 26.12.1.
* Yarn Classic 1.22.22.
* A Solana RPC endpoint.
* Solana keypair files in JSON format, as created by `solana-keygen`, for the Allocation Admin and, if the invest loop runs, the invest signer.
* SOL in each signer wallet for fees, plus a little extra in the invest signer.
* A small amount of each vault's token in the Allocation Admin wallet, such as 0.01 USDC for a USDC vault.
* A server with persistent storage for the safety file.

**Step 1**

### Install and Build

Clone the repository, install its dependencies, and build its three packages.

```bash theme={"theme":"css-variables"}
git clone https://github.com/Kamino-Finance/kvault-bot.git
cd kvault-bot
yarn install --frozen-lockfile --production=false
yarn build
```

[View Code](https://github.com/Kamino-Finance/kvault-bot)

**Step 2**

### Create the Profile

Create `.env.mainnet-beta` in the repository root. This profile runs only the allocation loop, in dry-run mode.

```bash theme={"theme":"css-variables"}
RPC_ENDPOINT=<RPC_URL>
INVEST_LOOP=false
ALLOCATION_REBALANCE_LOOP=true
ALLOCATION_DRY_RUN=true
ALLOCATION_ADMIN_SECRET_PATH=/path/to/allocation_admin.json
ALLOCATION_CONFIG_PATH=/path/to/allocation_config.json
DANGER_BLACKLIST_PATH=/path/to/state/danger_blacklist.json
```

> [!NOTE]
>
> Use absolute paths. Relative paths resolve from the `investing-bot` folder.

> [!WARNING]
>
> The repository's `.env.example` turns on the invest loop and `INVEST_UI_VAULTS`. The invest loop has no dry run, so a copy left unchanged invests every vault listed in the Kamino app as soon as it starts. It also sets a 10-second invest interval, a 100-token minimum, and relative paths. Start from the profile above instead.

> [accordion] Required Settings
>
> | Setting | Default | What it does |
> | - | - | - |
> | `RPC_ENDPOINT` | None | Primary RPC URL. At least one of `RPC_ENDPOINT`, `RPC_ENDPOINTS`, or `RPC_ENDPOINT_*` is required. |
> | `INVEST_LOOP` | `false` | Runs the invest loop. |
> | `ALLOCATION_REBALANCE_LOOP` | `false` | Runs the allocation loop, including danger detection, in a worker thread. |
> | `INVESTOR_SECRET_PATH` | `/run/secrets/investor_keypair` | Keypair that signs invest transactions. Any wallet with SOL works. |
> | `ALLOCATION_ADMIN_SECRET_PATH` | `/run/secrets/allocation_admin` | Keypair of the vaults' Allocation Admin. |
> | `ALLOCATION_CONFIG_PATH` | Empty | Allocation config file. The invest loop also reads it to enforce utilization limits. |
> | `DANGER_BLACKLIST_PATH` | `./danger_blacklist.json` | Safety file, on persistent storage. Its folder must exist. Required in production. Outside production, an unset value falls back to a temporary file for development only. |
> | `NODE_ENV` | None | `production` makes `DANGER_BLACKLIST_PATH` required and switches logs to JSON. |
> | `PROFILE` | None | Profile file to load, `.env.PROFILE`. Set it in the shell. Defaults to `CLUSTER`. |
> | `CLUSTER` | `mainnet-beta` | Solana cluster. Also picks the default profile. Changing it does not change the program addresses. |

> [accordion] RPC and Transaction Settings
>
> | Setting | Default | What it does |
> | - | - | - |
> | `WS_ENDPOINT` | None | WebSocket URL. When unset, derived from the RPC URL by switching `https` to `wss`. |
> | `RPC_ENDPOINTS` | `[]` | Fallback RPCs as a JSON array of objects with `url` and optional `dedicatedWriteUrl`, `name`, and `feePercentileSupportOverride`. |
> | `RPC_ENDPOINT_*` | None | One fallback RPC URL per variable, ordered by suffix. A suffix containing `FEES_TRITON_STYLE`, `FEES_HELIUS_STYLE`, or `FEES_NONE` sets its fee API support. |
> | `USE_RPC_CONFIG_FILE` | `false` | Switches to indexed mode, which uses `RPC_READ_*`, `RPC_SEND_*`, and `RPC_PRIORITY_FEE_*`. |
> | `RPC_READ_*` | None | Indexed mode: read RPC URLs, such as `RPC_READ_1`. At least one is required. |
> | `RPC_SEND_*` | None | Indexed mode: optional write RPC URL for the read URL with the same number. |
> | `RPC_PRIORITY_FEE_*` | None | Indexed mode: RPC URLs with a priority fee API, ending in `_TRITON` or `_HELIUS`. |
> | `RPC_MULTICAST_ENDPOINTS` | `[]` | Extra endpoints that also receive every transaction, as a JSON array of objects with `name` and `connection`. |
> | `RPC_MULTICAST_ENDPOINT_*` | None | One extra endpoint URL per variable, named after its suffix in lowercase with underscores as hyphens, so `RPC_MULTICAST_ENDPOINT_IRONFORGE` is `ironforge`. |
> | `RPC_REQUEST_TIMEOUT_MS` | `120000` | Timeout for one RPC request. |
> | `EXTERNAL_REQUEST_TIMEOUT_MS` | `30000` | Timeout for one request to KSwap or the token flags feed. |
> | `SIMULATE` | `true` | Test-runs each transaction to estimate compute units before sending. |
> | `SPAM` | `false` | Sends the same transaction several times. |
> | `MULTICAST_JITO` | `false` | Also sends transactions to Jito validators with a tip. |
> | `PRIORITY_FEE_PERCENTILE` | `50` | Priority fee percentile from 0 to 100, `true` for the 50th, or `false` to turn it off. Needs an RPC with a fee API. |
> | `PRIORITY_MICRO_LAMPORTS_PER_CU_DEFAULT` | `5000` | Fallback priority fee, in micro-lamports per compute unit. Must sit between the minimum and maximum. |
> | `PRIORITY_MICRO_LAMPORTS_PER_CU_MIN` | `1` | Lowest priority fee. |
> | `PRIORITY_MICRO_LAMPORTS_PER_CU_MAX` | `4000000` | Highest priority fee. |

> [accordion] Invest Loop Settings
>
> | Setting | Default | What it does |
> | - | - | - |
> | `INVEST_VAULTS` | Empty | Vaults to invest, separated by commas or spaces. |
> | `INVEST_OWNERS` | Empty | Owners whose vaults are also invested. |
> | `INVEST_UI_VAULTS` | `false` | Also invests the vaults listed in the Kamino app, read from `https://cdn.kamino.finance/resources.json`. |
> | `INVEST_MIN_SLOT_BYPASS_VAULTS` | Empty | Vaults exempt from `MIN_SECONDS_SINCE_LAST_INVEST`. The program's own delay still applies. |
> | `MIN_INVEST_TOKENS` | `10` | Invests a vault only when its move is larger than this many whole tokens, counted per token. |
> | `MIN_SECONDS_SINCE_LAST_INVEST` | `1200` | Shortest time between two invests of the same vault. |
> | `LOOP_INTERVAL_MS` | `600000` | Sleep between invest passes. |
> | `RESERVE_INVEST_COOLDOWN_MS` | `600000` | How long a reserve is skipped for a vault after the program rejects its invest. `0` turns it off. |
> | `VAULT_RESERVES_MAX_UNIQUE_RESERVES_PER_BATCH` | `50` | Reserves loaded per batch. |

> [accordion] Allocation and Danger Settings
>
> | Setting | Default | What it does |
> | - | - | - |
> | `ALLOCATION_DRY_RUN` | `false` | Logs allocations without sending them. The invest loop still sends. |
> | `GRID_SEARCH_RESOLUTION` | `0.01` | Step size of the max-yield search, as a share of vault assets, above 0 and up to 1. Smaller steps find better yield but cost far more compute. |
> | `GRID_SEARCH_MAX_CANDIDATES` | `5000000` | Most allocations one search can try for a vault. |
> | `GRID_SEARCH_MAX_MS` | `300000` | Longest one search can run for a vault. |
> | `DANGER_PASS_INTERVAL_SECONDS` | `300` | Longest sleep between allocation passes. |
> | `MARKET_PRICE_MAX_AGE_SECONDS` | `300` | Oldest KSwap price the bot accepts. Older prices pause normal rebalancing and the invest loop's token purchases. |
> | `MAX_STALE_PRICE_DURATION_SECONDS` | `3600` | Oracle price age at which the stale price check starts lowering a reserve's score. |
> | `REINVEST_COOLDOWN_SECONDS` | `2700` | How long a reserve gets no new funds after a temporary exit. |
> | `KAMINO_TOKEN_FLAGS_URL` | `https://tokens.kamino.finance/tokens-flags.json` | Feed that marks which tokens are stablecoins or liquid staking tokens. |

> [accordion] Other Settings
>
> | Setting | Default | What it does |
> | - | - | - |
> | `KSWAP_API_BASE_URL` | `https://api.kamino.finance/kswap` | KSwap API for swap routes and market prices. |
> | `KSWAP_API_KEY` | None | Optional KSwap API key, sent in the `x-api-key` header. |
> | `DEFAULT_SWAP_SLIPPAGE_BPS` | `100` | Swap slippage tolerance, in basis points, from 0 to 9999. |
> | `DEFAULT_PRICE_SLIPPAGE_BPS` | `150` | Largest gap from the reference price allowed before a swap is signed, in basis points, from 0 to 9999. |
> | `KLEND_PROGRAM_ID` | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` | Kamino Lend program address. |
> | `KVAULTS_PROGRAM_ID` | `KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd` | Kamino Vaults program address. |
> | `SERVER` | `true` | Runs the health server. |
> | `SERVER_PORT` | `8080` | Health server port, from 1 to 65535. A blank value uses the default. |
> | `LOOP_HEARTBEAT_TIMEOUT_MS` | 3 × `RPC_REQUEST_TIMEOUT_MS` | The health server reports not ready after a loop sends no heartbeat for this long. |
> | `VERBOSE` | `false` | Logs the details of each allocation computation. |
> | `LOG_LEVEL` | `info` | Log level. |

> [accordion] How Profiles and Paths Work
>
> `PROFILE` in the shell selects `.env.PROFILE` in the repository root. Without `PROFILE`, `CLUSTER` selects it, and the default is `mainnet-beta`. Settings already set in the shell override the profile. The profile can reference other environment variables, and the bot expands them on load. Without a profile file, the bot uses the shell environment alone. `NODE_OPTIONS` must be set in the shell, because Node reads it before the profile loads.
>
> `yarn start` and `yarn cli` run from the `investing-bot` folder, so relative paths, including `--path`, resolve from there. If a keypair file is not found, the bot also looks in the parent folder.
>
> A blank value for a number setting is rejected at startup. The bot sets its own time zone to UTC, so all log timestamps are in UTC.

**Step 3**

### Write the Allocation Config

Assign a strategy to each vault. Each entry in `allocationsConfig` gives one strategy to a list of vaults, written as plain addresses or as objects with their own settings. This config splits one vault 25/75 between two reserves.

```json theme={"theme":"css-variables"}
{
  "allocationsConfig": [
    {
      "strategy": "FIXED_WEIGHTS",
      "vaults": [
        {
          "vault": "<VAULT_ADDRESS>",
          "fixedReserves": [
            { "reserve": "<RESERVE_A_ADDRESS>", "weight": 1 },
            { "reserve": "<RESERVE_B_ADDRESS>", "weight": 3 }
          ]
        }
      ],
      "rebalanceFrequencySeconds": 3600,
      "riskAppetiteMode": "SENSIBLE"
    }
  ]
}
```

> [accordion] Allocation Config Fields
>
> | Field | Set on | Default | What it does |
> | - | - | - | - |
> | `strategy` | Entry, or vault to override | Required on the entry | Strategy for the entry's vaults. |
> | `vaults` | Entry | Required | Vault addresses or vault objects. An empty list is ignored with a warning. |
> | `vault` | Vault | Required | Vault address. |
> | `rebalanceFrequencySeconds` | Entry or vault | `3600` | Shortest time between rebalances. An entry value overrides every vault's own value. |
> | `riskAppetiteMode` | Entry | `SENSIBLE` | Danger threshold: `PARANOID`, `SENSIBLE`, or `YOLO`. Any other value fails loading. |
> | `includeReservesSupplyFarmRewardsApy` | Entry or vault | `true` | Counts farm reward APY when comparing yields. A vault value wins. |
> | `allocationDryRun` | Entry or vault | `false` | Dry run. The entry value applies to plain addresses, and vault objects use their own. `ALLOCATION_DRY_RUN=true` forces it for all vaults. |
> | `driftRatePercent` | Entry or vault | None | Share of the gap closed per due rebalance, above 0 and up to 100. Unset applies the target at once. Not allowed with `MAX_YIELD_DRIPPING`. |
> | `drippingRatePercent` | Entry or vault | `20` | `MAX_YIELD_DRIPPING` only: share of the gap closed per due rebalance, above 0 and up to 100. |
> | `enforceUtilizationCap` | Entry or vault | `false` | `MAX_YIELD_DRIPPING` only: limits how far each move can shift a reserve's utilization. |
> | `maxUtilizationChangeBps` | Entry or vault | `100` | `MAX_YIELD_DRIPPING` only: largest utilization change per move, in basis points, above 0 and up to 10000. Turn the limit off with `enforceUtilizationCap`, not 0. |
> | `maxVaultDominanceBps` | Entry or vault | None | Vault's share of a reserve's supply, in basis points, at or above which the bot exits at any risk appetite. Above 0 and up to 10000. |
> | `fixedReserves` | Vault | None | For `FIXED_WEIGHTS`: `reserve` and `weight` pairs. For `MAX_YIELD_WITH_FIXED_RESERVES` and `MAX_YIELD_STABLE`: the reserves that share a minimum allocation. |
> | `reservesAllocationPercentageBPS` | Vault | None | Minimum combined allocation for `fixedReserves`, in basis points, from 0 to 10000. |
> | `fixedReservesStrategy` | Vault | `EQUAL` | Label only. It must name a known strategy but does not change which one runs. |

> [accordion] How the Config Is Validated
>
> The bot checks the file at startup and rejects invalid strategies, addresses, duplicates, frequencies, flags, rates, and basis point ranges. It does not check that an address belongs to a real vault.
>
> Before each rebalance, the bot checks that every reserve in `fixedReserves` is already in the vault's allocation list. A vault given as a plain address has no `fixedReserves`.
>
> A `driftRatePercent` set on an entry also fails loading when one of its vault objects switches to `MAX_YIELD_DRIPPING`. In that case, set the rate on the other vault objects instead.

**Step 4**

### Create the Safety File

Create the folder on persistent storage, then initialize the file.

```bash theme={"theme":"css-variables"}
mkdir -p /path/to/state
yarn cli danger init --path /path/to/state/danger_blacklist.json
```

> [!NOTE]
>
> The CLI does not load the profile. Pass `--path` with every `danger` command.

**Step 5**

### Run a Dry Run

Start the allocation loop without sending transactions. The logs show the vault set, strategy, excluded reserves, and target weights.

```bash theme={"theme":"css-variables"}
PROFILE=mainnet-beta INVEST_LOOP=false ALLOCATION_REBALANCE_LOOP=true ALLOCATION_DRY_RUN=true yarn start
```

> [!NOTE]
>
> Dry run covers only the allocation loop and writes nothing to the safety file. It does not check that the key is each vault's Allocation Admin. The invest loop sends transactions whenever it is on.

**Step 6**

### Go Live

Before going live, check each vault's reserve whitelist, caps, minimum amounts, and invest delays. The program can reject a transaction even when the bot's own checks pass.

Set `ALLOCATION_DRY_RUN=false` in the profile and start the bot in production mode.

```bash theme={"theme":"css-variables"}
NODE_ENV=production PROFILE=mainnet-beta yarn start
```

> [!NOTE]
>
> To run the invest loop too, set `INVEST_LOOP=true` and `INVESTOR_SECRET_PATH`, and list the vaults with `INVEST_VAULTS`, `INVEST_OWNERS`, or `INVEST_UI_VAULTS`. With all three empty, the invest loop invests every vault on chain.

**Step 7**

### Monitor and Recover

The health server on port 8080 exposes `/health`, `/live`, and `/ready`. `/ready` fails when a loop stops sending heartbeats or danger passes keep failing.

A blacklisted reserve stays blacklisted until it is cleared manually. Inspect the safety file, fix the cause, then clear the reserve.

```bash theme={"theme":"css-variables"}
yarn cli danger list --path /path/to/state/danger_blacklist.json
yarn cli danger clear-reserve <RESERVE_ADDRESS> --path /path/to/state/danger_blacklist.json
```

> [!WARNING]
>
> Never replace a live safety file with an empty one or delete its deposit freeze records. They hold the original caps the bot restores.

> [accordion] Commands
>
> | Command | What it does |
> | - | - |
> | `yarn build` | Compiles the `investing-bot`, `tx`, and `logger` packages. |
> | `yarn build:prod` | Cleans the build output, then compiles. |
> | `yarn start` | Runs the bot from source. Build first. |
> | `yarn dry-run` | Uses the `.env.local` profile with allocation dry run on and a higher Node memory limit. It still sends invest transactions if that profile turns on `INVEST_LOOP`. |
> | `yarn cli print-rebalance-strategies` | Lists the available strategies. |
> | `yarn cli danger init --path <PATH>` | Creates the safety file if it does not exist. |
> | `yarn cli danger list --path <PATH>` | Shows blacklists, pending exits, and deposit freeze records. |
> | `yarn cli danger clear-reserve <RESERVE_ADDRESS> --path <PATH>` | Removes one reserve from the blacklist. |
> | `yarn cli danger clear-all --path <PATH>` | Removes every reserve from the blacklist. |
> | `yarn config:generate` | Regenerates `.env.example` and the README tables from the code. |
> | `yarn config:check` | Checks that `.env.example` and the README tables match the code. |
> | `yarn lint` | Runs Prettier and ESLint. |
> | `yarn lint:fix` | Runs Prettier and ESLint with fixes. |
> | `yarn clean` | Deletes the build output. |
> | `yarn clean:deps` | Deletes all installed dependencies. |
> | `yarn clean:all` | Deletes the build output and all installed dependencies. |
> | `yarn test`, `yarn test-localnet` | Not usable as shipped. The repository does not include its tests, fixtures, or localnet files. |

> [accordion] How Recovery Works
>
> The CLI does not load the profile. Without `--path`, it uses an exported `DANGER_BLACKLIST_PATH`, then `./danger_blacklist.json` in the `investing-bot` folder. Run commands from the repository root.
>
> Clear commands send no transactions. They keep pending exits, deposit freeze records, and no-new-funds periods, and the running bot picks up cleared entries on its next pass without a restart.
>
> Clear a reserve only after its cause is fixed, because an active catastrophic signal blacklists it again. After clearing, keep the allocation loop running with dry run off for the affected vaults, and check after a successful pass that exits have finished and caps are where they should be.

> [accordion] How Health Checks Work
>
> Use `/ready` as the deployment readiness probe. It requires a heartbeat from every enabled loop and successful danger passes, and the bot rechecks it every 15 seconds. With no loop turned on, the process runs only the health server. Settings for the enabled loops are checked at startup, before any loop starts.
>
> The allocation loop runs in a separate worker with a 4 GB limit on its long-lived memory and 2 GB for short-lived memory. If the worker crashes, the bot restarts it up to three times, five seconds apart, and a completed pass resets that count. A worker that stays unhealthy needs a full process restart.
>
> `SIGINT` and `SIGTERM` stop the worker, then the health server. The process exits after 20 seconds if shutdown has not finished. Production logs are JSON. `LOG_LEVEL` sets the level, and `VERBOSE=true` adds allocation detail.

> [card] [Allocations](https://docs.kamino.com/curators/vaults/concepts/allocations.md)
>
> Weight, cap, type, and priority mechanics.

> [card] [Roles & ownership](https://docs.kamino.com/curators/vaults/concepts/roles-and-ownership.md)
>
> Vault Admin, Allocation Admin, and Farm Authority.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.