bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 26쪽 중 14쪽
o submit transactions through Safe, define `SAFE_API_KEY` as described in the current repository README. Treat that README as the source of truth for current environment variables and command options.
4. Install dependencies:
```bash
./install.sh
```
5. Compile the contracts:
```bash
forge clean && forge compile
```
#### Running scripts
The scripts are experimental and provided as-is. Pin and review the repository revision you use, test the complete cluster configuration and scripts, run the documented dry run, and independently review every generated transaction and Safe payload before production execution. A successful dry run does not validate asset, oracle, liquidity, governance, cap, LTV, fee, or liquidation-risk choices.
Use the `ExecuteSolidityScript.sh` script to run the management script:
```bash
./script/ExecuteSolidityScript.sh script/clusters/[CLUSTER_FILE] [options]
```
Replace `[CLUSTER_FILE]` with your cluster-specific file name (e.g., `Cluster.s.sol`).
##### Important options:
* `--dry-run`: Simulates the script without executing transactions
* `--rpc-url URL|CHAIN_ID`: Required if `DEPLOYMENT_RPC_URL` not defined in `.env`
* `--account ACCOUNT` or `--ledger`: Required if `DEPLOYER_KEY` not defined in `.env`
* `--batch-via-safe`: Creates a batch payload file for Safe multisig execution
* `--safe-address SAFE_ADDRESS`: Authorized Safe multisig address
* `--timelock-address`: Schedules transactions in the timelock controller
* `--risk-steward-address`: Executes transactions via the risk steward contract
##### Example commands:
Initial deployment:
```bash
./script/ExecuteSolidityScript.sh ./script/clusters/Cluster.s.sol --account DEPLOYER --rpc-url 1
```
Managing a deployed cluster with governance contracts:
```bash
./script/ExecuteSolidityScript.sh ./script/clusters/Cluster.s.sol --batch-via-safe --safe-address DAO --timelock-address wildcard --rpc-url 1
```
#### Important notes
* Always use `--dry-run` first, then inspect the target chain, callers, destinations, calldata, values, role paths, and resulting state before signing
* Environment variables in `.env` take precedence over command line arguments
* After deployment, commit the generated `.json` files in the scripts directory as they serve as the deployed contracts addresses cache
### Further reading and references
* [euler-vault-scripts README](https://github.com/euler-xyz/euler-vault-scripts/blob/master/README.md)
* [Cluster.s.sol example](https://github.com/euler-xyz/euler-vault-scripts/blob/master/script/clusters/Cluster.s.sol)
### Read next
* [Curate](/curate)
* [Launch toolkit](/launch)
* [Final review](/launch#final-review)
## Hooks and custom logic
The [**Euler Vault Kit (EVK)**](/curate/vaults/evk/overview) provides a flexible hooking system that allows vault governors to extend vault functionality or restrict certain operations. This guide explains how hooks work and provides examples of common use cases.
### Hook system overview
Hooks are implemented through a hook configuration that consists of two parameters:
* The hook target: The address of a contract that implements the hook logic
* The hooked operations: A bitfield that specifies which operations should trigger the hook
When a hooked operation is invoked, the vault will:
1. Check if the operation is enabled in the hooked ops bitfield
2. Call the hook target with the same `msg.data` that was provided to the vault
3. Append the EVC-authenticated caller as trailing calldata
4. Revert the operation if the hook call fails
#### Hook target implementation
Every hook target contract must implement the `isHookTarget()` function, which returns a special function selector (magic value). This function checks that the contract is coded to be a hook target. Depending on the use case, `isHookTarget()` can be further strengthened by checking whether the calling address is a proxy deployed by a recognized EVault factory. Example implementation can be as follows:
```solidity
function isHookTarget() external view returns (bytes4) {
if (eVaultFactory.isProxy(msg.sender)) return this.isHookTarget.selector;
else return 0;
}
```
### Example use cases
#### Access control
The [`HookTargetAccessControl`](https://github.com/euler-xyz/evk-periphery/blob/master/src/HookTarget/HookTargetAccessControl.sol) contract demonstrates how to implement role-based access control for vault operations. This is useful for:
* Restricting deposits to whitelisted addresses
* Limiting borrowing to specific users
* Implementing KYC/AML requirements
* Implementing KYB or entity-level eligibility requirements
* Enforcing allowlists for permissioned or RWA-backed vaults
* Creating permissioned vaults for institutional users
Access-control hooks are commonly used when eligibility is determined offchain and then published onchain through roles, allowlists, credential registries, or a custom policy contract. The hook should check the EVC-authenticated account appended to calldata, not only `msg.sender`, because vault operations may be routed through EVC batches, operators, or integration contracts.
#### Circuit breakers
Hooks can be used as vault-level circuit breakers for selected operations. A circuit-breaker hook can revert when a configured condition is active, such as:
* Pausing new deposits or borrows during oracle, liquidity, or asset incidents
* Blocking transfers of vault shares during an issuer or transfer-agent event
* Disabling flash loans or other high-risk actions during an exploit response
* Enforcing utilization, exposure, or concentration ceilings during status checks
* Allowing de-risking actions such as repay or withdraw while blocking actions that increase exposure
Design circuit breakers narrowly. Broad pauses can protect against some incidents, but they can also interrupt normal operations, integrations, liquidations, or user exits if they are applied to the wrong operation set.
#### Compliance and RWA controls
For tokenized asset and RWA markets, hooks can encode operation-level rules that match the vault's eligibility and transfer assumptions. Common examples include:
* Requiring KYC/KYB approval before `deposit`, `mint`, `borrow`, or `transfer`
* Checking jurisdiction, sanctions, accreditation, investor-type, or entity-status registries
* Enforcing per-account exposure limits or minimum position sizes
* Restricting vault-share transfers to approved recipients
* Blocking new exposure when the underlying asset, issuer, custodian, oracle, or redemption process is paused
Hooks gate only selected hooked EVK operations using configured onchain conditions. They do not by themselves perform legal review, identity verification, KYC/KYB, sanctions screening, issuer administration, transfer-agent processing, determine legal eligibility, or make a vault or market compliant. Those outcomes depend on external data and processes, governance, and the exact operations covered. Document policy sources, stale-data and provider failures, upgrades, bypasses, privileged roles, revocation, and emergency behavior before launching a permissioned or RWA-related vault.
#### Other use cases
1. **Flash Loan Fees**
* Enforce a percentage fee on flash loans
* Collect fees in any token
* Scale fees with gas costs
2. **Utilization Caps**
* Block vault utilization from exceeding a threshold
* Implement dynamic caps based on market conditions
* Protect against high utilization risks
3. **Minimum Debt Sizes**
* Prevent creation of dust positions
* Set debt floors so liquidations are more likely to be economically viable
* Reduce gas costs for liquidators
4. **Custom Collateral Restrictions**
* Limit the number of collateral assets
* Implement custom collateral validation
* Add additional risk checks
### Limitations
1. **[ERC-4626](https://eips.ethereum.org/EIPS/eip-4626) Compliance**
* Some hook configurations may cause the vault to not be fully ERC-4626 compliant
* The `max*` functions may be inaccurate with hooks installed
2. **Operation Scope**
* Hooks can only affect operations specified in the hooked ops bitfield
* Hooks do not cover operations outside the configured bitfield, and some operations may not be hookable
* A reverting, unavailable, or gas-intensive hook can deny service to covered operations, including de-risking or liquidation paths if configured carelessly
3. **Gas Costs**
* Each hooked operation requires an additional external call
* Complex hook logic can significantly increase gas costs
* Consider the impact on user experience
## Euler Vault Kit introduction
The Euler Vault Kit (EVK) is a modular framework for building lending markets from ERC-4626 vaults. Each vault holds one underlying asset and can be configured with its own collateral relationships, oracle routes, LTVs, caps, interest-rate model, liquidation settings, hooks, fees, and governance.
EVK lets developers, curators, DAOs, and other market creators:
* launch lending markets for ERC-20 assets;
* configure risk parameters for each vault-to-vault relationship;
* choose governed or immutable deployments; and
* connect vaults into isolated pairs, multi-collateral markets, or larger clusters.
### Why build with EVK?
Multiple vaults for the same asset can coexist with different parameters. LTVs are set between individual liability and collateral vaults, so a market creator can isolate a pair or deliberately connect several vaults. Existing vaults can also be accepted as collateral to help bootstrap a new market, with the new vault inheriting dependencies on that collateral vault's configuration and liquidity.
Liquidations use a reverse Dutch auction-style discount rather than one fixed bonus. The discount increases as a position's health deteriorates, up to the maximum configured by the vault governor.
Hooks can add custom accounting, access rules, or conditions to selected operations. The creator also chooses the vault's oracle or router, unit of account, and interest-rate model. If the oracle is a router, its routes may be managed by a separate router governor.
EVK vaults work with the Ethereum Vault Connector (EVC). EVC batching supports flows such as one-transaction leverage, while operators let users delegate control of selected accounts to another address or contract for automation and other account workflows.
### Market structures
EVK supports several market structures:
* **Isolated pairs:** one collateral vault supports borrowing from one liability vault.
* **Multi-collateral markets:** a liability vault accepts several collateral vaults.
* **Vault clusters:** connected vaults accept one another as collateral across a broader market.
More connected structures can improve capital and liquidity reuse, but they also create dependencies between the participating vaults. Choose the structure that matches the intended assets, governance, and risk model.
:::tip
**Before you begin**
Plan the underlying assets, collateral relationships, oracle routes, unit of account, IRM, caps, LTVs, hooks, and governance before deploying. Review the [core concepts](/introduction) if you are new to Euler's architecture.
:::
:::note
**The Toolbox and labels**
Use the [Toolbox](/curate/toolbox) to deploy or manage an EVK vault. Labels and public metadata help apps display and discover vaults; verify deployed addresses, roles, and configuration independently. See [Labels and metadata](/curate/vaults/labeling) and [Vault metadata](/build/data-querying/perspectives).
:::
## Overview
**The Euler Vault Kit (EVK)** is a system for constructing credit vaults: [ERC-4626](https://eips.ethereum.org/EIPS/eip-4626) vaults extended with lending and borrowing. Borrower interest is their core yield source, unlike many ERC-4626 implementations that allocate assets to external strategies. Users can borrow from a credit vault when they have sufficient eligible collateral in other credit vaults. The liability vault decides which credit vaults it accepts as collateral.
### Key components
#### Vault architecture
A vault consists of several components:
* **Underlying Asset**: The ERC-20 token held by the vault. Each vault holds exactly one underlying asset.
* **EVault**: The primary entry-point contract implementing common vault logic:
* Tracks deposits and borrows
* Accrues interest
* Validates position health
* Permits liquidations
* **Price Oracle**: Interfaces with external pricing systems to compute collateral and liability values
* **IRM (Interest Rate Model)**: Computes interest rates to incentivize borrowing behavior
* **ProtocolConfig**: Global protocol-level configuration controlling interest fee destinations and splits
* **Hook Target**: Optional contract that can implement custom logic for vault operations through hooks
* **DToken**: A read-only ERC-20 interface for debt amounts, making debt modifications visible in block explorers and trackable by tax-accounting software
#### Vault creation and governance
Vaults are created through a factory contract, which deploys a proxy pointing to the implementation contract. This pattern enables gas-efficient deployment and gives integrators a way to verify factory provenance. After creation, vaults can be either governed, where the creator retains or transfers governance rights, or finalized, where governance is revoked by setting governor to `address(0)`.
#### Upgradeability vs immutability
When creating a vault, a boolean `upgradeable` flag is specified:
* If `upgradeable` is true, the factory creates a beacon proxy, allowing the factory admin to upgrade the vault's implementation
* If `upgradeable` is false, the factory creates a minimal proxy contract, making the vault immutable
The factory has a configured `upgradeAdmin` that can change the implementation for upgradeable vaults. Verify its current holder and control path onchain for the selected deployment. Vault creators choose whether a factory-admin implementation change can affect their vault or whether its implementation is immutable.
:::info
The upgrade functionality is intended for critical bugs discovered in the vault implementation.
:::
#### Governance risk
The combination of upgradeability and governance creates different risk profiles:
| | Upgradeable | Immutable |
| ------------- | ------------------------ | --------- |
| **Governed** | Factory Admin + Governor | Governor |
| **Finalized** | Factory Admin | None |
Immutability removes specific change authorities but also removes their recovery options. See [EVK security](/curate/vaults/evk/security) for the resulting governance, oracle, collateral, and implementation tradeoffs.
### Core functionality
#### Exchange rate and shares
Vaults implement the ERC-4626 standard, where shares represent proportional claims on vault assets. The exchange rate grows as interest accrues, and shares maintain the same decimals as the underlying asset. The exchange rate is calculated as:
```
exchangeRate = (cash + totalBorrows + VIRTUAL_DEPOSIT) / (totalShares + VIRTUAL_DEPOSIT)
```
The virtual deposit mechanism mitigates manipulation through rounding-based "stealth deposits" and keeps the exchange rate well-defined even with zero shares.
#### Token transfers
Vaults use two internal abstractions for token movements:
* `pullAssets`: First attempts a Permit2-authorized transfer, then falls back to the underlying asset `transferFrom`
* `pushAssets`: Uses `transfer` on the underlying asset, with checks to prevent transfers to virtual sub-accounts
Permit2 can improve user experience by allowing approvals to be created as signed messages bundled into the same EVC batch as operations like `deposit`. Users need to approve the Permit2 contract once, and some users may already have done this when interacting with Uniswap or other apps.
With the advent of EIP-7702, the need for Permit2 is reduced, as EIP-7702 allows approvals to be bundled with transactions in a more native way. However, not all networks support EIP-7702 yet, and many wallets are still catching up. As a result, Permit2 remains useful for smoother user experiences across different environments and wallet implementations.
#### Internal balance tracking
The vault uses internal balance tracking instead of reading its own balance from the underlying asset. This prevents users from manipulating the exchange rate through direct transfers and is more gas efficient. However, this means that rebasing/fee-on-transfer tokens are not supported, as the vault cannot track unexpected balance changes.
#### Balance forwarding
Balance forwarding enables automated distribution of rewards while keeping gas costs low. When an account opts in, every time its balance changes an external contract is notified of the updated balance. This external contract has no special privileges in the vault, but its `balanceTrackerHook` method must not revert or use up all gas. In practice, reward campaigns for Euler vaults run on offchain platforms such as [Merkl](https://app.merkl.xyz/), which do not rely on balance forwarding.
#### Interest rate models and compounding
Interest Rate Models (IRMs) determine the interest rate based on the vault's state, typically using a function of utilization. The most common function is a "linear-kink" model that starts with a gradual slope and becomes steep at a target utilization value.
Interest is compounded deterministically every second using exponentiation. Because accrued interest is added to `totalBorrows`, it increases utilization. The amount of interest owed/earned is independent of how frequently the contract is interacted with, except for the effect of accumulator rounding.
IRMs return interest rates in terms of "second percent yield" (SPY) values, which are per-second compounded interest rates scaled by `1e27`. For consistency, conversion to annualized equivalents should use the number of seconds in the average Gregorian calendar year (365.2425 days).
#### Fees
Interest-fee settings and recipients are configuration-, deployment-, network-, and vault-dependent. Verify the current deployed settings for the relevant network and vault. A governance proposal alone does not prove that a change was executed.
Vault governors can configure the portion of accrued borrower interest allocated as fees through the `interestFee` parameter, subject to the applicable bounds. Accumulated fees are converted into vault shares. Once minted, those shares participate in the same asset-per-share changes as other shares.
The `ProtocolConfig` contract's `protocolFeeShare` determines how the accumulated `interestFee` shares are split between the vault's fee receiver and the protocol fee receiver, subject to the contract's cap. It is a split of the configured interest fee, not an additional percentage charged on top. Read the vault's `interestFee`, its fee receiver, and the applicable protocol share and receiver together.
#### Supply and borrow caps
Vault governors can configure:
* Supply cap: Limit on the amount of underlying assets that can be deposited
* Borrow cap: Limit on the amount that can be borrowed
Both caps are denominated in the underlying asset and are packed into 2-byte decimal floating point values. Caps can be transiently violated since they are only enforced at the end of a batch. If a cap was not in violation at the start of a batch but is at the end, the transaction will be reverted.
#### Dtoken (debt token)
Vaults provide a read-only ERC-20 interface for debts through the DToken contract. This interface tracks debt modifications through Transfer events and supports off-chain analysis and tax accounting. The DToken contract is the first (and only) contract created by EVault, so its address can be calculated from the vault's address and the nonce `1`.
### Sub-accounts
The EVC provides each user with 256 virtual account addresses, known as sub-accounts, that are separated from one another. This lets users manage multiple positions with different risk para프로젝트로 돌아가기