Understand solidity with simple ERC 20 token contract

in #utopian-io8 years ago (edited)


In the first part of the solidity post I mentioned how to install a local test chain and send commands to it using web3.js and nodejs. We have learned about tools for the development of smart contract programs on the ethereum network, however, we have not learned how to create a smart contracts.

Solidity

Solidty is most known and the most used contract-oriented programming language. It is statically typed, solidity supports inheritance and data types defined by user. The basis of smart contracts are tokens. Virtual assets that can be transferred between ethereum network addresses. We will focus on them because they generate most of the traffic in the ethereum network.

ERC 20 Tokens

Ethereum has standardized the contract scheme for tokens to facilitate their use by the application and exchanges. Bellow you can find interface code for ERC20 standard token, interface in the solidity is similliar to interfaces or abstract classes in other programming languages.


interface ERC20 {
    function totalSupply() constant returns (uint256 );
    function balanceOf(address _owner) constant returns (uint256 balance);
    function transfer(address _to, uint256 _value) returns (bool success);
    function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
    function approve(address _spender, uint256 _value) returns (bool success);
    function allowance(address _owner, address _spender) constant returns (uint256 remaining);
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
    }  

All functions above must be implemented in the smart contract of ERC20 compatibile token. All these function are straighforward, their names tell us what they do, we also have two events and i will explain every function and event.

ERC20 Token

Header

Bellow line by line i will explain ERC20 token smart contract code.
contract eUSDToken is ERC20 {
In the first line we are declaring that our token uses previously coded interface
uint public constant _totalSupply = 21000000;
That variable is the totalSupply of freshly created token. Good to know that in solidity we dont have decimal point numbers.
string public constant symbol = "eUSD";
string public constant name = "eUSD Token";
Token symbol and name used to describe it
uint8 public constant decimals = 2;
Decimals describes what is the smallest part of our token in that case one hundredth because we dont have decimal point numbers in solidity total supply determines the amount of the smallest currency fractions. So total supply of whole tokens will is equal to _totalSupply/(10)^decimals
mapping(address => uint256) balances;
Variable above maps Token blanaces to the thereum addresses
mapping(address => mapping(address => uint256)) allowed;
Variable is used in case one user allows other to spend his token ballance.

Functions and events

First function is the constructor of our smart contract. It assigns all tokens to the contract creator.
function eUSDToken() { balances[msg.sender] = _totalSupply; }
Function bellow returns totalSupply of the tokens
function totalSupply() constant returns (uint256 ) { return _totalSupply; }
Function bellow returns ballance of the tokens for the address
function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; }
Function bellow transfer specified amount of tokens from sender to the receiver. Before it checks if sender has enough tokens. If transfer is successful funcion triggers Transfer event.
function transfer(address _to, uint256 _value) returns (bool success) { require(balances[msg.sender] >= _value && _value > 0); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; }
Function below is used when someone, who you approved to, wants spend your assets.
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0); balances[_from] -= _value; balances[_to] += _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; }
Function bellow assign ammount of tokens which other user may spend from your ballance.
function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
Function bellow returns ammount of tokens which one user allowed other to spend.
function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
Events are logged by ethereum network. Events are used by light clients. Thanks to the events light clients can interact with etherem network very fast.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);

Compiling smart contract

Now when we have our smart contract source code, we are ready to compile it and deploy on the network. We will have to install solc compiler with npm, open console and type npm install -g solc.
Save the token contract code in the file with .sol extension and compile it with following command solcjs MyFile.sol --bin, solc will create bytecode of your contract, to interact with it using web3js you will also need ABI file, to generate one type following command solcjs MyFile.sol --abi

Deploying smart contract

In the first i wrote how to run and install testrpcs. Run it right now so you can deploy smart contract. Run the following code

Web3 = require('web3')
provider = new Web3.providers.HttpProvider("http://localhost:8545")
web3 = new Web3(provider)
acc = web3.eth.accounts[0]
abiF = fs.readFileSync('MyFile_sol_Myfile.abi')
abi  = JSON.parse(abiF.toString())
binF = fs.readFileSync('MyFile_sol_Myfile.bin')
bin = myTokenBINFile.toString()
contract = web3.eth.contract(abi)
data = { data: bin, from: account, gas: 999999 }
deployed = contract.new(data)

Now you can interact with you contract code via web3js library e.g following code will show all token holders!

caddr = deployed.address
instance = contract.at(caddr)
web3.eth.accounts.forEach(address => {
 tokens = instance.balanceOf.call(address)
 console.log(address + ": " + tokens)
}) 

ICO

In the next post i will write how to run your own ICO on the ethereum blockchain with token vesting bonuses and time period based on block height.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution has been approved

You can contact us on Discord.
[utopian-moderator]

Your contribution cannot be approved yet because it is not as informative as other contributions. See the Utopian Rules. Please edit your contribution and add try to improve the length and detail of your contribution (or add more images/mockups/screenshots), to reapply for approval.

You may edit your post here, as shown below:

You can contact us on Discord.
[utopian-moderator]

Your post is so beautiful

Excellent post :) . Regards Nainaz.

Thanks for your help to get tokens of erc.....

Excellent post!!!
thank you

Hey @whd I am @utopian-io. I have just upvoted you!

Achievements

  • WOW WOW WOW People loved what you did here. GREAT JOB!
  • You are generating more rewards than average for this category. Super!;)
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.077
BTC 61257.99
ETH 1614.53
USDT 1.00
SBD 0.40