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:
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
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.
Transfer Tokens to Smart Contract
Finally let's transfer tokens to this contract