EVM -> Solana

Solana에서 ERC4626이란?

ERC‑4626은 토큰화된 볼트(Tokenized Vault) 표준으로, 하나의 기초 ERC‑20 자산을 받아 비례 소유권을 나타내는 지분 토큰을 발행하는 볼트의 표준 인터페이스를 정의합니다. 입금/발행/출금/상환(deposit/mint/withdraw/redeem) 라이프사이클을 공식화하며, 오프체인에서 안전하게 미리 확인할 수 있는 조회 함수도 제공합니다.

Key Characteristics

  • 단일 자산 보관: 볼트는 하나의 ERC‑20만 보유하며, 모든 계산은 해당 자산 기준으로 표현됩니다.
  • 지분 회계: totalAssets() ↔ totalSupply(); convertToShares()와 convertToAssets()가 예측 가능한 비율을 보장합니다.
  • 조합 가능한 인터페이스: DEX, 애그리게이터, 프런트엔드가 별도의 어댑터 없이 표준을 준수하는 모든 볼트와 통합할 수 있습니다.
  • 전략에 구애받지 않음: 일드 파밍, 대출, 스테이킹, 델타 중립 등 어떤 전략이든 동일한 인터페이스 뒤에서 동작합니다.

Solana 프로그램 및 계정 모델

'프로그램'이란 정확히 무엇일까요?

Solana 프로그램은 한 번 배포하면 계속 재사용하는 공유 ELF‑BPF 바이너리입니다. 상태가 없는 순수한 로직이며 변경할 수 없고, 거버넌스가 제어하는 “ProgramData” 계정을 통해서만 업그레이드할 수 있습니다.

LaTeX
Program  ──┐
           └─> handles instructions
Accounts ───┘  (carry all mutable state)

배포 감각: Uniswap‑v2 Router가 배포할 유일한 스왑 컨트랙트라고 생각해 보세요. 새로운 유동성 풀은 새 컨트랙트가 아니라 Router가 제어하는 새 데이터 계정이 됩니다.

계정 = 스토리지 컨테이너

Solana에서 계정을 생성할 때는 먼저 정확한 데이터 크기를 지정합니다(예: space = 128 bytes). 그러면 블록체인이 해당 크기만큼의 스토리지를 확보하고, 사용자는 그 크기에 비례하는 lamport(네트워크의 수수료 통화)를 예치합니다. 예치금이 rent 면제 기준을 충족하면 해당 계정은 이후 rent를 계속 내지 않아도 됩니다. 또한 각 계정에는 특정 프로그램의 공개 키를 저장하는 owner 필드가 있으며, 해당 프로그램만 계정의 데이터를 수정할 수 있습니다. 다른 프로그램에서 보낸 트랜잭션은 이를 변경할 수 없습니다.

PDA(Program Derived Address)

Program Derived Address(PDA)는 프로그램 ID와 고정된 시드 집합으로부터 결정론적으로 생성되므로 개인 키가 없습니다. 오프체인에서 트랜잭션에 서명할 수 없기 때문에, 프로그램이 invoke_signed()를 호출하면 Solana 런타임이 합성 서명을 제공하여 PDA가 서명한 것처럼 처리합니다. 덕분에 프로그램은 PDA를 자신의 지갑처럼 사용해 민트 권한, 토큰 계정, 설정 데이터를 보유할 수 있으며, 키 탈취나 권한 위조의 위험도 없앨 수 있습니다. 결과적으로 PDA 자체가 소유자가 되어, Solidity의 onlyOwner 패턴을 Solana의 내장 권한 모델로 대체합니다.

CPI(Cross Program Invocation)

위의 token::transfer(...) 호출은 SPL Token program에 대한 Cross Program Invocation을 수행합니다. Ethereum의 IERC20.transferFrom과 같은 역할을 하지만, Solana의 계정 모델에서는 호출되는 프로그램이 읽거나 쓸 모든 계정(from, to, authority)과 PDA 서명자 시드를 함께 제공해야 합니다. 명령이 실행되기 전에 런타임이 각 계정에 필요한 쓰기 가능 또는 서명자 권한이 있는지 검증하므로, 전송은 원자적으로 실행되며 동적 재진입 공격이 발생할 여지가 없습니다.

ERC‑4626 방식 볼트 입금의 권한 흐름

Deposit

  • 트랜잭션 포함 항목: 사용자의 Token Account(서명자), Vault Token Account(쓰기 가능), Share Mint(쓰기 가능), Vault State PDA(쓰기 가능).
  • CPI #1 → spl_token::transfer 사용자 → 볼트.

Withdraw / Redeem

  • 역순으로 진행: 지분 소각 → 기초 자산 전송.

프로그램 내부 상태 업데이트 (vault_state.total_assets += amount)

트랜잭션에서 접근하는 모든 계정이 명시적으로 드러나므로, 지갑은 부수 효과를 시뮬레이션하고 서명 시점에 사용자에게 정확한 미리보기를 보여줄 수 있습니다.

ERC-4626용 Token Extension Program은 어떤 모습일까요?

이 컨트랙트는 ERC 4626 경제 모델을 따르면서 외부 Spl20 토큰을 기초 자산으로 사용하는 볼트를 구현합니다. 생성자에서 Spl20 컨트랙트 주소와 해당 토큰의 민트 주소를 기록한 다음, Spl20 인터페이스를 통해 토큰의 소수 자릿수(assetDecimals)를 조회합니다. 볼트의 총 자산은 totalAssets 함수에서 Spl20 컨트랙트의 getTokenAccount를 호출하고, 이 컨트랙트 주소가 보유한 잔액을 읽어 가져옵니다. 이 값을 바탕으로 convertToShares와 convertToAssets가 기초 자산과 볼트 지분 간의 올바른 비율을 유지합니다.

셰어는 별도의 토큰 컨트랙트를 통해 발행되지 않고, 단순한 shareBalance 및 shareAllowance 매핑으로 추적되며, _mint 및 _burn 함수가 전체 셰어 공급량(totalShareSupply)을 업데이트합니다. 예치 시 컨트랙트는 먼저 들어오는 자산 수량이 0보다 큰지 확인하고, spl20.transfer로 해당 자산을 볼트로 옮긴 뒤, 비례하는 셰어 수량을 계산하여 수령자에게 지급합니다. 상환 시에는 소유권 또는 허용량(allowance)을 확인하고, 지정된 셰어를 소각한 다음, 또 다른 spl20.transfer를 통해 그에 상응하는 수량의 기초 자산을 수령자에게 돌려보냅니다.

커스텀 nonReentrant modifier가 상태를 변경하는 두 함수를 모두 보호합니다. 진입 시 locked 플래그를 설정해 중첩 호출을 차단하고 종료 시 해제하여 재진입 공격을 방지합니다. 전체적으로 이 컨트랙트는 사용자가 Spl20 토큰을 예치하고 인출할 때 내부 셰어를 발행하고 소각하는 최소한의 ERC 4626 스타일 볼트를 제공하며, 자산 대비 셰어 비율을 유지하고, 기본적인 승인 로직과 재진입 방지 기능을 포함하면서도 외부 셰어 토큰 구현에 의존하지 않습니다.

Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface ISpl20 {
    function mintTokens(address to, address mintAddr, uint256 amount) external;
    function transfer(address to, address mintAddr, uint256 amount) external;
    function getMint(address mintAddr) external view returns (uint8, uint256, address, address, address);
    function getTokenAccount(address owner, address mintAddr) external view returns (address, address, uint256, bool);
}

contract Spl4626Vault {
    ISpl20  public immutable spl20;
    address public immutable mintAddr;
    uint8   public immutable assetDecimals;
    uint256 public totalShareSupply;

    mapping(address => uint256) public shareBalance;
    mapping(address => mapping(address => uint256)) public shareAllowance;

    bool private locked;

    event Approval(address indexed owner, address indexed spender, uint256 value);
    event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
    event Withdraw(address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares);

    modifier nonReentrant() {
        require(!locked, "REENTRANCY");
        locked = true;
        _;
        locked = false;
    }

    constructor(ISpl20 _spl20, address _mintAddr) {
        spl20 = _spl20;
        mintAddr = _mintAddr;
        (uint8 dec,, , ,) = _spl20.getMint(_mintAddr);
        assetDecimals = dec;
    }

    function totalAssets() public view returns (uint256 assets) {
        (, , assets, ) = spl20.getTokenAccount(address(this), mintAddr);
    }

    function convertToShares(uint256 assets) public view returns (uint256) {
        return totalShareSupply == 0 ? assets : (assets * totalShareSupply) / totalAssets();
    }

    function convertToAssets(uint256 shares) public view returns (uint256) {
        return totalShareSupply == 0 ? shares : (shares * totalAssets()) / totalShareSupply;
    }

    function _mint(address to, uint256 amount) internal {
        totalShareSupply += amount;
        shareBalance[to] += amount;
    }

    function _burn(address from, uint256 amount) internal {
        shareBalance[from] -= amount;
        totalShareSupply -= amount;
    }

    function approve(address spender, uint256 amount) external returns (bool) {
        shareAllowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function deposit(uint256 assets, address receiver) external nonReentrant returns (uint256 shares) {
        require(assets > 0, "zero assets");
        spl20.transfer(address(this), mintAddr, assets);
        shares = convertToShares(assets);
        _mint(receiver, shares);
        emit Deposit(msg.sender, receiver, assets, shares);
    }

    function redeem(uint256 shares, address receiver, address owner) external nonReentrant returns (uint256 assets) {
        require(shares > 0, "zero shares");
        if (msg.sender != owner) {
            uint256 allowed = shareAllowance[owner][msg.sender];
            require(allowed >= shares, "allowance too low");
            if (allowed != type(uint256).max) {
                shareAllowance[owner][msg.sender] = allowed - shares;
            }
        }
        assets = convertToAssets(shares);
        _burn(owner, shares);
        spl20.transfer(receiver, mintAddr, assets);
        emit Withdraw(msg.sender, receiver, owner, assets, shares);
    }
}

솔라나에서 ERC4626 구현하는 방법

1. conceptual map

Piece온체인 객체Purpose
기초 자산 민트민트 (이미 존재함)ERC-20에 해당하는 자산 (예: USDC)
셰어 민트새 민트 (PDA 권한)볼트에 대한 비례 지분을 추적
Vault ATAtoken account (PDA 소유)기초 자산을 보관
Vault State PDA소규모 데이터 계정저장 항목: share_mint, pda_bump, 선택적 수수료
token account Owner PDA서명자 PDAVault ATA 및 셰어 민트에 대한 권한

하나의 tx는 항상 정확히 하나의 기초 자산을 이동시키며, 필요한 경우 정확히 비례하는 수량의 셰어를 발행/소각합니다. 나머지는 모두 장부 관리입니다.

2. 엔드투엔드 호출 흐름 (간략화)

1) deposit (자산 → 셰어)

2) tx composer (지갑)

  • 추가: user ata, vault ata, share mint, vault state, pda, Token Program
  • 프로그램 deposit(assets) 호출

3) 프로그램

  • token::transfer (user → vault)
  • 셰어 계산: shares = assets * total_supply / total_assets
  • token::mint_to (shares → user), token_account_owner_pda를 서명자로 사용
  • vault_state.total_assets 업데이트 (선택 사항, 언제든 다시 계산 가능)
  • DepositEvt 발생

4) 지갑 미리보기: 모든 계정이 명시적으로 지정되어 있으므로 서명 전에 -X 자산 및 +Y 셰어를 표시할 수 있습니다.

5) redeem / withdraw (셰어 → 자산)는 동일한 순서를 역순으로 진행합니다.

3. Write program

ERC‑4626 클론처럼 동작하는 작은 솔라나 볼트를 출시한다고 상상해 보세요. 초기화 시 단일 트랜잭션으로 세 가지 핵심 PDA를 생성합니다. 셰어 민트 주소와 bump를 기록하는 VaultState 계정, 프로그램이 소유하는 셰어 민트, 그리고 기초 자산을 보관할 토큰 볼트 계정입니다. 동일한 PDA 서명자인 token_account_owner_pda는 VaultState 내부에 캐시되어, 프로그램이 개인 키를 노출하지 않고도 수탁자 역할을 할 수 있게 합니다. 사용자가 deposit을 호출하면 볼트는 사용자의 토큰을 가져오고, 비례하는 “셰어”를 발행하며, DepositEvt를 발생시켜 인덱서에 감사 추적 기록을 제공합니다. 첫 번째 예치자는 1 : 1 교환 비율을 적용받고, 이후 예치는 볼트 가치와 셰어를 일치시키기 위해 고전적인 supply × assets / totalAssets 공식을 사용합니다. 반대로 redeem은 사용자의 셰어를 소각하고, 전체 자산 중 사용자의 몫을 계산한 뒤, 기초 토큰을 다시 내보내며 확인 차원에서 WithdrawEvt도 발생시킵니다. 두 CPI 흐름 모두 token::transfer, mint_to, burn에만 의존하므로 Anchor의 안전 검사가 모든 잔액 변경을 보호합니다. 수익 전략이나 수수료 로직은 포함되어 있지 않으며, 이 스니펫은 전략을 연결할 수 있는 미니멀한 뼈대입니다. 약 90줄의 Rust 코드이지만, 이더리움에서 ERC‑4626 볼트를 연동해 본 사람이라면 누구에게나 익숙한 “예치, 발행, 인출, 상환”의 전체 라이프사이클을 제공합니다.

Rust
use anchor_lang::prelude::*;
use anchor_spl::token::{
    self, Mint, Token, TokenAccount,
    Transfer, MintTo, Burn,
} as const;

declare_id!("VaUlt4626pHkYwWjSfERn6y6oAYcg4UH8zQcAXXXXXXXXX"); // replace after deploy

#[account]
pub struct VaultState {
    pub share_mint: Pubkey,
    pub pda_bump:   u8,
}
const VAULT_STATE_SIZE: usize = 8 + 32 + 1;

#[program]
pub mod spl_4626_vault {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        let state        = &mut ctx.accounts.vault_state;
        state.share_mint = ctx.accounts.share_mint.key();
        state.pda_bump   = *ctx.bumps.get("token_account_owner_pda").unwrap();
        Ok(())
    }

    pub fn deposit(ctx: Context<Deposit>, assets: u64) -> Result<()> {
        require!(assets > 0, CustomError::ZeroAmount);
        token::transfer(ctx.accounts.transfer_into_vault_ctx(), assets)?;

        let supply        = ctx.accounts.share_mint.supply;
        let total_assets  = ctx.accounts.vault_token_account.amount;
        let shares = if supply == 0 {
            assets
        } else {
            (assets as u128 * supply as u128 / total_assets as u128) as u64
        };

        token::mint_to(ctx.accounts.mint_shares_ctx(), shares)?;

        emit!(DepositEvt {
            caller:   ctx.accounts.signer.key(),
            receiver: ctx.accounts.signer.key(),
            assets,
            shares,
        });
        Ok(())
    }

    pub fn redeem(ctx: Context<Redeem>, shares: u64) -> Result<()> {
        require!(shares > 0, CustomError::ZeroAmount);

        let supply        = ctx.accounts.share_mint.supply;
        let total_assets  = ctx.accounts.vault_token_account.amount;
        let assets        = (shares as u128 * total_assets as u128 / supply as u128) as u64;

        token::burn(ctx.accounts.burn_shares_ctx(), shares)?;
        token::transfer(ctx.accounts.transfer_out_ctx(), assets)?;

        emit!(WithdrawEvt {
            caller:   ctx.accounts.signer.key(),
            receiver: ctx.accounts.signer.key(),
            owner:    ctx.accounts.signer.key(),
            assets,
            shares,
        });
        Ok(())
    }
}

#[event]
pub struct DepositEvt {
    pub caller:   Pubkey,
    pub receiver: Pubkey,
    pub assets:   u64,
    pub shares:   u64,
}
#[event]
pub struct WithdrawEvt {
    pub caller:   Pubkey,
    pub receiver: Pubkey,
    pub owner:    Pubkey,
    pub assets:   u64,
    pub shares:   u64,
}

#[error_code]
pub enum CustomError {
    #[msg("amount must be > 0")]
    ZeroAmount,
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init,
        payer  = signer,
        seeds  = [b"vault_state"],
        bump,
        space  = VAULT_STATE_SIZE,
    )]
    pub vault_state: Account<'info, VaultState>,

    #[account(seeds = [b"token_account_owner_pda"], bump)]
    /// CHECK: program-derived signer
    pub token_account_owner_pda: AccountInfo<'info>,

    #[account(
        init,
        payer = signer,
        seeds = [b"share_mint"],
        bump,
        mint::decimals   = mint_of_token_being_sent.decimals,
        mint::authority  = token_account_owner_pda,
    )]
    pub share_mint: Account<'info, Mint>,

    #[account(
        init,
        payer = signer,
        seeds = [b"token_vault", mint_of_token_being_sent.key().as_ref()],
        bump,
        token::mint      = mint_of_token_being_sent,
        token::authority = token_account_owner_pda,
    )]
    pub vault_token_account: Account<'info, TokenAccount>,

    pub mint_of_token_being_sent: Account<'info, Mint>,

    #[account(mut)] pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
    pub token_program:  Program<'info, Token>,
    pub rent:           Sysvar<'info, Rent>,
}

#[derive(Accounts)]
pub struct Deposit<'info> {
    #[account(mut, seeds=[b"vault_state"], bump)]
    pub vault_state: Account<'info, VaultState>,
    #[account(seeds=[b"token_account_owner_pda"], bump)]
    /// CHECK:
    pub token_account_owner_pda: AccountInfo<'info>,

    #[account(mut,
        seeds=[b"token_vault", mint_of_token_being_sent.key().as_ref()],
        bump,
        token::mint      = mint_of_token_being_sent,
        token::authority = token_account_owner_pda
    )]
    pub vault_token_account: Account<'info, TokenAccount>,

    #[account(mut)] pub sender_token_account: Account<'info, TokenAccount>,
    #[account(mut)] pub sender_share_account: Account<'info, TokenAccount>,

    #[account(seeds=[b"share_mint"], bump)]
    pub share_mint: Account<'info, Mint>,
    pub mint_of_token_being_sent: Account<'info, Mint>,

    #[account(mut)] pub signer: Signer<'info>,
    pub token_program: Program<'info, Token>,
}

#[derive(Accounts)]
pub struct Redeem<'info> {
    #[account(mut, seeds=[b"vault_state"], bump)]
    pub vault_state: Account<'info, VaultState>,
    #[account(seeds=[b"token_account_owner_pda"], bump)]
    /// CHECK:
    pub token_account_owner_pda: AccountInfo<'info>,

    #[account(mut,
        seeds=[b"token_vault", mint_of_token_being_sent.key().as_ref()],
        bump,
        token::mint      = mint_of_token_being_sent,
        token::authority = token_account_owner_pda
    )]
    pub vault_token_account: Account<'info, TokenAccount>,

    #[account(mut)] pub sender_token_account: Account<'info, TokenAccount>,
    #[account(mut)] pub sender_share_account: Account<'info, TokenAccount>,

    #[account(seeds=[b"share_mint"], bump)]
    pub share_mint: Account<'info, Mint>,
    pub mint_of_token_being_sent: Account<'info, Mint>,

    #[account(mut)] pub signer: Signer<'info>,
    pub token_program: Program<'info, Token>,
}

impl<'info> Deposit<'info> {
    fn transfer_into_vault_ctx(&self) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
        CpiContext::new(
            self.token_program.to_account_info(),
            Transfer {
                from:      self.sender_token_account.to_account_info(),
                to:        self.vault_token_account.to_account_info(),
                authority: self.signer.to_account_info(),
            },
        )
    }
    fn mint_shares_ctx(&self) -> CpiContext<'_, '_, '_, 'info, MintTo<'info>> {
        let seeds = &[b"token_account_owner_pda", &[self.vault_state.pda_bump]];
        CpiContext::new_with_signer(
            self.token_program.to_account_info(),
            MintTo {
                mint:      self.share_mint.to_account_info(),
                to:        self.sender_share_account.to_account_info(),
                authority: self.token_account_owner_pda.to_account_info(),
            },
            &[seeds],
        )
    }
}

impl<'info> Redeem<'info> {
    fn burn_shares_ctx(&self) -> CpiContext<'_, '_, '_, 'info, Burn<'info>> {
        let seeds = &[b"token_account_owner_pda", &[self.vault_state.pda_bump]];
        CpiContext::new_with_signer(
            self.token_program.to_account_info(),
            Burn {
                mint:      self.share_mint.to_account_info(),
                from:      self.sender_share_account.to_account_info(),
                authority: self.token_account_owner_pda.to_account_info(),
            },
            &[seeds],
        )
    }
    fn transfer_out_ctx(&self) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
        let seeds = &[b"token_account_owner_pda", &[self.vault_state.pda_bump]];
        CpiContext::new_with_signer(
            self.token_program.to_account_info(),
            Transfer {
                from:      self.vault_token_account.to_account_info(),
                to:        self.sender_token_account.to_account_info(),
                authority: self.token_account_owner_pda.to_account_info(),
            },
            &[seeds],
        )
    }
}

모든 데이터를 저장하고 합의에 참여하는 노드

  • 이더리움: 아카이브 노드
  • 솔라나: [해당 없음]

일부 데이터를 저장하고 합의에 참여하는 노드

  • 이더리움: 풀 노드
  • 솔라나: 합의 노드

일부 데이터를 저장하고 합의에 참여하지 않는 노드

  • 이더리움: 라이트 노드
  • 솔라나: RPC 노드

Keep Learning

Solana의 ERC20 알아보기

Ethereum과 Solana의 토큰 발행 방식이 어떻게 다른지 확인해 보세요

Explore
Solana에서 ERC4626이란? | Solana