Truffle Suite Framework
Truffle Suite is a development framework for building, testing and deploying Ethereum smart contracts. It provides a range of tools that make Ethereum development easier and more efficient. This article will introduce how to use the Truffle Suite framework to develop a simple smart contract and show some basic code examples.
Install Truffle Suite
Before starting, you need to install Truffle Suite. You can install it via npm, just enter the following command in the terminal:
npm install -g truffle
This command will install Truffle Suite globally.
Create a smart contract
In Truffle Suite, you can use Solidity language to write smart contracts. We will create a simple smart contract that can store and retrieve a string. First, we need to create a new Truffle project in the terminal. Enter the following command in the terminal:
mkdir myproject cd myproject truffle init
This command will create a new Truffle project and initialize some default files and folders.
Next, we need to create a new contract file. Create a file named in
contracts
the folderMyContract.sol
and write the following code in it:pragma solidity ^0.8.0; contract MyContract { string myString; function setString(string memory _string) public { myString = _string; } function getString() public view returns (string memory) { return myString; } }
This contract defines a
MyContract
contract named and two functions defined in it:setString
andgetString
.setString
Functions are used to setmyString
the value of a string variable;getString
functions are used to getmyString
the value. Now we have a simple smart contract.Write test scripts
Next, we need to write a test script to test our contract. Create a file named in
test
the foldermycontract.js
and write the following code:const MyContract = artifacts.require("MyContract"); contract("MyContract", () => { it("should set the string correctly", async () => { const myContract = await MyContract.deployed(); await myContract.setString("Hello, world!"); const result = await myContract.getString(); assert(result === "Hello, world!"); }); });
This test script uses
assert
the library to test our contract. It first deploys our contract and then callssetString
a function to setmyString
the value. Finally, it callsgetString
the function to getmyString
the value and uses itassert
to check if it is equal to the value we set.Run test script
Now that we have written a simple smart contract and test script, we need to run the test script to test our contract. Enter the following command in the terminal:
truffle test
This command will run our test script and output the test results. If everything is fine, you should see the following output:
Contract: MyContract √ should set the string correctly (104ms) 1 passing (139ms)
This output tells us that our test passed.
Deploy smart contracts
Now that we have completed developing and testing our contract, we need to deploy our contract. In Truffle Suite, you can use
truffle migrate
commands to deploy smart contracts. Enter the following command in the terminal:truffle migrate
This command will compile and deploy our contract and output the deployment results. If everything is fine, you should see the following output:
Starting migration... ====================== > Network name: 'development' > Network id: 5777 > Block gas limit: 6721975 1_initial_migration.js ====================== Deploying 'Migrations' ---------------------- > transaction hash: 0x9de7a3f6e0a2c84b6f8f7c7a0d1e2b2d9e9d7a7b659ef1b3f3b3be8d295c3a49 > Blocks: 0 Seconds: 0 > contract address: 0x5FbDB2315678afecb367f032d93F642f64180aa3 > block number: 2 > block timestamp: 1627652324 > account: 0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1 > balance: 99.99999958 > gas used: 261494 > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.00522988 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00522988 ETH 2_deploy_contracts.js ===================== Deploying 'MyContract' ---------------------- > transaction hash: 0x0b8c1d0d5c6f4e4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e > Blocks: 0 Seconds: 0 > contract address: 0x692a70D2e424a56D2C6C27aA97D1a86395877b3C > block number: 4 > block timestamp: 1627652324 > account: 0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1 > balance: 99.99891672 > gas used: 146281 > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.00292562 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00292562 ETH Summary ======= > Total deployments: 2 > Final cost: 0.0081555 ETH
This output tells us that our contract has been successfully deployed to the Ethereum network.
Summarize
In this article, we introduced how to use the Truffle Suite framework to develop, test, and deploy a simple smart contract. Truffle Suite provides a series of tools to make Ethereum development easier and more efficient. We hope this article can help you get started with Truffle Suite and play a role in your Ethereum development
Decentralized Applications (DApps)
Simple decentralized applications (DApps) and show some basic code examples.
Install Truffle Suite
Before starting, you need to install Truffle Suite. You can install it via npm, just enter the following command in the terminal:
npm install -g truffle
This command will install Truffle Suite globally.
Create DApp
In Truffle Suite, you can use Solidity language to write smart contracts and use web3.js to interact with smart contracts. We will create a simple DApp that can store and retrieve a number. First, we need to create a new Truffle project in the terminal. Enter the following command in the terminal:
mkdir mydapp cd mydapp truffle init
This command will create a new Truffle project and initialize some default files and folders.
Next, we need to create a new contract file. Create a file named in
contracts
the folderMyContract.sol
and write the following code in it:pragma solidity ^0.8.0; contract MyContract { uint256 myNumber; function setNumber(uint256 _number) public { myNumber = _number; } function getNumber() public view returns (uint256) { return myNumber; } }
This contract defines a
MyContract
contract named and two functions defined in it:setNumber
andgetNumber
.setNumber
Functions are used to set the value of a numeric variablemyNumber
;getNumber
functions are used to getmyNumber
the value. Now we have a simple smart contract.Next, we need to write a simple front-end interface to interact with the smart contract. Create a file named in the root directory
index.html
and write the following code:<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>My DApp</title> </head> <body> <h1>My DApp</h1> <form> <label for="number">Number:</label> <input type="number" id="number" /><br /> <button type="submit">Set Number</button> </form> <p>Current Number: <span id="current-number"></span></p> <script src="./js/web3.min.js"></script> <script src="./js/app.js"></script> </body> </html>
This front-end interface contains a form that allows the user to enter a number and calls
setNumber
functions to set the number in the smart contract. It also contains a<p>
label that displays the current number in the smart contract.Next, we need to write a JavaScript file to interact with the smart contract. Create a file named in
js
the folderapp.js
and write the following code:window.addEventListener("load", async () => { if (typeof web3 !== "undefined") { web3 = new Web3(web3.currentProvider); } else { web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); } const contractAddress = "0x692a70D2e424a56D2C6C27aA97D1a86395877b3C"; const myContract = new web3.eth.Contract( [ { constant: false, inputs: [ { name: "_number", type: "uint256", }, ], name: "setNumber", outputs: [], payable: false, stateMutability: "nonpayable", type: "function", }, { constant: true, inputs: [], name: "getNumber", outputs: [ { name: "", type: "uint256", }, ], payable: false, stateMutability: "view", type: "function", }, ], contractAddress ); const currentNumber = await myContract.methods.getNumber().call(); document.getElementById("current-number").textContent = currentNumber; const form = document.querySelector("form"); form.addEventListener("submit", async (event) => { event.preventDefault(); const number = document.getElementById("number").value; await myContract.methods.setNumber(number).send({ from: web3.eth.defaultAccount }); const newNumber = await myContract.methods.getNumber().call(); document.getElementById("current-number").textContent = newNumber; }); });
This JavaScript file uses the web3.js library to interact with the smart contract. It first checks whether the web3 object already exists. If it does not exist, it creates a new web3 object and connects to the local Ethereum node. It then creates a new smart contract object and calls
getNumber
a function to get the current number. Finally, it listens for the form's submit event and callssetNumber
a function to set the number in the smart contract.Run DApp
Now that we have written a simple DApp, we need to run it. Enter the following command in the terminal:
truffle develop
This command will start a local Ethereum node and output some information. Next, enter the following command in the Truffle project root directory:
truffle migrate
This command will compile and deploy our contract and output the deployment results. If everything is fine, you should see the following output:
Starting migration... ====================== > Network name: 'development' > Network id: 5777 > Block gas limit: 6721975 1_initial_migration.js ====================== Deploying 'Migrations' ---------------------- > transaction hash: 0x9de7a3f6e0a2c84b6f8f7c7a0d1e2b2d9e9d7a7b659ef1b3f3b3be8d295c3a49 > Blocks: 0 Seconds: 0 > contract address: 0x5FbDB2315678afecb367f032d93F642f64180aa3 > block number: 2 > block timestamp: 1627652324 > account: 0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1 > balance: 99.99999958 > gas used: 261494 > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.00522988 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00522988 ETH 2_deploy_contracts.js ===================== Deploying 'MyContract' ---------------------- > transaction hash: 0x0b8c1d0d5c6f4e4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e4d4e > Blocks: 0 Seconds: 0 > contract address: 0x692a70D2e424a56D2C6C27aA97D1a86395877b3C > block number: 4 > block timestamp: 1627652324 > account: 0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1 > balance: 99.99891672 > gas used: 146281 > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.00292562 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00292562 ETH Summary ======= > Total deployments: 2 > Final cost: 0.0081555 ETH
This output tells us that our contract has been successfully deployed to the local Ethereum node.
Next, enter the following command in the Truffle project root directory:
npm run dev
This command will start a local web server and open our DApp. If everything goes well, you should see a web page with a form and numbers. You can enter a number in the form and click the "Set Number" button to set the number in the smart contract, and the number in the web page will also be updated.