Mastering Contract Interaction in Solidity

πŸ”— Why Contracts Need to Communicate

  • Build modular DeFi ecosystems
  • Integrate with existing protocols (Uniswap, Aave)
  • Enable complex multi-contract architectures

πŸ“œ Core Interaction Methods

1. Interface Declarations


interface IERC20 {
    function transfer(address to, uint amount) external returns (bool);
}

contract MyContract {
    IERC20 token;
    
    constructor(address _token) {
        token = IERC20(_token);
    }
    
    function sendTokens(address recipient, uint amount) public {
        require(token.transfer(recipient, amount), "Transfer failed");
    }
}

2. Low-Level Calls


function callExternal(address _contract) public payable {
    (bool success, bytes memory data) = _contract.call{value: 1 ether}(
        abi.encodeWithSignature("deposit()")
    );
    require(success, "Call failed");
}

⚠️ Critical Security Considerations

Risk Prevention
Reentrancy Attacks Checks-Effects-Interactions pattern
Malicious Contracts Whitelist trusted addresses
Gas Limit Issues Estimate gas before execution

πŸ’‘ Pro Tip: Safe Contract Interaction Flow

  1. Verify target contract exists
  2. Check function signature validity
  3. Handle failed transactions gracefully
  4. Use OpenZeppelin's Address utility library

πŸ”¨ Real-World Example: DEX Integration


interface IUniswap {
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external;
}

contract MyDEX {
    IUniswap uniswap;
    
    constructor(address _uniswap) {
        uniswap = IUniswap(_uniswap);
    }
    
    function swapTokensForETH(uint amountIn, uint amountOutMin) public {
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = uniswap.WETH();
        
        uniswap.swapExactTokensForETH(
            amountIn,
            amountOutMin,
            path,
            msg.sender,
            block.timestamp + 300
        );
    }
}

πŸš€ Your Interaction Challenge

Create two contracts:

  • Vault.sol: Stores ETH deposits
  • Manager.sol: Manages multiple vaults

Implement functions to:

  1. Create new vaults from Manager
  2. Transfer ETH between vaults
  3. Track total deposits across all vaults

Comments

Popular posts from this blog

Mastering Events & Logging in Solidity: The Blockchain’s Communication Channel

Solidity Security Essentials: Protect Your Smart Contracts

Error Handling in Solidity: Safeguard Your Smart Contracts