how can I force a query to Hedera to be directed to a mirror node?

61 Views Asked by At

When I call a smart contract view function on the Hedera Testnet, I have to pay in HBAR for the response. My understanding is that Queries should go to mirror nodes but in my case this does not happen.

Here is the code :

import { Client, ContractCallQuery, Hbar, HbarUnit } from '@hashgraph/sdk';
import { accountId, derPrivateKey } from "./account";

async function main() {
  const client = Client.forTestnet();
  client.setOperator(accountId, derPrivateKey);
  client.setMirrorNetwork('testnet.mirrornode.hedera.com:443')

  const contractId = "0.0.1183384";
  const scRead2 = new ContractCallQuery()
      .setContractId(contractId)
      .setGas(8_000_000)
      .setFunction('verifyDefaultMessage')
  let cost = await scRead2.getCost(client);
  cost = new Hbar(cost.to(HbarUnit.Tinybar).multipliedBy(1).dividedToIntegerBy(1), HbarUnit.Tinybar);
  console.log(`- Cost to query the the view function: ${cost.to(HbarUnit.Hbar).toString()}`);
  const scRead2Tx = await scRead2.setQueryPayment(cost).execute(client);
  const scRead2ReturnValue = scRead2Tx.getBool();
  return scRead2ReturnValue ? "Success" : "Failure";
}

main().then(res => {
  console.log(res);
  process.exit(0)
}).catch(err => {
  console.error(err);
  process.exit(1);
});

In order to be sure that a mirror node is configured, I added the line:

client.setMirrorNetwork('testnet.mirrornode.hedera.com:443')

Everything works fine, but the balance of the account in the client keeps getting smaller every time this is executed.

1

There are 1 best solutions below

0
Micha Roon On

Based on the information provided in the extracts, it seems like you're experiencing a decrease in your account balance because you're making a call to a smart contract's view function. Even though view functions are read-only and don't modify the state of the contract, they still consume resources (CPU, memory, etc.) on the network to execute. Therefore, they incur a fee in HBAR, which is deducted from your account balance. The setMirrorNetwork() function you're using sets the mirror node that the SDK client will use to subscribe to updates (like new transactions or consensus messages). However, it doesn't redirect the execution of smart contract calls or queries to the mirror node. The execution of smart contract calls and queries is still performed by the main Hedera network, not the mirror network. That's why you're seeing a decrease in your account balance each time you execute the view function. If you want to avoid incurring fees for reading data from a smart contract, you might want to consider using a mirror node's API, if it provides one. However, keep in mind that not all mirror nodes may support this functionality. For more information, you can refer to the following sources: