2

I am using a ERC20 Token contract as indicated below. (I have deleted the irrelevant portions).

pragma solidity ^0.4.24;

import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";

contract TNStoken is Ownable {

using SafeMath for uint256;

mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 totalSupply_;

string public name;
string public symbol;
uint8 public decimals;

constructor() public {
    name = "The Neverending Story Token";
    symbol = "TNS";
    decimals = 18;
    totalSupply_ = 100 * 10**6 * 10**18;
    balances[msg.sender] = totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
    require(_to != address(0));
    require(_value <= balances[msg.sender] - locked[msg.sender]);

    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    emit Transfer(msg.sender, _to, _value);
    return true;
}

function balanceOf(address _owner) public view returns (uint256) {
    return balances[_owner];
}

function totalSupply() public view returns (uint256) {
    return totalSupply_;
}
}

Now, this contract is deployed, and after this deployment, I have another contract that uses this ERC20 contract. The address of the ERC20 token contract is passed to the constructor of this contract, as follows:

contract Adoption {
    TNSToken token;
    address[16] public adopters;
    address owner;

    constructor(address _token) public {
        token = TNSToken(_token);
        ownder = msg.sender;
    }

    function adopt(uint petId) public {
        require(petId >= 0 && petId <= 15);
        token.transfer(address(this), 5 * 10**18);
        adopters[petId] = msg.sender;
    }
}

Now, the point is that this Adoption contract function adopt() is calling the TNSToken contract function transfer(), so inside the transfer() function, msg.sender will be the address of the Adoption contract (and not the account that is paying tokens for pet adoption).

So, how do I indicate to the transfer() function that I want the account address to be used for token transfer ?

One possibility is to pass this function msg.sender while calling it from the Adoption contract.... Is this the right way to deal with this problem ?

2

If you want the tokens transferred from the user's account, the correct way is to first ask the user to call approve for your Adoption contract's address, and then use the transferFrom function within the contract.

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.