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.
$ mkdir KVStore
$ cd KVStore
Initialize the Truffle project.
$ truffle init
Starting init...
================
> Copying project files to /Users/trident/Projects/DApp/KVstore/Temp
Init successful, sweet!
Try our scaffold commands to get started:
$ truffle create contract YourContractName # scaffold a contract
$ truffle create test YourTestName # scaffold a test
http://trufflesuite.com/docs
The following directories and files are created.
$ tree
.
├── contracts
├── migrations
├── test
└── truffle-config.js
4 directories, 1 file
Create a KVStore contract with the following command.
$ truffle create contract KVStore
The KVStore.sol file is created as shown below.
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract KVStore {
constructor() public {
}
}
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.
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract KVStore {
mapping(string => string) store;
function get(string memory key) public view returns(string memory) {
return store[key];
}
function set(string memory key, string memory value) public {
store[key] = value;
}
}
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.
PRIVATE_KEY=["YOUR_PRIVATE_KEY"]
Second, proceed with network configuration. To use the Metadium Testnet, add the network configuration as follows.