Code

Selected smart contract snippets and open-source repositories. Real code, not abstractions.

github.com/rainwaters11

Repositories

Snippets

Foundry Invariant Test -- Pool Balance Conservation

solidity

A stateful fuzz test asserting that total pool value is conserved across arbitrary swap sequences. Foundry explores random call sequences to find violations.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "forge-std/Test.sol";
import {PoolManager} from "v4-core/PoolManager.sol";

contract PoolInvariantTest is Test {
    PoolManager manager;
    uint256 initialTotalValue;

    function setUp() public {
        manager = new PoolManager();
        initialTotalValue = _totalPoolValue();
    }

    /// @dev Invariant: pool value is conserved
    ///      across all swap sequences
    function invariant_poolValueConserved() 
        public view 
    {
        uint256 current = _totalPoolValue();
        assertApproxEqRel(
            current,
            initialTotalValue,
            1e15  // 0.1% tolerance for fees
        );
    }

    function _totalPoolValue() 
        internal view returns (uint256) 
    {
        // Sum token0 + token1 reserves
        // normalized to common base
        return manager.getReserve0() 
            + manager.getReserve1();
    }
}

Timelock Execution Guard -- Governance Pattern

solidity

A governance-controlled timelock that enforces minimum delay between proposal and execution. Multisig authorization required for queued operations.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract TimelockGuard {
    uint256 public immutable MIN_DELAY = 2 days;
    address public immutable MULTISIG;

    mapping(bytes32 => uint256) public queued;

    error NotAuthorized();
    error NotQueued(bytes32 txHash);
    error TimelockActive(uint256 readyAt);

    constructor(address _multisig) {
        MULTISIG = _multisig;
    }

    modifier onlyMultisig() {
        if (msg.sender != MULTISIG) 
            revert NotAuthorized();
        _;
    }

    function queue(bytes32 txHash) 
        external onlyMultisig 
    {
        queued[txHash] = block.timestamp 
            + MIN_DELAY;
    }

    function execute(bytes32 txHash) 
        external onlyMultisig 
    {
        uint256 readyAt = queued[txHash];
        if (readyAt == 0) 
            revert NotQueued(txHash);
        if (block.timestamp < readyAt) 
            revert TimelockActive(readyAt);

        delete queued[txHash];
        // Execute governance action...
    }
}