Skip to content

Commit

Permalink
Create read-functions-off-chain.md
Browse files Browse the repository at this point in the history
  • Loading branch information
crosschainer authored Feb 12, 2025
1 parent fe5d44c commit 448b933
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/read-functions-off-chain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Read Functions Off-Chain

This document explains how to execute read functions (i.e. view or simulated transactions) to retrieve computed data from a smart contract without incurring transaction fees.

## Overview

In many blockchain environments, you can simulate transactions or call "read" functions to obtain data from a smart contract. This method avoids sending an on-chain transaction and therefore is free. The example below demonstrates how to read the balance for a specific address by calling the `balance_of` function of a contract.

The process works as follows:

1. **Payload Construction:**
A payload is constructed with:
- **sender:** The caller's address.
- **contract:** The target smart contract address.
- **function:** The name of the function to be executed (`balance_of`).
- **kwargs:** A JSON object with the function arguments (in this case, the `address` to check).

2. **Encoding:**
The payload is converted into a JSON string, encoded into bytes, and then converted to a hexadecimal string.

3. **RPC Query:**
The hex-encoded payload is appended to the RPC URL path for a simulated transaction query (using `https://node.xian.org/abci_query?path="/simulate_tx/<hex>"`).

4. **Response Handling:**
The response is received in Base64 encoding. It is then decoded and checked:
- If the decoded value is invalid or empty, the contract’s variable is queried directly.
- Otherwise, the function extracts the computed result (the balance).

5. **Result Formatting:**
The balance is parsed as a floating-point number and formatted to 8 decimal places before being returned.

## Code Example

```javascript
async function execute_balance_of(contract, address) {
let payload = {
"sender": "",
"contract": contract,
"function": "balance_of",
"kwargs": {
"address": address
}
};
let bytes = new TextEncoder().encode(JSON.stringify(payload));
let hex = toHexString(bytes);
let response = await fetch('https://node.xian.org/abci_query?path="/simulate_tx/' + hex + '"');
let data = await response.json();
let decoded = atob(data.result.response.value);
result_decoded = JSON.parse(decoded)["result"];
return result_decoded;
}

0 comments on commit 448b933

Please sign in to comment.