Solidity – Using Payable Custom Token in NFT

nftpayablesolidity

I'm creating an NFT game and I have a big question about payable.

Below I'm putting my code that I'm invoking a new Hero.

function invokeRandomHero() public payable {
    require(msg.value == 0.001 ether);
    uint randGenetic = _generateRandomGenetic();
    _invokeRandomHero(randGenetic);
  }

If you notice I'm using a test with the "Ether" coin, my question is, how can I do the same charge but with my own coin?
I'm going to create a contract for a new currency called for example "SLP" (example only, equal to axie).

How do I use this currency charge to perform the "summon a new hero" transaction?

Best Answer

The payable keyword is only useful when dealing with the blockchain's native asset/coin - in this case Ethers. You can't create own coins, you can only create your own tokens. So I assume you are meaning ERC20 tokens.

If you want to associate a token price for invoking the function, you should use the two staged transfer:

  1. User approves for the contract to withdraw X amount of his tokens, with the approve function in ERC20

  2. User notifies the contract the user wishes to buy something with tokens, and the contract withdraws the tokens from the user with the transferFrom function, and gives him his hero.

Tutorial of this two-phased token trade can be found for example here: https://ethereum.org/en/developers/tutorials/transfers-and-approval-of-erc-20-tokens-from-a-solidity-smart-contract/

Related Topic