MATRIX
Search
K

Calling a smart contract function (JS, NodeJS)

by Delbypoc
This tutorial is for educational purposes only, I’m not responsible for any losses, damages, or other liabilities which may occur by using any info/code provided here(or anywhere else it is posted).
Text

Description automatically generated
I’m under no circumstances a Javascript professional (or a JS Ninja/Expert)!
The code is not production-ready! (only for learning purposes)
In this guide, I’m going to show you how to call a smart contract function on MATRIX AI NETWORK.
This is a continuation of the last guide:
We will make use of the following packages : ‘aiman’, ‘matrixjs-tx’, ‘bignumber.js’, ‘bs58’, ‘fs’.
You can install them by using :
npm install aiman matrixjs-tx bignumber.js bs58 fs
and declare them:
Text

Description automatically generated
For testing, I will use the smart contract from the last guide:
Text

Description automatically generated
It contains one function that changes the result value and a view function.
After running Truffle migrate (from the last guide), some files will also get generated under the build/contracts folder, SimpleContract.json
I will read it using fs (it will be required to get the contract ABI)
Text

Description automatically generated
Now I will initialize the man3 instance with a provider:
And other variables that will be used in building the tx:
Text

Description automatically generated
Next, I will declare and implement a function that will prepare the tx and broadcast it:
Text

Description automatically generated
Text

Description automatically generated
The program should output the tx that got broadcasted (blurred out a few details):
Graphical user interface, text

Description automatically generated
After solving the promise (and tx get mined), we should have the “result” variable of the smart contract changed to 220.
We can also check the input parameters by decoding the transaction “input” (I will use https://lab.miguelmota.com/ethereum-input-data-decoder/example/ for this)
Graphical user interface, application

Description automatically generated
The whole program source code can be found at the github page: (Matrix-AI-Network-Code-Snippets/callingSmartContractFunction.js at main · CognitiveProcessing/Matrix-AI-Network-Code-Snippets (github.com))
For more documentation on the packages used, you can check: https://www.npmjs.com/package/bignumber.js
Also, check out the official Matrix AI Network Developer Portal: dev.matrix.io