Call - code sample
Making Calls in Swisstronik
Let's implement a function called sendShieldedQuery to make a call to a smart contract, using SwisstronikJS.
Open your Hardhat project and run
npm i @swisstronik/utilsit from the main directory.
NOTE: If you don't know how to set up a Hardhat project, please review the Contract deployment - Hardhat
Create a file
totalSupply.jswithin the scripts folder in your Hardhat project, this file will contain the code to run the call to get the total supply.Import SwisstronikJS & Hardhat in the
totalSupply.jsscript
const hre = require("hardhat");
const { encryptDataField, decryptNodeResponse } = require("@swisstronik/utils");Let's add the code to implement a function called
sendShieldedQueryto useencryptDataField()anddecryptNodeResponse()
You can reuse this sendShieldedQuery code snippet to make calls to any smart contracts in the Swisstronik blockchain.
const hre = require("hardhat");
const { encryptDataField, decryptNodeResponse } = require("@swisstronik/utils");
/**
* Make a shielded query/call on the Swisstronik blockchain.
*
* @param {object} provider - The provider object for making the call.
* @param {string} destination - The contract address to call.
* @param {string} data - Encoded data for the function call.
*
* @returns {Uint8Array} - Encrypted response from the blockchain.
*/
const sendShieldedQuery = async (provider, destination, data) => {
// Obtain the RPC link from the network configuration
const rpcLink = hre.network.config.url;
// Encrypt the call data using SwisstronikJS's encryption function
const [encryptedData, usedEncryptionKey] = await encryptDataField(rpcLink, data);
// Execute the query/call using the provider
const response = await provider.call({
to: destination,
data: encryptedData,
});
// Decrypt the response using SwisstronikJS's decryption function
return await decryptNodeResponse(rpcLink, response, usedEncryptionKey);
};Let's add the
mainfunction to use thesendShieldedQueryto make a call to thefunction totalSupply() external view returns (uint256)in the ERC20 smart contract.
You can reuse this script to make calls in Swisstronik (make sure you are calling a reading-only function) and don't forget to replace the variables marked with the replace_ prefix with your own values in the main function
Run
npx hardhat run scripts/totalSupply.js --network swisstronikYou should see the decoded number printed in your console π
Last updated