In the following, we report a usage example of the CredoraMetrics contract, showing a JavaScript sample code based on the HardHat development environment.
Prerequisites
Must have an Ethereum or Sepolia wallet. You can fund your Sepolia wallet here.
Sufficient ETH for transaction fees.
Node.js and npm installed.
Setup
Create a new app directory and install hardhat dependencies:
Get On-Chain Metrics Using Synchronous Getter Functions
Step 1: Add a new Task to the Hardhat Script
Extend the hardhat.config.js with a task that aims to fetch Credora data from the blockchain.
constdivisionFactor=18;task("getNAV","Get NAV data stored on-chain").addParam("contract","The contract address").addParam("entity","The entity name").setAction(async (taskArgs, hre) => {constfs=require("fs");constcontractAddress=taskArgs.contract;constentity=ethers.encodeBytes32String(taskArgs.entity);constsigner= (awaithre.ethers.getSigners())[0];// Get the ABI from the compiled JSON artifactconstartifactPath="node_modules/@credora/on-chain-metrics-test/contracts/abi/CredoraMetrics.json";constabi=JSON.parse(fs.readFileSync(artifactPath,"utf-8"));// Connect to the deployed contractconstcontract=newethers.Contract(contractAddress, abi, signer); constresult=awaitcontract.getNAV(entity,{ gasLimit:1000000 }); let decimalResult =ethers.formatUnits(result, divisionFactor);console.log('NAV:', decimalResult);});
The getNAV task receives in input the entity name and the contract address to call the getNAV smart contract function.
The returned value is an unsigned integer (uint256) and needs to be divided by a factor of 10^18 to convert it to its final floating-point format.
Step 2: Configure Environment Variables
Export the following environment variables:
ETHEREUM_RPC_URL, ETHEREUM_SEPOLIA_RPC_URL, FLOWTESTNET_RPC_URL (e.g. https://eth-sepolia.g.alchemy.com/v2/{ALCHEMY_APIKEY})
PRIVATE_KEY of the wallet
Step 3: Run
From the same directory, run the following by passing the address of the Credora contract and the name of the entity owning the data:
Navigate to the contracts directory and create a new Solidity file, e.g., MetricsConsumer.sol
pragmasolidity ^0.8.20;/** * @title Metrics Consumer Contract * @notice This contract implements the CredoraFunctions for managing financial asset metrics. */import"@credora/on-chain-metrics/contracts/CredoraFunctions.sol";contractMetricsConsumerisCredoraFunctions {// Example storage for metricsmapping(bytes32=>uint256) private scores;mapping(bytes32=>uint256) private nav;mapping(bytes32=>bytes8) private nav_currency;mapping(bytes32=>bytes8) private rae;mapping(bytes32=>uint256) private borrowCapacities;mapping(bytes32=>uint256) private impliedPDs;mapping(bytes32=>uint256) private impliedPDTenors;// Implementations of fulfill functions that update the state and emit eventsfunctionfulfillScore(bytes32_entity,uint256_metric_data) externaloverride { scores[_entity] = _metric; // Update the metric }functionfulfillNAV(bytes32_entity,uint256_metric_data,bytes8 currency) externaloverride { nav[_entity] = _metric; // Update the metric }functionfulfillRAE(bytes32_entity,bytes8_metric_data) externaloverride { rae[_entity] = _metric; // Update the metric }functionfulfillBorrowCapacity(bytes32_entity,uint256_metric_data) externaloverride { borrowCapacities[_entity] = _metric; // Update the metric }functionfulfillImpliedPD(bytes32_entity,uint256_metric_data) externaloverride { impliedPDs[_entity] = _metric; // Update the metric }functionfulfillImpliedPDtenor(bytes32_entity,uint256_metric_data) externaloverride { impliedPDTenors[_entity] = _metric; // Update the metric }functioninvalidateData(bytes32_entity) externaloverride {// Do something when data gets invalidated }}
Step 2: Write a Deployment Script
Navigate to the scripts directory and create a new deployment script, e.g., deploy.js:
asyncfunctionmain() {const [deployer] =awaitethers.getSigners();console.log("Deploying contracts with the account:",deployer.address);constMyContract=awaitethers.getContractFactory("MetricsConsumer");constmyContract=awaitMyContract.deploy();console.log("Contract deployed to address:",myContract.address);}main().then(() =>process.exit(0)).catch((error) => {console.error(error);process.exit(1); });
Deploying contracts with the account:0xYourAccountAddressContract deployed to address:0xYourContractAddress
Step 5: Test the callbacks
Once Credora has subscribed your contract, the callbacks can be self-tested by calling the testTriggerCallbacks function (only available on Testnets) on the Credora Smart Contract.
To do so, you can move inside the Credora package and run the related hardhat task (available at node_modules/@credora/on-chain-metrics/tasks/Testers/testTriggerCallbacks.js), which provides a set of random metrics and triggers the callbacks of the subscribed contract.