soliditysmartcontractsmetamaskerc20ethers.js

Is smart contract receive, hold and send different kinds of ERC-20 tokens


I'm creating a smart contract using solidity and publishing it to the Mumbai Test Network.

Right now when I'm interacting with the contract on the client-side using ethers and metamask it's automatically using the MATIC token.

I want the smart contract to be able to receive different kinds of ERC-20 tokens and afterward be able to transfer them.

const parsedAmount = ethers.utils.parseUnits(amount.toString(), 'ether');
const contract = await tokenContract.createTransfer({ value: parsedAmount });

For example, I want to be able to send the test token shown in the picture.

Link to the faucet

enter image description here

I've searched online and read docs but couldn't find an answer for this problem...

If needed, I will add any info you think will clarify this question!

Thanks in advance :)


Solution

  • The ERC-20 standard doesn't define any way to let the receiving contract know about a transfer that is not initiated by the receiver. It "only" emits an event but that's not readable from onchain.

    All ERC-20 balances are stored in the respective token contracts. For example, if an address holds 10 USDC, this information is stored on the USDC contract - no matter if the holder is an end user address or a contract.

    Combined these two things together, you can send a transaction to the USDC (or any other ERC-20) token contract, invoking the transfer() function where the receiver is your contract. This will effectively transfer USDC from the user to your contract address.

    const usdcContract = new ethers.Contract(usdcAddress, usdcAbi, metamaskSigner);
    const to = "0x123..."; // your contract address
    const amount = "1000000"; // 1 token with six decimals
    await usdcContract.transfer(to, amount);