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
- Verify target contract exists
- Check function signature validity
- Handle failed transactions gracefully
- 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:
- Create new vaults from Manager
- Transfer ETH between vaults
- Track total deposits across all vaults
Comments
Post a Comment