Smart Contracts
Security Features

Security Features

Comprehensive overview of security mechanisms in DogWithCap smart contracts.

Security Architecture

DogWithCap implements multiple layers of security to protect user funds and ensure platform integrity.

Defense in Depth

Layer 1: OpenZeppelin Battle-Tested Contracts
Layer 2: Access Control & Ownership
Layer 3: Reentrancy Protection
Layer 4: Rate Limiting
Layer 5: Emergency Controls
Layer 6: Input Validation

Core Security Features

1. Reentrancy Protection

All state-changing functions use OpenZeppelin's ReentrancyGuard.

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
 
contract DogWithCapStaking is ReentrancyGuard {
    function stake(uint256 amount, address referrer) 
        external 
        nonReentrant  // βœ… Protected
    {
        // State changes before external calls
        // ...
    }
}

Protection Against:

  • Recursive calls
  • Cross-function reentrancy
  • Cross-contract reentrancy

Pattern Used:

  • State changes BEFORE external calls
  • nonReentrant modifier on all critical functions
  • Checks-Effects-Interactions pattern

2. Access Control

import "@openzeppelin/contracts/access/Ownable.sol";
 
contract DogWithCapStaking is Ownable {
    // Admin-only functions
    function setDailyInterestRate(uint256 newRate) 
        external 
        onlyOwner  // βœ… Owner only
    {
        // ...
    }
}

Owner Capabilities:

  • βœ… Adjust interest rates (within bounds)
  • βœ… Pause/unpause contract
  • βœ… Deposit rewards
  • βœ… Update milestone requirements
  • βœ… Process cash out requests

Owner CANNOT:

  • ❌ Withdraw user funds
  • ❌ Modify user positions
  • ❌ Change rate beyond constraints
  • ❌ Access user private keys

3. Rate Limiting

uint256 public constant CLAIM_COOLDOWN = 60; // 60 seconds
mapping(address => uint256) public lastActionTime;
 
modifier rateLimited() {
    require(
        block.timestamp >= lastActionTime[msg.sender] + CLAIM_COOLDOWN,
        "Cooldown active"
    );
    _;
    lastActionTime[msg.sender] = block.timestamp;
}

Prevents:

  • Spam attacks
  • Gas price manipulation
  • Flash loan attacks
  • Front-running exploits

Applied To:

  • Staking
  • Claiming interest
  • Claiming referrals
  • Claiming vesting
  • Cash out requests

4. Emergency Pause

import "@openzeppelin/contracts/security/Pausable.sol";
 
contract DogWithCapStaking is Pausable {
    function stake(uint256 amount, address referrer) 
        external 
        whenNotPaused  // βœ… Can be paused
    {
        // ...
    }
}

When to Pause:

  • Critical vulnerability discovered
  • Suspicious activity detected
  • Maintenance required
  • External dependency issues

What Gets Paused:

  • All user-facing functions
  • Staking
  • Claiming
  • Cash out requests

What Still Works:

  • View functions
  • Admin functions
  • Emergency withdrawals (if enabled)

5. Input Validation

// Custom errors for gas efficiency
error AmountZero();
error AmountTooLow();
error SelfReferral();
error InvalidPosition();
 
function stake(uint256 amount, address referrer) external {
    if (amount == 0) revert AmountZero();
    if (amount < MIN_STAKE_AMOUNT) revert AmountTooLow();
    if (msg.sender == referrer) revert SelfReferral();
    
    // Additional validations...
}

Validations:

  • βœ… Non-zero amounts
  • βœ… Minimum thresholds
  • βœ… Maximum limits
  • βœ… Valid addresses
  • βœ… Position ownership
  • βœ… Sufficient balances

6. SafeERC20

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
 
using SafeERC20 for IERC20;
 
function stake(uint256 amount, address referrer) external {
    // βœ… Safe transfer with return value check
    stakingToken.safeTransferFrom(msg.sender, address(this), amount);
}

Protects Against:

  • Non-standard ERC20 implementations
  • Silent failures
  • Return value issues
  • Token approval edge cases

Economic Security

Interest Rate Constraints

uint256 public constant MIN_DAILY_INTEREST_RATE = 50;   // 0.05%
uint256 public constant MAX_DAILY_INTEREST_RATE = 1000; // 1%
 
function setDailyInterestRate(uint256 newRate, string calldata reason) 
    external 
    onlyOwner 
{
    if (newRate < MIN_DAILY_INTEREST_RATE || newRate > MAX_DAILY_INTEREST_RATE) {
        revert InvalidInterestRate();
    }
    // ...
}

Prevents:

  • Unrealistic APR promises
  • Platform insolvency
  • User exploitation

Reward Pool Management

function _processRewardPayout(uint256 requestedAmount) 
    private 
    returns (uint256) 
{
    uint256 contractBalance = stakingToken.balanceOf(address(this));
    uint256 reservedForStakes = stats.totalStaked;
    uint256 reservedForCashOut = totalCashOutTokensInContract;
    
    uint256 availableForRewards = contractBalance > (reservedForStakes + reservedForCashOut)
        ? contractBalance - reservedForStakes - reservedForCashOut
        : 0;
    
    uint256 maxPayout = availableForRewards < stats.rewardPool
        ? availableForRewards
        : stats.rewardPool;
    
    uint256 payout = requestedAmount > maxPayout ? maxPayout : requestedAmount;
    
    if (payout > 0) {
        stats.rewardPool -= payout;
    }
    
    return payout;
}

Ensures:

  • User stakes always protected
  • Cash out funds reserved
  • Rewards paid from pool only
  • Platform solvency maintained

Minimum Stakes

uint256 public constant MIN_STAKE_AMOUNT = 100 * 10**18;

Prevents:

  • Dust attacks
  • Contract spam
  • Economic exploits
  • Position bloat

Audit Trail

Event Emission

Every significant action emits events:

emit PositionCreated(user, positionId, amount, referrer, timestamp);
emit PositionClaimed(user, positionId, interest, total, days, timestamp);
emit MilestoneAchieved(user, level, bonus, vesting, timestamp);
emit AdminAction(action, target, value, timestamp);

Benefits:

  • Complete transaction history
  • Off-chain monitoring
  • Forensic analysis
  • User transparency

Interest Rate History

struct InterestRateChange {
    uint256 oldRate;
    uint256 newRate;
    uint256 timestamp;
    string reason;
}
 
InterestRateChange[] public interestRateHistory;

Provides:

  • Full rate change log
  • Justification records
  • Historical transparency
  • Audit capability

Known Limitations

⚠️

Understanding limitations is part of security.

1. Permanent Staking

Design: Users cannot withdraw principal.

Mitigation:

  • Clearly communicated
  • Warning in UI
  • Documentation emphasis
  • Emergency withdrawal option (admin-enabled)

2. Centralized Rate Control

Design: Owner can adjust interest rates.

Mitigation:

  • Rate change constraints (0.05% - 1%)
  • Change history on-chain
  • Reason required
  • Community notification

3. Oracle Dependencies

Design: Token price from GeckoTerminal API.

Mitigation:

  • Multiple price sources planned
  • Price bounds checking
  • Fallback mechanisms
  • Manual override capability

4. Cross-Chain Risks

Design: Manual cash out processing.

Mitigation:

  • Admin verification
  • Refund capability
  • Event logging
  • User notifications

Attack Vectors & Mitigations

Flash Loan Attacks

Vector: Manipulate positions with borrowed funds.

Mitigation:

  • βœ… 60-second cooldown
  • βœ… Permanent staking (no instant withdrawals)
  • βœ… Time-weighted calculations
  • βœ… Minimum stake amounts

Front-Running

Vector: Watch mempool and front-run transactions.

Mitigation:

  • βœ… Rate limiting per address
  • βœ… Cooldown prevents rapid actions
  • βœ… No critical timing dependencies
  • βœ… Slippage not applicable (fixed rates)

Sybil Attacks

Vector: Create multiple accounts to game referrals.

Mitigation:

  • βœ… Self-referral blocked
  • βœ… Minimum stake requirements
  • βœ… Volume-based milestones
  • βœ… Economic disincentives

Reentrancy

Vector: Recursive calls to drain funds.

Mitigation:

  • βœ… ReentrancyGuard on all functions
  • βœ… Checks-Effects-Interactions pattern
  • βœ… State updates before transfers
  • βœ… SafeERC20 usage

Integer Overflow/Underflow

Vector: Arithmetic errors to manipulate balances.

Mitigation:

  • βœ… Solidity 0.8+ (built-in overflow checks)
  • βœ… SafeMath patterns
  • βœ… Proper type sizing
  • βœ… Bounds checking

Emergency Procedures

Emergency Withdrawal

bool public emergencyWithdrawEnabled;
 
function setEmergencyWithdraw(bool _enabled) external onlyOwner {
    emergencyWithdrawEnabled = _enabled;
}
 
function emergencyWithdraw() external nonReentrant {
    require(emergencyWithdrawEnabled, "Not enabled");
    
    // Return user's staked amount (no interest, no penalties)
    uint256 totalWithdrawable = user.totalStaked;
    
    // Transfer back to user
    stakingToken.safeTransfer(msg.sender, totalWithdrawable);
}

When Used:

  • Critical vulnerability found
  • Platform sunset
  • Force majeure events

User Impact:

  • Recover principal
  • No interest paid
  • Positions closed

Contract Pause

function pause() external onlyOwner {
    _pause();
}
 
function unpause() external onlyOwner {
    _unpause();
}

Use Cases:

  • Suspicious activity
  • Upgrade preparation
  • Maintenance window
  • Security response

Security Best Practices

For Users

User Security Checklist:

  1. βœ… Verify contract address
  2. βœ… Check transaction details before signing
  3. βœ… Use hardware wallet for large amounts
  4. βœ… Never share private keys
  5. βœ… Verify approval amounts
  6. βœ… Monitor position regularly
  7. βœ… Enable wallet notifications
  8. βœ… Keep recovery phrase secure

For Developers

Developer Security Checklist:

  1. βœ… Validate all inputs
  2. βœ… Use latest OpenZeppelin contracts
  3. βœ… Follow Checks-Effects-Interactions
  4. βœ… Test edge cases thoroughly
  5. βœ… Monitor events in real-time
  6. βœ… Implement circuit breakers
  7. βœ… Document security assumptions
  8. βœ… Regular security reviews

Audit Status

⚠️

Smart contract audit in progress.

Audit Scope

  • Core staking logic
  • Vesting mechanisms
  • Referral system
  • Access control
  • Emergency functions
  • Economic model
  • Event emission
  • Gas optimization

Expected Timeline

  • Audit Start: TBD
  • Initial Report: TBD
  • Fixes Applied: TBD
  • Final Report: TBD

Bug Bounty Program

Coming soon: Bug bounty program details.

Planned Rewards

SeverityReward Range
Critical10,000βˆ’10,000 - 50,000
High5,000βˆ’5,000 - 10,000
Medium1,000βˆ’1,000 - 5,000
Low100βˆ’100 - 1,000

Scope

  • Smart contracts
  • Frontend vulnerabilities
  • Backend API security
  • Infrastructure issues

Incident Response

Response Plan

  1. Detection: Monitoring alerts trigger
  2. Assessment: Evaluate severity
  3. Containment: Pause if critical
  4. Investigation: Determine root cause
  5. Resolution: Deploy fix
  6. Communication: Notify users
  7. Post-Mortem: Document learnings

Communication Channels

  • Discord announcements
  • Twitter updates
  • Email notifications
  • Website banner

Security Resources

Documentation

Tools Used

  • Hardhat for testing
  • Slither for static analysis
  • Mythril for symbolic execution
  • Tenderly for monitoring

Responsible Disclosure

Found a vulnerability? Please report responsibly:

πŸ“§ Email: security@dogwithcap.xyz

Please Include:

  • Detailed description
  • Steps to reproduce
  • Potential impact
  • Suggested fix (if any)

Response Time:

  • Acknowledgment: 24 hours
  • Initial assessment: 48 hours
  • Resolution timeline: Case-dependent

Next Steps


Security is a continuous process, not a destination.
We're committed to maintaining the highest security standards for our users.