How to Call a smart-contract from a DApp on a CENNZnet blockchain

charingane
5 min readJan 29, 2020

--

Introduction:

Before we start in our tutorial we will introduce some information about CENNZnet, CENNZnet is a public open blockchain network that allows anyone to build decentralized applications with first-class usabilities, such as easy bootstrapping for new dApps and seamless onboarding for new users, by leveraging CENNZnet protocols. CENNZnet uses proof of stake to reach consensus and secure the network, which encourages participation and reduces energy consumption. On CENNZnet, users stake CENNZ to run a node as a validator.
CENNZnet consists of a series of protocols and services that are fundamental for building any commercial-grade applications, such as single-sign-on, exchange, communication, storage, token generation, attestation (and KYC services powered by it), etc.

Get Started

installation:

In this guide I will use Windows10, You can check references at the end of this article to check out how to install dependencies of Linux and Mac.
make sure that you have Node >=10.13.0 and Yarn >=1.10.1 installed in your computer

//Install client globally
npm i @cennznet/cli -g
//install api, generic asset, cennzx ...
npm i --save @cennznet/api @cennznet/crml-generic-asset @cennznet/crml-cennzx-spot @cennznet/crml-attestation

Connecting to Network

Now you need to make an API key so you can connect to the endpoint, like:
1. Register an account with unfrastructure.
2. Log in and create a project.
3. Use the API key as the endpoint.

CENNZnet UI

Now we will use the CENNZnet UI to interact via a web browser, you can run it locally using these commands:

git clone https://github.com/cennznet/cennnznet-ui
cd cennznet-ui && yarn install
yarn run start

Now you can launch the UI, Access the UI via http://localhost:3000
go to settings and use the API key that we have created above to connect to the Rimu testnet.

then go to accounts and create some accounts, make sure that you save seed or mnemonic words, you will need also an initial balance to deploy smart contract and make transactions, go here https://cennznet.js.org/faucet-ui/ and paste your address to get the free balance to test (do it until you get a sufficient amount).

Spin2Win Contract

You can follow this doc to build and deploy the example smart contract: “spin2win”.
After you build and deploy the contract you will get two items to be used in the next step: Contract address, Contract ABI
or you can download them from here: https://github.com/cennznet/spin2win/releases

Tips: If you get this error “system.ExtrinsicFailed” when you deploy a smart contract make sure that you put a sufficient amount of gas, on my own, I use 1,000,000 as gas.

Connect to a Smart contract:

to construct a contractABI instance we will use this code

const { ContractAbi } = require ('@cennznet/types/polkadot';)
const ABIJson = require('./Spin2Win.json');
function spin2win(accountId){
const contractAbi = new ContractAbi(ABIJson);
return contractAbi.messages.spin(accountId);
};

You can be sure if that code is fine by adding a console.log of the function and get similar to this picture below:

Tips2: If you get an error of accountId than change it to your smart contract address. if you get the error “ContractAbi undefined” I fix this error by adding to my code the class ContractAbi , you can find it in node_modules.

our next step is to call a contract and make a user receive a random reward after a spin. You can read more information about api.tx.contracts here: https://cennznetdocs.com/api/latest/tutorials/0_Overview.md

const { contractAddress } = "";  
const payload = spin2win(address);
const endowment = new BN('10000');
const tx = api.tx.contracts.
call(
contractAddress,
endowment,
// deposit amount, can be 0: BigNumber
1000000,
// gas fee
payload
// the payload when calling specific message
);

the call extrinsic used form: call(dest: Address, value: Compact<BalanceOf>, gas_limit: Compact<Gas>, data: Bytes) Makes a call to an account, optionally transferring some balance.
* If the account is a smart-contract account, the associated code will be executed and any value will be transferred.
* If the account is a regular account, any value will be transferred.
* If no account exists and the call value is not less than existential_deposit, a regular account will be created and any value will be transferred.

The last step: sign and send the tx. You can get the transaction status and all the event details inside the code and also check them on CENNZnet UI with block hash.

const txHash = await tx.signAndSend(    
master.address,
async ({events, status}) => {
if (status.isFinalized && events !== undefined) {
const blockHash = status.asFinalized;
console.log('@---blockHash---@:', u8aToHex(blockHash));
}});
return txHash;

Here a video shows a test of the game. I will work on a web simulation ASAP so please stay tuned.

Congratulations on reaching this far 🤩 Hope this article was helpful for you all. and please don’t hesitate to ask questions.

Common issues:

“ system.ExtrinsicFailed “, If you get this error when you try to deploy your contract. that means the balance is not enough. try to use the faucet to get free test-token and try again.
The network(Localhost or Rimu) of deploying contract and calling contract should be the same one.
@cennznet/crml-* are peer dependencies to @cennznet/api, they need to be installed together. Do not put @plugnet/* or @polkadot/* in your package.json
★” ReferenceError: Api is not defined”, that means you didn’t define the API first. you can fix it by adding to your code
const { Api }=require(‘@cennznet/api’)
if you get an error to print “txHash” you can fix like txHash.toHex()

--

--