Ethereum Development - Starting with the Truffle Scaffold
I started learning blockchain development this week to build up some knowledge before the company’s blockchain project begins. This blog post is a review of what I’ve learned.
What is Truffle
Truffle is a development framework for the Solidity language on Ethereum. It is implemented in JavaScript.
Although it’s built with JavaScript, which we’re familiar with,
Truffle is mainly a tool for compiling and deploying smart contracts (though it does have other features).
What is Solidity
In blockchain application development, you can roughly understand Solidity as a language for writing backend code. In technical terms, this backend code is called a smart contract.
Main Functions of Truffle
Truffle provides two main functions in blockchain application development:
- Compile smart contracts
- Deploy smart contracts
Installation
Just like a regular npm package, install it directly with npm.
# Install truffle globally
$ npm i truffle -g
Initialize Your Project
# Create a new directory
$ mkdir myproject
$ cd myproject
# Initialize
$ truffle init
# After running the command
Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!
Commands:
# Other truffle operations: compile, deploy, test
Compile: truffle compile
Migrate: truffle migrate
Test contracts: truffle test
After completion, you’ll see the following directory structure:
contract/ - Smart contract Solidity code
migrations/ - Smart contract deployment scripts
test/ - Test files
truffle.js - Truffle configuration file
Below is the auto-generated Solidity code. Most development work will involve writing code like this. After compilation, you can call these methods from frontend JavaScript.
pragma solidity ^0.4.17;
contract Migrations {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
function Migrations() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
Compile Solidity
$ truffle compile
After running the command, a build folder will appear.
Inside are our compiled Solidity files, ultimately in JSON format.
build/
contracts/
Migrations.json
This JSON file is the smart contract we’ll use frequently.
In blockchain frontend development, you import this JSON file into your frontend code and call its methods.