Transaction - code sample
Sending Transactions in Swisstronik
Let's implement a function called sendShieldedTransaction to send a transaction 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
transfer.jswithin the scripts folder in your Hardhat project, this file will contain the code to run the transfer.Import SwisstronikJS & Hardhat in the
transfer.jsscript
const hre = require("hardhat");
const { encryptDataField } = require("@swisstronik/utils");Let's add the code to implement a function called
sendShieldedTransactionto useencryptDataField()
You can reuse this sendShieldedTransaction code snippet to interact with any smart contracts in the Swisstronik blockchain.
const hre = require("hardhat");
const { encryptDataField } = require("@swisstronik/utils");
/**
* Send a shielded transaction to the Swisstronik blockchain.
*
* @param {object} signer - The signer object for sending the transaction.
* @param {string} destination - The address of the contract to interact with.
* @param {string} data - Encoded data for the transaction.
* @param {number} value - Amount of value to send with the transaction.
*
* @returns {Promise} - The transaction object.
*/
const sendShieldedTransaction = async (signer, destination, data, value) => {
// Get the RPC link from the Hardhat network configuration
const rpcLink = hre.network.config.url;
// Encrypt transaction data
const [encryptedData] = await encryptDataField(rpcLink, data);
// Construct and sign the transaction with encrypted data
return await signer.sendTransaction({
from: signer.address,
to: destination,
data: encryptedData,
value,
});
};Let's add the
mainfunction to use thesendShieldedTransactionto send a transaction that callsfunction transfer(address recipient, uint256 amount)in the smart contract.
You can reuse this script to execute transactions in Swisstronik (as long as it's a writing function), just make sure to replace the variables marked with the replace_ prefix with your own values in the main function
Run
npx hardhat run scripts/transfer.js --network swisstronikYou should see the transaction receipt object printed in your console π
Last updated