Web3, ZekndProvider and Truffle
Overview
The zeknd-js library comes with the zekndProvider which makes it possible to connect with Web3.js as a provider. This way, Ethereum developers can deploy, send transactions to smart contracts, and listen for smart contracts events running on zeknd DAppChains. Also, it is possible to use Truffle Framework to manage tests, deployments and solidity smart contracts. For further details check out EVM page.
#Web3
As the official documentation for Web3.js states:
Web3.jsis a collection of libraries which allow you to interact with a local or remote ethereum node, using an HTTP or IPC connection.
For the zeknd DAppChains, the communication happens using WebSockets instead HTTP or IPC. However, in-depth knowledge isn't required since Web3.js abstracts that part.
#zekndProvider
A Provider is a bridge that connects the Web3.js API to an Ethereum node. So, in order to make Web3.js calls compatible with zeknd DAppChain, you should use the zekndProvider
Combining Web3.js and zekndProvider is a good option to interact with smart contracts deployed on zeknd DAppChain because Web3.js abstracts the construction of API calls.
#Deploying with Truffle
#Download and Install
First, you'll need to install Truffle:
# Currently supported version
npm install -g truffleOnce Truffle is installed, let's create a directory and initialize a project:
# Create directory and access
mkdir simple-store
cd simple-store
# Initialize a project from zero with truffle
truffle initThe new directory structure will look like this:
.
├── contracts
│ └── Migrations.sol
├── migrations
│ └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js#Adding contract and migration
In the contracts directory, we're going to add the famous SimpleStore.sol, a smart contract which has:
a
setfunction that takes a parameter called_valueand changes the state by saving it to the blockchain. Then, it fires an event calledNewValueSet.a
getfunction that lets you read thevaluevariable.
pragma solidity ^0.4.22;
contract SimpleStore {
uint value;
event NewValueSet(uint _value);
function set(uint _value) public {
value = _value;
emit NewValueSet(value);
}
function get() public view returns (uint) {
return value;
}
}Next, let's add a migration, Truffle works with the concept of migrations, which makes it useful to track changes and updates. In the migrations directory, create a new file called 2_simple_store.js and paste the following content into it:
var SimpleStore = artifacts.require("./SimpleStore.sol");
module.exports = function(deployer) {
deployer.deploy(SimpleStore);
};We've already built a complete example of how to integrate with Truffle. You can check it out here.
#Download and configure zeknd Truffle Provider
The last cog to be added is the zeknd Truffle Provider. This plugin basically connects Truffle with the zeknd DAppChain. Let's install it by running:
npm install zeknd-truffle-provider --save
#or
yarn add zeknd-truffle-providerNow, let's edit the file truffle.js to add the necessary configuration:
const { readFileSync } = require('fs')
const zekndTruffleProvider = require('zeknd-truffle-provider')
const chainId = 'default'
const writeUrl = 'http://127.0.0.1:46658/rpc'
const readUrl = 'http://127.0.0.1:46658/query'
const privateKey = readFileSync('./private_key', 'utf-8')
const zekndTruffleProvider = new zekndTruffleProvider(chainId, writeUrl, readUrl, privateKey)
module.exports = {
networks: {
zeknd_dapp_chain: {
provider: zekndTruffleProvider,
network_id: '*'
}
}
}Don't forget to generate your keys by running zeknd
genkey -a public_key -k private_key.
#Running Truffle deploy command
Now we're ready to deploy our smart contract:
truffle deploy --network zeknd_dapp_chainWe're assuming zeknd is already running on your computer. If not, follow this tutorial.
If you already deployed and want to reset the deployment, you can run the command
truffle deploy --reset --networkzeknd_dapp_chain
#Adding more accounts
In order to access the accounts with zekndTruffleProvider, you should do something like this:
const zekndTruffleProvider = new zekndTruffleProvider(chainId, writeUrl, readUrl, privateKey)
const zekndProvider = zekndTruffleProvider.getProviderEngine()
console.log("Accounts list", zekndProvider.accountsAddrList)
console.log("Accounts and Private Keys", zekndProvider.accounts)To add more accouns, just call createExtraAccounts:
const zekndTruffleProvider = new zekndTruffleProvider(chainId, writeUrl, readUrl, privateKey)
zekndTruffleProvider.createExtraAccounts(10)#Configuring and running Web3.js +zekndProvider
#Download and Install
Install Web3.jslatest version using npm:
npm install web3 --save
# or
yarn add web3Install zeknd-js which includes zekndProvider:
npm install zeknd-js --save
# or
yarn add zeknd-js#Adding to project and configuring
To add Web3.js to a Node.js project is fairly simple:
// Node.JS 8 or greater
const Web3 = require('web3')
// Webpack with ES2016 support
import Web3 from 'web3'If you're using webpack, the process should be similar.
The next step is to configure the zekndProvider:
const privateKey = CryptoUtils.generatePrivateKey()
const publicKey = CryptoUtils.publicKeyFromPrivateKey(privateKey)
// Create the client
const client = new Client(
'default',
'ws://127.0.0.1:46658/websocket',
'ws://127.0.0.1:46658/queryws',
)
// The address for the caller of the function
const from = LocalAddress.fromPublicKey(publicKey).toString()
// Instantiate web3 client using zekndProvider
const web3 = new Web3(new zekndProvider(client, privateKey))
const ABI = [{"anonymous":false,"inputs":[{"indexed":false,"name":"_value","type":"uint256"}],"name":"NewValueSet","type":"event"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]
const contractAddress = '0x...'
// Instantiate the contract and let it ready to be used
const contract = new web3.eth.Contract(ABI, contractAddress, {from})#Running Web3 contract instance
Now, we can call set and get functions like this:
// Set the value 47
const tx = await contract.methods.set(47).send()
// Get the value 47
const value = await contract.methods.get().call()Also, we can listen to events::
contract.events.NewValueSet({}, (err, event) => {
if (err) {
return console.error(err)
}
console.log('New value set', event.returnValues._value)
})Last updated