# Deposits & withdrawals

> The ERC-7540 request, roll and claim flow for depositing into and redeeming from a vault, with viem code and the read API.

Source: https://docs.degenhive.ai/vaults/depositors

A vault takes deposits and pays redemptions once a day. You request, the daily roll settles every request at one share price, and you claim. This page covers each call for depositors, wallets and integrators.

> [!IMPORTANT]
> Vaults are not deployed yet and not externally audited. `VAULT` and `USDC` in the code below are placeholders; addresses publish at launch on [Network](https://docs.degenhive.ai/network.md).

> **Figure: A UTC day in a HyperVault.** Requests wait for the day's roll; the roll takes fees, prices shares and settles the queue, and the depositor claims afterwards.
>
> Left, during UTC day D: requestDeposit pulls USDC at once and can be cancelled until 00:00 UTC; requestRedeem moves shares to escrow and cannot be cancelled. Above them: the keeper or manager may roll from 00:00 UTC, anyone from 02:00 UTC. Middle: roll(), once per UTC day, in four steps: 1. take fees, management and performance above the high-water mark; 2. set pricePerShare and raise the high-water mark; 3. mint deposit shares into escrow for each controller; 4. settle withdrawals, up to 16 epochs per roll. Deposits feed step 3 and redemptions feed step 4. A dashed branch from step 4: if idle USDC is short, anyone may call forceDeleveraging, which bridges USDC from Core, trims positions and settles. Right: settled shares earn from the roll, before any claim. Then claim shares with deposit, mint or realize, and USDC with redeem, withdraw or claimWithdraw.

## The day

| Time (UTC) | What happens |
|---|---|
| Day D | You call `requestDeposit` or `requestRedeem`. A deposit can still be cancelled. |
| D+1, 00:00 | The roll is due. The cancel window for deposits queued on day D closes. |
| D+1, 00:00 to 02:00 | The keeper, manager or council may roll. |
| D+1, from 02:00 | Anyone may roll. |
| After the roll | Your shares or USDC are claimable. |

A request made after 00:00 but before that day's roll joins the next epoch and settles at the following roll. If nobody rolls for several days, the next roll settles everything queued.

## Request a deposit

```solidity
function requestDeposit(uint256 assets, address controller, address owner) external returns (uint256 requestId);
```

The vault pulls `assets` USDC from `owner` at once, so approve the vault first. `controller` is the address that later claims the shares. Pending USDC sits outside NAV: it earns nothing and pays no fee. `requestId` is always 0, because requests are fungible per controller.

Reverts:

- `DepositBelowMinimum(amount, minAmount)`: below 10 USDC.
- `VaultCapExceeded(afterTvl, cap)`: over the vault cap or the manager's skin-in-the-game limit.
- `NotWhitelisted(account)`: a private vault, and the owner or controller is not on its list.
- `VaultWindingDown()` or `EngineDrawdownStopped()`: the vault is closing, or its drawdown latch is set.
- `BridgeInFlight()`: inside a 30-second bridge window. Retry shortly.
- `RollPending()`: you already have a deposit pending in a different epoch. This happens when you request again after 00:00 before the roll. Wait for the roll.
- `Unauthorized()`: the caller is neither `owner` nor an operator of `owner`.

### Cancel a pending deposit

```solidity
function cancelDeposit() external returns (uint256 refunded);
```

Only the controller can cancel, and the refund goes to the controller. It works until 00:00 UTC of the day the deposit settles. After that it reverts with `RollPending()`; with nothing pending it reverts with `NothingPending()`.

## Claim your shares

The roll mints your shares into the vault's escrow at the new share price. They are in the supply and earn from that moment, claimed or not.

```solidity
function deposit(uint256 assets, address receiver, address controller) external returns (uint256 shares);
function mint(uint256 shares, address receiver, address controller) external returns (uint256 assets);
function realize(address user) external;
```

- `maxDeposit(controller)` returns the claimable USDC amount and `maxMint(controller)` the claimable shares. Pass either to `deposit` or `mint`. Partial claims work.
- Two-argument `deposit(assets, receiver)` and `mint(shares, receiver)` use the caller as controller.
- `realize(user)` called by the user or an operator delivers every claimable share to `user`. Anyone else calling it only moves settled epochs into the claimable state.
- `previewDeposit` and the other `preview*` functions revert with `AsyncFlowOnly()`. Read `maxDeposit` and `position` instead.

The ERC-4626 `Deposit` event fires at claim time, not at request time.

## Request a redemption

```solidity
function requestRedeem(uint256 shares, address controller, address owner) external returns (uint256 requestId);
```

The owner, an operator of the owner, or a spender with a share allowance may call it. Shares move into escrow at once. They stay in the supply, so they keep gaining or losing and keep paying fees until the roll settles them. Redemptions are never paused and never whitelist-gated.

> [!WARNING]
> A redemption request cannot be cancelled. Once shares are in escrow, they leave the vault at the next roll price that can be paid.

Reverts: `InsufficientShares()`, `InsufficientAllowance(allowed, needed)`, `RollPending()` or `WithdrawEpochPending()` (you already have a redemption pending in another epoch), and for the manager, `ManagerCoInvestLocked(coInvestUsdc, minRequiredUsdc)`.

## Settlement

At the roll, the vault prices each pending redemption epoch at the new share price:

`USDC owed for an epoch`

```math
owed = shares * pricePerShare / 1e18
```

It pays from idle USDC and pulls the rest from the engine's HyperEVM balance. Epochs settle in order, oldest first, up to 16 per call. The first epoch idle USDC cannot cover stops the line, and so does every later one.

## Unfunded withdrawals

If the engine's capital is on HyperCore, a roll can leave redemptions unpaid. `unfundedWithdrawUsdc()` then returns the shortfall. Anyone can push it through:

```solidity
function forceDeleveraging(uint32[] calldata assetIds, uint32 sourceDex)
    external returns (uint256 settledEpochs, uint256 ordersSent, bool bridgeTriggered);
function settlePendingWithdrawals(uint256 maxEpochs) external returns (uint256 settled);
```

1. Call `forceDeleveraging(assetIds, 4294967295)`. It settles what idle USDC covers, then asks the engine to send its HyperEVM idle, bridge what HyperCore can release, and trim the listed positions with reduce-only orders. Non-role callers always use `ANY_SOURCE` (`4294967295`), so the engine draws from spot, dex 0, then other dexes.
2. Wait for the bridged USDC to land. The bridge window is 30 seconds, and the engine allows one bridge and one trim every 2 minutes.
3. Call `settlePendingWithdrawals(0)` (0 means up to 16 epochs). Anyone may call it when it settles at least one epoch. Repeat both calls until `unfundedWithdrawUsdc()` is 0.

Backlog epochs settle at the lower of the live share price and the last roll price. A redemption that waits through a backlog takes any loss in that time but no gain.

`forceDeleveraging` reverts with `NothingUnfunded()` when there is nothing to fund and `BridgeInFlight()` inside a bridge window.

## Claim your USDC

```solidity
function redeem(uint256 shares, address receiver, address controller) external returns (uint256 assets);
function withdraw(uint256 assets, address receiver, address controller) external returns (uint256 shares);
function claimWithdraw() external returns (uint256 paid);
```

- `maxRedeem(controller)` returns settled shares and `maxWithdraw(controller)` settled USDC. `redeem` and `withdraw` pay by share or by USDC amount, in part or in full.
- `claimWithdraw()` pays the caller everything settled, plus any refunded deposits. Only the controller itself can call it.
- With nothing claimable, they revert with `InsufficientClaimable()` or `NothingPending()`.

There is no withdrawal fee.

## Code: deposit, then claim

**viem**

```ts
import {
  createPublicClient, createWalletClient, defineChain, erc20Abi, http, parseAbi, parseUnits, type Address,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";

const hyperEvm = defineChain({
  id: 999,
  name: "HyperEVM",
  nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 },
  rpcUrls: { default: { http: ["https://rpc.hyperliquid.xyz/evm"] } },
});

const VAULT = process.env.VAULT as Address; // placeholder, published at launch
const USDC = process.env.USDC as Address;   // placeholder, published at launch
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const publicClient = createPublicClient({ chain: hyperEvm, transport: http() });
const wallet = createWalletClient({ account, chain: hyperEvm, transport: http() });

export const vaultAbi = parseAbi([
  "struct VaultPosition { uint256 shares; uint256 pendingDepositUsdc; uint64 pendingDepositEpoch; uint256 pendingRedeemShares; uint64 pendingRedeemEpoch; uint256 claimableDepositAssets; uint256 claimableDepositShares; uint256 claimableRedeemShares; uint256 claimableRedeemAssets; uint256 claimableRefundUsdc; bool whitelisted; }",
  "function requestDeposit(uint256 assets, address controller, address owner) returns (uint256)",
  "function cancelDeposit() returns (uint256)",
  "function maxDeposit(address controller) view returns (uint256)",
  "function deposit(uint256 assets, address receiver) returns (uint256)",
  "function requestRedeem(uint256 shares, address controller, address owner) returns (uint256)",
  "function maxRedeem(address controller) view returns (uint256)",
  "function redeem(uint256 shares, address receiver, address controller) returns (uint256)",
  "function claimWithdraw() returns (uint256)",
  "function position(address user) view returns (VaultPosition)",
  "function balanceOf(address account) view returns (uint256)",
  "function pricePerShareUsdc() view returns (uint256)",
  "function unfundedWithdrawUsdc() view returns (uint256)",
  "error DepositBelowMinimum(uint256 amount, uint256 minAmount)",
  "error VaultCapExceeded(uint256 afterTvl, uint256 cap)",
  "error NotWhitelisted(address account)",
  "error RollPending()",
  "error BridgeInFlight()",
  "error InsufficientClaimable()",
]);

// 1. Approve and request.
const assets = parseUnits("5000", 6);
await publicClient.waitForTransactionReceipt({
  hash: await wallet.writeContract({ address: USDC, abi: erc20Abi, functionName: "approve", args: [VAULT, assets] }),
});
const { request } = await publicClient.simulateContract({
  account, address: VAULT, abi: vaultAbi, functionName: "requestDeposit",
  args: [assets, account.address, account.address],
});
await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract(request) });

// 2. After the next roll (from 00:00 UTC), claim everything that settled.
const claimable = await publicClient.readContract({
  address: VAULT, abi: vaultAbi, functionName: "maxDeposit", args: [account.address],
});
if (claimable > 0n) {
  await wallet.writeContract({ address: VAULT, abi: vaultAbi, functionName: "deposit", args: [claimable, account.address] });
}
```

**cast**

```bash
cast send $USDC "approve(address,uint256)" $VAULT 5000000000 --rpc-url $HYPEREVM_RPC --account me
cast send $VAULT "requestDeposit(uint256,address,address)" 5000000000 $ME $ME --rpc-url $HYPEREVM_RPC --account me

# after the roll
CLAIMABLE=$(cast call $VAULT "maxDeposit(address)(uint256)" $ME --rpc-url $HYPEREVM_RPC)
cast send $VAULT "deposit(uint256,address)" $CLAIMABLE $ME --rpc-url $HYPEREVM_RPC --account me
```

## Code: redeem, then claim

**viem**

```ts
// Same clients and vaultAbi as deposit.ts.
const shares = await publicClient.readContract({
  address: VAULT, abi: vaultAbi, functionName: "balanceOf", args: [account.address],
});
await wallet.writeContract({
  address: VAULT, abi: vaultAbi, functionName: "requestRedeem", args: [shares, account.address, account.address],
});

// After the roll. If the vault is short, anyone can call forceDeleveraging first.
const unfunded = await publicClient.readContract({ address: VAULT, abi: vaultAbi, functionName: "unfundedWithdrawUsdc" });
const settled = await publicClient.readContract({
  address: VAULT, abi: vaultAbi, functionName: "maxRedeem", args: [account.address],
});
if (settled > 0n) {
  await wallet.writeContract({
    address: VAULT, abi: vaultAbi, functionName: "redeem", args: [settled, account.address, account.address],
  });
} else if (unfunded > 0n) {
  console.log(`redemptions short by ${unfunded} (USDC 1e6); see Unfunded withdrawals`);
}
```

**cast**

```bash
SHARES=$(cast call $VAULT "balanceOf(address)(uint256)" $ME --rpc-url $HYPEREVM_RPC)
cast send $VAULT "requestRedeem(uint256,address,address)" $SHARES $ME $ME --rpc-url $HYPEREVM_RPC --account me

# after the roll: pay out everything settled for you
cast send $VAULT "claimWithdraw()" --rpc-url $HYPEREVM_RPC --account me
```

## Operators

```solidity
function setOperator(address operator, bool approved) external returns (bool);
function isOperator(address controller, address operator) external view returns (bool);
```

An operator acts for you: it can request deposits from your USDC, request redemptions of your shares, and claim to any receiver. Approval is a transaction; the vault has no signature-based operator approval. `cancelDeposit` and `claimWithdraw` stay with you alone. Setting yourself or the zero address reverts with `InvalidPolicy()`.

## Private vaults

A vault with `whitelistEnabled` accepts deposit requests only when both owner and controller are on its list. Claiming shares to a different receiver needs that receiver listed too. With `whitelistTransfers` also on, shares can only be sent to listed addresses. Redemptions and redemption claims are never gated. The compliance admin, the manager or the council edits the list with `setWhitelistedLp(lp, allowed)`. Check your status in `position(user).whitelisted`.

## Share transfers

Shares are an ERC-20 with 6 decimals; the token address is the vault. `transfer` and `transferFrom` work as usual, with these limits:

- On a private vault with `whitelistTransfers`, the receiver must be listed (`NotWhitelisted`).
- The protocol allocator cannot send or receive shares.
- A third-party manager cannot transfer below their skin-in-the-game floor (`ManagerCoInvestLocked`).

At token launch, deposits, claims and transfers also notify `HyperBookRewards`. These calls revert with `HookGasTooLow()` unless at least 530,000 gas is left for the hook. Estimate gas rather than setting a tight limit.

## Wind-down refunds

If the manager or council winds a vault down, pending deposits are not converted. The next roll refunds them in full, and you collect the USDC with `claimWithdraw()`. You can also cancel before that roll. Redemptions, claims and rolls carry on as usual until the vault is empty. See [Risk](https://docs.degenhive.ai/vaults/risk.md#wind-down).

## Reading state

On-chain, `position(user)` returns everything about one account:

```solidity
struct VaultPosition {
    uint256 shares;                 // in your wallet
    uint256 pendingDepositUsdc;
    uint64 pendingDepositEpoch;
    uint256 pendingRedeemShares;
    uint64 pendingRedeemEpoch;
    uint256 claimableDepositAssets;
    uint256 claimableDepositShares;
    uint256 claimableRedeemShares;
    uint256 claimableRedeemAssets;
    uint256 claimableRefundUsdc;
    bool whitelisted;
}
```

Other views: `pricePerShare()` (1e18 = 1 USDC per share), `pricePerShareUsdc()`, `highWaterMark()`, `totalAssets()`, `rollDue()`, `currentEpoch()`, `lastRollDay()`, `unfundedWithdrawUsdc()`.

The read API at `https://api.degenhive.ai/v1` serves the same data without a node. No key is needed; the limit is 300 requests per 60 seconds per IP. Amounts are base-unit integer strings.

`GET https://api.degenhive.ai/v1/vaults/{vault}/positions/{account}`

Shares, value at the last share price, pending deposit and redemption with their epochs, and claimable USDC for one account.

`GET https://api.degenhive.ai/v1/vaults/{vault}`

Vault detail: tier, TVL, share price, high-water mark, fees, engine, last roll and forecast job.

`GET https://api.degenhive.ai/v1/vaults/{vault}/withdraw-epochs`

Settled redemption epochs with their shares, USDC and price.

```bash
curl -s https://api.degenhive.ai/v1/vaults/$VAULT/positions/$ME
curl -s "https://api.degenhive.ai/v1/vaults/$VAULT/rolls?limit=7"
```

## Related

- [Vaults](https://docs.degenhive.ai/vaults.md) Tiers, roles and the daily epoch.
- [Fees](https://docs.degenhive.ai/vaults/fees.md) What the roll charges and where it goes.
- [Risk rails](https://docs.degenhive.ai/vaults/risk.md) Stops, drawdown latches and wind-down protections.
- [API](https://docs.degenhive.ai/api.md) The full read API.
