bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 26쪽 중 22쪽
e units and freshness, available cash, the borrow cap, interest rate, and resulting account health.
An account can have only one enabled controller at a time. Use separate [sub-accounts](/learn/sub-accounts) for positions with different liability vaults.
### Repay debt
The caller supplies the borrow asset and the second argument identifies the account whose debt is reduced:
```solidity
uint256 currentDebt = IEVault(borrowVault).debtOf(debtAccount);
IERC20 borrowAsset = IERC20(IEVault(borrowVault).asset());
// The allowance can include a buffer for interest that accrues before repay.
// repay(max, ...) still pulls only the amount actually owed.
uint256 repaymentAllowance = currentDebt + (currentDebt / 100);
borrowAsset.approve(borrowVault, repaymentAllowance);
// type(uint256).max repays the account's full current debt.
uint256 repaid = IEVault(borrowVault).repay(
type(uint256).max,
debtAccount
);
```
For a partial repayment, pass an amount no greater than the current debt. Do not add an asset-amount buffer to a partial `repay`, because repaying more than the debt can revert. For a full repayment, approve enough for accrued debt and use `type(uint256).max`; the vault then pulls the amount actually owed.
Anyone can fund a repayment for `debtAccount`; the payer and debt account do not need to be the same address. The payer must control the asset balance and applicable vault or Permit2 allowance.
If the payer owns shares of the same borrow vault, `repayWithShares` can burn shares to reduce debt:
```solidity
(uint256 sharesBurned, uint256 assetsRepaid) =
IEVault(borrowVault).repayWithShares(
type(uint256).max,
debtAccount
);
```
`repayWithShares` authenticates the share holder through the EVC context. Simulate it when the share value, debt, or exchange rate may change.
### Batch a collateral deposit and borrow
The EVC can enable collateral, deposit, enable the controller, and borrow atomically. Calls targeting the EVC itself use `onBehalfOfAccount: address(0)`; vault calls use the account being authenticated.
```solidity
IEVC.BatchItem[] memory items = new IEVC.BatchItem[](4);
items[0] = IEVC.BatchItem({
targetContract: address(evc),
onBehalfOfAccount: address(0),
value: 0,
data: abi.encodeCall(
IEVC.enableCollateral,
(account, collateralVault)
)
});
items[1] = IEVC.BatchItem({
targetContract: collateralVault,
onBehalfOfAccount: account,
value: 0,
data: abi.encodeCall(
IEVault.deposit,
(collateralAmount, account)
)
});
items[2] = IEVC.BatchItem({
targetContract: address(evc),
onBehalfOfAccount: address(0),
value: 0,
data: abi.encodeCall(
IEVC.enableController,
(account, borrowVault)
)
});
items[3] = IEVC.BatchItem({
targetContract: borrowVault,
onBehalfOfAccount: account,
value: 0,
data: abi.encodeCall(
IEVault.borrow,
(borrowAmount, receiver)
)
});
IEVC(evc).batch(items);
```
This example assumes the collateral asset allowance already exists. If the flow applies a signed permit, include and validate the correct approval call before the deposit. EVC account and vault-status checks can be deferred until the end of a batch, but each item's ordering, authentication, allowance, and receiver semantics still matter.
Simulate the final batch against the intended chain and block, then re-check the decoded calls before signing.
### Flash liquidity
EVault exposes `flashLoan(uint256 amount, bytes data)`. It transfers the requested underlying asset to the EVC-authenticated caller, invokes `onFlashLoan(data)` on that caller, and requires the vault's asset balance to be restored before the callback completes.
```solidity
contract FlashBorrower is IFlashLoan {
using SafeERC20 for IERC20;
IEVault public immutable vault;
IERC20 public immutable asset;
constructor(IEVault vault_) {
vault = vault_;
asset = IERC20(vault_.asset());
}
function execute(uint256 amount, bytes calldata userData) external {
// Production code must add its own caller authorization.
vault.flashLoan(amount, abi.encode(amount, userData));
}
function onFlashLoan(bytes memory data) external {
require(msg.sender == address(vault), "unexpected vault");
(uint256 amount, bytes memory userData) =
abi.decode(data, (uint256, bytes));
// Perform the reviewed atomic operation using amount and userData.
asset.safeTransfer(address(vault), amount);
}
}
```
The standard balance check requires repayment in the same transaction. A configured hook can impose additional policy or fees, and the borrower contract must restrict who can start the flow and what external calls can be made. Verify available vault cash and simulate the complete callback path.
### Assets and shares
Assets are units of the vault's underlying ERC-20; shares represent proportional ownership of the vault. Their exchange rate changes as interest accrues and fees or losses affect the vault.
Use the ERC-4626 conversion and preview functions rather than copying the vault's internal accounting formula:
```solidity
uint256 assetsForShares = IEVault(vault).convertToAssets(shares);
uint256 sharesForAssets = IEVault(vault).convertToShares(assets);
uint256 expectedShares = IEVault(vault).previewDeposit(assets);
uint256 sharesToBurn = IEVault(vault).previewWithdraw(assets);
```
Conversions can round differently depending on the operation. Read the underlying and share decimals independently, preserve integer precision, and treat previews as state-dependent estimates rather than execution guarantees.
### Integration checklist
Before executing a vault interaction:
1. Resolve the chain-specific EVC, vault, asset, ABI, and Permit2 addresses from current sources.
2. Verify factory provenance, proxy or implementation status, asset, decimals, and bytecode.
3. Check caps, cash, hooks, pause state, controller, collateral set, LTVs, oracle path, and governance.
4. Keep the authenticated account, share owner, debt account, token payer, and asset receiver distinct in the integration model.
5. Decode every approval and call, simulate the final payload, and enforce slippage or outcome bounds where the operation supports them.
6. Re-read live state after confirmation; indexed data and simulations can lag or become stale.
### Read next
* [EVC integration guide](/build/evc/integration-guide)
* [Euler SDK](/build/sdk)
* [EVK overview](/curate/vaults/evk/overview)
* [Contract addresses](/build/contract-addresses)
* [Lens contracts](/build/data-querying/using-lens-contracts)
## EVC utils guide
[`EVCUtil.sol`](https://github.com/euler-xyz/ethereum-vault-connector/blob/master/src/utils/EVCUtil.sol) is a utility abstract contract designed to make it easier to build contracts that interact with the [**Ethereum Vault Connector (EVC)**](/build/evc). It provides authentication helpers, context-aware modifiers, and patterns for enforcing that your contract is called through the EVC when required.
### Why use `EVCUtil`?
* **Authentication:** Checks that your contract is called by the EVC in the correct context, reducing unauthorized-access risk when implemented correctly.
* **Context Awareness:** Provides helpers to retrieve the true sender (`onBehalfOfAccount`) and to check if your contract is being called as part of a batch, liquidation, or operator action.
* **Implementation Patterns:** Encourages consistent patterns for vaults, modules, and periphery contracts that need to integrate with the EVC.
### Key features and patterns
#### 1. `callThroughEVC` modifier
The `callThroughEVC` modifier routes a function through the EVC, even if it is called directly. If the call does not originate from the EVC, the modifier will route the call through the EVC's `call()` method, which then calls back into the contract with the correct execution context.
**Why is this needed?**
Vaults and contracts often rely on the EVC to trigger the requested account and vault status checks. These checks typically must be performed at the end of the operation or batch. By using `callThroughEVC`, direct calls are routed through the same context so status checks are deferred to the end of the operation or batch.
**Usage:**
```solidity
function myFunction() external callThroughEVC {
// This will always execute in the correct EVC context
}
```
#### 2. `onlyEVCAccount` and `onlyEVCAccountOwner` modifiers
* `onlyEVCAccount`: Uses the standard authentication rule allowing the account owner or any of its EVC accounts.
* `onlyEVCAccountOwner`: Uses the standard authentication rule allowing only the account owner. This modifier is typically used for governance functions that should only be callable by the account owner.
**Usage:**
```solidity
function restrictedAction() external onlyEVCAccount {
// Only callable by the EVC or a valid EVC account
}
```
#### 3. `_msgSender` and `_msgSenderForBorrow`
* `_msgSender()`: Returns the logical sender, resolving the EVC context if needed.
* `_msgSenderForBorrow()`: Like `_msgSender`, but also checks that the contract is enabled as a controller for the account.
**Usage:**
```solidity
function doSomething() external {
address user = _msgSender();
// Use 'user' as the logical sender
}
```
#### 4. Address prefix and common owner checks
* `_getAddressPrefix(address)`: Returns the 19-byte prefix shared by all sub-accounts of an owner.
* `_haveCommonOwner(address, address)`: Checks if two accounts share the same owner (i.e., same prefix).
**Usage:**
```solidity
bytes19 prefix = _getAddressPrefix(account);
bool sameOwner = _haveCommonOwner(account1, account2);
```
### Example: minimal EVC-aware contract
```solidity
import "ethereum-vault-connector/utils/EVCUtil.sol";
contract Example is EVCUtil {
constructor(address evc) EVCUtil(evc) {}
function onlyEVCOwnerOperation() external onlyEVCAccountOwner {
address user = _msgSender();
// ...
}
}
```
### Read next
* [EVC overview](/build/evc)
* [EVC integration guide](/build/evc/integration-guide)
* [EVC implementation security](/build/evc/security)
## Overview
**The Ethereum Vault Connector (EVC)** is the account and coordination layer for modular lending in Euler V2. Acting as the primary entry point for advanced interactions, the EVC lets integrators build, automate, and orchestrate multi-step workflows across multiple vaults. For offchain TypeScript integrations, the [Euler SDK](/build/sdk) abstracts most of these workflows; the pages in this section cover the contract level.
### What the EVC coordinates
In Euler V2, the EVC mediates cross-vault operations:
* **Batching:** Group multiple actions (deposits, borrows, swaps, repayments, etc.) into a single atomic transaction.
* **Sub-accounts:** Create up to 256 separated positions per wallet, enabling strategy separation and clearer account-level risk tracking.
* **Operators:** Delegate control of sub-accounts to reviewed contracts or automation bots for advanced use cases, such as stop-loss or intent-based trading.
* **Signed delegation:** Authorize delegated execution with signed messages through the EVC `permit` function.
* **Deferred checks:** Defer required account and vault status checks until the end of a call or batch. Only constraints represented by those required checks are deferred.
* **Unified Authentication:** The EVC handles authentication, so vaults can focus on authorization and business logic.
### Core concepts
#### Batching
The EVC's batching system allows integrators to bundle multiple operations, across different vaults and even external contracts, into a single transaction. All operations succeed or fail together, which reduces partial-execution risk within that batch.
#### Sub-accounts
Each user address is granted 256 virtual sub-accounts. These allow for position separation and management of multiple strategies under a single wallet. Risk is still determined by the vaults, controllers, collateral, and operators enabled for each sub-account.
#### Operators
Operators generalize the concept of token approvals. By assigning an operator to a sub-account, users can delegate control to automation contracts, keepers, or other parties. Operator permissions should be granted only after reviewing the delegated contract or account.
The EVC `permit` function lets an account owner sign an authorization offchain so another address can submit it onchain. Integrators can use this for delegated execution flows, while still treating the signed message as a sensitive permission that should be scoped and reviewed before signing.
#### Deferred checks and atomicity
Vaults request account and vault status checks, and the EVC can defer those checks until the end of a call or batch. Intermediate state may violate constraints represented by the deferred checks; the transaction succeeds only if all required final checks pass. A vault that fails to request the correct check is not protected by deferral. Integrators should model the full execution flow and failure cases.
#### Authentication and authorization
The EVC authenticates the originator of every action, while vaults retain control over authorization. This separation of concerns keeps account authentication and vault-level permissioning distinct.
#### Liquidations
Liquidations are orchestrated through the EVC so debt transfer or takeover, collateral seizure, and any liquidation incentive logic are executed atomically according to the controller vault's rules.
A key part of this process is the EVC's `controlCollateral` function. When a borrower's position becomes undercollateralized, the liability (controller) vault can invoke `controlCollateral` to seize collateral from the borrower's enabled collateral vaults. This function lets the controller vault transfer or withdraw collateral on behalf of the account in violation while the liquidator takes over the corresponding debt. From the collateral vault's perspective, this appears as a standard withdrawal or share transfer, but it is executed under the EVC's controller context and the liability vault's liquidation rules.
### What integrators can do with the EVC
* Build custom frontends and bots that leverage batching, sub-accounts, and operators
* Create advanced automation, such as stop-loss, auto-rebalancing, or liquidation-response tooling
* Integrate with other protocols using atomic cross-vault operations
* Simulate complex transactions before execution
* Design new market structures and risk management systems
For a full technical reference, see the [EVC whitepaper](https://github.com/euler-xyz/ethereum-vault-connector/blob/master/docs/whitepaper.md), the [EVC repository](https://github.com/euler-xyz/ethereum-vault-connector) or the EVC dedicated [website](https://evc.wtf).
### Read next
* [EVC implementation security](/build/evc/security)
* [Interact with Euler](/build/evc/integration-guide)
* [EVC utils](/build/evc/evc-utils)
* [Build](/build)
## Interact with Euler
Use the EVC when an integration needs authenticated batching, sub-accounts, collateral and controller management, operators, permits, simulation, or cross-vault actions. The examples below are building blocks; production integrations must resolve deployed interfaces, approvals, account state, and target-chain addresses. For offchain TypeScript integrations, the [Euler SDK](/build/sdk) abstracts these EVC patterns — batching, sub-accounts, permits, and simulation — behind typed helpers; this guide shows the underlying contract-level calls.
:::warning
**Derived-account token safety**
Most ERC-20 tokens are **not EVC-aware**. An EVC sub-account is an ordinary address derived by XOR, but its owner does not hold a separate private key for that derived address. EVC-aware contracts can authenticate its owner through EVC context; an ordinary ERC-20 transfer cannot.
Do not send ordinary ERC-20 tokens directly to a derived sub-account address unless a reviewed EVC-aware recovery flow exists for that exact token and integration. A normal ERC-20 contract cannot authenticate the EVC owner, so the owner generally cannot transfer those tokens back with a wallet signature. This is different from depositing into a vault with the sub-account as share receiver: the vault shares are managed through EVC-aware vault logic.
:::
### 1. Batching operations
Batching lets you group multiple actions into a single atomic transaction. Use the `batch` function and the `BatchItem` struct:
```solidity
IEVC.BatchItem[] memory items = new IEVC.BatchItem[](2);
// Example: Deposit collateral and then borrow in a single batch.
// Assumes the collateral asset is approved and the collateral/controller
// vaults are already enabled for myAccount.
items[0] = IEVC.BatchItem({
targetContract: collateralVault,
onBehalfOfAccount: myAccount,
value: 0,
data: abi.encodeWithSelector(IVault.deposit.selector, depositAmount, myAccount)
});
items[1] = IEVC.BatchItem({
targetContract: borrowVault,
onBehalfOfAccount: myAccount,
value: 0,
data: abi.encodeWithSelector(IVault.borrow.selector, borrowAmount, myAccount)
});
connector.batch(items);
```
All operations succeed or fail together. You can batch across multiple vaults and even external contracts.
### 2. Using sub-accounts
Sub-accounts allow you to separate positions and strategies. Each address prefix has 256 derived account addresses. Token allowances, vault collateral/controller enablement, and operator permissions are separate mechanisms and can still be required for a workflow.
#### Address structure and derivation
All 256 sub-accounts belonging to the same owner share the first 19 bytes of their Ethereum address. The only difference between them is the very last byte. This means that, on-chain, you can easily recognize which sub-accounts belong to the same owner: they will look almost identical, except for the final two characters.
A sub-account address is created by XOR-ing your main address with a number from 0 to 255 (as a `uint8`).
* Your main address is sub-account 0 (no change).
* Sub-account 1 is your address XOR 1, sub-account 2 is your address XOR 2, and so on up to 255.
This structure makes sub-accounts easy to group and identify onchain while preserving unique addresses for each sub-account.
##### Example: deriving a sub-account address in Solidity
```solidity
function getAccount(address owner, uint8 accountId) public pure returns (address) {
return address(uint160(owner) ^ uint160(accountId));
}
// Usage:
address myAddress = /* your main address */;
address account3 = getAccount(myAddress, 3); // This is your 4th sub-account
```
For each operation, distinguish the account authenticated through `onBehalfOfAccount` from the address that receives assets or shares:
* **Deposits:**
* `onBehalfOfAccount` must be an address that actually controls the ERC-20 balance and allowance—commonly the main wallet. A typical XOR-derived EOA sub-account has no separate signer.
* The `receiver` parameter (in the deposit function) can be a sub-account address, so the deposited shares are credited to the sub-account.
* **Borrows:**
* `onBehalfOfAccount` should be the sub-account for which you want to create the debt position.
* The `receiver` should be an address that can control the received ERC-20 tokens—commonly the main wallet—not an unsigned derived address.
##### Example: deposit to a sub-account
```solidity
// Deposit tokens from your main address, but credit the shares to subAccount3
IEVC.BatchItem[] memory items = new IEVC.BatchItem[](1);
items[0] = IEVC.BatchItem({
targetContract: vault,
onBehalfOfAccount: myAddress, // tokens are pulled from here
value: 0,
data: abi.encodeWithSelector(IVault.deposit.selector, depositAmount, subAccount3) // shares go to sub-account
});
connector.batch(items);
```
##### Example: borrow from a sub-account
```solidity
// Borrow on behalf of subAccount3, but send tokens to your main address
IEVC.BatchItem[] memory items = new IEVC.BatchItem[](1);
items[0] = IEVC.BatchItem({
targetContract: vault,
onBehalfOfAccount: subAccount3, // debt is created here
value: 0,프로젝트로 돌아가기