0

I am trying to execute the following code obtained from`Solidity Tutorial

pragma solidity 0.5.4;
contract ERC20Token {
    string name;
    mapping(address => uint256) public balances;

    function mint() payable public {
        balances[msg.sender] += msg.value;//use tx.origin, 
    }
}
contract MyContract {
    address public token;

    address payable wallet;

    constructor(address payable _wallet, address _token) public {
        wallet = _wallet;
        token = _token;
    }
    function() external payable{
       buyToken();
    }
    function buyToken() public payable {
        ERC20Token _token = ERC20Token(address(token));
        _token.mint();
        wallet.transfer(msg.value);
    }
}

The tutorial says that I have to use tx.origin instead of msg.sender but tx.origin is a vulnerability. Somebody please guide me how to solve this problem.

  • What are the intentions of this? What is the expected behavior? It's hard to answer without knowing what should actually happen – flygoing Jan 23 '20 at 21:31
  • 3
    I'm not sure I would spend time on a tutorial that is recommending known security risks. It's better to learn good patterns and best practices from the beginning, IMO. – Rob Hitchens Jan 23 '20 at 21:39
  • I have also heard that tx.origin is recommended for removal. I am following this tutorial because its giving some meat for using remix ide. But I would highlight anything vulnerable. – zak100 Jan 23 '20 at 23:14
1

You're correct that msg.sender is advised over tx.origin. The reason this isn't working is because you aren't sending any ETH with the mint() call, so it's 0, and the token balance isn't increasing. It's hard to understand the intended outcome, but you'd probably want to have mint only be callable by MyContract, and have mint take a parameter and called as _token.mint(msg.value), then use that parameter as the number of tokens.

  • I have changed the mint() function to: function mint(uint no_of_tokens) payable public { balances[msg.sender] += no_of_tokens; }, and the buyToken function is: function buyToken() public payable { ERC20Token _token = ERC20Token(address(token)); _token.mint(msg.value); wallet.transfer(msg.value); } , but stiil I am getting zero balance, somebody please guide me. Zulfi. – zak100 Jan 25 '20 at 2:04
  • @zak100 Your issue now is that msg.sender in mint is the MyContract account. mint should also take an address to mint to, or MyContract should transfer the tokens to msg.sender after minting. – flygoing Jan 26 '20 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.