0

I'm familiar with smart contracts development. Although, every time I developed something, I used traditional ether. For the sake of simplicity, let's assume this contract.

pragma solidity ^0.5.0;

contract  Example {

    constructor () public {}

    function () external payable {}

    function getBalance() public view returns (uint256) {
        return address(this).balance;
    }

    function withdraw() public {
        msg.sender.transfer(address(this).balance);
    }
}

How do I take this exact contract and simply allow it to do exactly the same, but using DAI instead? Please be practical, I read a lot of theory stuff already, I'm just looking to the actual code on how to do this.

2
        pragma solidity ^0.5.0;

        //import ERC20 functionality ...

        contract  Example {

            ERC20   public token;

            //@param _token the address of the DAI smart contract
            constructor(ERC20 _token) public {
                token = ERC20(_token);
            }

            function () external payable {}

            function getBalance() public view returns (uint256) {
                return token.balanceOf(address(this));
            }

            function withdraw() public {
                token.transfer(msg.sender, getBalance());
            }
        }

You've already read a lot of theory, so here's a practical example of your exact code but using DAI instead of ether, hope it helps.

  • To receive payments from an ERC20 you usually implement a approve + .transferFrom. – Ismael Aug 26 at 19:33
  • 1
    I agree with respect to payment patterns but he just wanted his code to be compatible with DAI. – phant0m Aug 26 at 22:16

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.