TransWikia.com

How to send ERC20 token to smart contract in constructor

Ethereum Asked by user938363 on January 24, 2021

When deploying a smart contract to a private network, how to send ERC20 token (on the same private network) in msg.value to the smart contract in constructor?

Here is the contract:

pragma ^0.7.0;

interface ERC20 {
  //standard ERC20 functions
}
contract MyContract () {
  address erc20Contract;
  uint256 value;

  constructor (address _erc20) {
    ERC20 token = ERC20(_erc20); //_erc20 is the deployed address of ERC20 token
    erc20Contract = _erc20;
    //need to transfer msg.value token to the contract
    value = msg.value; //<<==how to transfer msg.value to the contract with ERC20 function, such as token.transfer()?
  }
}

One Answer

As you were already told in comments, you can't send tokens the same way you send Ethers. msg.value always refers to Ether value and never to tokens.

Tokens are just smart contracts which have some standard functionality. To transfer tokens the easiest way is to call the token contract's transfer function (if it's an ERC20 token). Yes, you can even call that in a constructor explicitly.

Correct answer by Lauri Peltonen on January 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP