Check our terms and conditions, privacy policies, and cookies policy.
Copyright 2024 © All rights Reserved. Designed by LACNet
Before deploying your smart contracts in the LACChain Networks, see this overview that explains the minor changes you will need to incorporate to them.
Make sure Node and NPM are installed on your system.
node -v
npm -v
Create a directory as MyFirstContract.
> mkdir MyFirstContract
> cd MyFirstContract
Create a package json to manage the dependencies.
> npm init
This command prompts you things such as the name and version of your application. You can simply hit RETURN to accept the defaults for most of them.
Install web3.js.
> npm install --save web3
Install ethereumjs library to sign transactions
> npm install --save @ethereumjs/tx@3.5.2
Install solc to compile the smart contracts.
> npm install --save solc@0.8.0
Create two more directories named contracts and build, and switch from the current directory to Contracts.
> mkdir contracts
> mkdir build
> cd contracts
Create MyContract.sol file under contracts directory and paste the code below:
// We will be using Solidity version 0.8.0
pragma solidity 0.8.0;
contract MyContract {
string private message = "My First Smart Contract";
function getMessage() public view returns(string memory) {
return message;
}
function setMessage(string memory newMessage) public {
message = newMessage;
}
}
Now, create a compile.js file under MyFirstContract folder and paste this code.
console.log("Compiling...")
const path = require("path");
const fs = require("fs-extra");
const solc = require("solc");
const buildPath = path.resolve(__dirname, "./build");
const contractPath = path.resolve(__dirname, "./contracts", "MyContract.sol");
const myContractSource = fs.readFileSync(contractPath, "utf8");
var input = {
language: 'Solidity',
sources: {
'MyContract.sol' : {
content: myContractSource
}
},
settings: {
outputSelection: {
'*': {
'*': [ '*' ]
}
}
}
};
const output = JSON.parse(solc.compile(JSON.stringify(input)));
const contracts = output.contracts["MyContract.sol"];
const contract = contracts["MyContract"];
fs.writeFileSync(path.resolve(buildPath, `MyContract.json`), JSON.stringify(contract.abi, null, 2), 'utf8');
const contractDeploy = {
interface: contract.abi,
bytecode: contract.evm.bytecode.object
};
module.exports = contractDeploy
The above code reads the contract file MyContract.sol, compiles it using solc compiler, and saves the output of contracts in the json file.
Create a deploy.js file under MyFirstContract directory and paste the below code inside the file.
console.log("Deploying...")
const Web3 = require("web3");
const {default: Common} = require('@ethereumjs/common');
var Tx = require('@ethereumjs/tx').Transaction;
const { bytecode } = require("./compile");
// TYPE YOUR PRIVATE KEY
var privateKey = Buffer.from('8b2c4ca73a4ce874432997a1a0851ff11283996f512b39f2640d009d8dc8b408', 'hex');
// Specify lacchain network node to connect to
const web3 = new Web3(“PUT_YOUR_NODE_IP:80");
const deploy = async () => {
const txCount = await web3.eth.getTransactionCount('1306E8B4CD9593c49E2A021DAF7d513d7E634405')
const nodeAddress = “”
const expiration = 1836394529
let value = web3.eth.abi.encodeParameters(
["address","uint256"],
[nodeAddress,expiration])//setting the value
var rawTx = {
nonce: web3.utils.toHex(txCount),
gasPrice: '0x00',
gasLimit: '0x300000',
value: '0x00',
data: '0x'+bytecode+value.substr(2)
}
const c = Common.custom()
c.setHardfork('homestead')
var tx = new Tx(rawTx,{ common: c });
const signedTx = tx.sign(privateKey)
var serializedTx = signedTx.serialize();
console.log(serializedTx.toString('hex'));
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);
};
deploy();
After copying the code, consider changing the following values:
Run the command below at SmartContract directory to deploy MyFirstContract.
> node deploy.js
It takes some time for deployment. Once deployed, the address (where contract is deployed) is displayed on the terminal as below.
Deploying…
Compiling…
contractAddress: 0x235645C35894e985d398b27287E6880b03830dE8
Copy the contractAddress you got, in this example it would be 0x235645C35894e985d398b27287E6880b03830dE8 . It would be use later to send a transaction.
Create a sendTransaction.js file under MyFirstContract directory and paste the below code inside the file.
console.log("Send a Transaction...")
const Web3 = require("web3");
const {default: Common} = require('@ethereumjs/common');
var Tx = require('@ethereumjs/tx').Transaction;
// TYPE YOUR PRIVATE KEY
var privateKey = Buffer.from('8b2c4ca73a4ce874432997a1a0851ff11283996f512b39f2640d009d8dc8b408', 'hex');
const contractAddress = “”
// Specify lacchain network node to connect to
const web3 = new Web3(“:80”);
const send = async () => {
const txCount = await web3.eth.getTransactionCount('1306E8B4CD9593c49E2A021DAF7d513d7E634405')
const bytesFunc = web3.eth.abi.encodeFunctionSignature('setMessage(string)')
const parameter = web3.eth.abi.encodeParameter('string', 'my first transaction');
const nodeAddress = “”
const expiration = 1836394529
let value = web3.eth.abi.encodeParameters(
["address","uint256"],
[nodeAddress,expiration])//setting the value
var rawTx = {
nonce: web3.utils.toHex(txCount),
to: contractAddress,
gasPrice: '0x00',
gasLimit: '0x300000',
value: '0x00',
data: bytesFunc+parameter.substr(2)+value.substr(2)
}
const c = Common.custom()
c.setHardfork('homestead')
var tx = new Tx(rawTx,{ common: c });
const signedTx = tx.sign(privateKey)
var serializedTx = signedTx.serialize();
// console.log(serializedTx.toString('hex'));
web3.eth.call({
to: contractAddress, // contract address
data: "0xce6d41de" //getMessage()
}).then(result => {
let decoded = web3.eth.abi.decodeParameter('string',result)
console.log("Current value:",decoded)
}).catch(ex => {
console.log(ex);
});
await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', function(receipt){
console.log("TransactionHash:",receipt.transactionHash)
});
web3.eth.call({
to: contractAddress, // contract address
data: "0xce6d41de" //getMessage()
}).then(result => {
let decoded = web3.eth.abi.decodeParameter('string',result)
console.log("New value set:",decoded)
}).catch(ex => {
console.log(ex);
});
};
send();
Run the command below at SmartContract directory to send a transaction to smart contract previously deployed.
After copying the code, consider changing the following values:
> node sendTransaction.js
It takes some seconds. Once sent, you will see on your terminal like this.
Send a Transaction…
Current value: My First Smart Contract
TransactionHash: 0x6fceac86513e3938caa3ce2b61d08d4fbc1e98231e30ab15416457baa38c5d8c
New value set: my first transaction
You have set a new value in your smart contract.
Check our terms and conditions, privacy policies, and cookies policy.
Copyright 2024 © All rights Reserved. Designed by LACNet