1

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.

1 Answer 1

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.