1

I want to exchange token for a commodity using smart contracts. I have deployed my token contract address in my private block chain network. How should I create another contract that exchanges a commodity using the transfer function from the deployed token contract?

5

You have a balance in your Token contract T. In order for your Commodity contract C to accept tokens and give the user the commodity in exchange, contract C would have to implement a function that accepts the tokens like follows:

function buyCommodityWithTokens(address _tokenAddress) public { 
  ERC20 token = ERC20(_tokenAddress);
  require(token.balanceOf(msg.sender) >= 100); // Assume the commodity being bought costs 100 tokens.

  commodityBalance[msg.sender] += 1; //We give the user the commodity

  token.transferFrom(msg.sender, this, 100); // transfer the tokens

}

Please take into consideration that the function above is not taking security measures under consideration.

For this to work, the token owner must first call approve on the token contract to allow contract C to use tokens on his behalf.

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.