How to Code Ethereum — A Three Part Series (Part 3)

in #cryptocurrency6 years ago

 It is important that you test whether your platform or system has any bugs. In the first part of this article, we saw that Truffle is used for testing contracts in a simple way. Go to the project that we discussed in part 2, open a few command interfaces and then launch ganache-cli. 

ganache-cli -p 7545

set up a new folder and name it “test.” Then create a test file named “TestExample.js” in it, then paste the following details in it.

var Wrestling = artifacts.require(“Wrestling”);


contract(‘Wrestling’, function(accounts) {


// “it” is the block to run a single test


it(“should not be able to withdraw ether”, function() {


Wrestling.deployed().then(function (inst) {


// We retrieve the instance of the deployed Wrestling contract

wrestlingInstance = inst;

var account0 = accounts[0];

// how much ether the account has before running the following transaction

var beforeWithdraw = web3.eth.getBalance(account0);

// We try to use the function withdraw from the Wrestling contract

// It should revert because the wrestling isn’t finished

wrestlingInstance.withdraw({from: account0}).then(function (val) {

assert(false, “should revert”);

}).catch(function (err) {

// We expect a “revert” exception from the VM, because the user

// should not be able to withdraw ether

console.log(‘Error: ‘ + err);

// how much ether the account has after running the transaction

var afterWithdraw = web3.eth.getBalance(account0);

var diff = beforeWithdraw — afterWithdraw;

// The account paid for gas to execute the transaction

console.log(‘Difference: ‘ + web3.fromWei(diff, “ether”));

})

})

})

});

The effect of this is that it will get the Wrestling Contract, install it on our test network and then try to utilize the withdraw function. This should return an error since no one should be able to withdraw from a game before it ends.

To run the test on the development console, use the following command

truffle test — network development

The best thing would be for you to try and play a wrestling game and then ensure that it is only the winning party that can be able to withdraw the ether. Here is another technique to use when testing and you can also get more information from Truffle’s documentation. You can also use these security tools that have been developed by the community to test your code.

Business Logic

Apart from testing the internal workings of the contract, test it as a whole to see if it can do what is was created to accomplish.

One of the first things you should do is to ensure that the contract is well commented upon. This will result in clear and well-written code. Also, ensure that the Smart Contract is as simple as possible and just write in the part of your contract that needs to be decentralized. In case the Smart Contract is a part of dapp, distinguish between what should be included in the blockchain and what needs to be on the user interface and at the backend of the application.

Have a Good Understanding of the Platform

Reading the docs will give you a good understanding of what you are doing. You also need to read more about Solidity.

For instance, you should know that the fixed-point variable or floats or double have not yet been fully developed. Any division that uses the type “uint” for instance like 7/3 will get rounded to the closest integer. In this case, that is 2. Therefore, there are still many things on this platform that are still being worked on.

Since Blockchain is public, anyone who is interested can decipher the value that your variables hold, even if you try to hide the information. It is also possible for someone to figure out how you generate random number strings and generate their own.

Contracts that are only valid for certain periods of time are also quite popular. You will need to use a third-party application to make the contract run at certain times considering that Smart Contracts cannot trigger themselves. Also, some bad miners can try and interfere with your smart contract in case it is dependent on time to execute a transaction.

You should also be aware that since the Smart Contracts are public, anyone can access it and read it and even interact with it. You should also be aware that in case your contract interacts or in other way connects to other contracts an evil miner can interfere with how your contract gets executed.

Just keep in mind that since there’s lots of cash involved, people will do just about anything to interfere with your smart contracts.

External Parties

There are many users who are actively trying to make the use of Ethereum Blockchain as easy as possible, such that you do not have to download it into your device. This has led to the development of MEW, which allows you to move ether and install smart contracts. You can also use INFURA to connect to the Ethereum Blockchain through an API. This creates a solid tool when it is used together with Truffle.

Keep in mind that due to the amount of cash that is moved in these platforms, most hackers target them. Therefore, you have to decide whether security or convenience is more important to you. So, make your decision based on how much money you move around on this platform and the number of transactions that you carry out.

 How to Get Started

There is so much information that can help you to get started.

When it comes to security, do as much research as you can on the subject matter and always ensure that you use good programming practices.You can also participate in programs where people are asked to find bugs since you can get a lot of rewards for this.In case you detect a bug and how to do something in a better way, make sure to share it with the rest of the community, to help everyone gain from your knowledge. 

Tokens and ERCs

Tokens on Ethereum are smart contracts.

If you have come across terms such as ERC20, ERC721 among others, just know that these are basic functions that are being used by the community. You can even set up your functions and come up with scripts that can manage coins. The code used is for providing guidelines and is not the actual rules that are used.

While you do not have to follow the rules strictly, there are several advantages to doing so. First, it will make it easier for everyone to understand what you have developed and how to interact with it. Therefore, they will be more open to it. For instance, if you use Dapps or Mist, they will know how to interact with it. You will also find the ready-made implementation of the smart contract as it has already been developed by the community using Frameworks such as OpenZeppelin. It has been already tried and tested by many experienced users.

In this tutorial, we will set up an incomplete ERC20 token and then turn it into an ERC721 token, to distinguish the difference between these two tokens and help you understand how tokens work.

Making a Token

Use the following functions and events to come up with an ERC token.

contract ERC20Interface {

function totalSupply() public constant returns (uint);

function balanceOf(address tokenOwner) public constant returns (uint balance);

function allowance(address tokenOwner, address spender) public constant returns (uint remaining);

function transfer(address to, uint tokens) public returns (bool success);

function approve(address spender, uint tokens) public returns (bool success);

function transferFrom(address from, address to, uint tokens) public returns (bool success);

event Transfer(address indexed from, address indexed to, uint tokens);

event Approval(address indexed tokenOwner, address indexed spender, uint tokens);

}

The first thing would be to give the token a name

string public name = “Our Tutorial Coin”;

Then assign it a symbol

string public symbol = “OTC”;

the give it decimals

uint8 public decimals = 2;

 You cannot fully use fixed numbers in Solidity since it doesn’t support this. This means that all numbers have to be represented as integers. Now 123456 can turn into 1234.56 if two decimals are used, or they can turn into 12.3456 if four decimals are used. If you use a value of 0, it means that you don’t want your tokens to be visible. Ether has 18 decimals.

We shall start by using 0 tokens. This function “totalSupply()” gets the “totalSupply” variable.

function totalSupply() public constant returns (uint256 _totalSupply) {

 return totalSupply;

}

To send tokens to another address, use the “transfer()” function.

function transfer(address _to, uint256 _value) public returns (bool) {

// avoid sending tokens to the 0x0 address

require(_to != address(0));

// make sure the sender has enough tokens

require(_value <= balances[msg.sender]);

// we substract the tokens from the sender’s balance

balances[msg.sender] = balances[msg.sender] — _value;

// then add them to the receiver

balances[_to] = balances[_to] + _value;

// We trigger an event, note that Transfer has a capital “T,” it’s not the function itself with

Transfer(msg.sender, _to, _value);

// the transfer was successful, we return a true

return true;

}

This is the center of the ERC20 token.

To make a token compliant with ERC20, you have to use the following functions “approve(),” “transferFrom(),” and “allowance().” The work of the alliance function is to determine how much one address can send to another address. When one address approves another one, then the approved address can spend money that is in the account of the approving address. This can represent a security issue. For instance, if the approving address allows X tokens to be transferred from it and then decided to reduce the amount to Y tokens, the approved address can quickly transfer X tokens into its account before the allowance is changed to Y tokens.

To address the various shortcomings that ERC20 has, ERC223 and ERC777 were developed. The main work of ERC223 is to prevent money from being sent to the wrong address, while the ERC777 will send notifications to the receiving address about any tokens that are sent into it.

ERC721

This is fundamentally different from the ERC20 token.

Each address in ERC20 has a balance of tokens, while in ERC721, each address will have a list of tokens.

mapping(address => uint[]) internal listOfOwnerTokens;

When using Solidity, you have to manually keep track of tokens since it doesn’t have “indexOf()” method of arrays. To make our work easier, we can use mapping to know who owns which tokens.

mapping(uint => address) internal tokenIdToOwner;

The “transfer()” function that is in ERC721 will assign the token to a new owner. To prevent the old owner from transferring the token to another address, you have to add more instructions inside the “transfer()” method.

Minting

To create new ERC20 and ERC721 tokens, use the function “Mint().” It is important that you only set a few authorized addresses to be able to mint tokens in your contract. Mint is not present in the standard interface, rather it is an added functionality, in the same way, that you can add other functionalities to the token.

Metadata

Non-fungible assets symbolize an asset. To describe this asset, you can use such a string

mapping(uint => string) internal referencedMetadata;

A smart contract doesn’t contain tangible assets; rather it is a certification. For instance, the same way you can store a license plate number in a contract but not the physical vehicle.

To store virtual assets, you can use IPFS has as the metadata. The file that is kept in the IPFS is referred to as IPFS hash. If you store any file on IPFS, it will always be available on the network or at least any computer that is connected to the IPFS network.

There is a proposal for an ERC821, whose purpose is to come up with better designs, but the discussion on this issue has not yet been completed, so you can chime into that discussion if you are interested.

You can see different ways that ERC20 and ERC721 have been used in the Githushub repository.

You can also check out the OpenZepplin framework, as they have good smart contracts that are regularly assessed. Before making use of any contract, always read it first, so that you can make up your mind about which is the best one to use.

This is the end of the 3-part series.

Bonus Information: ICOs and CrowdSales

Initial Coin Offerings (ICOs) are not exactly about the development of Ethereum, rather, they are a way of raising money from many people.

In case a new company wants to raise funds, to run their operations, they come up with new coins, which they then sellout to the public within a limited period throw an ICO or crowdfunding.

Before Blockchains ever existed, most new companies used crowdfunding websites to raise the funds they needed. These websites took a percentage of the funds raised as their commission. But with ICOs, these middlemen are taken out of the picture, and the companies raise their funds directly.

Considering the number of scams that exist, if you are an investor, you need to be cautious about where you invest your cash. On the other hand, if you are a developer, a crowdsale is a smart contract where tokens are sold in exchange for ether for a limited time frame. There is no standard way of doing this, but you can get an example from OpenZepplin repo, or you can check out this tutorial on Ethereum’s website.