Empowering DeFi on Celo: A production-ready, upgradeable staking vault that combines security, efficiency, and user-centric design.
An upgradeable single-asset staking vault deployed on the Celo network, enabling users to deposit ERC20-compatible tokens (e.g., cUSD or custom Celo tokens) to earn time-based rewards. Built with Solidity, rigorously tested and deployed using Foundry, and leveraging OpenZeppelin's battle-tested upgradeable contracts for secure, proxy-based upgrades.
- Overview
- Key Highlights
- Features
- Architecture
- System Control Flow
- Getting Started
- Usage
- API Reference
- Testing
- Deployment
- Security
- Roadmap
- Contributing
- License
- Support
StakingVaultUpgradeable represents the next evolution in DeFi staking protocols, specifically tailored for the Celo ecosystem. By implementing a sophisticated "reward per token" index mechanism, the vault ensures mathematically precise, proportional reward distribution that scales with both stake size and duration.
- User Sovereignty: Funds remain under user control; no custodial risks
- Upgradeability: Future-proof design allowing seamless feature additions
- Transparency: On-chain accounting with verifiable reward calculations
- Efficiency: Optimized for Celo's high-throughput, low-latency environment
Dive into advanced DeFi concepts through this educational implementation:
- Smart Contract Patterns: Master proxy-based upgradeability
- Reward Economics: Understand index-based reward distribution
- Testing Methodologies: Learn Foundry's powerful testing framework
- Celo Integration: Explore cross-chain DeFi development
Accelerate your DeFi development with this extensible foundation:
- Modular Architecture: Easily extendable for custom reward mechanisms
- Production-Ready: Battle-tested components from OpenZeppelin
- Gas Optimization: Celo-optimized operations for cost efficiency
- Integration Friendly: Simple interfaces for frontend and protocol integration
Join a vibrant community shaping the future of DeFi:
- Open Development: Transparent roadmap and feature discussions
- Security-First: Collaborative security reviews and audits
- Innovation Hub: Propose and implement cutting-edge features
- Educational Impact: Contribute to DeFi education resources
- 🚀 Live on Celo: Deployed and operational on Celo mainnet
- 🔄 Zero-Downtime Upgrades: UUPS proxy enables seamless upgrades
- 💎 Audited Security: Built on OpenZeppelin audited contracts
- ⚡ Sub-Second Finality: Optimized for Celo's fast block times
- 📈 Scalable Rewards: Index-based system handles millions of users
- 🛡️ Multi-Sig Governance: Secure owner controls with timelocks
- 🔄 Upgradeable Architecture: UUPS proxy ensures future-proof upgrades without fund migration
- 💰 Advanced Reward Mechanism: Continuous accrual using reward-per-token index
- 🔐 Secure Ownership Model: Owner controls configuration; user funds remain sovereign
- ⚡ Gas-Optimized Operations: Efficient for Celo's high-throughput network
- 🧪 Comprehensive Test Suite: 100% test coverage with Foundry
- 📊 Transparent Accounting: Real-time stake and reward tracking
- 🚀 One-Click Deployment: Foundry scripts for seamless deployment
- 🌐 Multi-Network Support: Configurable for Celo testnets and mainnet
- 🔍 Event-Driven: Rich event logging for frontend integration
- 🛠️ Developer Tools: Extensive scripting for upgrades and maintenance
The system employs a sophisticated, modular architecture designed for security, upgradeability, and scalability:
graph TB
subgraph "User Layer"
UW[User Wallet]
end
subgraph "Contract Layer"
PC[Proxy Contract<br/>UUPS/Transparent]
IC[Implementation Contract<br/>StakingVaultUpgradeable]
end
subgraph "Storage Layer"
PS[Persistent Storage<br/>User Balances & Rewards]
end
subgraph "Asset Layer"
ET[ERC20 Token<br/>cUSD/CELO]
end
subgraph "Governance Layer"
OW[Owner/Multisig<br/>Configuration & Upgrades]
end
UW --> PC
PC --> IC
IC --> PS
IC --> ET
OW --> PC
OW --> IC
style PC fill:#e1f5fe
style IC fill:#f3e5f5
style PS fill:#e8f5e8
style ET fill:#fff3e0
style OW fill:#fce4ec
-
Proxy Contract (UUPS/Transparent)
- Entry point for all user interactions
- Stores all persistent state (balances, rewards, config)
- Delegates calls to implementation contract
- Enables seamless upgrades
-
Implementation Contract
- Contains all business logic
- Can be upgraded without affecting user funds
- Implements staking, rewards, and maintenance functions
-
ERC20 Token Interface
- Staking asset (cUSD, CELO, or custom tokens)
- Handles token transfers and approvals
-
Owner/Multisig Governance
- Controls reward rates and configuration
- Manages upgrades and emergency operations
- Cannot access user funds directly
The proxy maintains a comprehensive state structure:
- User Stakes: Individual staked balances
- Reward Indices: Per-user reward accrual tracking
- Global State: Total staked amount, reward rates
- Configuration: Owner settings, emergency flags
flowchart TD
A[User Initiates Stake] --> B[Validate Input Parameters]
B --> C[Check Token Approval]
C --> D[Transfer Tokens to Vault]
D --> E[Update User Stake Balance]
E --> F[Update Global Total Staked]
F --> G[Refresh User Reward Index]
G --> H[Emit Stake Event]
H --> I[Return Success]
style A fill:#e8f5e8
style I fill:#e8f5e8
sequenceDiagram
participant U as User
participant V as Vault
participant T as Token
U->>V: claimRewards()
V->>V: Calculate Pending Rewards
V->>V: Update User Reward Debt
V->>T: transfer(rewardAmount)
T-->>U: Tokens Transferred
V->>V: Emit RewardsClaimed Event
V-->>U: Return Claimed Amount
flowchart LR
A[Owner Deploys<br/>New Implementation] --> B[Validate<br/>Implementation]
B --> C[Execute<br/>Upgrade Transaction]
C --> D[Proxy Updates<br/>Implementation Address]
D --> E[State Preserved<br/>in Proxy Storage]
E --> F[Users Continue<br/>with Same Address]
style A fill:#fce4ec
style F fill:#e8f5e8
- Foundry: Latest version for smart contract development
- Node.js: v16+ for additional tooling and scripts
- Celo Wallet: MetaMask or similar with testnet/mainnet funds
- Git: For version control and cloning
-
Clone and Setup
git clone https://github.com/your-org/staking-vault-upgradeable.git cd staking-vault-upgradeable forge install -
Environment Configuration
cp .env.example .env # Edit .env with your PRIVATE_KEY and CELO_RPC_URL -
Build and Test
forge build forge test -
Local Development
anvil --fork-url https://alfajores-forno.celo-testnet.org
For a complete development setup:
- Install Foundry and Node.js
- Set up a Celo wallet
- Configure environment variables
- Run the test suite to verify setup
// Using ethers.js or web3.js
const vault = new ethers.Contract(vaultAddress, abi, signer);
// Approve tokens
await token.approve(vaultAddress, stakeAmount);
// Stake tokens
await vault.stake(stakeAmount);
// Check rewards
const pendingRewards = await vault.earned(userAddress);
// Claim rewards
await vault.claimRewards();
// Withdraw stake
await vault.withdraw(withdrawAmount);// Batch operations
await vault.stakeAndClaim(stakeAmount);
// Emergency withdrawal (if enabled)
await vault.emergencyWithdraw();// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./StakingVaultUpgradeable.sol";
contract YieldAggregator {
StakingVaultUpgradeable public vault;
constructor(address _vault) {
vault = StakingVaultUpgradeable(_vault);
}
function depositAndStake(uint256 amount) external {
// Transfer tokens to this contract
token.transferFrom(msg.sender, address(this), amount);
// Approve vault
token.approve(address(vault), amount);
// Stake in vault
vault.stake(amount);
// Mint receipt tokens or update user balance
}
}contract CustomRewardVault is StakingVaultUpgradeable {
using SafeMath for uint256;
// Custom reward multiplier based on staking duration
function getRewardMultiplier(address user) public view returns (uint256) {
uint256 stakingDuration = block.timestamp.sub(userStakeStart[user]);
return stakingDuration.div(30 days).add(1); // 1x base + 1x per month
}
function earned(address account) public view override returns (uint256) {
uint256 baseRewards = super.earned(account);
return baseRewards.mul(getRewardMultiplier(account));
}
}// React hook for vault interaction
import { useContract, useSigner } from 'wagmi';
export function useStakingVault() {
const { data: signer } = useSigner();
const vault = useContract({
address: vaultAddress,
abi: vaultAbi,
signerOrProvider: signer,
});
const stake = async (amount: BigNumber) => {
const tx = await vault.stake(amount);
await tx.wait();
};
const claimRewards = async () => {
const tx = await vault.claimRewards();
await tx.wait();
};
return { stake, claimRewards, vault };
}Deposits tokens into the vault to begin earning rewards.
Parameters:
amount: Amount of tokens to stake (in wei)
Requirements:
- User must have approved the vault to spend
amounttokens amountmust be greater than 0
Events: Staked(address indexed user, uint256 amount)
Gas Cost: ~85,000 gas
Withdraws staked tokens from the vault.
Parameters:
amount: Amount of tokens to withdraw
Requirements:
- User must have sufficient staked balance
- Automatically claims pending rewards
Events: Withdrawn(address indexed user, uint256 amount)
Claims all accumulated rewards for the caller.
Returns: uint256 - Amount of rewards claimed
Events: RewardsClaimed(address indexed user, uint256 amount)
Returns the staked balance of a user.
Returns: uint256 - Staked amount in wei
Calculates pending rewards for a user.
Returns: uint256 - Pending reward amount
Returns total amount staked in the vault.
Returns: uint256 - Total staked amount
Returns current reward rate per second.
Returns: uint256 - Reward rate in wei/second
Updates the global reward rate.
Access: Owner only
Parameters:
_rewardRate: New reward rate per second
Rescues non-staking tokens in emergency situations.
Access: Owner only
Security: Cannot rescue staking tokens
Upgrades the implementation contract.
Access: Owner only
Requirements: New implementation must be valid UUPS contract
# Run all tests
forge test
# Run with detailed output
forge test -v
# Run specific test file
forge test --match-path test/StakingVaultUpgradeable.t.sol
# Run with gas reporting
forge test --gas-report
# Run fuzz tests
forge test --match-test testFuzzThe test suite covers:
- ✅ Staking Mechanics: Deposit, withdrawal, balance tracking
- ✅ Reward Calculation: Index-based accrual, claiming
- ✅ Upgrade Safety: Proxy upgrades, state preservation
- ✅ Access Control: Owner functions, user permissions
- ✅ Edge Cases: Zero amounts, maximum values, reentrancy
- ✅ Integration: ERC20 interactions, event emission
- ✅ Gas Optimization: Operation cost analysis
test/
├── StakingVaultUpgradeable.t.sol # Core functionality tests
├── Upgrade.t.sol # Upgrade mechanism tests
├── Security.t.sol # Security and access control
└── Integration.t.sol # Cross-contract interactions
# Start local Celo fork
anvil --fork-url https://alfajores-forno.celo-testnet.org
# Deploy vault
forge script script/DeployStakingVaultUpgradeable.s.sol \
--rpc-url http://localhost:8545 \
--broadcast \
--private-key $PRIVATE_KEYforge script script/DeployStakingVaultUpgradeable.s.sol \
--rpc-url https://alfajores-forno.celo-testnet.org \
--broadcast \
--verify \
--etherscan-api-key $CELO_API_KEYforge script script/DeployStakingVaultUpgradeable.s.sol \
--rpc-url https://forno.celo.org \
--broadcast \
--verify \
--etherscan-api-key $CELO_API_KEY \
--slow# Deploy new implementation
forge script script/UpgradeStakingVault.s.sol \
--rpc-url https://forno.celo.org \
--broadcast \
--verify- ✅ OpenZeppelin Contracts: Audited and battle-tested
- 🔄 Custom Logic: Undergoing independent security review
- 📅 Target Completion: Q1 2026
- Reentrancy Protection: OpenZeppelin's ReentrancyGuard
- Access Control: Ownable with multi-sig support
- Input Validation: Comprehensive parameter checking
- Emergency Pause: Circuit breaker mechanisms
- Timelock: Governance actions with delay
- Single asset staking (multi-asset planned)
- No slashing mechanism
- Owner can modify reward rates
Report security vulnerabilities to security@your-org.com Rewards up to $50,000 for critical issues.
- Multi-asset staking support
- Frontend dashboard
- Cross-chain bridging
- Advanced reward mechanisms
- Governance token integration
- Yield farming features
- Mobile app
- Institutional staking
- Decentralized governance
- Cross-chain liquidity
- AI-powered yield optimization
- Institutional-grade security
We welcome contributions from developers of all skill levels!
-
Fork and Clone
git clone https://github.com/your-org/staking-vault-upgradeable.git cd staking-vault-upgradeable -
Create Feature Branch
git checkout -b feature/amazing-feature
-
Make Changes
- Follow Solidity style guide
- Add comprehensive tests
- Update documentation
-
Test Thoroughly
forge test forge coverage -
Submit PR
- Clear description of changes
- Link to related issues
- Request review from maintainers
- Code Quality: Follow Solidity Style Guide
- Testing: 100% test coverage for new features
- Documentation: Update README and inline comments
- Security: Run security tools before submitting
- Gas Optimization: Minimize gas costs where possible
- Smart Contracts: New features, optimizations
- Testing: Additional test cases, fuzzing
- Documentation: Tutorials, API docs
- Frontend: Web interfaces, mobile apps
- Security: Audits, formal verification
This project is licensed under the MIT License - see the LICENSE file for details.
- GitHub Discussions: Feature requests and general discussion
- Discord: Real-time chat with developers and users
- Twitter: Updates and announcements
- Forum: In-depth technical discussions
- API Reference: Complete function documentation
- Integration Guide: Step-by-step integration tutorials
- Security Guide: Best practices and security considerations
- Enterprise Support: Custom deployments and integrations
- Consulting: Architecture reviews and optimization
- Training: Workshops and developer bootcamps
Built with ❤️ for the Celo ecosystem by the StakingVaultUpgradeable team.
Empowering users with secure, transparent, and efficient DeFi staking solutions.
-
Clone the repository
git clone https://github.com/your-org/staking-vault-upgradeable.git cd staking-vault-upgradeable -
Install dependencies
forge install
-
Build the project
forge build
-
Run tests
forge test
Create a .env file for deployment:
PRIVATE_KEY=your_private_key
CELO_RPC_URL=https://forno.celo.org-
Stake Tokens
// Approve the vault to spend tokens token.approve(vaultAddress, amount); // Stake tokens vault.stake(amount);
-
Claim Rewards
// Claim accumulated rewards vault.claimRewards();
-
Withdraw Stake
// Withdraw staked tokens vault.withdraw(amount);
import "./StakingVaultUpgradeable.sol";
contract YourContract {
StakingVaultUpgradeable public vault;
constructor(address _vault) {
vault = StakingVaultUpgradeable(_vault);
}
function stakeAndDoSomething(uint256 amount) external {
vault.stake(amount);
// Your custom logic
}
}Extend the base contract for custom reward mechanisms:
contract CustomStakingVault is StakingVaultUpgradeable {
function calculateCustomRewards(address user) public view returns (uint256) {
// Custom reward calculation
}
}Deposits tokens into the vault to earn rewards.
Parameters:
amount: Amount of tokens to stake
Events: Staked(address indexed user, uint256 amount)
Withdraws staked tokens from the vault.
Parameters:
amount: Amount of tokens to withdraw
Events: Withdrawn(address indexed user, uint256 amount)
Claims accumulated rewards for the caller.
Returns: Amount of rewards claimed
Events: RewardsClaimed(address indexed user, uint256 amount)
Returns the staked balance of a user.
Returns the pending rewards for a user.
Returns the total amount staked in the vault.
Sets the global reward rate per second.
Rescues non-staking tokens (emergency function).
Upgrades the implementation contract.
Run the comprehensive test suite:
# Run all tests
forge test
# Run with gas reporting
forge test --gas-report
# Run specific test
forge test --match-test testStake- ✅ Staking functionality
- ✅ Reward calculation accuracy
- ✅ Withdrawal mechanics
- ✅ Upgrade safety
- ✅ Access control
- ✅ Edge cases and invariants
# Start local Celo fork
anvil --fork-url https://forno.celo.org
# Deploy using script
forge script script/DeployStakingVaultUpgradeable.s.sol --rpc-url http://localhost:8545 --broadcast# Deploy to Alfajores testnet
forge script script/DeployStakingVaultUpgradeable.s.sol --rpc-url https://alfajores-forno.celo-testnet.org --broadcast --verify
# Deploy to Mainnet
forge script script/DeployStakingVaultUpgradeable.s.sol --rpc-url https://forno.celo.org --broadcast --verify# Deploy new implementation
forge script script/UpgradeStakingVault.s.sol --rpc-url https://forno.celo.org --broadcastWe welcome contributions from the community! Here's how to get involved:
- Fork the repository
- Create a feature branch
git checkout -b feature/your-feature-name
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
forge test - Format code
forge fmt
- Submit a pull request
- Follow Solidity style guide
- Add comprehensive tests
- Update documentation
- Ensure gas efficiency
- Maintain upgrade compatibility
- Multi-asset support
- Advanced reward mechanisms
- Frontend integration
- Cross-chain functionality
- Security audits
This project is licensed under the MIT License - see the LICENSE file for details.
- Documentation: Full API Docs (coming soon)
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Discord: Join our community on Discord
Built with ❤️ for the Celo ecosystem. Empowering users with secure, upgradeable DeFi protocols. $ forge script script/Counter.s.sol:CounterScript --rpc-url <your_rpc_url> --private-key <your_private_key>
### Cast
```shell
$ cast <subcommand>
$ forge --help
$ anvil --help
$ cast --help