A simple Solana vault program built with the Anchor framework.
This project demonstrates how to create, deposit to, withdraw from, and close a vault account on Solana, with full TypeScript tests.
This project is a minimal Solana smart contract (program) for a "vault" system, where each user can:
- Initialize their own vault (a PDA account)
- Deposit SOL into their vault
- Withdraw SOL from their vault
- Close their vault and reclaim all funds
All logic is written in Rust using Anchor, and tested with TypeScript using the Anchor test framework.
- Each user gets a unique vault (like a private bank account)
- Deposit and withdraw SOL at any time
- Only the owner can access their vault
- Vaults are Program Derived Addresses (PDAs) for security
- Full test suite in TypeScript
- Rust program: Located in
programs/anchor-vault/src/lib.rs - TypeScript tests: Located in
tests/anchor-vault.ts
The program uses Program Derived Addresses (PDAs) to create unique vault accounts for each user, ensuring only the owner can interact with their vault.
- Stores bump seeds for address derivation.
- Created with seeds:
['state', user_pubkey]
- Holds the actual SOL.
- Created with seeds:
['vault', vault_state_pubkey]
- The user interacting with the vault.
- The built-in Solana program for account creation and SOL transfers.
- Creates a new
vault_stateandvaultPDA for the user. - Transfers enough SOL to make the vault rent-exempt.
- Transfers SOL from the user to their vault.
- Transfers SOL from the vault back to the user.
- Uses PDA seeds to sign for the vault.
- Transfers all remaining SOL from the vault to the user.
- Closes the
vault_stateaccount, returning rent to the user.
# Install dependencies
yarn install
# Build the program
anchor build
# Run tests (this will start a local validator, deploy, and test)
anchor testanchor-vault/
├── Anchor.toml # Anchor config
├── Cargo.toml # Rust workspace config
├── programs/
│ └── anchor-vault/
│ ├── Cargo.toml
│ └── src/
│ └── lib.rs # Main program logic
├── tests/
│ └── anchor-vault.ts # TypeScript tests
├── migrations/
│ └── deploy.ts
├── package.json
├── tsconfig.json
└── target/ # Build output (auto-generated)
- The user calls
initialize, which creates their unique vault accounts.
- The user calls
deposit(amount)to move SOL into their vault.
- The user calls
withdraw(amount)to move SOL from their vault back to their wallet.
- The user calls
closeto empty the vault and reclaim rent.
All these actions are tested in tests/anchor-vault.ts using the Anchor TypeScript client.
MIT
This project is a great starting point for learning Anchor and Solana PDAs! Feel free to fork, modify, and experiment.