Introduction
This tutorial will walk you through the process of creating a simple Ethereum smart contract using Solidity, the programming language for writing Ethereum smart contracts.
Prerequisites
To follow this tutorial, you will need:
- Node.js and npm installed on your system
- Truffle Suite, a development environment, testing framework, and asset pipeline for Ethereum
- Ganache, a personal blockchain simulator for Ethereum
You can install Truffle and Ganache with the npm command:
npm install -g truffle
npm install -g ganache-cli
Project creation
Let's start by creating a new directory for our project and initialize a new Truffle project.
mkdir ethereum-contract
cd ethereum-contract
truffle init
Write the Smart Contract
Let's create a new file called SimpleStorage.sol
in the contracts/
directory and add the following code:
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint public data;
function set(uint x) public {
data = x;
}
function get() public view returns (uint) {
return data;
}
}
This is a very simple contract that stores an integer and provides two functions, set
and get
, for changing and getting the value.
Creating the migration file
To deploy the contract on the blockchain, you will need to create a migration file. Create a new file called 2_deploy_contracts.js
in the migrations/
directory and add the following code:
const SimpleStorage = artifacts.require("SimpleStorage");
module.exports = function (deployer) {
deployer.deploy(SimpleStorage);
};
Test the contract
Before deploying the contract, we should write some tests of it. Create a new file called simpleStorage.js
in the test/
directory and add the following code:
const SimpleStorage = artifacts.require('SimpleStorage');
contract('SimpleStorage', () => {
it('should set the value of data variable', async () => {
const simpleStorage = await SimpleStorage.deployed();
await simpleStorage.set(10);
const result = await simpleStorage.get();
assert(result.toNumber() === 10);
});
});
Run the tests with the command:
truffle test
Distribute the contract
Finally, we distribute the contract on our local blockchain using Ganache. Run the command:
ganache-cli
In another terminal, run the migration command:
truffle migrate
Conclusion
Congratulations! You have just written and deployed your first smart contract on Ethereum with Solidity.