Skip to content

Conversation

@junhoyeo
Copy link
Member

@junhoyeo junhoyeo commented Sep 19, 2025

Summary by CodeRabbit

  • New Features
    • Adds a Crest Vault product: deposit/withdraw flows with share lock, fee accounting (platform & performance), on-chain allocation/rebalance and position management with admin/curator controls.
  • Chores
    • Adds core package scaffolding, git submodules, formatting/tooling configs, and a format script.
  • Scripts
    • Adds end-to-end deployment scripts for vault setup.
  • Tests
    • Adds extensive integration and unit tests covering deposits, withdrawals, fees, allocations, rebalances, positions, and security.
  • Documentation
    • Adds a placeholder README for the core package.

@coderabbitai
Copy link

coderabbitai bot commented Sep 19, 2025

Walkthrough

Adds a new core package implementing a multi-contract vault system (Vault, Accountant, Teller, Manager), supporting scripts, tests, mocks, Foundry config, TypeScript index fetcher, remappings, tooling configs, and three git submodules for dependencies.

Changes

Cohort / File(s) Change Summary
Repository tooling & config
.prettierignore, .prettierrc.js, .gitmodules, .vscode/settings.json, package.json
Adds Prettier plugins and Solidity formatting overrides, updates ignore rules, VSCode Solidity formatter setting, package scripts/devDependency, and registers three git submodules.
Core package manifest & config
packages/core/package.json, packages/core/foundry.toml, packages/core/.gitignore, packages/core/README.md, packages/core/remappings.txt
Adds @crest/core package manifest, Foundry config, gitignore for build/artifacts, placeholder README, and Solidity remappings for local libs.
Git submodules
packages/core/lib/forge-std, packages/core/lib/hyper-evm-lib, packages/core/lib/boring-vault
Adds/updates pointers for three external library submodules.
Vault core contracts
packages/core/src/CrestVault.sol, packages/core/src/interfaces/BeforeTransferHook.sol
New CrestVault ERC20-share implementation with authorize/requireAuth model, before-transfer hook, manage/enter/exit flows, allocation/rebalance stubs, and related events. Adds BeforeTransferHook interface.
Accounting & fees
packages/core/src/CrestAccountant.sol
New CrestAccountant contract: exchange-rate accounting, platform/performance fees, high-water-mark logic, cooldowns, fee accumulation and collection, access control, and utility converters.
Teller / onboarding
packages/core/src/CrestTeller.sol
New CrestTeller for USDT0 deposits/withdrawals, share-locking, accountant integration, pause controls, and deposit/withdraw previews.
Manager / lifecycle
packages/core/src/CrestManager.sol
New CrestManager integrating Hyperliquid interactions (allocate, rebalance, close positions), allocation logic, curator controls, slippage checks, and position tracking.
Example & deployment scripts
packages/core/src/Counter.sol, packages/core/script/Counter.s.sol, packages/core/script/DeployCrestVault.s.sol
Adds a simple Counter example and Forge scripts for deploying Counter and orchestrating CrestVault system deployment.
Tests & mocks
packages/core/test/Counter.t.sol, packages/core/test/CrestVaultTest.t.sol, packages/core/test/Hyperliquid.t.sol, packages/core/test/mocks/ERC20Mock.sol
Adds unit and extensive integration Forge tests (vault lifecycle, allocation, fees, Hyperliquid interactions) plus ERC20Mock for testing.
Developer utilities
packages/core/typescript/fetch-index.ts
Adds a TypeScript utility that queries Hyperliquid API to resolve spot/perp/token indices by symbol.
Foundry test harness additions
packages/core/test/**
New test fixtures, simulators, and scenario setups for Hyperliquid core and precompile simulations (referenced from tests).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Teller as CrestTeller
    participant Vault as CrestVault
    participant Accountant as CrestAccountant
    participant Manager as CrestManager
    participant HL as HyperliquidCore

    rect #E8F4F1
        User->>+Teller: deposit(assets, receiver)
        Teller->>Accountant: previewDeposit / compute shares
        Teller-->>Vault: enter(from, asset, amount, to, shares)
        Vault-->>User: emit Enter / Deposit
    end

    rect #F3F3FF
        Curator/Admin->>+Manager: allocate(spotIndex, perpIndex)
        Manager->>Vault: request assets / transfer
        Manager->>HL: bridge funds, place orders (spot/perp)
        HL-->>Manager: order confirmations / indices
        Manager-->>Vault: emit Allocated
    end

    rect #FFF7E6
        Curator/Admin->>Manager: rebalance() / closeAllPositions()
        Manager->>HL: close positions, retrieve assets
        Manager-->>Vault: emit Rebalanced / PositionClosed
        Manager->>Accountant: trigger rate update (optional)
    end
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Poem

In my burrow I nibble at lines of code,
Vaults and tellers sprout along the road.
Fees that climb and locks that keep,
Tests that run while rabbits sleep.
Hooray — deploy, rebalance, and off we go! 🥕


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Free

📥 Commits

Reviewing files that changed from the base of the PR and between 7e218ba and 33d46a9.

📒 Files selected for processing (1)
  • packages/core/test/CrestVaultTest.t.sol (1 hunks)

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands and usage tips.

Comment on lines +1 to +59
class HyperliquidAPI {
async _requestInfo<T extends object>(request: { type: string }): Promise<T> {
const response = await fetch('https://api.hyperliquid.xyz/info', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
});
return response.json();
}

async _getSpotIndex(symbol: string) {
const { tokens, universe } = await this._requestInfo<{
tokens: { name: string; index: number }[];
universe: {
index: number;
tokens: [tokenIndex: number, quoteTokenIndex: number];
}[];
}>({ type: 'spotMeta' });

const token = tokens.find((token) => token.name === symbol);
if (token?.index === undefined) {
throw new Error(`Token ${symbol} not found`);
}
const spot = universe.find((asset) => asset.tokens[0] === token.index);
if (spot?.index === undefined) {
throw new Error(`Spot ${symbol} not found`);
}
return {
tokenIndex: token.index,
spotIndex: spot.index,
meta: { token, spot },
};
}

async _getPerpIndex(symbol: string) {
const { universe } = await this._requestInfo<{
universe: {
szDecimals: number;
name: string;
maxLeverage: number;
marginTableId: number;
}[];
}>({ type: 'meta' });

const perpIndex = universe.findIndex((asset) => asset.name === symbol);
return { perpIndex, meta: universe[perpIndex] };
}

async getIndexesBySymbol(symbol: string) {
const spot = await this._getSpotIndex(symbol);
const perp = await this._getPerpIndex(symbol);
return {
symbol,
tokenIndex: spot.tokenIndex,
spotIndex: spot.spotIndex,
perpIndex: perp.perpIndex,
};
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거는 다른 모듈에다 가져다 써도 되겠다

Copy link
Member Author

@junhoyeo junhoyeo Sep 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

allocate (vault 에 남아 있는 USDC 를 가지고 기존 포지션 확장) 및 rebalance (포지션 변경 체크) 시에 자산의 spot/perp index 넣어줘야 함!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

지금 쌓고 있는 데이터에 자산의 spot/perp index을 추가로 더 쌓아야 하나? 아니면 컨트랙트 안에서만 사용하는거야?

Copy link
Member Author

@junhoyeo junhoyeo Sep 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

spot/perp index 는 immutable (아마) 해서, 컨트랙트의 allocate/rebalance 호출하기 전에 가져오면 될 듯

@junhoyeo junhoyeo changed the title [WIP][core] Implement CrestVault [core] Implement CrestVault Sep 19, 2025
junhoyeo and others added 5 commits September 20, 2025 09:12
- Fixed arithmetic overflow in P&L calculations by adding proper type casting
- Changed minimum balance requirement from 200 to 50 USDT0 for better capital efficiency
- Replaced simplified market maker comments with actual order placement
- Updated outdated comment about closeAllPositions using placeholder amounts
- All 27 tests now pass with proper rate limiting

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@junhoyeo junhoyeo merged commit 00a07c6 into main Sep 20, 2025
4 checks passed
@junhoyeo junhoyeo deleted the junhoyeo/vault branch September 20, 2025 15:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants