ETH Smart Contract — Part 1: Getting Started – Ngô Việt Khánh Huy

The raise of Ethereum and Decentralized Applications (DApp) using smart contract attracts huge amount of developers, including myself. However, it’s a whole new stack which comes with many concepts and tool sets. Many people find it’s difficult to find where and how to start. That’s the reason why I write this series ETH Smart Contract. Each article in this series are targeted to be short and focus on real practices, so reader can quickly involve and get their hands dirty. Every journey starts with a single step, you know.
In this article, we will get started with writing a simple Smart Contract and test it in local environment using nodejs and Truffle. Truffle is a suite for building DApp, which provides many tools for building smart contracts (compile, environment, config, test, web3 integration, etc.).
Make sure you have node >= 8.0 installed. Issue commands below to install truffle globally and init new project. I named the project smartcontract here, you can change it to something else if preferred.
npm install -g truffle
mkdir smartcontract
cd smartcontract
truffle init
Truffle project is set up with below structure:
contracts
> Migrations.sol migrations
> 1_initial_migration.js test
truffle-config.js
The structure is pretty simple, right? You will know the purposes of those stuffs later on. For now, just go ahead to something cool first.
Now, we will create a simple smart contract named SimpleStorage and test it using Truffle. The project will be something similar to the image below:
Here is the file SimpleStorage.sol inside contracts folder. The contract is pretty simple: it stores an unsigned integer (default is 0). This value can be read and updated via public methods get and set. The contract is written by Solidity, you can reference to its documents for more details if interested.
Create a new file 2_initial_simple_storage.js inside migrations folder. Truffle requires a migration file to compile and deploy the contract. To keep the article short, I won’t explain so much about migration. You can find more info about it in Truffle’s document here.
Now, we will write some tests against the contract. I’ll use Chai here, if you come from NodeJS world, you may have already known about it.
npm init
npm install --save-dev --save-exact chai chai-as-promised chai-bignumber
Create file SimpleStorageTest.js inside test with following content:
Issue command below to execute test, you should see the tests executed and passed.
So, that’s it. Pretty simple up to now right? In this article, we have get started with a simple smart contract and write unit test for it using Truffle and Chai. In next article, I’ll continue on how we simulate an Ethereum network locally and deploy our contracts there.
Published at Tue, 29 Oct 2019 07:45:51 +0000
{flickr|100|campaign}
