Solidity ERC20 – How to Approve and TransferFrom in a Contract

erc-20solidity

I have a contract with the following function:

function offerTokenTribute(address[] _tokenContractAddresses, uint256[] _tokenTributes) public {
  require(_tokenContractAddresses.length == _tokenTributes.length);

  Member storage member = members[msg.sender];
  member.approved = false; // should be already, but lets be safe

  for (uint8 i = 0; i < _tokenContractAddresses.length; i++) {
    ERC20 erc20 = ERC20(_tokenContractAddresses[i]);
    erc20.approve(this, _tokenTributes[i]);
    member.tokenTributeAddresses.push(_tokenContractAddresses[i]);
    member.tokenTributeAmounts.push(_tokenTributes[i]);
  }

  TokenTributeOffered(msg.sender, _tokenContractAddresses, _tokenTributes);
}

The problem is the erc20.approve function is not approving on behalf of the original msg.sender, it is changing msg.sender to the contract address (I verified this by checking allowances).

Is there any way to do this from my contract, or is the only solution to call the approval outside of my contract (non-ideal)?

Best Answer

No, there is no way around it.

It is a security feature, a contract cannot impersonate other account.