3

What is the general process-flow of approving contract a to spend tokens on behalf of contract b and how would a sufficient function implementation look like which successfully achieves this?

For example let's consider following scenario. I created a standard ERC20 token and minted the token supply to contract a. Now I want to allow contract b to spend the minted ERC20 tokens on behalf contract a

2

If contract A owns tokens and you want contract B to spend then contract A has to approve contract B. And contract B has to use transferFrom with.

contract A {
  ERC20 token; // <--- generic ERC20 token contract
  B seller;    // <--- ticket seller accepts ERC20 tokens

  event TicketPurchased(uint);

  function buyTicket(uint amount) public {

    // Contract A approves the seller to transfer tokens
    token.approve(address(seller), amount);

    // Call seller for it to transfer tokens
    uint ticketId = seller.buyTicket(amount);

    // Generate event with ticket id to capture from UI
    emit TicketPurchased(ticketId);
  }
}

contract B {
  address wallet;   // <--- wallet where tokens from purchases will be moved to
  ERC20 token;      // <--- generic erc20 token

  function buyTicket(uint amount) public returns (uint) {

    // Transfer tokens from the caller to wallet
    // (here msg.sender will be Contract A)
    token.transferFrom(msg.sender, wallet, amount);

    return 1;   // <--- ticket id
  }
}

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.