When creating a smart contract in which a user must provide payment, can an amount of a token be required instead of Ether? Could you enable a user to have an option between Ether or a token?


In a smart contract written in solidity, there exists the payable modifier which allows the sender to attach Ether to a transaction which will be accepted by the contract as a fee for providing its service. There is no predefined modifier that would allow the same functionality for any ERC20 compliant token. However, you can achieve this functionality by implementing a workaround. You can accept a payment of amount in the token at tokenAddress as follows:

function provideService() external {
    ERC20Interface tokenContract = ERC20Interface(tokenAddress);
    require(tokenContract.transferFrom(msg.sender, this, amount));
    // provide service here

It is necessary that the client has approved the token transfer beforehand. You can find the complete ERC20 Token standard at https://theethereum.wiki/w/index.php/ERC20_Token_Standard for further information.

You could enable the option to pay with Ether or a token by writing separate functions for both, and implementing your application frontend accordingly.

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.