ERC20 Token Smart Contract for Ethereum Blockchain

Reading Time: 5 minutes

Since the inception of Blockchain technology; Bitcoin, Ethereum, or crypto-currencies are hot topics and buzzing around the world many startups based on Blockchain technologies are using cryptocurrencies, in other words, crypto tokens for the utilization of their products. These crypto tokens can be deployed on many Blockchain like Ethereum, Cardano, Binance, Polkadot, etc. It’s another topic of discussion, on which blockchain these crypto tokens need to be implemented but as Ethereum being the first market mover, this blog post explains, how you can create such a token on the Ethereum blockchain.

Before creating an Ethereum based token (ERC20 token), understand first the basics of Smart-contract and their native programming language Solidity.

Smart Contract

A smart contract is simply a set of rules that contains the business logic or a protocol according to which all the transactions on a Blockchain should happen. The general purpose of a Smart contract is to satisfy common contractual conditions like creating its token, perform arbitrary competitions, function to send and receive tokens, and store states of transactions.

Solidity

Solidity is an object-oriented and high-level smart-contract programming language, which is developed on top of Ethereum Virtual Machine (EVM). Solidity compiler converts smart-contract code into EVM bytecode which is sent to the Ethereum network as a deployment transaction. It would be best to have a good understanding of Solidity programming language to efficiently write an Ethereum Smart Contract and build an application on smart-contract.

Coding example of smart-contract

This section contains the example of a smart-contract code written using the Solidity programming language.

Prerequisite

Integrated development environment (IDE)

Remix as the IDE. It is a web-based IDE with built-in static analysis and a testnet EVM. Remix provides the possibility to compile and deploy it to Ethereum testnet with Metamask. Here is a good blog post for it.

There is also another web-based IDE available like EthFiddle. For more information related to IDE please visit here.

Programming Language

Solidity

ERC20 Token Info
  • Symbol – N47
  • Name – N47Token
  • Decimals – 0
  • Total Supply – 1000000
Smart-contract Code
// SPDX-License-Identifier: unlicensed
pragma solidity 0.8.4;
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
    function safeAdd(uint a, uint b) public pure returns (uint c) {
        c = a + b;
        require(c >= a);
    }
    function safeSub(uint a, uint b) public pure returns (uint c) {
        require(b <= a);
        c = a - b;
    }
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
// ----------------------------------------------------------------------------
abstract contract ERC20Interface {
    function totalSupply() virtual public view returns (uint);
    function balanceOf(address tokenOwner) virtual public view returns (uint balance);
    function allowance(address tokenOwner, address spender) virtual public view returns (uint remaining);
    function transfer(address to, uint tokens) virtual public returns (bool success);
    function approve(address spender, uint tokens) virtual public returns (bool success);
    function transferFrom(address from, address to, uint tokens) virtual public returns (bool success);
    event Transfer(address indexed from, address indexed to, uint tokens);
    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals
// assisted token transfers
// ----------------------------------------------------------------------------
contract N47Token is ERC20Interface, SafeMath {
    string public symbol;
    string public  name;
    uint8 public decimals;
    uint public _totalSupply;
    mapping(address => uint) balances;
    mapping(address => mapping(address => uint)) allowed;
    // ------------------------------------------------------------------------
    // Constructor
    // ------------------------------------------------------------------------
    constructor() {
        symbol = "N47";
        name = "N47Token";
        decimals = 0;
        _totalSupply = 1000000;
        balances[msg.sender] = _totalSupply;
        emit Transfer(address(0), msg.sender, _totalSupply);
    }
    // ------------------------------------------------------------------------
    // Total supply
    // ------------------------------------------------------------------------
    function totalSupply() public override view returns (uint) {
        return _totalSupply - balances[address(0)];
    }
    // ------------------------------------------------------------------------
    // Get the token balance for account tokenOwner
    // ------------------------------------------------------------------------
    function balanceOf(address tokenOwner) public override view returns (uint balance) {
        return balances[tokenOwner];
    }
    // ------------------------------------------------------------------------
    // Transfer the balance from token owner's account to receiver account
    // - Owner's account must have sufficient balance to transfer
    // - 0 value transfers are allowed
    // ------------------------------------------------------------------------
    function transfer(address receiver, uint tokens) public override returns (bool success) {
        balances[msg.sender] = safeSub(balances[msg.sender], tokens);
        balances[receiver] = safeAdd(balances[receiver], tokens);
        emit Transfer(msg.sender, receiver, tokens);
        return true;
    }
    // ------------------------------------------------------------------------
    // Token owner can approve for spender to transferFrom(...) tokens
    // from the token owner's account
    //
    // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
    // recommends that there are no checks for the approval double-spend attack
    // as this should be implemented in user interfaces 
    // ------------------------------------------------------------------------
    function approve(address spender, uint tokens) public override returns (bool success) {
        allowed[msg.sender][spender] = tokens;
        emit Approval(msg.sender, spender, tokens);
        return true;
    }
    // ------------------------------------------------------------------------
    // Transfer tokens from sender account to receiver account
    // 
    // The calling account must already have sufficient tokens approve(...)-d
    // for spending from sender account and
    // - From account must have sufficient balance to transfer
    // - Spender must have sufficient allowance to transfer
    // - 0 value transfers are allowed
    // ------------------------------------------------------------------------
    function transferFrom(address sender, address receiver, uint tokens) public override returns (bool success) {
        balances[sender] = safeSub(balances[sender], tokens);
        allowed[sender][msg.sender] = safeSub(allowed[sender][msg.sender], tokens);
        balances[receiver] = safeAdd(balances[receiver], tokens);
        emit Transfer(sender, receiver, tokens);
        return true;
    }
    // ------------------------------------------------------------------------
    // Returns the amount of tokens approved by the owner that can be
    // transferred to the spender's account
    // ------------------------------------------------------------------------
    function allowance(address tokenOwner, address spender) public override view returns (uint remaining) {
        return allowed[tokenOwner][spender];
    }
}

Using the above code, smart-contract can be deployed on Ethereum Mainnet or Testnet. Deploying a smart contract is technically a transaction, that needs to pay Gas (fees) in terms of ETH (Native token for Ethereum network), in the same way, that needs to pay gas for a simple ETH transfer. However, Gas costs for contract deployment are far higher.

** To create another token, simply change those values in the smart contract marked as highlight lines.

Summary

Blockchain technology is way deeper than token and smart contracts. There are many technical aspects like Consensus, Blocks, Wallets, Transactions, Decentralization, mining, etc. The goal of this article was just to provide an overview of smart-contract creation. Just feel free to write down your valuable comments.

Why Multi-sig wallet?

Reading Time: 3 minutes

Bitcoins are generally stored in Bitcoin’s blockchain addresses, which are Public/Private key pairs of ECDSA. Around 80% of the bitcoins are stored using standard (single-key)🔑 addresses, which usually starts with number “1”. Therefore, anyone who have access to any private key corresponding to that standard address can move funds and these transfers are irreversible. This kind of bitcoin(₿) storing nature led to critical problems.

Security👮

When user creates wallet, wallet generates pair of Key. These wallet files are typically stored on machines and securely store on disk using encryption. However, after taking best practices for securing wallet, there are chances of being offline attack. There are possibly chance of malware or hacker’s attack on your system when user login to their wallet. This kind of single-key storage is risky and led to create protocol that stores key offline. These wallets known as “Cold storage or Hardware wallet”. Hardware wallets generates key based on Random number generator and if that generated key had weaknesses, funds may be at risk without any malware or hacker attack. Obviously attacking on hardware wallet have their own expenses, so it is safer than storing on machine.

Access Control 🔑

When it comes to business for handling bitcoin, then its different game compared to individual. In most of organization, leaving key of bitcoin wallet to employees is not reliable as one can move funds without leaving any traces. There are some way to get rid of them by splitting keys and giving access to their CEO, CFO but again for larger business where many transactions needed, it is not reliable. Businesses need some internal policies for transaction. Nevertheless, there is another solution for it.

The Solution: Multi-sig 👥📝

Blockchain industry is evolving rapidly and to overcome above-mentioned flow of bitcoin, they have upgraded their protocol and brought up alternative to single-key addresses. In upgraded version, new type of address defined and standardized that is called P2SH (pay-to-script-hash) and these addresses starts with “3” instead of “1”. The new addresses need multiple private keys to transact bitcoin and this known as Multi-signature or “Multi-sig”. The X number of keys are required out of arbitrary set of Y key to transact a P2SH address. This also called as “X-of-Y”. Therefore, single-key address considered as “1-of-1”. Because of limitation of blockchain, most of multi-sig implementation are either “2-­of-­2” or “2-­of-­3”.

The easiest example of “2-of-2” multi-sig address is “bank locker” 🏦 with 2 keys where one key held by bank and other is customer. To open deposit box, both keys are needed else it is impossible to open locker.

Unlike single-key, the malware or hackers attack on machine can be avoided using multi-sig “2-of-2” address scheme by storing keys of wallet on two separate devices i.e computer and phone. As both keys are stored on different devices, funds cannot be stolen on malware or hacking attack. However, question arise, what happen if one loses their phone? In such cases “2-of-3”, address scheme is useful by storing another key offline. In case of loss of one device, still fund can be recovered using offline key and available device.

As we can see, multi-sig technology helps both business and individual users by improving security and access controls.