Hedera
  • Welcome to Hedera — let’s build the future
  • Getting Started
    • Environment Setup
    • Web2 Developers
      • Transfer HBAR
      • Create a Token
      • Create a Topic
    • EVM Developers
      • Deploy a Contract
  • Tutorials
    • Smart Contracts
      • How to Mint & Burn an ERC-721 Token Using Hardhat and Ethers (Part 1)
      • How to Set Access Control, a Token URI, Pause, and Transfer an ERC-721 Token Using Hardhat (Part 2)
      • How to Upgrade an ERC-721 Token with OpenZeppelin UUPS Proxies and Hardhat (Part 3)
      • How to Verify a Smart Contract on HashScan
      • Deploy a Smart Contract Using Remix
      • Deploy a Smart Contract Using Hardhat and Hiero JSON-RPC Relay
      • Deploy Your First Smart Contract
      • Deploy a Contract Using the Hedera Token Service
      • Send and Receive HBAR Using Solidity Smart Contracts
      • Deploy By Leveraging Ethereum Developer Tools On Hedera
      • Deploy a Subgraph Using The Graph and Hedera JSON-RPC Relay
      • Deploy Smart Contracts on Hedera Using Truffle
      • The Power of Native Hedera Tokens as ERC-20 Tokens: A step-by-step guide
      • HTS x EVM - Part 1: How to Mint NFTs
      • HTS x EVM - Part 2: KYC & Update
      • HTS x EVM - Part 3: How to Pause, Freeze, Wipe, and Delete NFTs
      • Hedera Smart Contracts Workshop
        • Setup
        • Solidity
        • Hedera SDK JS
        • Hardhat and EthersJs
        • Outro
      • Foundry
        • How to Setup Foundry and Write a Basic Unit Test
        • How to Deploy and Verify a Hedera Smart Contract with Foundry
        • How to Test A Solidity Event
        • How to Fork Testnet on Latest Block
    • Consensus
      • Submit Your First Message
      • Submit Message to Private Topic
      • Query Messages with Mirror Node
    • Tokens
      • Create and Transfer Your First NFT
      • Create and Transfer Your First Fungible Token
      • Create and Transfer an NFT using a Solidity Contract
      • Structure Your Token Metadata Using JSON Schema V2
      • Hedera Token Service - Part 1: How to Mint NFTs
      • Hedera Token Service - Part 2: KYC, Update, and Scheduled Transactions
      • Hedera Token Service - Part 3: How to Pause, Freeze, Wipe, and Delete NFTs
      • Create Your First Frictionless Airdrop Campaign
    • Local Node
      • How to Run Hedera Local Node in a Cloud Development Environment (CDE)
        • Run a Local Node in Gitpod
        • Run a Local Node in Codespaces
      • How to Set Up a Hedera Local Node
      • Set Up a Hedera Local Node using the NPM CLI
    • More Tutorials
      • Create and Fund Your Hedera Testnet Account
      • How to Create a Personal Access Token (API Key) on the Hedera Portal
      • How to Auto-Create Hedera Accounts with HBAR and Token Transfers
      • How to Configure a Mirror Node and Query Data
      • How to Generate a Random Number on Hedera
      • Get Started with the Hedera Consensus Service Fabric Plugin
        • Virtual Environment Setup
      • Schedule Your First Transaction
      • How to Connect to Hedera Networks Over RPC
        • Configuring Hashio RPC endpoints
        • Configuring Hiero JSON-RPC Relay endpoints
        • Configuring Validation Cloud RPC endpoints
      • JavaScript Testing
      • Create a Hedera DApp Integrated with WalletConnect
      • How to Connect MetaMask to Hedera
    • Demo Applications
    • Starter Projects
    • Building on Hedera (course)
  • Networks
    • Mainnet
      • Mainnet Accounts
      • Mainnet Consensus Nodes
        • Node Requirements
          • FAQ
      • Fees
        • Transaction Records
    • Testnets
      • Testnet Accounts
      • Testnet Consensus Nodes
    • Localnet
      • Single Node Configuration
      • Multinode Configuration
    • Network Explorers and Tools
    • Release Notes
      • Consensus Node
      • Hedera Mirror Node
  • Core Concepts
    • Accounts
      • Account Creation
      • Auto Account Creation
      • Account Properties
    • Keys and Signatures
    • Schedule Transaction
    • Smart Contracts
      • Understanding Hedera's EVM Differences and Compatibility
        • For EVM Developers Migrating to Hedera
          • Accounts, Signature Verification & Keys (ECDSA vs. ED25519)
          • JSON-RPC Relay and EVM Tooling
          • Token Management with Hedera Token Service
          • Decimal Handling (8 vs. 18 Decimals)
          • Handling HBAR Transfers in Contracts
        • For Hedera-Native Developers Adding Smart Contract Functionality
          • Integrating ED25519 Accounts and Advanced Features Into Smart Contracts
          • JSON-RPC Relay and State Queries
          • Extending Token Management with Smart Contracts
      • Creating Smart Contracts
      • Compiling Smart Contracts
      • System Smart Contracts
        • Hedera Account Service
        • Hedera Schedule Service
      • Gas and Fees
      • JSON-RPC Relay
      • Deploying Smart Contracts
      • Smart Contract Addresses
      • Verifying Smart Contracts
      • Smart Contract Traceability
      • Tokens Managed by Smart Contracts
        • ERC-20 (Fungible Tokens)
        • ERC-721 (Non-Fungible Token)
        • ERC-3643 Real World Assets (RWA)
        • ERC-1363 (Payable Tokens)
        • Hedera Token Service System Contract
      • Wrapped HBAR (WHBAR)
      • Smart Contract Rent
      • Smart Contract Security
      • EVM Archive Node Queries
    • Tokens
      • Tokenization on Hedera
      • Hedera Token Service (HTS) Native Tokenization
        • Token Types and ID Formats
        • Token Properties
        • Token Creation
        • Custom Fee Schedule
        • Token Airdrops
      • ERC/EVM-Compatible Tokenization
      • Hybrid (HTS + EVM ) Tokenization
    • Staking
      • Staking Program
      • Stake HBAR
    • Hashgraph Consensus Algorithm
      • Gossip About Gossip
      • Virtual Voting
    • Transactions and Queries
      • Transaction Properties
    • State and History
    • Mirror Nodes
      • Hedera Mirror Node
      • One Click Mirror Node Deployment
      • Run Your Own Mirror Node
        • Run Your Own Mirror Node with Google Cloud Storage (GCS)
        • Run Your Mirror Node with Amazon Web Services S3 (AWS)
  • Open Source Solutions and Integrations
    • AI Studio on Hedera
      • ElizaOS Plugin for Hedera
      • Hedera AI Agent Kit
      • MCP Server
      • OpenConvAI
    • AI Tools for Developers
      • Hedera Hivemind
      • Kapa AI
    • Asset Tokenization Studio (ATS)
      • Web User Interface (UI)
      • Frequently Asked Questions (FAQs)
    • HashioDAO
      • Governance Token DAO
      • NFT DAO
      • Multisig DAO
      • DAO Proposals
      • Local Environment Setup
    • Hedera CLI
    • Hedera Contract Builder
    • Hedera Custodians Library
      • How to use it
    • Hedera Developers Code Repository
    • Hedera Developer Playground
    • Hedera Wallet Snap By MetaMask
      • Hedera Wallet Snap Documentation
      • Tutorial: MetaMask Snaps – What Are They and How to Use Them
    • Interoperability and Bridging
      • LayerZero
    • NFT Studio
      • Airdrop List Verifier
      • Metadata Validator
      • NFT Rarity Inspector
      • NFT Token Holders List Builder
      • NFT Risk Calculator
      • Token Balance Snapshot
      • Hedera NFT SDK
    • Oracle Networks
      • Chainlink Oracles
      • Pyth Oracles
      • Supra Oracles
    • Stablecoin Studio
      • Core Concepts
      • Web UI Application
      • CLI Management
      • TypeScript SDK
    • Hedera Guardian
    • Hedera WalletConnect
  • SDKs & APIs
    • SDKs
      • Build Your Hedera Client
      • Set Up Your Local Network
      • Network Address Book
      • Keys
        • Generate a new key pair
        • Import an existing key
        • Create a key list
        • Create a threshold key
        • Generate a mnemonic phrase
        • Recover keys from a mnemonic phrase
      • HBAR
      • Specialized Types
      • Pseudorandom Number Generator
      • Transactions
        • Create a Batch Transaction
        • Transaction ID
        • Modify transaction fields
        • Create an unsigned transaction
        • Manually sign a transaction
        • Submit a transaction
        • Sign a multisignature transaction
        • Get a transaction receipt
        • Get a transaction record
      • Schedule Transaction
        • Schedule ID
        • Create a schedule transaction
        • Sign a scheduled transaction
        • Delete a schedule transaction
        • Get schedule info
        • Network Response Messages
      • Queries
      • General Network Response Messages
      • Accounts and HBAR
        • Create an account
        • Update an account
        • Transfer cryptocurrency
        • Approve an allowance
        • Delete an allowance
        • Delete an account
        • Get account balance
        • Get account info
        • Network Response Messages
      • Consensus Service
        • Create a topic
        • Update a topic
        • Submit a message
        • Delete a topic
        • Get topic messages
        • Get topic info
        • Network Response
      • Token Service
        • Token ID
        • NFT ID
        • Token types
        • Create a token
        • Custom token fees
        • Update a token
        • Update token custom fees
        • Update NFT metadata
        • Transfer tokens
        • Airdrop a token
        • Claim a token
        • Cancel a token
        • Reject a token
        • Delete a token
        • Mint a token
        • Burn a token
        • Freeze an account
        • Unfreeze an account
        • Enable KYC account flag
        • Disable KYC account flag
        • Associate tokens to an account
        • Dissociate tokens from an account
        • Pause a token
        • Unpause a token
        • Wipe a token
        • Atomic swaps
        • Get account token balance
        • Get token info
        • Get NFT info
        • Network Response Messages
      • File Service
        • Create a file
        • Append to a file
        • Update a file
        • Delete a file
        • Get file contents
        • Get file info
        • Network Response Messages
      • Smart Contract Service
        • Delegate Contract ID
        • Create a smart contract
        • Update a smart contract
        • Delete a smart contract
        • Call a smart contract function
        • Ethereum transaction
        • Get a smart contract function
        • Get smart contract bytecode
        • Get smart contract info
        • Hedera Service Solidity Libraries
        • Network Response Messages
      • Signature Provider
        • Provider
        • Signer
        • Wallet
        • Local Provider
    • Mirror Node REST API
      • Accounts
      • Balances
      • Blocks
      • Schedule Transactions
      • Smart Contracts
      • Tokens
      • Topics
      • Transactions
      • Network
    • Hedera Consensus Service gRPC API
    • Hedera APIs
      • Basic Types
        • AccountAmount
        • AccountID
        • ContractID
        • CryptoAllowance
        • CurrentAndNextFeeSchedule
        • FeeComponents
        • FeeData
        • FeeSchedule
        • FileID
        • Fraction
        • HederaFunctionality
        • Key
        • KeyList
        • NftAllowance
        • NftTransfer
        • NodeAddress
        • NodeAddressBook
        • RealmID
        • ScheduleID
        • SemanticVersion
        • ServicesConfigurationList
        • ServiceEndpoint
        • Setting
        • ShardID
        • Signature
        • SignatureList
        • SignatureMap
        • SignaturePair
        • SubType
        • TransferList
        • TransactionID
        • ThresholdKey
        • ThresholdSignature
        • TokenAllowance
        • TokenBalance
        • TokenBalances
        • TokenFreezeStatus
        • TokenPauseStatus
        • TokenID
        • TokenKycStatus
        • TokenRelationship
        • TokenTransferList
        • TokenType
        • TokenSupplyType
        • TopicID
        • TransactionFeeSchedule
      • Cryptocurrency Accounts
        • CryptoService
        • CryptApproveAllowance
        • CryptoDeleteAllowance
        • CryptoCreate
        • CryptoTransfer
        • CryptoUpdate
        • CryptoDelete
        • CryptoGetAccountBalance
        • CryptoGetAccountRecords
        • CryptoGetInfo
        • CryptoGetStakers
      • Consensus Service
        • Consensus Service
        • ConsensusCreateTopic
        • ConsensusUpdateTopic
        • ConsensusSubmitMessage
        • ConsensusDeleteTopic
        • ConsensusTopicInfo
        • ConsensusGetTopicInfo
      • Schedule Service
        • ScheduleService
        • SchedulableTransactionBody
        • ScheduleCreate
        • ScheduleDelete
        • ScheduleSign
        • ScheduleGetInfo
      • Token Service
        • TokenService
        • CustomFees
          • AssessedCustomFee
          • CustomFee
          • FractionalFee
          • FixedFee
          • RoyaltyFee
        • TokenCreate
        • TokenUpdate
        • TokenFeeScheduleUpdate
        • TokenDelete
        • TokenMint
        • TokenBurn
        • TokenFreezeAccount
        • TokenUnfreezeAccount
        • TokenGrantKyc
        • TokenRevokeKyc
        • TokenAssociate
        • TokenDissociate
        • TokenWipeAccount
        • TokenPause
        • TokenUnpause
        • TokenGetInfo
        • TokenGetNftInfo
        • TokenGetNftInfos
        • TokenGetAccountNftInfo
      • File Service
        • FileService
        • FileCreate
        • FileAppend
        • FileUpdate
        • FileDelete
        • FileGetContents
        • FileGetInfo
      • Smart Contracts
        • SmartContractService
        • ContractCall
        • ContractCallLocal
        • ContractCreate
        • ContractUpdate
        • ContractDelete
        • ContractGetByteCode
        • ContractGetInfo
        • ContractGetRecords
      • Miscellaneous
        • Duration
        • ExchangeRate
        • Freeze
        • FreezeType
        • GetByKey
        • GetBySolidityID
        • NetworkGetVersionInfo
        • NetworkService
        • Query
        • QueryHeader
        • Response
        • ResponseCode
        • ResponseHeader
        • SystemDelete
        • SystemUndelete
        • TimeStamp
        • Transaction
        • TransactionBody
        • TransactionContents
        • TransactionGetFastRecord
        • TransactionGetReceipt
        • TransactionGetRecord
        • TransactionReceipt
        • TransactionRecord
        • TransactionResponse
        • UncheckedSubmit
    • Hedera Status API
  • Support & Community
    • Glossary
    • Contributing to Hedera documentation
      • Contribution Guidelines
        • Creating Issues
        • Creating Pull Requests
        • Hedera Improvement Proposal (HIP)
        • Submit Demo Applications
      • Style Guide
        • Understanding different types of documentation
        • Use of HBAR and tinybars
        • Use of web2 and web3
        • Language and grammar
        • Formatting
        • Punctuation
        • GitBook Markdown Syntax
    • Discord
    • GitHub
    • Stack Overflow
    • Hedera Blog
    • Bug Bounty
    • Hedera Help
    • Documentation Survey
    • Meetups
    • Brand Guidelines
    • Status Page
Powered by GitBook
LogoLogo

INTRODUCTION

  • Fees
  • Core Concepts
  • Network Information

TOOLS

  • Bridge
  • Oracles
  • Explorers
  • Developer Portal & Faucet

RESOURCES

  • Status
  • Bug Bounty
  • Build on Hedera (course)
  • Documentation Survey
On this page
  • Introduction to EVM Archive Node Queries
  • API Endpoint Overview
  • Key Parameters
  • Prerequisites
  • Gas Estimation
  • Example Request
  • Expected Response
  • Decoding the Result:
  • Contract Queries
  • Example Request
  • Expected Response
  • Decoding the Result
  • EVM Transaction Simulations
  • Example Request
  • Expected Response
  • Decoding the Results with Ethers.js
  • Step 1: Install Ethers.js
  • Step 2: Decode the Hexadecimal Result
  • Reference

Was this helpful?

Edit on GitHub
  1. Core Concepts
  2. Smart Contracts

EVM Archive Node Queries

PreviousSmart Contract SecurityNextTokens

Last updated 5 months ago

Was this helpful?

Introduction to EVM Archive Node Queries

enhances Hedera Mirror Nodes with extended EVM execution capabilities, allowing developers to perform gas-free smart contract queries, estimate gas usage, and simulate EVM transactions without committing state changes. These enhancements empower developers to:

  • Perform Gas-Free Smart Contract Queries: Retrieve data from smart contracts without incurring gas costs.

  • Estimate Gas Usage: Determine the gas required for executing specific contract functions.

  • Simulate EVM Transactions: Test transactions that involve state changes without committing those changes to the blockchain.

This guide uses real examples of interactions with smart contracts, including 's DeFi contracts on the Hedera network:

  • SaucerSwap's HashScan verified DeFi smart contract:

    • 0x00000000000000000000000000000000002e7a5d

  • The HashScan link to the verified smart contract can be found .


API Endpoint Overview

The API endpoint and parameters used for all operations described in this guide is:

POST /api/v1/contracts/call

Key Parameters

  • estimate (boolean): Determines the operation type.

    • true: Performs gas estimation.

    • false: Executes a query or simulation.

  • block (string): Specifies the block for the operation (e.g., "latest" or a specific block number).

  • data (string): Encoded function call data in hexadecimal format following the ABI specifications.

  • from (string, optional): Address initiating the call. Required for simulations involving state changes.

  • to (string): Target smart contract address (SaucerSwap's DeFi contract for this guide).

  • value (number, optional): Amount of tinybars to send with the transaction. Relevant for simulations involving value transfers.


Prerequisites

Before proceeding, ensure you have:

  • Basic knowledge of EVM smart contracts:

  • Essential tools installed and configured:

    • cURL for making HTTP requests.

    • Ethers.js (v6 or later or equivalent libraries) for interacting with the EVM-compatible networks.

  • Function data encoding:

    • Familiarity with encoding function data into the required EVM-compatible hexadecimal format.


Gas Estimation

Estimating gas usage helps determine the cost required to execute a smart contract function without actually performing the transaction.

Example Request

Here's how to estimate gas usage using the /api/v1/contracts/call endpoint:

curl -X POST https://mainnet.mirrornode.hedera.com/api/v1/contracts/call \
-H "Content-Type: application/json" \
-d '{
    "block": "latest",
    "data": "0x1f00ca74000000000000000000000000000000000000000000000000000000003b9aca00000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000163b5a00000000000000000000000000000000000000000000000000000000000b2ad5",
    "estimate": true,
    "to": "0x00000000000000000000000000000000002e7a5d"
}'

Expected Response

The API returns an estimated gas value in hexadecimal format:

{
  "result": "0x0000000000007f0d"
}

Decoding the Result:

To interpret the hexadecimal gas estimate, follow these steps:

  1. Extract the result: the field from the API response containing the gas estimate in hexadecimal format.

  2. Convert Hexadecimal to BigInt:

    Use JavaScript's BigInt to convert the hexadecimal string to a numerical value.

    // Assuming you have the result from the API response
    const hexString = "0x0000000000007f0d";
    const gasEstimate = BigInt(hexString);
    console.log("Gas Estimate:", gasEstimate.toString());

    Output:

    Gas Estimate: 32525 

The gas estimate result represents the value in tinybars.

Understanding the Logic

  • Hexadecimal Representation: Smart contracts and blockchain APIs often use hexadecimal strings to represent numerical values, ensuring precise and compact data transmission.

  • Conversion to BigInt: JavaScript's BigInt is used to handle large integers that exceed the safe integer limit of the standard Number type, ensuring accuracy in calculations.

  • Interpretation: The numerical value (32525 in this case) represents the estimated gas required to execute the specified smart contract function.


Contract Queries

Contract queries allow developers to retrieve data from smart contracts without altering the blockchain state. This is particularly useful for reading data such as token balances, contract states, and more.

Example Request

Retrieve the token balance using a contract’s view function:

curl -X POST https://mainnet.mirrornode.hedera.com/api/v1/contracts/call \
-H "Content-Type: application/json" \
-d '{
    "block": "latest",
    "data": "0x1f00ca74000000000000000000000000000000000000000000000000000000003b9aca00000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000163b5a00000000000000000000000000000000000000000000000000000000000b2ad5",
    "to": "0x00000000000000000000000000000000002e7a5d"
}'

Expected Response

The API returns the result of the contract’s view function in hexadecimal format:

{
  "result": "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000efd80e2d6000000000000000000000000000000000000000000000000000000003b9aca00"
}

Decoding the Result

To interpret the hexadecimal result (e.g., token balance), follow these steps:

  1. Extract the result:

    The result field contains the data returned by the smart contract function.

  2. Convert Hexadecimal to BigInt:

    const hexString = "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000efd80e2d6000000000000000000000000000000000000000000000000000000003b9aca00";
    const balance = BigInt(hexString);
    console.log("Token Balance:", balance.toString());

    Output:

    Token Balance: 32 # value represented in decimal

Understanding the Logic

  • Hexadecimal Representation: The smart contract's balanceOf function returns the token balance in hexadecimal format.

  • Conversion to BigInt: Using BigInt ensures accurate representation of potentially large token balances.

  • Interpretation: The numerical value (32 in this case) represents the token balance of the specified address


EVM Transaction Simulations

Simulate EVM transactions (non-view functions) that involve state changes to test contract interactions without committing them. This can be useful for testing token transfers, approvals, and other state-altering functions without changing the blockchain state.

Example Request

This example simulates a token transfer by testing contract interactions without altering the state.

curl -X POST https://mainnet.mirrornode.hedera.com/api/v1/contracts/call \
-H "Content-Type: application/json" \
-d '{
    "block": "latest",
    "data": "0x",
    "estimate": false,
    "from": "0x00000000000000000000000000000000000004e2",
    "to": "0x00000000000000000000000000000000000004e4",
    "value": 1000
}'

Expected Response

The empty result indicates that the simulation ran successfully without errors:

{
  "result": "0x"
}

Decoding the Results with Ethers.js

Step 1: Install Ethers.js

If you haven't already, install Ethers.js using npm:

npm install ethers

Step 2: Decode the Hexadecimal Result

Below is a detailed explanation of how to extract and interpret the result from the API response.

Example Scenario

You have made an API request to retrieve a token balance, and received the following response:

{
  "result": "0x0000000000007f0d"
}

You want to convert this hexadecimal result to a human-readable token balance.

JavaScript Code Example

const { ethers } = require('ethers');

// Example API response
const response = {
  data: {
    result: "0x0000000000007f0d" // Replace with actual API result
  }
};

// Step 1: Extract the hex string from the API response
const hexString = response.data.result;

// Step 2: Convert the hexadecimal string to a BigInt
const tokenBalance = BigInt(hexString);

// Step 3: Display the token balance
console.log("Token Balance:", tokenBalance.toString());

Output:

Token Balance: 32525 # value represented in decimals

Understanding the Logic

  1. Extracting the result:

    const hexString = response.data.result;
    • Purpose: Assign the result from the API response to the variable hexString.

    • Content: The hexString contains the ABI-encoded data returned by the smart contract function.

  2. Converting Hexadecimal to BigInt:

    const tokenBalance = BigInt(hexString);
    • Purpose: Convert the hexadecimal string to a BigInt for numerical operations.

    • Explanation:

    • BigInt: A JavaScript data type that can represent integers with arbitrary precision, suitable for handling large numbers often used in blockchain applications.

    • Conversion: The BigInt constructor automatically parses the hexadecimal string (prefixed with 0x) and converts it to its numerical equivalent.

  3. Displaying the Token Balance:

    console.log("Token Balance:", tokenBalance.toString());
    • Purpose: Output the numerical value of the token balance to the console.

    • Explanation:

      • .toString(): Converts the BigInt to a string for readable output.

Practical Example with Ethers.js for Complex Decoding

For more complex return types (e.g., multiple values, arrays), Ethers.js can be used to decode the result based on the contract's ABI.

const { ethers } = require('ethers');

// Example API response
const response = {
  data: {
    result: "0x000000000000002000000000000000000000000000000000000000000000000020000000efd80e2d6000000000000000000000000000000000000000000000000000000003b9aca00"
  }
};

// Step 1: Extract the hex string from the API response
const hexString = response.data.result;

// Step 2: Define the ABI for the function you want to decode
const abi = [
  'function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts)'
];

// Step 3: Create an interface using the ABI
const abiInterface = new ethers.Interface(abi);

// Step 4: Decode the result using decodeFunctionResult
const decodedResult = abiInterface.decodeFunctionResult('getAmountsIn', hexString);

// Step 5: Access the decoded data
console.log("Decoded Amounts:", decodedResult[0].toString());

Output:

Decoded Amounts: 32525 # value represented in tinybars

Explanation

  1. Define the ABI:

    const abi = [
      'function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts)'
    ];
    • The ABI specifies the getAmountsIn function which returns an array of uint256 values.

  2. Create an Interface:

    const abiInterface = new ethers.Interface(abi);
    • ethers.Interface uses the ABI to understand how to decode the data.

  3. Decode the Result:

    const decodedResult = abiInterface.decodeFunctionResult('getAmountsIn', hexString);
    • decodeFunctionResult interprets the result based on the function's return type.

  4. Access the Decoded Data:

    console.log("Decoded Amounts:", decodedResult[0].toString());
    • The decoded result is accessed as decodedResult[0] and converted to a string for readability.


Reference

For detailed specifications, refer to the .

Understanding of and function encoding.

To decode the data returned by the Mirror Node, you need the of the smart contract you are interacting with. The ABI defines the structure of inputs and outputs for the contract's functions.

HIP-584
SaucerSwap
here
Swagger documentation
HIP-584 Proposal
REST API Documentation
Swagger Documentation
Ethers.js Documentation
ABI (Application Binary Interface)
ABI