SafeERC20Lib
A library providing safe wrappers around ERC20 token operations. It handles tokens that returnfalse on failure, tokens that don’t return a value, and validates that the target address contains code.
Overview
Many ERC20 tokens have non-standard implementations that either:- Don’t return a boolean value from
transfer,transferFrom, orapprove - Return
falseinstead of reverting on failure - Have other quirks that break standard assumptions
Functions
safeTransfer
The ERC20 token contract address
The recipient address
The amount of tokens to transfer
NoCode()- If the token address has no contract codeTransferReverted()- If the transfer call revertedTransferReturnedFalse()- If the transfer returnedfalse
safeTransferFrom
The ERC20 token contract address
The address to transfer tokens from (must have given approval)
The recipient address
The amount of tokens to transfer
NoCode()- If the token address has no contract codeTransferFromReverted()- If the transferFrom call revertedTransferFromReturnedFalse()- If the transferFrom returnedfalse
safeApprove
The ERC20 token contract address
The address authorized to spend tokens
The allowance amount
NoCode()- If the token address has no contract codeApproveReverted()- If the approve call revertedApproveReturnedFalse()- If the approve returnedfalse
Error handling
All functions in this library:- Check for contract code - Ensures the token address has code before attempting a call
- Check call success - Verifies the low-level call didn’t revert
- Check return value - If a value is returned, verifies it decodes to
true
- Standard ERC20 tokens that return
trueon success - Tokens that don’t return any value (empty return data)
- Tokens that return
falseon failure instead of reverting
Usage example
Related errors
See ErrorsLib for the error definitions:NoCode()TransferReverted()TransferReturnedFalse()TransferFromReverted()TransferFromReturnedFalse()ApproveReverted()ApproveReturnedFalse()