bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 26쪽 중 21쪽
# Governor contracts
Governor contracts can hold the `governorAdmin` authority of Euler Vault Kit (EVK) vaults and compatible oracle routers. They authenticate and forward administrative calls according to their role configuration. A curator, DAO, multisig, or risk steward can hold one or more roles in a governor, depending on the deployment.
The result is a flexible way to separate routine parameter changes, timelocked governance, and emergency actions.
### The role of governor contracts
An EVK vault exposes a `governorAdmin` address with broad vault-configuration authority. The exact callable functions depend on the target contract and governor. This vault-level authority is distinct from the EVault factory's `upgradeAdmin`, which can affect factory-linked upgradeable vault implementations; see [Factory Governor](/build/periphery/factory-governor).
### Roles and configuration
Governor contracts use role-based access control, often selector-based, to manage permissions:
* **DEFAULT_ADMIN_ROLE:** The most powerful role, able to grant/revoke other roles and perform admin actions. It should generally be held by a reviewed multisig or DAO-controlled address.
* **WILD_CARD:** Grants access to all function selectors, typically held by a timelock for day-to-day governance.
* **Function Selector Roles:** Grant access to specific functions, allowing granular permissioning.
* **Guardian and emergency roles:** Their names and powers vary by implementation and can include `LTV_EMERGENCY_ROLE`, `HOOK_EMERGENCY_ROLE`, and `CAPS_EMERGENCY_ROLE`. Inspect role membership and callable selectors rather than inferring authority from a label.
Careful assignment and monitoring of these roles is critical. A misconfigured role can affect vault behavior, oracle routing, caps, LTVs, or emergency response.
### Types of governor contracts
Euler provides several specialized governor contracts, each with different operational tradeoffs:
#### `GovernorGuardian`
`GovernorGuardian` is a simple, proxy-like governor for vaults. Default admins can call any function, while guardians can pause or unpause the vault. It includes a cooldown to prevent repeated pausing and allows selective re-enabling of methods (e.g., only allow withdrawals/repays). Its authority and recovery behavior depend on deployed roles and configuration; review those values rather than treating the contract type as a safety designation.
#### `GovernorAccessControl`
`GovernorAccessControl` provides selector-based access control: permissions are granted per function selector, or globally via the `WILD_CARD` role. Whitelisted callers can invoke specific functions on target contracts, with authentication and forwarding handled by the governor. It can be used standalone or as part of a timelock-enabled governance suite. This is the most flexible and granular governor type.
#### `GovernorAccessControlEmergency`
This contract inherits from `GovernorAccessControl` and adds emergency roles for rapid response. Emergency guardians can instantly lower borrow LTV, pause vault operations, or lower supply/borrow caps. These actions can provide a circuit breaker during risk events. Recovery from emergency states, such as unpausing, goes through the timelock process when a timelock is installed.
#### `CapRiskSteward`
`CapRiskSteward` is a specialized risk management contract that works alongside selector-based governors. It allows authorized users to adjust supply and borrow caps within predefined bounds and cooldowns, and to update interest rate models (IRM) only to those deployed by a recognized factory. This can delegate limited parameter management to reviewed stewards while keeping broader control with the governor and timelock.
### Timelock integration: dual timelock model
The recommended deployment uses the `GovernorAccessControlEmergencyFactory`, which sets up:
* **Admin Timelock:** Holds the `DEFAULT_ADMIN_ROLE`, controls governance of the governor contract itself (break-glass, rarely used).
* **Wildcard Timelock:** Holds the `WILD_CARD` role, used for day-to-day governance (parameter changes, etc.).
The dual timelock model makes queued changes visible before execution, gives users time to respond to pending changes, and separates emergency actions from routine parameter changes.
### How to call the `GovernorAccessControl` contract
To call a function on a vault via `GovernorAccessControl`, you must append the target vault address to the calldata. This allows the governor to authenticate the call and forward it to the correct vault. Here's a simple example in Solidity:
```solidity
// Assume you want to call setCaps(uint16,uint16) on a vault via the governor
address vault = VAULT_ADDRESS;
uint16 supplyCap = 1000;
uint16 borrowCap = 500;
// Fetch the governor address from the vault contract
address governor = IVault(vault).governorAdmin();
// Encode the function selector and arguments
bytes memory encodedCall = abi.encodeWithSelector(
IEVault.setCaps.selector,
supplyCap,
borrowCap
);
// Append the vault address (20 bytes) to the calldata using abi.encodePacked
bytes memory encodedCallWithTarget = abi.encodePacked(encodedCall, vault);
// Call the governor contract
(bool success, bytes memory result) = governor.call(encodedCallWithTarget);
require(success, "Governor call failed");
```
This pattern is also used for `GovernorAccessControlEmergency` and `CapRiskSteward` contracts. The governor contract extracts the trailing address and forwards the call to the vault, authenticating the caller's permissions for the function selector.
### Read next
* [Periphery contracts](/build/periphery)
* [Build](/build)
* [Launch toolkit](/launch)
## Periphery contracts
Euler periphery contracts support deployment, governance, swap execution, read helpers, and order-flow routing around EVK and EVC integrations.
| If you want to... | Start with |
| --------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| Review factory deployments for EVK, EulerEarn, IRMs, routers, and governance modules | [Factory contracts](/build/periphery/factories) |
| Understand vault governor contracts, timelocks, emergency controls, and delegated parameter changes | [Governor contracts](/build/periphery/governors) |
| Review factory-wide upgrade and read-only pause authority | [Factory Governor](/build/periphery/factory-governor) |
| Work with swap helpers and related periphery swap contracts | [Periphery swaps](/build/periphery/swaps) |
| Route order flow through Euler supporting contracts | [Order-flow router](/build/periphery/orderflow-router) |
## Order flow router
The [Euler Order Flow Router](https://github.com/euler-xyz/euler-orderflow-router) is an offchain meta-aggregator used by Euler swap and Multiply flows. It queries configured routing strategies, compares eligible responses, and returns route details and calldata that an application can place into an EVC batch.
This allows a user to open, rebalance, or close a position in one transaction while still reviewing the route, slippage bound, and resulting position before signing.
### How it fits into a swap
A router response can provide data for `Swapper` and `SwapVerifier`:
1. `Swapper` executes the encoded external route and, in target-debt mode, performs `repay` or `_repayAndDeposit`.
2. The selected `SwapVerifier` function checks the configured minimum output or maximum remaining debt and deadline.
3. For regular output paths, a verifier function can also skim and deposit or transfer output after the amount check.
4. The EVC completes the required vault and account status checks for the batch.
The router builds a quote and payload; it does not execute the user's transaction. Applications should validate the returned chain, tokens, vaults, accounts, recipients, targets, calldata, amounts, approvals, slippage, and deadline.
See [Periphery swaps](/build/periphery/swaps) for the execution and verification flow.
### Strategies and pipelines
Requests pass through a chain-specific pipeline. A strategy can answer a request, modify it, combine routes, or invoke another stage.
Current source includes:
* **`StrategyAggregators` (`aggregators`):** gathers quotes from configured aggregators and compares eligible responses.
* **`StrategyCombinedUniswap`:** combines an aggregator exact-input leg with a Uniswap exact-output remainder where configured.
* **ERC-4626 and asset wrappers:** compose deposits, redemptions, or direct conversion routes with other quote legs.
* **Connection strategies:** join routes through an intermediary token or another strategy stage.
Provider and pipeline configuration varies by chain and can change over time. Check the current [router repository](https://github.com/euler-xyz/euler-orderflow-router) and API for the intended request.
### Multiply entry and exit
A typical Multiply entry batch can:
1. supply the initial margin;
2. borrow while the required liquidity check is deferred;
3. swap into the collateral asset;
4. route output through the selected verifier path; and
5. finish the verifier and EVC status checks.
A typical unwind withdraws collateral, executes a target-debt swap, lets `Swapper` repay the debt, and uses `verifyDebtMax` to enforce a maximum remaining balance. The exact batch depends on the quote, token behavior, existing account state, and periphery version.
### Debt-target routing
Debt continues to accrue between quote and execution. Depending on configuration, the router can:
* combine an aggregator exact-input route with an exact-output remainder; or
* size an exact-input quote with a buffer, then use target-debt post-processing to repay and handle any surplus.
The caller should set a deadline and remaining-debt maximum that account for interest, fees, slippage, rounding, liquidity, and token behavior.
### Integration checklist
* Decode and validate returned targets and calldata according to the application's policy.
* Confirm input and output amounts and token decimals.
* Verify the output destination expected by the selected verifier flow.
* Keep approvals scoped to the intended spender and amount.
* Simulate the complete EVC batch against current state.
* Show the provider, route, fees, slippage bound, deadline, and resulting position to the signer.
* Handle no-quote, stale-quote, and provider-error responses.
### Resources
* [Order Flow Router repository](https://github.com/euler-xyz/euler-orderflow-router)
* [Deployed API schema](https://swap.euler.finance/)
* [Periphery swaps](/build/periphery/swaps)
* [EVK swap periphery source](https://github.com/euler-xyz/evk-periphery/tree/master/src/Swaps)
## Swaps
Swaps are a core building block in Euler. They let users open leveraged positions, replace collateral, repay debt, and complete liquidations without splitting the workflow across several transactions. The EVC can combine vault operations, an external swap, and explicit result checks in one atomic batch.
### Why swaps matter
Swaps support several common workflows:
* **Open a leveraged position:** borrow an asset, swap it for collateral, and deposit the result.
* **Replace collateral:** withdraw one collateral asset, swap it, and deposit the replacement.
* **Repay debt:** withdraw collateral, swap it for the liability asset, and repay the outstanding debt.
* **Complete a liquidation:** swap received collateral for the liability asset needed to repay debt.
If a required operation or post-swap check fails, the EVC batch reverts as a single transaction.
### How swaps are executed
A typical EVC batch follows this progression:
1. Withdraw or borrow the asset to be swapped.
2. Send it to the `Swapper`.
3. Execute the route through an external venue.
4. Deposit the output, repay debt, or transfer the result as required.
5. Use `SwapVerifier` to check the resulting amount or remaining debt.
6. Complete the EVC account and vault status checks.
### Swapper and SwapVerifier
Euler's reference flow separates execution from verification:
* **`Swapper` executes the route.** It calls handlers for external venues and supports exact-input, exact-output, and target-debt modes. It is permissionless and should not retain funds or standing approvals.
* **`SwapVerifier` checks the result.** The caller supplies a minimum output or maximum remaining debt and a deadline. The selected verifier function checks that condition and reverts if it is not met.
* **The EVC provides atomic sequencing.** Place the verifier after the swap operations in the same batch so a failed postcondition reverts the transaction.
`SwapVerifier` checks caller-selected amount or debt bounds. It does not quote a route or calculate oracle-based price impact.
Use the [`Swapper` source](https://github.com/euler-xyz/evk-periphery/blob/master/src/Swaps/Swapper.sol), [`SwapVerifier` source](https://github.com/euler-xyz/evk-periphery/blob/master/src/Swaps/SwapVerifier.sol), and [periphery swap documentation](https://github.com/euler-xyz/evk-periphery/blob/master/docs/swaps.md) for the version you integrate.
### Swap modes
* **Exact input:** spend a specified input amount and receive the output produced by the route.
* **Exact output:** buy a specified output amount. Supporting handlers return unused input to the configured input vault or account.
* **Target debt:** calculate the amount needed to reach a debt target, execute the swap, and call `repay` or `_repayAndDeposit`. `verifyDebtMax` then checks the remaining debt.
Handler behavior depends on the selected route and mode. Generic handlers can execute calldata built offchain, so applications should review the complete payload rather than assume every `SwapParams` field is enforced onchain.
### Verifier output paths
| Function | Checked condition | Action after the check |
| ---------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `verifyAmountMinAndSkim` | At least `amountMin` assets are available to skim from an EVault before `deadline` | Skims the available assets to `receiver` |
| `verifyAmountMinAndDeposit` | The verifier holds at least `amountMin` underlying assets before `deadline` | Deposits its balance into the selected ERC-4626 vault for `receiver` |
| `verifyAmountMinAndTransfer` | The verifier holds at least `amountMin` of the asset before `deadline` | Transfers its balance to `receiver` |
| `verifyDebtMax` | Account debt is no greater than `amountMax` before `deadline` | Checks the resulting debt without performing repayment |
### Example: swap collateral to repay debt
1. Withdraw collateral to `Swapper`.
2. Execute the swap in target-debt mode. `Swapper` performs the repayment and can deposit surplus output according to the selected mode.
3. Call `SwapVerifier.verifyDebtMax` to check that the remaining debt is within the configured maximum.
4. Complete the EVC account and vault status checks.
### Security and integration checks
* Confirm the chain, contracts, tokens, vaults, account, receiver, handler, target, calldata, approvals, and output destination.
* Set amount or debt bounds and deadlines from the quote reviewed by the user, allowing for fees, slippage, interest accrual, and rounding.
* Simulate the complete ordered batch against current state.
* Keep approvals to `Swapper` scoped to the intended transaction.
* Check the resulting balances, debt, controller, collateral set, and account health after execution.
### Read next
* [Order flow router](/build/periphery/orderflow-router)
* [Periphery contracts](/build/periphery)
* [EVC security considerations](/build/evc/security)
## Interacting with vaults
Euler Vault Kit (EVK) vaults extend ERC-4626 with borrowing and repayment. This guide covers the direct contract calls and EVC batch patterns used by applications, bots, and smart contracts.
Use the ABI and chain-specific addresses from [`euler-interfaces`](https://github.com/euler-xyz/euler-interfaces). Before submitting a transaction, verify the selected vault's asset, factory provenance, EVC, hooks, caps, collateral configuration, oracle route, liquidity, and governance state.
:::note
Direct vault calls work for simple actions. Use the [Ethereum Vault Connector integration guide](/build/evc/integration-guide) when a flow needs atomic batching, sub-accounts, controller or collateral changes, operators, or simulation. For offchain TypeScript integrations, the [Euler SDK](/build/sdk) abstracts both the direct calls and the EVC patterns away.
:::
### Deposit assets
An EVK deposit follows ERC-4626: the authenticated caller supplies underlying assets and `receiver` receives vault shares.
```solidity
IERC20 asset = IERC20(IEVault(vault).asset());
// Approve the vault to pull the underlying asset.
asset.approve(vault, assets);
// Deposit assets and mint shares to receiver.
uint256 shares = IEVault(vault).deposit(assets, receiver);
```
Use `previewDeposit`, `maxDeposit`, and transaction simulation before execution. The actual result remains subject to rounding, caps, hooks, token behavior, and state changes before inclusion.
#### Permit2 allowances
EVK vaults can pull assets through an existing Permit2 allowance before falling back to the underlying token's `transferFrom` allowance. A signed Permit2 message does not authorize the vault merely by being passed to `deposit`: the permit must first be applied to Permit2, either in an earlier call or as part of a reviewed batched flow.
A user normally needs an underlying-token approval to Permit2 once, followed by a scoped Permit2 allowance for the selected vault. Check the Permit2 address configured by the vault, allowance amount, expiration, nonce, chain, token, and spender before signing or submitting anything.
See the [Permit2 repository](https://github.com/Uniswap/permit2) for its interfaces and signature format.
### Withdraw or redeem
Use `withdraw` when specifying an asset amount, or `redeem` when specifying a share amount:
```solidity
// Burn enough owner shares to receive an exact asset amount.
uint256 sharesBurned = IEVault(vault).withdraw(assets, receiver, owner);
// Burn an exact share amount and receive the resulting assets.
uint256 assetsReceived = IEVault(vault).redeem(shares, receiver, owner);
```
The authenticated caller must be `owner` or have sufficient vault-share allowance from `owner`. A withdrawal can still fail because of insufficient vault cash, account-health checks, hooks, or concurrent state changes. For borrowing accounts, simulate the complete EVC flow rather than relying only on `maxWithdraw` or `maxRedeem`.
Do not send underlying assets to an unsigned EVC-derived sub-account. Set `receiver` to an address that can control the received ERC-20 tokens unless the exact receiver flow is EVC-aware and reviewed.
### Borrow assets
Borrowing uses two different vault roles:
* The **collateral vault** holds the account's collateral shares.
* The **borrow vault** is the liability vault, becomes the account's controller, and sends its underlying asset to the borrow receiver.
The borrow vault must accept the collateral vault through a nonzero current LTV configuration.
```solidity
// 1. Deposit the collateral asset.
IERC20 collateralAsset = IERC20(IEVault(collateralVault).asset());
collateralAsset.approve(collateralVault, collateralAmount);
IEVault(collateralVault).deposit(collateralAmount, account);
// 2. Enable collateral and the liability/controller vault.
IEVC(evc).enableCollateral(account, collateralVault);
IEVC(evc).enableController(account, borrowVault);
// 3. Borrow from the liability vault.
uint256 borrowed = IEVault(borrowVault).borrow(borrowAmount, receiver);
```
The debt belongs to the EVC-authenticated `account`; `receiver` only controls where the borrowed tokens are sent. Check both borrow and liquidation LTVs, oracl프로젝트로 돌아가기