(Part 7) Ethereum Solidity - Fallback, Ethereum Fractions And Collateral Backed Contract(PT 7)

in #utopian-io5 years ago

Repository

https://github.com/igormuba/EthereumSolidityClasses/tree/master/class7

What Will I Learn?

  • What are fallback functions
  • Use fallback to generate tokens
  • Use fallback to implement collateral backed withdrawals
  • Ethereum fractions and implementing them on contract

Requirements

  • Internet connection
  • Code editor
  • Browser

Difficulty

  • Intermediate

Tutorial Contents

Fallback functions definition and use case

Fallback functions are functions that are executed when you make an invalid call to the contract, either because there is no function with the signature you have provided or because you didn't provide a name at all of what function you want to call, or even if you accidentally (or not) call for a function that does not exist.

Contracts can either have zero or one fallback, but not more, as it would not make sense to make more than one since they are considered "backups", but they can also be very helpful.

On ICOs fallback functions can be used to generate tokens from deposits sent to the contract, allowing the users to send Ethereum to the contract without them having to worry about how to call functions nor touch Solidity code!

Implementing a fallback

On this example, I will use an example from the first class, where I taught you how to build a very simple contract for a simple token
https://steemit.com/utopian-io/@igormuba/part-1-ethereum-solidity-development-getting-started-lower-level-explanation-pt-1

For simplicity, we won't comply with ERC20 standard and any security library such as safe math, but if you want to read more about the ERC20 standard and how to use third party libraries for security, the second and the sixth tutorial have content and links to good material on those fields
https://steemit.com/utopian-io/@igormuba/part-2-ethereum-solidity-development-deploying-securiy-and-erc20-compliance-pt-2
https://steemit.com/utopian-io/@igormuba/part-6-ethereum-solidity-custom-varaible-functionalities-libraries-using-libraries-for-security-pt-6

If you are not following this series, don't worry, let me explain this piece of code and what will we do with it!

pragma solidity ^0.5.0;

contract firstClassContract{
    address public creator; //address of contract creator to be defined
    uint256 public totalSupply; //total coin supply
    mapping (address => uint256) public balances; //mapping balances to addresses
    
    constructor() public{
        creator = msg.sender; //the creator of the contract
        totalSupply = 0; //to monitor the total supply
    }

    function balanceOf(address owner) public view returns(uint256){
        return balances[owner];
    }
    
    function sendTokens(address receiver, uint256 amount) 
        public returns(bool){
            address owner = msg.sender; //this is the caller of the function
            
            require(amount > 0); //the caller has to have a balance of more than zero tokens
            require(balances[owner] >= amount); //the balance must be bigger than the transaction amount
            
            balances[owner] -= amount; //deduct from the balance of the sender first
            balances[receiver] += amount; //add to the balance of the receiver after
            return true;
        }

}

The contract above creates a dummy token with the initial supply of zero, it has simple functions to get balances and transfer, as mentioned before, it does not comply with any standard and security good practices, but that is not the goal of this specific section.

I recommend you to read and understand the code before proceeding, it is not that hard :)

You might have noticed, the total supply of the token is zero and at the moment there is absolutely no function to change it, which makes the dummy token even "dummier", and this is where our fallback function comes, to start the function simply

function() external payable{
        
    }

NOTE: On solidity 5 onwards the fallback function when implemented should have the external access modifier

Sadly, the fallback function can't take any arguments, because it would defeat the original purpose of being a safety function.

We will take advantage of how it works to configure how we will "print" the token, and this is pretty much a simpler way of how ICOs implemented their crowdsale logic! There are many ways you could go fancy with it, for instance, check the articles below of suggestions from Vitalik Buterin (Ethereum co-founder) on how he views as the best way to build ICOs
https://coincodex.com/article/1329/vitalik-buterin-suggest-improvements-to-ico-model/
https://medium.com/swissborg/vitalik-buterin-believes-the-ico-market-has-to-evolve-swissborg-answers-b132173e6a0c

Our contract will simply receive the Ethereum from our users and return 10x that amount in tokens

For this, inside the fallback

function() external payable{
        balances[msg.sender] += msg.value/100000000000000000;
    }

Now, this is interesting, you might have noticed that msg.value should probably hold how many Ethereum were sent by the user in the transaction, but if you don't know much about Ethereum you might have expected that line to be something like

balances[msg.sender] += msg.value*10;

Let's see why that

Wei, Gwei, Finney, and Ether

As a solidity developer, it is very, VERY important to be mindful of the different names the same currency can have!
The same way the United States currency can have many names, such as "dollar", "cent", "buck", "penny" and more, Ethereum currency also have many names, being them
image.png

Yes, I would like to know who came out with those names.
but I want you to be mindful that Ethereum has 18 zeroes on the decimals, so 1 Ether is
1.000000000000000000 (trust me, it was hard to type that precisely)

We want out token to be worth 10 for each 1 Ether, so we need to divide the amount we receive (the value is counted in wei, the smallest unit of measure possible) to reduce 17 zeroes from it, leaving in practice 10 times the amount of Ether sent.

Testing the code we can see that it works, be sure to send it in ether, though!! Look where there is the field value
image.png
image.png

Restricting access to the fallback function

You can restrict the access for the fallback by giving a custom modifier, just remember, there is no way to call the fallback from inside the contract itself, so either way it will still be an external function.

If you are not familiar with custom access modifiers and/or are not following my tutorial series, my fifth tutorial has some content and a few external links to other articles about it and it is worth checking it
https://steemit.com/utopian-io/@igormuba/part-4-ethereum-solidity-custom-access-modifiers-security-breach-alerts-assert-and-require-pt-4

In this example we will explore the use of adding a custom access modifier so that the fallback function can only be called by the owner of the contract, the owner will use this function to withdraw Ether from the contract, but he will then send collateral tokens back to the contract.

First, change the creator address

address payable public creator; //added the payable modifier

for the next step, delete the previous payable fallback function and replace it by

//this function replaces the fallback to print tokens
    function createTokens() public payable{
        balances[msg.sender] += msg.value/100000000000000000;
    }
       
//modifier to check if the caller is the creator
    modifier ownerCheck(){
        require(msg.sender==creator);
        _;
    }

//new fallback
    function() external payable{
       
    }

Inside the fallback let us put the logic to allow the owner to claim the funds from the contract and give back the collateral

//we will withdraw 1 Ethereum at a time giving collateral at the same time
    function() external ownerCheck payable{
       balances[creator]-=10;
       creator.transfer(1000000000000000000);
    }

Testing the collateral fallback function

Let us see if the contract works as expected!

Like before, let us send 2 Ether to the contract to ensure it will have enough funds to cover the costs of the transaction.
image.png

The difference is that now we click the button to call the function createTokens as the fallback is to withdraw funds
image.png

And now the withdrawal with collateral deposit
Notice the balance from the creator of the contract
image.png
We call the fallback and he indeed receives the withdrawal
image.png

And he also successfully paid the collateral to keep the value of the contract

image.png

Curriculum

Beneficiaries

This post has as beneficiaries
@utopian.pay with 5%
using the SteemPeak beneficiary tool

image.png

Sort:  

Thank you for your contribution @igormuba.
After analyzing your tutorial we suggest only one point:

  • We again suggest that you be careful about punctuation. You've improved but there are still phrases without punctuation.

Your tutorial is great, thanks for making contributions!

We are waiting for your next tutorial.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Congratulations @igormuba! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You published more than 250 posts. Your next target is to reach 300 posts.
You published a post every day of the week

Click here to view your Board
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Support SteemitBoard's project! Vote for its witness and get one more award!

Hi, @igormuba!

You just got a 0.27% upvote from SteemPlus!
To get higher upvotes, earn more SteemPlus Points (SPP). On your Steemit wallet, check your SPP balance and click on "How to earn SPP?" to find out all the ways to earn.
If you're not using SteemPlus yet, please check our last posts in here to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.

Hi @igormuba!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @igormuba!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.31
TRX 0.11
JST 0.035
BTC 66739.07
ETH 3228.97
USDT 1.00
SBD 4.23