Skip to main content

Smart Contract Security

Architecture Overview​

Karpous smart contracts implement a security-first design pattern derived from battle-tested DeFi protocols, specifically combining elements from BoringVault and Maple Finance.


KarpousVault (BoringVault Pattern)​

Design Philosophy​

The vault is intentionally minimal - approximately 100 lines of Solidity code. This extreme simplicity is a security feature:

  • Fewer lines of code = fewer bugs
  • No complex state = no state manipulation attacks
  • Passthrough only = no fund accumulation risk

Contract Code Analysis​

contract KarpousVault is Auth {
// IMMUTABLE: Cannot be changed after deployment
address public immutable LEDGER;

// Only authorized portals can trigger passthrough
mapping(address => bool) public isPortal;

function passthrough(
address from,
address token,
uint256 amount,
bytes32 depositId,
ProductType product
) external {
if (!isPortal[msg.sender]) revert UnauthorizedPortal();

// Pull from user
ERC20(token).safeTransferFrom(from, address(this), amount);

// IMMEDIATELY forward to Ledger - NO STORAGE
ERC20(token).safeTransfer(LEDGER, amount);
}
}

Security Properties​

PropertyGuarantee
Fund StorageNEVER - always 0 balance
Ledger AddressIMMUTABLE - set at deployment
Portal AuthorizationMultisig controlled
Upgrade RiskNONE - not upgradeable

Attack Resistance​

Attack TypeProtection
Re-entrancyNo callbacks, immediate transfer
Flash LoansNo funds to borrow
Price ManipulationNo price dependencies
Admin Rug PullCannot change Ledger destination
Contract CompromiseEmpty vault = nothing to steal

Access Control Implementation​

Role-Based Access Control (RBAC)​

We use OpenZeppelin AccessControl for granular permission management:

Permission Matrix​

FunctionAdminOperatorSolverUser
Grant RolesY---
Set ConfigurationY---
Approve Withdrawals-Y--
Update Prices-Y--
Fulfill Withdrawals--Y-
Fulfill Claims--Y-
Request Withdrawal---Y
Request Claim---Y
Deposit---Y

Reentrancy Protection​

Implementation​

All state-modifying functions use ReentrancyGuard:

Protected Functions​

ContractProtected Functions
FTokenPortaldeposit()
FTokenPortalV2deposit()
EarnPortaldeposit()
DirectPurchasePortalpurchase()
EarnWithdrawalQueuerequestWithdrawal(), cancelWithdrawal(), fulfillWithdrawals()
ProductYieldQueuerequestClaim(), fulfillClaims()
YieldClaimQueuerequestClaim(), fulfillClaims()

Time-Lock Mechanisms​

Maturity Periods​

All sensitive operations include mandatory waiting periods:

Purpose​

Attack TypeMitigation
Flash Loan AttacksCannot borrow and withdraw in same tx
MEV ExploitationTime window reduces profitability
Rushed ApprovalsForces manual review period
Social EngineeringTime for detection and response

Configuration​

OperationMaturity PeriodRationale
Withdrawal1 minuteFlash attack prevention
Yield Claim1 hourHigher security for yields
Auto-Renewal24 hours graceUser opt-out window

Withdrawal Security Model​

Maple Finance-Inspired Approval Flow​

Why This Design?​

  1. Human Review: Every withdrawal is manually reviewed
  2. No Direct Contract Access: Solver pays from own wallet (refilled from Ledger)
  3. Cancellation Option: Users can cancel pending requests
  4. Batch Efficiency: Multiple fulfillments in single transaction

Supply Cap Protection​

Asset Supply Limits​

Each asset has a maximum supply cap to prevent over-concentration:

struct AssetConfig {
bool active;
uint16 baseYieldBps;
uint256 currentPrice;
uint256 minDeposit;
uint256 maxSupply; // Maximum USDT that can be deposited
}

Input Validation​

Comprehensive Checks​

Error Handling​

Custom errors for gas efficiency and clarity:

error InvalidLedgerAddress();
error UnauthorizedPortal();
error ZeroAmount();
error TokenNotSupported();
error AssetNotActive();
error AssetSupplyCapExceeded();
error PositionNotUnlocked();
error PositionAlreadyWithdrawn();
error NotPositionOwner();

Event Logging​

Comprehensive Audit Trail​

All significant actions emit events for off-chain tracking:


Dependency Security​

Trusted Libraries​

LibraryVersionPurposeAudit Status
Solmate6.xGas-optimized primitivesExtensively reviewed
OpenZeppelin5.xAccess control, utilitiesFormally audited

Minimal Dependencies​

We deliberately minimize dependencies to reduce supply chain risk:

  • No complex DeFi integrations
  • No oracle dependencies for core functions
  • No upgradeable proxy patterns for vault

Testing Coverage​

Test Statistics​

MetricValue
Total Tests211
Passing211 (100%)
CoverageCore functions fully tested

Test Types​

TypeDescriptionCount
Unit TestsIndividual function testing150+
Integration TestsFull flow testing40+
Edge CasesBoundary conditions20+

Tested Scenarios​

  • Normal deposit/withdrawal flows
  • Lock period expiration
  • Access control violations
  • Reentrancy attempts
  • Supply cap enforcement
  • Fee calculations
  • Auto-renewal mechanics