Custom Safe{Wallet} Guard: Limits, Whitelist, Time Windows

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Custom Safe{Wallet} Guard: Limits, Whitelist, Time Windows
Complex
~3-5 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

When developing a multisignature wallet on Ethereum, you often need to go beyond standard M-of-N logic. Business rules — spending limits, whitelists, time windows — require additional validation at the contract level. Safe{Wallet} provides a Guard — a contract provider called on every transaction. But writing a robust Guard is tricky: incorrect data decoding, gas leaks, and locking the Guard itself. From our practice: for one DAO we developed a SpendingLimitGuard with daily limits, and for a large corporate treasury a TimeWindowGuard. A custom Guard is 10x more flexible than the built-in limits, and our approach reduces gas costs by 40% compared to typical implementations. Order turnkey development — we'll analyze your requirements. Get a consultation from an engineer to evaluate the project.

How Guard integrates into Safe architecture

Safe executes transactions via execTransaction. Before and after execution, two hooks of the Guard contract are called, as described in Safe documentation:

interface ITransactionGuard {
    function checkTransaction(
        address to,
        uint256 value,
        bytes memory data,
        Enum.Operation operation,
        uint256 safeTxGas,
        uint256 baseGas,
        uint256 gasPrice,
        address gasToken,
        address payable refundReceiver,
        bytes memory signatures,
        address msgSender
    ) external;

    function checkAfterExecution(bytes32 txHash, bool success) external;
}

checkTransaction — here we implement all validation. If it reverts, the transaction will not execute. checkAfterExecution — post-factum logic: audit logs, counter updates. One Guard is set per Safe. Only the Safe itself (via multisig) can change the Guard. This is important: the Guard cannot be changed unilaterally, even by the Safe owner.

What types of Guards exist and when to use them?

Type of Guard What it controls Implementation complexity Example use case
Spending limit Daily/weekly limits on ETH and ERC-20 Medium DAO operational expenses without full quorum
Whitelist Allowed recipient addresses and contracts Low Treasury working only with verified partners
Time window Hours/days of week when transactions are allowed Low Protection from attacks during non-working hours
DelegateCall guard Prohibit or restrict DelegateCall High Prevent changes to Safe storage via delegated calls

Combining these types in one Guard gives maximum flexibility. For example, withdrawal limits + time windows for large amounts.

What can be controlled via Guard?

Spending limits

The most common case — daily/weekly limits for operational expenses without collecting full quorum of signers:

contract SpendingLimitGuard is BaseGuard {
    struct Limit {
        uint256 dailyLimit;
        uint256 spent;
        uint256 lastReset;
    }
    
    mapping(address => mapping(address => Limit)) public limits; // safe => token => limit
    
    function checkTransaction(
        address to,
        uint256 value,
        bytes memory data,
        Enum.Operation operation,
        // ... other parameters
    ) external override {
        address safe = msg.sender;
        
        // Check ETH limit
        if (value > 0) {
            Limit storage ethLimit = limits[safe][address(0)];
            _resetIfNeeded(ethLimit);
            require(
                ethLimit.spent + value <= ethLimit.dailyLimit,
                "Daily ETH limit exceeded"
            );
            ethLimit.spent += value;
        }
        
        // Decode ERC-20 transfer if this is a transfer() call
        if (data.length >= 4 && bytes4(data[:4]) == IERC20.transfer.selector) {
            (address recipient, uint256 amount) = abi.decode(data[4:], (address, uint256));
            Limit storage tokenLimit = limits[safe][to]; // to = token address
            _resetIfNeeded(tokenLimit);
            require(
                tokenLimit.spent + amount <= tokenLimit.dailyLimit,
                "Daily token limit exceeded"
            );
            tokenLimit.spent += amount;
        }
    }
    
    function _resetIfNeeded(Limit storage limit) internal {
        if (block.timestamp >= limit.lastReset + 1 days) {
            limit.spent = 0;
            limit.lastReset = block.timestamp;
        }
    }
}

Important nuance: Guard receives data as raw bytes. To analyze calls, you need to decode the 4-byte selector and arguments. This works for standard functions but not for arbitrary contract interactions without a known ABI. Incorrect decoding is one of the common causes of bugs.

Whitelist of recipient addresses

mapping(address => mapping(address => bool)) public allowedRecipients;

function checkTransaction(address to, uint256 value, bytes memory data, ...) external override {
    // If direct ETH transfer — check whitelist
    if (data.length == 0 && value > 0) {
        require(allowedRecipients[msg.sender][to], "Recipient not whitelisted");
    }
    
    // For DelegateCall — separate logic (or full prohibition)
    if (operation == Enum.Operation.DelegateCall) {
        require(allowedDelegateTargets[msg.sender][to], "DelegateCall target not allowed");
    }
}

DelegateCall requires special attention: through DelegateCall a contract can change Safe storage, including the list of owners. Many Guard implementations prohibit DelegateCall entirely or restrict to a strict whitelist.

Time windows

For DAOs with different access levels at different times (protection from attacks during non-working hours):

uint256 public allowedStartHour; // 0-23 UTC
uint256 public allowedEndHour;

function checkTransaction(...) external override {
    uint256 hour = (block.timestamp / 3600) % 24;
    require(
        hour >= allowedStartHour && hour < allowedEndHour,
        "Transactions not allowed at this time"
    );
}

Why order a turnkey Guard?

Ready-made solutions cover only 20% of custom use cases, while a Guard developed for you covers 100% of your needs. We guarantee no reentrancy, correct delegatecall handling, and MEV protection. The team has many years of blockchain development experience and has implemented over 30 Guards for DAOs and corporate treasuries.

How we develop a Guard: step-by-step

Analytics and specification

Define specific rules: which transaction types to restrict, how the Guard is managed (who can change limits — only Safe or a designated admin), whether an audit log of events is needed. We create a technical specification with a restrictions table.

Development and testing

BaseGuard from @safe-global/safe-contracts is the base contract with supportsInterface implementation. We implement checkTransaction and checkAfterExecution. Tests with a real Safe in Foundry: fuzzing via Echidna, static analysis via Slither. Test edge cases: empty data, large arrays, multisend.

Audit

A Guard with financial restrictions requires an audit — we always check data decoding logic and DelegateCall cases. We use Slither and Echidna for fuzzing. If necessary, we engage third-party auditors.

Deployment and setup

Contract verification on the blockchain. Setting the Guard via Safe UI with address verification before signing. Parameter configuration (limits, whitelist) via multisig.

What's included in the work

  • Analytical report with rules description
  • Guard source code in Solidity (0.8.x) with comments
  • Foundry tests (unit + integration) + Slither report
  • Deployment and verification script
  • Documentation for operation and updates
  • 2 weeks of post-launch support
Common mistakes in Guard development
  • Locking the Guard itself from upgrade. If the Guard forbids all transactions to arbitrary addresses, it can block setGuard(address(0)) — i.e., removing itself. Always verify that Safe can remove the Guard.
  • Ignoring the data.length == 0 case. Empty data + value > 0 = direct ETH transfer. data.length > 0 + to = contract call. Don't mix logic.
  • Gas limitations. The Guard is called inside execTransaction. Complex logic in checkTransaction increases gas cost of each Safe transaction. Avoid infinite loops.

Time frame estimates

Type of Guard Time without audit Time with audit
Basic (spending limits) 2–3 days 5–7 days
Combined (limits + whitelist + windows) 3–5 days 7–10 days
Complex (with DelegateCall restrictions) 5–7 days 10–14 days

The cost is calculated individually. Contact us to discuss your project and get a consultation from an engineer with many years of blockchain experience.

Smart Contract Development

We faced a situation: a contract was deployed, two weeks later a message arrives—the pool drained for $800k. Looked at the transaction in Tenderly: attacker called deposit(), inside an ERC-777 callback re-called withdraw()—balance only updated after the second exit. Classic reentrancy, but not via ETH transfer—through an ERC-777 hook. ReentrancyGuard was only on withdraw().

Such cases are not rare. A smart contract is financial logic with no possibility to patch it overnight. Our team develops turnkey contracts, embedding protection against reentrancy, MEV, and gas attacks from the early stages.

How We Develop Smart Contracts Turnkey

We start with business logic audit and stack selection. Solidity 0.8.x is the standard for EVM-compatible chains: Ethereum, Arbitrum, Optimism, Polygon, BSC, Avalanche C-Chain. For Solana, we use Rust and Anchor: the account and program model requires explicit declaration of all resources. For projects requiring formal verification, Move (Aptos, Sui) fits—linear types eliminate resource copying at the compiler level. Vyper is chosen for contracts where audit simplicity is critical (Curve Finance).

Language Execution Model Typical Domain Risks
Solidity 0.8.x EVM, sequential DeFi, NFT, tokens Reentrancy, overflow (unchecked)
Rust (Anchor) Solana, parallel High-throughput DEX, games Incorrect account declaration
Move Aptos/Sui, resource Large protocols Ecosystem complexity
Vyper EVM, limited syntax Critical contracts (Curve) Compiler stability dependency

Gas optimization is not premature optimization—it is an architectural decision. On Ethereum mainnet, deploying a poorly designed contract can cost a significant amount of ETH due to suboptimal storage layout. Repacking a Proposal structure from 7 slots to 4 saved thousands of gas per vote—substantial savings when scaled across thousands of votes per day.

Typical gas mistakes: passing arrays via memory instead of calldata in external functions (2–3x more expensive); using require with long strings instead of custom errors like error InsufficientBalance(...). Custom errors are cheaper on revert and pass structured data to the frontend.

Why Smart Contract Audit Is Critical for Security

Audit is not a one-time check—it is a built-in development stage. We use three levels:

  1. Static analysisSlither (30 seconds in CI) detects reentrancy, uninitialized variables, dangerous delegatecall.
  2. Fuzzing and invariant testsFoundry with --fuzz-runs 50000 finds edge cases missed by hundreds of unit tests. Real case: an AMM contract with custom math passed 150 Hardhat tests; Foundry found an integer division truncation that allowed a dust attack to accumulate dust on the contract. Echidna checks invariants ("sum of all balances ≤ totalSupply").
  3. Manual code review—our engineers with 10+ years in blockchain identify logic errors that tools miss. For protocols with TVL > $1M, external audit from Trail of Bits, Consensys Diligence, or OpenZeppelin is mandatory. Timeline: 2–4 weeks.

Any upgradeable protocol must have a timelock. TimelockController from OpenZeppelin: operation proposed → wait minimum delay (48–72 hours) → executed. Without timelock, one compromised deployer wallet means losing the entire pool.

What Upgrade Patterns Do We Choose?

Pattern Mechanism Risk When to Use Our Experience
Transparent Proxy (OZ) admin vs user separation Storage collision, centralization Standard projects 15+ implementations
UUPS Upgrade logic in implementation Forget _authorizeUpgrade → contract permanently broken Gas-optimized projects 7 projects
Diamond (EIP-2535) Multiple facets Audit complexity Large protocols with 10+ contracts 3 deployments
Beacon Proxy One beacon for multiple proxies Beacon = single point of failure Factories of identical contracts 5 factories

Storage collision is the main danger of proxies. Implementation v2 must not add variables before existing ones. OpenZeppelin Upgrades plugin for Hardhat and Foundry checks this automatically, but only when using its API.

How to Protect a Contract from MEV and Front-Running

On Ethereum mainnet, transactions in the mempool are visible to all. MEV bots execute sandwich attacks on DEX, front-run mints and governance. Solution: commit-reveal scheme for auctions, private submission via Flashbots PROTECT RPC. EIP-7702 and PBS (proposer-builder separation) are changing the landscape but not yet widespread.

What Is the Development Process?

  1. Analysis—functional specification, call diagram, edge case analysis. Without this, coding starts in vain.
  2. Development—Solidity/Rust with tests in parallel. Test → code → refactoring. Use Foundry for fuzz and invariant tests.
  3. Internal audit—Slither + Echidna + manual code review. Foundry invariant tests for protocol invariants.
  4. External audit—for projects with real money. Timeline: 2–4 weeks.
  5. Deployment—Foundry scripts or Hardhat Ignition with verification on Etherscan. Gnosis Safe for ownership transfer immediately after deployment.
  6. Monitoring—Tenderly alerts, OpenZeppelin Defender, Forta Network.

What Is Included

  • Architecture documentation and contract specification (NatSpec).
  • Source code with repository and CI (Slither, Foundry, coverage).
  • Deployed contract with verification on blockchain explorer.
  • Audit results (internal and external upon request).
  • Access to monitoring and management (Gnosis Safe).
  • Code warranty: critical bug fixes within one month after deployment.
  • Consultation on web integration (wagmi, RainbowKit).

Estimated Timelines

  • ERC-20 token with basic functions: 1–2 weeks
  • Vesting contract with cliff/linear schedule: 2–3 weeks
  • NFT ERC-721/1155 with marketplace: 4–6 weeks
  • AMM or lending protocol: 2–4 months
  • Multichain protocol with bridge: 4–7 months

Audit adds 3–6 weeks and runs in parallel with final testing where possible. Cost is calculated individually—contact us for a free project evaluation.

Order smart contract development—get consultation on architecture and protection against reentrancy, MEV, and gas attacks. Want to discuss details? Write to us—we will select the optimal stack for your task.