Security Best Practices
This guide outlines the security best practices for the Cart.fun protocol. Following these guidelines will help ensure the security of your protocol implementation and integration.
Security is a shared responsibility. While the Cart.fun protocol is designed with security in mind, proper implementation of these best practices is essential to maintain a secure environment.
Account Security
Account Creation Best Practices
When creating accounts for the Cart.fun protocol, follow these best practices:
- Name
Use PDA Accounts- Type
- practice
- Description
Always use Program Derived Address (PDA) accounts for protocol entities
- Name
Store Bump Seeds- Type
- practice
- Description
Always store the bump seed in your account data
- Name
Validate Relationships- Type
- practice
- Description
Use Anchor's
has_oneconstraint to enforce account relationships
Example: Creating a PDA account properly
#[account(
init,
payer = authority,
space = protocol::Protocol::LEN,
seeds = [b"protocol_v1"],
bump
)]
pub protocol: Account<'info, Protocol>;
// Then in the struct, store the bump
pub struct Protocol {
pub bump: u8,
// Other fields...
}
Account Access Control
Implement rigorous access control mechanisms:
- Name
Authority Checks- Type
- practice
- Description
Always verify the authority when modifying accounts
- Name
Hierarchical Permissions- Type
- practice
- Description
Respect the hierarchical permission model
- Name
Signature Verification- Type
- practice
- Description
Use Anchor's
Signertype to verify transaction signatures
Example: Checking authority permissions
#[account(
mut,
constraint = platform.authority == authority.key() @ CartError::AccessDenied
)]
pub platform: Account<'info, Platform>,
#[account(mut)]
pub authority: Signer<'info>,
The hierarchical permission model in Cart.fun follows this order: Protocol Authority → Platform Authority → Marketplace Authority → Vendor Authority. Never allow a lower-level authority to modify higher-level accounts.
Authority Management
Authority Transfer
Implement secure authority transfer processes:
- Name
Two-Phase Transfer- Type
- practice
- Description
Use a propose-then-accept pattern for authority transfers
- Name
Recovery Mechanisms- Type
- practice
- Description
Implement authority recovery options like multisig or timelocks
Example: Two-phase authority transfer
// Phase 1: Current authority proposes new authority
pub fn propose_new_authority(ctx: Context<ProposeNewAuthority>, new_authority: Pubkey) -> Result<()> {
ctx.accounts.protocol.proposed_authority = Some(new_authority);
Ok(())
}
// Phase 2: New authority accepts the transfer
pub fn accept_authority(ctx: Context<AcceptAuthority>) -> Result<()> {
let protocol = &mut ctx.accounts.protocol;
require!(
Some(ctx.accounts.new_authority.key()) == protocol.proposed_authority,
CartError::InvalidProposedAuthority
);
protocol.authority = ctx.accounts.new_authority.key();
protocol.proposed_authority = None;
Ok(())
}
Authority Limitations
Restrict authority actions appropriately:
- Name
Scope Actions- Type
- practice
- Description
Limit what different authority levels can do
- Name
Multi-Authority Requirements- Type
- practice
- Description
Require multiple authorities for critical operations
Example: Multi-authority requirement
pub fn withdraw_large_amount(ctx: Context<WithdrawLargeAmount>) -> Result<()> {
require!(
ctx.accounts.treasury.multisig_approvals >= REQUIRED_APPROVALS,
CartError::InsufficientApprovals
);
// Proceed with withdrawal...
}
Input Validation
String Validation
Validate all string inputs:
- Name
Length Checks- Type
- practice
- Description
Always validate minimum and maximum string lengths
- Name
Format Checks- Type
- practice
- Description
Validate URLs, keys, and other formatted strings
- Name
Sanitization- Type
- practice
- Description
Sanitize inputs to prevent injection attacks
Example: String validation
pub fn validate_name(name: &str) -> Result<()> {
if name.is_empty() {
return Err(CartError::NameTooShort.into());
}
if name.len() > MAX_NAME_LENGTH {
return Err(CartError::NameTooLong.into());
}
Ok(())
}
Numerical Validation
Protect against numerical vulnerabilities:
- Name
Overflow/Underflow Protection- Type
- practice
- Description
Use checked arithmetic operations
- Name
Range Validation- Type
- practice
- Description
Verify values are within acceptable ranges
- Name
Fee Calculations- Type
- practice
- Description
Double-check fee calculations with multiple approaches
Example: Numerical validation
pub fn calculate_commission(amount: u64, rate: u64) -> Result<u64> {
// Check if rate is valid (between 0 and 10000 for a basis point system)
require!(rate <= 10000, CartError::InvalidCommissionRate);
// Use checked arithmetic to prevent overflow
let commission = amount
.checked_mul(rate)
.ok_or(CartError::ArithmeticOverflow)?
.checked_div(10000)
.ok_or(CartError::ArithmeticError)?;
Ok(commission)
}
Treasury Security
Withdrawal Controls
Implement strict controls for treasury withdrawals:
- Name
Withdrawal Limits- Type
- practice
- Description
Set daily or per-transaction withdrawal limits
- Name
Timelocks- Type
- practice
- Description
Implement timelock delays for large withdrawals
- Name
Multi-signature- Type
- practice
- Description
Require multiple signatures for critical treasury operations
Example: Withdrawal limits
pub fn withdraw_from_treasury(ctx: Context<WithdrawFromTreasury>, amount: u64) -> Result<()> {
let treasury = &ctx.accounts.treasury;
// Check daily withdrawal limit
require!(
treasury.today_withdrawals.checked_add(amount).unwrap() <= treasury.daily_limit,
CartError::DailyLimitExceeded
);
// Continue with withdrawal...
}
PDA Management
Seed Derivation
Follow these practices for PDA seed derivation:
- Name
Unique Seeds- Type
- practice
- Description
Ensure seeds create unique addresses for different accounts
- Name
Version Seeds- Type
- practice
- Description
Include version information in seeds to support upgrades
- Name
Cross-check PDAs- Type
- practice
- Description
Always verify PDAs match expected derivation
Example: PDA verification
#[account(
seeds = [
b"marketplace",
platform.key().as_ref(),
marketplace_id.as_bytes(),
],
bump = marketplace.bump,
)]
pub marketplace: Account<'info, Marketplace>,
Client-Side Security
SDK Best Practices
Follow these practices when using the Cart.fun SDK:
- Name
Wallet Protection- Type
- practice
- Description
Never expose private keys in client-side code
- Name
Input Validation- Type
- practice
- Description
Validate all inputs on the client before sending to the blockchain
- Name
Rate Limiting- Type
- practice
- Description
Implement rate limiting for SDK method calls
Transaction Validation
Validate transactions before signing:
- Name
Simulate First- Type
- practice
- Description
Always simulate transactions before submitting
- Name
Review Instructions- Type
- practice
- Description
Review all transaction instructions before signing
- Name
Verify Recipients- Type
- practice
- Description
Double-check recipient addresses for transfers
Example: Transaction simulation
// Simulate the transaction before sending
const simulation = await connection.simulateTransaction(transaction)
// Check for errors in the simulation
if (simulation.value.err) {
console.error('Transaction would fail:', simulation.value.err)
throw new Error(`Transaction simulation failed: ${simulation.value.err}`)
}
// Only proceed if simulation passed
const signature = await sendAndConfirmTransaction(connection, transaction, [
wallet,
])
Security Testing
Testing Practices
Implement a thorough security testing regimen:
- Name
Unit Testing- Type
- practice
- Description
Test individual components for security vulnerabilities
- Name
Integration Testing- Type
- practice
- Description
Test interactions between components for security issues
- Name
Fuzzing- Type
- practice
- Description
Use fuzzing to find unexpected vulnerabilities
- Name
Penetration Testing- Type
- practice
- Description
Conduct regular penetration testing
Security Audits
Engage in regular security audits:
- Name
Internal Audits- Type
- practice
- Description
Conduct regular internal security reviews
- Name
External Audits- Type
- practice
- Description
Engage third-party auditors for comprehensive reviews
- Name
Bug Bounty Programs- Type
- practice
- Description
Consider implementing a bug bounty program
Emergency Response
Have a plan for security incidents:
- Name
Incident Response Plan- Type
- practice
- Description
Develop a clear procedure for handling security incidents
- Name
Critical Updates- Type
- practice
- Description
Have a process for pushing critical security updates
- Name
Communication Protocol- Type
- practice
- Description
Establish clear communication channels for security issues
For more detailed information on security practices, refer to: