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

View this thread on steempeak.com
· @igormuba ·
$32.15
(Part 7) Ethereum Solidity - Fallback, Ethereum Fractions And Collateral Backed Contract(PT 7)
#### 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](https://files.steempeak.com/file/steempeak/igormuba/f1RC0gGJ-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](https://files.steempeak.com/file/steempeak/igormuba/mhk8QgRP-image.png)
![image.png](https://files.steempeak.com/file/steempeak/igormuba/FjigTo77-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](https://files.steempeak.com/file/steempeak/igormuba/Tuov8evc-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](https://files.steempeak.com/file/steempeak/igormuba/M41kpWOS-image.png)

And now the withdrawal with collateral deposit
Notice the balance from the creator of the contract
![image.png](https://files.steempeak.com/file/steempeak/igormuba/T3jK1HyI-image.png)
We call the fallback and he indeed receives the withdrawal
![image.png](https://files.steempeak.com/file/steempeak/igormuba/ojRkLeJ9-image.png)

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

![image.png](https://files.steempeak.com/file/steempeak/igormuba/p2k1kK4J-image.png)

#### Curriculum
- [(Part 6) Ethereum Solidity - Custom Variable Functionalities, Libraries, Using Libraries For Security(PT 6)](https://steemit.com/utopian-io/@igormuba/part-6-ethereum-solidity-custom-varaible-functionalities-libraries-using-libraries-for-security-pt-6)
- [(Part 5) Ethereum Solidity - Custom Access Modifiers, Security Breach Alerts, Assert And Require(PT 5)](https://steemit.com/utopian-io/@igormuba/part-4-ethereum-solidity-custom-access-modifiers-security-breach-alerts-assert-and-require-pt-4)
- [(Part 4) Ethereum Solidity Development - Inheritance, Working With Multiple Contracts And Simple Mutability(PT 4)](https://steemit.com/utopian-io/@igormuba/part-4-ethereum-solidity-development-inheritance-working-with-multiple-contracts-and-simple-mutability-pt-4)
- [(Part 3) Ethereum Solidity Development - Contract Mutability, DelegateCall And Calling Functions By Address(PT 3)](https://steemit.com/utopian-io/@igormuba/part-3-ethereum-solidity-development-contract-mutability-delegatecall-and-calling-functions-by-address-pt-3)
- [(Part 2) Ethereum Solidity Development - Deploying, Security And ERC20 Compliance(PT 2)](https://steemit.com/utopian-io/@igormuba/part-2-ethereum-solidity-development-deploying-securiy-and-erc20-compliance-pt-2)
- [(Part 1) Ethereum Solidity Development - Getting Started + Lower Level Explanation (PT 1)](https://steemit.com/utopian-io/@igormuba/part-1-ethereum-solidity-development-getting-started-lower-level-explanation-pt-1)

# Beneficiaries

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

![image.png](https://files.steempeak.com/file/steempeak/igormuba/hrYIggan-image.png)
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
post_id68,468,899
authorigormuba
permlinkpart-7-ethereum-solidity-fallback-ethereum-fractions-and-collateral-backed-contract-pt-7
categoryutopian-io
json_metadata{"community":"steempeak","image":["https:\/\/files.steempeak.com\/file\/steempeak\/igormuba\/f1RC0gGJ-image.png"],"users":["igormuba","utopian.pay"],"format":"markdown","tags":["utopian-io","tutorials","ethereum","solidity","blockchain"],"app":"steempeak","links":["https:\/\/github.com\/igormuba\/EthereumSolidityClasses\/tree\/master\/class7","https:\/\/steemit.com\/utopian-io\/@igormuba\/part-1-ethereum-solidity-development-getting-started-lower-level-explanation-pt-1","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","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","https:\/\/steemit.com\/utopian-io\/@igormuba\/part-4-ethereum-solidity-custom-access-modifiers-security-breach-alerts-assert-and-require-pt-4","https:\/\/steemit.com\/utopian-io\/@igormuba\/part-6-ethereum-solidity-custom-varaible-functionalities-libraries-using-libraries-for-security-pt-6","https:\/\/steemit.com\/utopian-io\/@igormuba\/part-4-ethereum-solidity-custom-access-modifiers-security-breach-alerts-assert-and-require-pt-4","https:\/\/steemit.com\/utopian-io\/@igormuba\/part-4-ethereum-solidity-development-inheritance-working-with-multiple-contracts-and-simple-mutability-pt-4"]}
created2019-01-07 02:55:21
last_update2019-01-07 02:55:21
depth0
children6
net_rshares62,837,485,718,271
last_payout2019-01-14 02:55:21
cashout_time1969-12-31 23:59:59
total_payout_value23.924 SBD
curator_payout_value8.222 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length10,930
author_reputation79,636,306,810,404
root_title"(Part 7) Ethereum Solidity - Fallback, Ethereum Fractions And Collateral Backed Contract(PT 7)"
beneficiaries
0.
weight500
accountutopian.pay
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (49)
@steemitboard ·
Congratulations @igormuba! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

<table><tr><td>https://steemitimages.com/60x70/http://steemitboard.com/@igormuba/posts.png?201901062358</td><td>You published more than 250 posts. Your next target is to reach 300 posts.</td></tr>
<tr><td>https://steemitimages.com/60x60/http://steemitboard.com/notifications/postallweek.png</td><td>You published a post every day of the week</td></tr>
</table>

<sub>_[Click here to view your Board](https://steemitboard.com/@igormuba)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>


To support your work, I also upvoted your post!


> Support [SteemitBoard's project](https://steemit.com/@steemitboard)! **[Vote for its witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1)** and **get one more award**!
properties (22)
post_id68,477,862
authorsteemitboard
permlinksteemitboard-notify-igormuba-20190107t075607000z
categoryutopian-io
json_metadata{"image":["https:\/\/steemitboard.com\/img\/notify.png"]}
created2019-01-07 07:56:06
last_update2019-01-07 07:56:06
depth1
children0
net_rshares0
last_payout2019-01-14 07:56:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length950
author_reputation38,705,954,145,809
root_title"(Part 7) Ethereum Solidity - Fallback, Ethereum Fractions And Collateral Backed Contract(PT 7)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@steem-plus ·
SteemPlus upvote
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](https://steemit.com/@steem-plus) to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.
properties (22)
post_id68,484,327
authorsteem-plus
permlinkpart-7-ethereum-solidity-fallback-ethereum-fractions-and-collateral-backed-contract-pt-7---vote-steemplus
categoryutopian-io
json_metadata{}
created2019-01-07 11:06:12
last_update2019-01-07 11:06:12
depth1
children0
net_rshares0
last_payout2019-01-14 11:06:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length435
author_reputation247,995,867,762,997
root_title"(Part 7) Ethereum Solidity - Fallback, Ethereum Fractions And Collateral Backed Contract(PT 7)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@portugalcoin ·
$7.69
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](https://join.utopian.io/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](https://review.utopian.io/result/8/2-1-1-1-1-3-1-3-).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , , , , , , , , ,
properties (23)
post_id68,510,901
authorportugalcoin
permlinkre-igormuba-part-7-ethereum-solidity-fallback-ethereum-fractions-and-collateral-backed-contract-pt-7-20190107t221642336z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit\/0.1","users":["igormuba"],"links":["https:\/\/join.utopian.io\/guidelines","https:\/\/review.utopian.io\/result\/8\/2-1-1-1-1-3-1-3-","https:\/\/support.utopian.io\/","https:\/\/discord.gg\/uTyJkNm","https:\/\/join.utopian.io\/"]}
created2019-01-07 22:16:42
last_update2019-01-07 22:16:42
depth1
children1
net_rshares14,731,889,138,408
last_payout2019-01-14 22:16:42
cashout_time1969-12-31 23:59:59
total_payout_value5.844 SBD
curator_payout_value1.848 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length821
author_reputation214,343,891,436,406
root_title"(Part 7) Ethereum Solidity - Fallback, Ethereum Fractions And Collateral Backed Contract(PT 7)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (19)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
post_id68,611,620
authorutopian-io
permlinkre-re-igormuba-part-7-ethereum-solidity-fallback-ethereum-fractions-and-collateral-backed-contract-pt-7-20190107t221642336z-20190109t224916z
categoryutopian-io
json_metadata{"app":"beem\/0.20.9"}
created2019-01-09 22:49:18
last_update2019-01-09 22:49:18
depth2
children0
net_rshares0
last_payout2019-01-16 22:49:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length64
author_reputation152,913,012,544,965
root_title"(Part 7) Ethereum Solidity - Fallback, Ethereum Fractions And Collateral Backed Contract(PT 7)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@steem-ua ·
#### 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](https://discord.gg/KpBNYGz)**
properties (22)
post_id68,512,244
authorsteem-ua
permlinkre-part-7-ethereum-solidity-fallback-ethereum-fractions-and-collateral-backed-contract-pt-7-20190107t225954z
categoryutopian-io
json_metadata{"app":"beem\/0.20.14"}
created2019-01-07 22:59:54
last_update2019-01-07 22:59:54
depth1
children0
net_rshares0
last_payout2019-01-14 22:59:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length287
author_reputation23,203,609,903,979
root_title"(Part 7) Ethereum Solidity - Fallback, Ethereum Fractions And Collateral Backed Contract(PT 7)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@utopian-io ·
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](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

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

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
post_id68,516,076
authorutopian-io
permlinkre-part-7-ethereum-solidity-fallback-ethereum-fractions-and-collateral-backed-contract-pt-7-20190108t005009z
categoryutopian-io
json_metadata{"app":"beem\/0.20.9"}
created2019-01-08 00:50:12
last_update2019-01-08 00:50:12
depth1
children0
net_rshares0
last_payout2019-01-15 00:50:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length590
author_reputation152,913,012,544,965
root_title"(Part 7) Ethereum Solidity - Fallback, Ethereum Fractions And Collateral Backed Contract(PT 7)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000