ERC-20 and Smart Contracts
Transfer an ERC-20 Token to a smart contracts
Transferring ERC-20 tokens to a smart contract involves a few steps, including setting an allowance and then using the transferFrom function to move the tokens. This process ensures that the smart contract can only withdraw the amount of tokens you've explicitly approved.
First, let's look at the necessary code to achieve this. We'll use the same basic ERC-20 token contract that we used previously.
Create Smart Contract Receiving an ERC20
We need a smart contract that will receive the tokens:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts@4.8.1/token/ERC20/IERC20.sol";
contract TokenReceiver {
IERC20 public token;
constructor(address tokenAddress) {
token = IERC20(tokenAddress);
}
function receiveTokens(address from, uint256 amount) public {
require(token.transferFrom(from, address(this), amount), "Transfer failed");
}
}
In this contract, the receiveTokens
function allows the contract to receive tokens from a specified address. It uses the transferFrom function of the ERC-20 token standard.
Copy this code into a new file src/my-contracts/TokenReceiver.sol
Deploy ERC20 Receiver
Let's deploy this ERC20receiver contract
forge create --rpc-url myblockchain --private-key $PK --broadcast --constructor-args $ERC20_CONTRACT_L1 src/my-contracts/TokenReceiver.sol:TokenReceiver
[⠊] Compiling...
No files changed, compilation skipped
Deployer: 0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC
Deployed to: 0x4Ac1d98D9cEF99EC6546dEd4Bd550b0b287aaD6D
Transaction hash: 0x31b45c9df0a823254fd51863e217801da809cc77915a7b2901ea348c74aa0cfe
Save Receiver Address
Note
The address 0x4Ac1d98D9cEF99EC6546dEd4Bd550b0b287aaD6D
is your receiver contract address.
export ERC20_RECEIVER_L1=0x...
Approve Token Expense
Now to send Tokens to that contract, the Receiver contracts needs to be allowed to take funds on behalf of the user. Therefore, we need to allow our receiver contract as spender on the TOK interface.
cast send $ERC20_CONTRACT_L1 --private-key $PK "approve(address,uint256)" $ERC20_RECEIVER_L1 20ether --rpc-url myblockchain
Transfer Tokens to Smart Contract
Finally let's transfer tokens to this contract
cast send $ERC20_RECEIVER_L1 --private-key $PK "receiveTokens(address,uint256)" $EWOQ 2ether --rpc-url myblockchain
Confirm transfer
cast call $ERC20_CONTRACT_L1 "balanceOf(address)(uint256)" $ERC20_RECEIVER_L1 --rpc-url myblockchain
Is this guide helpful?