Loading...
The blockchain developer may get in a need of deploying new smart contract with the help of user interaction. Let's say if the DApp is designed on ethereum blockchain which enables the user to create a lottery pool of its own and destroy after some fixed time period, The DApp developer might be willing to create a new smart contract for each of the lottery pools created by user just to enhance security and some functionalities to his DApp, He may need to compile and deploy several smart contracts then, that too involving user interaction.
In order to deploy smart contract , ethereum account is required. These key pairs can be got from any ethereum wallet, eg. metamask. Make sure the selected wallet has some funds in it.
To connect the appliction to blockchain RPC provider has a vital role. There are may free and paid rpc providers for ethereum network. Since free rpc provider might have very big load on it, you can select infura as provider. Create project and get api key.
As the complete project code is designed in node , install nodejs.
$ npm init
$ touch index.js
$ npm install web3
npm install solc
The complete package.json will look like this -
{
"name": "deploysmfromnodejs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"solc": "^0.8.6",
"web3": "^1.5.1"
}
}
Open index.js in any editor & Import the following in index.js file
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const Web3 = require('web3');
Set the smart contract file path
const contractPath = path.resolve(__dirname, 'Storage.sol');
const source = fs.readFileSync(contractPath, 'utf8');
here the contract file is Storage.sol
Configure the solidity compiler and compile the file
const input = {
language: 'Solidity',
sources: {
'Storage.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*'],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Storage.sol']['Storage'];
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
const privKey = '<private key>';
const address = '<address>';
const web3 = new Web3("https://ropsten.infura.io/v3/<api>");
replace the privatekey and address variables with the public/private key pairs and also the provider url in Web3(provider). Select the proper provider along with the network. Here the contract will be deployed on ropsten test network.
The bytecode and abi is taken from the compiled contract. these are needed to sign the transaction later.
const deploy = async() => {
console.log('Attempting to deploy from account:', address);
const incrementer = new web3.eth.Contract(abi);
const incrementerTx = incrementer.deploy({
data: bytecode
// arguments: [],
})
const createTransaction = await web3.eth.accounts.signTransaction({
from: address,
data: incrementerTx.encodeABI(),
gas: 3000000,
},
privKey
)
const createReceipt = web3.eth.sendSignedTransaction(createTransaction.rawTransaction).then((res) => {
console.log('Contract deployed at address', res.contractAddress);
});
};
First get the instance of contract in incrementer then create a raw transaction by deploying the contract and signing it with private key. later send the signed transaction to blockchain, the return receipt will be complete info about deployed contract.
deploy();
$ node index.js
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const Web3 = require('web3');
// Compile contract
const contractPath = path.resolve(__dirname, 'Storage.sol');
const source = fs.readFileSync(contractPath, 'utf8');
const input = {
language: 'Solidity',
sources: {
'Storage.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*'],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Storage.sol']['Storage'];
// Initialization
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
const privKey = '<private key>';
const address = '<address>';
const web3 = new Web3("https://ropsten.infura.io/v3/<api>");
// Deploy contract
const deploy = async() => {
console.log('Attempting to deploy from account:', address);
const incrementer = new web3.eth.Contract(abi);
const incrementerTx = incrementer.deploy({
data: bytecode
// arguments: [],
})
const createTransaction = await web3.eth.accounts.signTransaction({
from: address,
data: incrementerTx.encodeABI(),
gas: 3000000,
},
privKey
)
const createReceipt = web3.eth.sendSignedTransaction(createTransaction.rawTransaction).then((res) => {
console.log('Contract deployed at address', res.contractAddress);
});
};
deploy();