How to set up a local development environment with Remix for Solidity smart contract development
Hello readersđź‘‹
Many developers like to develop projects in their local environment as compared to developing on an Online IDE. If you want to do Solidity smart contract development in your local environment and don't know how to do that, you are at the right place.
In this blog, we will look at how to set up a local development environment for Solidity smart contract development.
Let's start!
Steps to be performed
The major steps which we will do are as follows -
- Setting up an IDE
- Setting up git
- Connecting to remix for building and deployment.
- Setting up metamask for deploying to a real blockchain.
Setting up an IDE
You can use any IDE you like but I generally prefer 'Vscode'. I think many of you might have this already installed.
If yes, you can move directly to the next step. Else, you can download Vscode from the following link
Setting up git
If you want to deploy your code on GitHub, etc. You will need git installed. If you already have it installed, you can skip this step. Else, you can download it from here
Creating a local demo project
Go to the directory of your choice and create a new project named "Solidity demo project 1" (You could name it anything of your choice).
Creating a demo contract
Open this project in Vscode now and create a new file named "MyContract.sol" for demonstration and copy the following code inside it -
// SPDX-License-Identifier: MIT
// compiler version must be greater than or equal to 0.8.10 and less than 0.9.0
pragma solidity ^0.8.10;
contract HelloWorld {
string public greet = "Hello World!";
}
You would not see any syntax highlights in your code yet. This is because you don't have the Solidity extension installed. Ok, let's install it.
Go to the Extensions tab in vscode and search for 'solidity' and install the first extension.
Now you could see syntax highlights in your code as follows-
Connect your project to Remix
The next step is to connect your project to Remix.
To connect your project to Remix, you first need to have the node package manager(npm).
If you don't have npm installed, you can download node from here and you are all set to go further.
As now node is installed, go to the terminal and install 'remixd' by entering the following command -
npm i -g @remix-project/remixd
Now, we need to connect remix to our localhost. We use the following command and press enter. -
remixd -s .
Here, the dot above means the local directory we are in. You can also replace dot with the absolute path to your directory here.
If the above line gives an error that execution of scripts is disabled in your system, then open Windows PowerShell in Administrator mode and run the following command and then try to again run the above remix command and you are good to go -
Set-ExecutionPolicy RemoteSigned
Now you should be able to connect to your project using remix.ethereum.org
Open remix.ethereum.org in your browser and then you could see an option named workspaces at the top left of your window and you could shift from the default workspace to the localhost.
Click on 'connect to localhost' and then click on connect on the dialog box which appears on your screen.
Now you could see your local project created inside remix on your browser. You could see all your files inside the project here.
Don't worry, we will still code on your local IDE Vscode. You will see all changes in your local IDE visible live here.
We will use Remix for deploying and testing our smart contracts only.
Understanding Remix
You can click the solidity logo icon in the list of items visible at the left of the screen and from there you can compile your smart contract.
You can then click the next tab under the solidity logo and you can deploy your contract from there.
Also, go to the plugins tab (option visible in left down) and search for the debugger plugin and activate it. This will help you to debug transactions. You could see a debugger button(looks like a bug) now visible.
Go to vscode again and you could see a new folder named 'artifacts' there. In the metadata.json file, you will have access to the abi and some other information now.
Git in project
Open the terminal. We can initialize git by using the command
git init
Now create a new file .gitignore and add the artifacts to the gitignore file.
Now run the following commands one by one
git add .
git commit -m "Initial commit"
If you want to push to Github, I am sure you know the command for that!
Let us move further.
Setting up metamask
Now we look at how to set up metamask in the browser so that we are able to communicate with a real blockchain.
First, install metamask from here and create a wallet there.
Now go to your remix IDE in your browser and we will now deploy our contract to the blockchain.
Go to the deploy tab in remix and switch Environment to the 'Injected Web3' provider. You could see the metamask extension popup in your browser. Click on 'Next' and then click on 'Connect' to connect your Metamask with Remix.
Also for test purposes here, I will switch to the Rinkeby test network instead of the Ethereum mainnet. (You should deploy on mainnet only on the final update because it costs real money to deploy. When you want to deploy for testing purposes, use any one of the test networks.)
If you want free ether on your test network, you can get it from a faucet (You just need to add your public address there).
Now click on 'Deploy' to deploy your contract. Confirm the transaction on Metamask (pay the gas fees) and now it's deployed on the blockchain and you can view this transaction on the etherscan.
Now your contract is deployed successfully on the blockchain. Now if you try to run any function in your contract that changes the state of the blockchain, you will get a Metamask popup to sign for that transaction to perform the function.
Setting up Truffle for Testing purposes
Now if we need to add testing to our project too, we need to add truffle to our project.
For truffle, we need to have npm installed.
Create a new empty project named 'Truffle demo' for understanding the Truffle setup.
Setting up Truffle
To install truffle globally on your machine, open terminal or command prompt and enter the following command:
npm install -g truffle
You can verify whether truffle is installed or not using the following command -
truffle version
To create a truffle project, open the directory where you want your project and then run the following command
truffle init
After running this command, you see it automatically created three directories- contracts/
, migrations/
, and test/
along with three files Migrations.sol
, 1_initial_migrations.js
, and truffle-config.js
.
contracts/
will store all your Solidity (.sol files). This is where you will add any smart contracts, libraries, or interfaces that you need at compile time.Migrations.sol
is a fully working smart contract written in Solidity. It is used by truffle to ensure that your project's deployment to the blockchain is carried out in the proper sequence.migrations/
will store truffle "deployer" Javascript files. Every time you want to deploy a contract, you will need to tell truffle which one, and what constructor arguments you may need.1_initial_migration.js
is the script that deploys our Migration contract. It is the most basic type of deployment because it requires no library linking or constructor arguments.
test/
is where we create and add our tests.truffle-config.js
is the main configuration for your Truffle project. This is where we define what networks to use, gas usages, addresses to deploy with, and a few other variables.
module.exports = {
networks: {}
}
Creating contracts
The contracts for our project are created inside the contracts folder. Let us create a simple contract named 'SimpleStorage.sol' and we add the following code to it.
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract SimpleStorage {
uint data;
function updateData(uint _data) external {
data = _data;
}
function readData() external view returns(uint) {
return data;
}
}
Checking the Solidity version
Your complete project should use the same Solidity version and it is defined in the truffle-config.js file. Open the truffle-config.js file and go to the compilers section and check for the solidity version. If you want to change your version to a customized one, change there.
In our case above, the Solidity version which will be used is 0.8.12
.
Compile your contracts
To compile all of your contracts, open the terminal and run the following command
truffle compile
The output you see is as follows-
This command creates artifacts in the build/contracts directory. The artifacts are JSON files for every contract which also contain the abi for the contract. These are useful for contracts to be interacted with the front end using web3.js.
Testing smart contracts
For testing our smart contracts, we need to create tests inside the test/
directory. Let us create the following test named 'simpleStorage.js' which is a test file for the 'SimpleStorage.sol' contract.
Add the following code to 'simpleStorage.js'
const SimpleStorage = artifacts.require('SimpleStorage.sol');
contract('SimpleStorage', () => {
it('Should update data', async () => {
const storage = await SimpleStorage.new();
await storage.updateData(10);
const data = await storage.readData();
assert (data.toString()==='10');
});
});
To run our tests, we run the following command -
truffle test
By using the above command, truffle starts a local development blockchain and runs our tests. You could see something like this -
We see whether our test succeeded or failed.
Deploying smart contracts to a local development blockchain (Ganache)
To deploy our contracts, we first need to create the migrations file. Go to the migrations folder and create a new file named '2_deploy_contract.js' and add the following code inside it.
const SimpleStorage = artifacts.require('SimpleStorage.sol');
module.exports = function(deployer) {
deployer.deploy(SimpleStorage);
// If we have arguments inside the constructor we can simply add it
// as further parameters inside the above line. Ex-
// deployer.deploy(SimpleStorage,parameter1,parameter2);
};
Once you have your migrations file ready, you can deploy your contracts to a local development blockchain using the following command -
truffle develop
The above command starts a local development blockchain(inbuilt version of Ganache). Here, we also get 10 new accounts and their private keys for testing with a balance of 10 ether each (fake ether).
You can also notice that your terminal now moves to the truffle(develop) section and for deployment, run the following command here -
migrate --reset
Your contracts were now successfully deployed. You could also see many details like transaction hash, contract address, etc.
Deploying smart contract to the public blockchain (Rinkeby Test network)
Now we deploy our project to a public blockchain say Rinkeby test network.
We need Metamask for the deployment which we have already set up.
We also need to create an Infura endpoint.
Firstly, we have to make the migrations file which is the same as done above for local deployment. If you did this already, you can move further.
Creating Infura endpoint
We need an API through which we can access the rinkeby network. Why Infura? Infura is used to access the test/main network and deploy our contract on them.
Let us create an infura endpoint on the rinkeby network
- Go to infura.io
- Sign up there if you don't have an account
- Go to the dashboard and click on the 'Create new project' button visible on the top right section of the screen.
- Select Product as Ethereum and Project name as 'Truffle demo' and click on Create.
- After creating the project, you can see that you get project id, secret, and endpoints for the rinkeby network. We will use this further.
After creating the Infura endpoint, we need an npm package HDWalletProvider which is used for signing our transactions.
Go back to the terminal of your project and enter the following command.
npm install @truffle/hdwallet-provider
Configuring truffle.js
Now we have, our truffle hdWallet-provider in our node modules, an endpoint from infura account, and the seed-phrase from our metamask account.
Let’s configure our truffle-config.js. Open truffle-config.js and import truffle hdWallet provider at the top. Add the following line to the top of the truffle-config.js file.
const HDWalletProvider = require('@truffle/hdwallet-provider');
We also create a new file named 'secrets.json' to store the mnemonic and Infura endpoint. Add the following code inside the secrets.json file.
{
"mnemonic": "Your 12 words secret seed phrase",
"projectEndpoint": "Your Infura project endpoint"
}
The above project endpoint looks like this -
wss://rinkeby.infura.io/ws/v3/YOUR_PROJECT_ID
Make sure to add the secrets.json file to .gitignore. Create a .gitignore file and add the following line to it.
secrets.json
Now we need to first fetch our mnemonic and project endpoint from the secrets.json file inside our truffle-config.js file. Add the following line inside truffle-config.js under the hd-wallet-provider import.
const { mnemonic, projectEndpoint } = require('./secrets.json');
Uncomment the following development portion inside the network section of your truffle-config.js file.
development: {
host: "127.0.0.1", // Localhost (default: none)
port: 8545, // Standard Ethereum port (default: none)
network_id: "*", // Any network (default: none)
},
Now to deploy to the Rinkeby test network, we will edit the following inside the network section of the truffle-config.js file.
Uncomment this part of the code.
Replace ropsten with rinkeby.
Add the mnemonic and projectEndpoint variables already fetched.
Make the network id as 4.
rinkeby: {
provider: () => new HDWalletProvider(mnemonic, projectEndpoint),
network_id: 4, // Ropsten's id
gas: 5500000, // Ropsten has a lower block limit than mainnet
confirmations: 2, // # of confs to wait between deployments. (default: 0)
timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
}
Save the file and then open the truffle console and then migrate on the rinkeby network using the following command.
truffle migrate --network rinkeby
That’s all done.
Your contract is successfully deployed on the public blockchain. You can check the contract address or transaction hash on Etherscan too.
Note:
To deploy on the main network, get the infura endpoint for the main network, and configure the config file.
Replace rinkeby with main, and network id with 1.
Then truffle migrate –network main
.
Conclusion
This is the end of the blog. Now, you are able to easily set up a local development environment for Solidity and create projects related to it.
All the best!I hope you find it helpful. Let me know your thought in the comment below.
Do like this blog and follow me!
Also, you could follow me on Twitter
Thanks for readingđź’›