Sample Contracts

This chapter describes creating and deploying smart contracts using the Truffle development environment.

Install Truffle development environment

Truffle is an environment where smart contracts can be developed and tested on blockchains that use Ethereum Virtual Machine (EVM) like Metadium.

Requirements

To use Truffle, Node.js v14 - v18 must be installed in Windows, Linux, or macOS environments.

Install Truffle

Install Truffle using NPM in your terminal.

$ npm install -g truffle

To check the installation of Truffle, run the following command:

$ truffle version
Truffle v5.11.5 (core: 5.11.5)
Ganache v7.9.1
Solidity - 0.8.21 (solc-js)
Node v18.19.0
Web3.js v1.10.0

Create project

Create a new directory for your new Truffle project. We will create a smart contract that implements key/value storage in the example. To do this, we create a directory called KVStore.

Initialize the Truffle project.

The following directories and files are created.

Create a KVStore contract with the following command.

The KVStore.sol file is created as shown below.

Writing a smart contract

Create a set function that stores Key/Value and a get function that uses Key to read the stored values as follows.

Setup

To compile and deploy, modify the truffle-config.js file.

First, wallet configuration is required. To avoid exposing the Private Key in the code, use dotenv and store the PRIVATE_KEY in the .env file as follows. If you use dotenv, install it using the npm i dotenv command to avoid compilation errors.

Second, proceed with network configuration. To use the Metadium Testnet, add the network configuration as follows.

Finally, proceed with compiler configuration. In the example, version 0.8.21 is used, and the optimizer is configured.

Smart contract compile

Smart contract deployment

Before deploying smart contracts, create a script file named 1_deploy_contracts.js in the migrations directory as follows:

Deploy the contract with the truffle migrate command.

Last updated