bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 29쪽
cipient CONTAINS '${address}'`,
},
};
// When the WebSocket connection is established, send the subscription request.
websocket.on('open', () => {
websocket.send(JSON.stringify(wsQuery));
});
// When a message (i.e., a matching transaction) is received, log the transaction and close the WebSocket connection.
websocket.on('message', (event) => {
const eventData = JSON.parse(event);
if (eventData && eventData.result && eventData.result.data) {
console.log('Matching transaction found: ' + JSON.stringify(eventData.result.data));
disconnectFromWebsocket();
}
});
// If an error occurs with the WebSocket, log the error and close the WebSocket connection.
websocket.on('error', (error) => {
console.error(error);
disconnectFromWebsocket();
});
} catch (err) {
// If an error occurs when trying to connect or subscribe, log the error and close the WebSocket connection.
console.error(err);
disconnectFromWebsocket();
}
};
// This function closes the WebSocket connection and resets the websocket and wsQuery variables.
const disconnectFromWebsocket = () => {
// If the WebSocket isn't open, exit the function.
if (!websocket || websocket.readyState !== WebSocket.OPEN) return;
// Send an 'unsubscribe' message to the server.
websocket.send(JSON.stringify({ ...wsQuery, method: 'unsubscribe' }));
// Close the WebSocket connection.
websocket.close();
// Reset the websocket and wsQuery variables.
websocket = null;
wsQuery = null;
};
// When the process is exiting, close the WebSocket connection if it's still open.
process.on('exit', () => {
disconnectFromWebsocket();
});
// Start the process by calling the queryForBalanceUpdate function.
queryForBalanceUpdate();
```
#### **Execute the Script**
Run the `index.js` script using Node.js:
```bash
node index.js
```
When tokens are transferred to the address set in the script the script will print out the details of the transfer.
# Oracles
Oracles are external data providers that enable smart contracts to interact with real-world data. In the Xion ecosystem, oracles play a crucial role in providing off-chain information such as asset prices, weather data, or sports scores, allowing developers to build dynamic and responsive decentralized applications (apps).
## Why Are Oracles Required?
Smart contracts operate within a deterministic environment, meaning that if you start from **block one** and execute all transactions to the **current block,** the result must always be the same. This determinism ensures blockchain security and consensus but also imposes a limitation as smart contracts cannot directly access data from the web or any external source that changes over time. Since web data is dynamic, integrating it directly into a blockchain would break its fundamental requirement for consistency and reproducibility.
To bridge this gap, oracles act as intermediaries that fetch, verify, and relay external data into the blockchain. By doing so, oracles enable smart contracts to securely access real-world information without compromising the deterministic nature of blockchain execution.
## Supported Oracles on Xion
Xion currently supports **Pyth** as its primary oracle provider. Pyth delivers price feeds from institutional grade market data sources, enabling smart contracts to access accurate and real-time price information without relying on centralized intermediaries. Pyth data feeds are accessible via the Xion **Testnet** and **Mainnet**.
# Creating a Smart Contract with Pyth Oracle Integration
Blockchains are **self contained networks** that cannot directly access external data, such as asset prices or market trends from the web. This limitation makes **oracles** essential as they serve as a bridge between **on-chain** smart contracts and **off-chain** real world information.
The **Pyth Network** is a decentralized oracle that provides **real-time, high frequency price feeds** for assets like cryptocurrencies, stocks, and commodities. This guide will walk you through integrating Pyth's price feed data into your smart contracts and also querying the data from a frontend app.
## How Pyth pricing works on XION
Pyth is a **pull (on-demand) oracle**, not a push oracle. That means:
* Pyth publishers update prices [off-chain on Pythnet](https://docs.pyth.network/price-feeds/core/how-pyth-works/cross-chain) about every \~400ms.
* **XION does not automatically receive those updates.**
* A price only gets written on XION **when someone submits an update transaction to the Pyth contract on the Xion chain**. If nobody triggers updates, the on-chain values can look outdated.
So if you query a feed on the Verona network and see a publish time from months ago, it usually **doesn’t mean the feed is broken,** it means no one has recently pushed an update on the Verona network.
## Pyth Contracts
Pyth deploys contracts on supported chains, enabling smart contracts on those networks to access pricing data through its decentralized system. You can find the Pyth contract address for XION's networks [here](https://docs.pyth.network/price-feeds/contract-addresses/cosmwasm).
| Network | Contract Address |
| -------------- | --------------------------------------------------------------- |
| Xion Testnet 2 | xion1wptw89weav8tnpgxg4fyhcahgk8yy99lka3w308536ktadkvjwxqe463hl |
## Price Feeds
Pyth provides price feeds for various assets. Each feed has a unique **feed ID**, which is required to query the data. You can find the complete list of available feeds for XION chains [here](https://www.pyth.network/developers/price-feed-ids#cosmwasm-stable).
### Keeping price feeds updated on XION
You have two options, depending on your app:
#### **Option A: Update prices inside your app flow (recommended)**
Whenever your app needs a fresh price (e.g., before a swap, mint, borrow, or liquidation), do this:
1. **Fetch the latest Pyth update data off-chain** from Hermes / Price Service.
* This update blob is signed and represents the newest price.
2. **Estimate the update fee** from the Pyth contract on the Verona network.
3. **Submit your normal execute transaction**, but include:
* the update data, and
* enough fee to pay the Pyth contract for writing the update on chain.
4. **Read the price in the same transaction** (or immediately after).\
Now your contract is using a current price.
**Key idea:** your app *pulls* the price update exactly when it needs it, so you pay gas only when the price is used.\
If you’re building a front end, treat “get price” as a 2-step process:
* `get_update_data(feed_ids) → update_blob` (off-chain)
* `execute(update_price_feeds, update_blob) → query_price` (on-chain)
This prevents “stale price” confusion during testing.
#### **Option B: Run a scheduler that pushes prices periodically**
If your app wants prices to stay fresh **even when nobody is using the App** (like a dashboard, keeper bots, or always-on DeFi protocols), run Pyth’s **Price Pusher**:
* It’s an off-chain service that **monitors selected feeds** and **regularly pushes updates** to a chain.
* Anyone can run it. You choose the interval and feeds (<https://docs.pyth.network/price-feeds/core/schedule-price-updates>). **Here's a** link to [Pyth’s Price Pusher guide](https://docs.pyth.network/price-feeds/core/schedule-price-updates/using-price-pusher).
**When to use this:**
* you need “near-real-time” prices always available on XION
* you don’t want end-users to be the ones paying update gas
* you run protocol bots/keepers anyway
### Fetching Price Data
A variety of queries can be made to the **Pyth contract**, including:
* **PriceFeed**
* **GetUpdateFeeForDenom**
* **GetUpdateFee**
* **GetValidTimePeriod**
For our use case, the key query is **PriceFeed**, as it retrieves the most recent price data for a given asset pair. This query requires only the **feed ID**, which you can find [here](https://www.pyth.network/developers/price-feed-ids#cosmwasm-stable).
### Query Price Feed from Contract
To query a price feed from the Pyth oracle in a your smart contract, you need to send a `WasmQuery::Smart` request to the Pyth contract with the correct `feed_id`. Below is an example:
```rust
use cosmwasm_std::{Deps, StdResult, WasmQuery, QueryRequest, to_binary};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
const PYTH_CONTRACT: &str = "xion1wptw89weav8tnpgxg4fyhcahgk8yy99lka3w308536ktadkvjwxqe463hl";
// Store with 0x prefix (matches Pyth documentation format)
const PRICE_FEED_ID: &str = "0x436ccb0d465f3cb48554bcc8def65ff695341b3ebe0897563d118b9291178d0f";
// Query message must be an enum wrapper, not a plain struct
// Pyth expects: {"price_feed": {"id": "..."}}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PythQueryMsg {
PriceFeed { id: String },
}
// Response structure matching Pyth's actual format
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct PriceFeedResponse {
pub price_feed: PriceFeed,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct PriceFeed {
pub id: String,
pub price: Price,
pub ema_price: Price,
}
// Price fields are returned as strings by Pyth, not integers
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct Price {
pub price: String,
pub conf: String,
pub expo: i32,
pub publish_time: i64,
}
/// Queries the price feed from the Pyth contract
pub fn query_pyth_price_feed(deps: Deps) -> StdResult<PriceFeedResponse> {
// Strip 0x prefix for CosmWasm (unlike EVM chains)
let feed_id = PRICE_FEED_ID.strip_prefix("0x").unwrap_or(PRICE_FEED_ID);
let query_msg = PythQueryMsg::PriceFeed {
id: feed_id.to_string(),
};
let response: PriceFeedResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: PYTH_CONTRACT.to_string(),
msg: to_binary(&query_msg)?,
}))?;
Ok(response)
}
/// Helper function to convert the string price to a decimal value
pub fn get_price_as_f64(price: &Price) -> Option<f64> {
let price_int: i64 = price.price.parse().ok()?;
let expo = price.expo as f64;
Some(price_int as f64 * 10_f64.powf(expo))
}
```
### Query Price Feed from Frontend
Below is JavaScript code to query the price feed from the Pyth contract using `cosmjs`:
```javascript
import { CosmWasmClient } from "@cosmjs/cosmwasm-stargate";
// Constants
const RPC_ENDPOINT = "https://rpc.xion-testnet-2.burnt.com:443";
const PYTH_CONTRACT = "xion1wptw89weav8tnpgxg4fyhcahgk8yy99lka3w308536ktadkvjwxqe463hl";
const PRICE_FEED_ID = "0x436ccb0d465f3cb48554bcc8def65ff695341b3ebe0897563d118b9291178d0f";
// Function to fetch price feed
async function fetchPythPriceFeed() {
try {
// Connect to the blockchain
const client = await CosmWasmClient.connect(RPC_ENDPOINT);
// Remove "0x" prefix for CosmWasm (unlike EVM chains)
const feedIdWithoutPrefix = PRICE_FEED_ID.startsWith("0x")
? PRICE_FEED_ID.slice(2)
: PRICE_FEED_ID;
// Use lowercase "price_feed" not "PriceFeed"
const queryMsg = {
price_feed: { id: feedIdWithoutPrefix },
};
console.log("Querying with:", queryMsg);
// Execute query
const response = await client.queryContractSmart(PYTH_CONTRACT, queryMsg);
console.log("Success! Pyth Price Feed Response:", response);
return response;
} catch (error: any) {
if (error.message?.includes("PriceFeedNotFound")) {
console.error("❌ Error: Price feed not found on testnet contract");
console.error(" This is expected - the testnet has no price feeds loaded yet.");
console.error(" Your query format is CORRECT, the data just doesn't exist.");
console.error("❌ Error fetching price feed:", error.message);
} else {
console.error("❌ Error fetching price feed:", error.message);
}
}
}
// Call the function
fetchPythPriceFeed();
```
**`queryContractSmart(PYTH_CONTRACT, queryMsg)`**: Sends a query to the Pyth contract to fetch the price feed.
# Indexers: Optimized Data Retrieval
The Key to Efficient Blockchain Data Retrieval
Indexers are specialized services that process and organize blockchain data, converting raw on-chain information into structured, easily searchable datasets. They enable developers to retrieve specific data points efficiently without scanning the entire blockchain, enhancing performance and simplifying data access.
From a high level you can look at Indexers as middleware between the blockchain and your application, providing several critical functions:
* **Data Extraction**: They extract raw data from the blockchain by monitoring blocks, transactions, and events.
* **Data Transformation**: They process and organize this data into structured formats optimized for queries.
* **Data Storage**: They maintain databases that allow for efficient searching and filtering of blockchain data.
* **API Access**: They expose this processed data through developer-friendly APIs.
## Why use an Indexer?
1. **Performance**: Applications can query indexed data much faster than directly querying the blockchain, leading to smoother user experiences.
2. **Reduced Chain Load**: By offloading read operations to indexers, your application reduces the load on the blockchain network.
3. **Complex Queries**: Perform complex data filtering and aggregation that would be impractical directly on-chain.
## Indexing CW721 NFTs: A Practical Example
When developing apps on Verona, direct blockchain queries might suffice initially but as your apps grow in complexity, the need for efficient data retrieval becomes more apparent. This is particularly true when working with CW721 NFTs.
### **The NFT Ownership Challenge**
Suppose you need to display all NFTs owned by a specific user in multiple Collections. Standard CW721 contract methods provide:
* **`NumTokens`**`:` Retrieves the total number of NFTs in a collection.
* **`OwnerOf`**`:` Fetches the owner of a specific token ID.
* **`Tokens`**`:` Lists all token\_ids that belong to a given owner, with pagination.
* **`AllTokens:`** Lists all token\_ids controlled by the contract.
* **`NftInfo`**`:`This returns metadata about one particular token.
* **`AllNftInfo`**`:` Returns the result of both `NftInfo` and `OwnerOf` for a token.
Without an indexer, fetching ownership details requires multiple blockchain queries of each collection and iterating through each token info individually. This can lead to performance bottlenecks and a sluggish user experience.
### Example of a Complex Query: **"Retrieve All NFTs Owned by a User in the Last 30 Days Across Multiple Collections"**
This query requires fetching all NFTs owned by a specific owner across multiple NFT collections, but only those acquired in the past 30 days. Doing this directly on-chain would be extremely inefficient and require multiple queries to gather, filter, and sort the data. An indexer simplifies this by maintaining a structured database of ownership changes, allowing for a single optimized query.
### **How Many Calls Would Be Required If Queried Directly on the Blockchain?**
If an indexer were not available, querying this information manually would involve the following steps:
1. **Fetch All CW721 Collections**
* Call the registry or manually input known NFT contracts.
* **1 query per chain supporting multiple CW721 contracts** (or a manually maintained list).
2. **Query Transfers for Each Collection Over the Last 30 Days**
* Use CosmWasm event queries to find all transfer events.
* If not, iterate through every block for the last 30 days and extract relevant events.
* **Potentially thousands of queries if no event indexing is available**.
3. **Filter Events for the Specific Wallet**
* Each event contains `from` and `to` fields.
* **Processing step (not a separate query but requires parsing)**.
4. **Fetch Metadata for Each Token Acquired in the Last 30 Days**
* Call `NftInfo` for each token to retrieve metadata (name, image, attributes).
* **1 query per NFT** (potentially dozens, hundreds or thousands).
5. **Resolve Metadata Links (IPFS, Arweave, etc.)**
* Fetch JSON metadata from IPFS or other storage solution.
* **1 external HTTP request per NFT**.
6. **Sort and Paginate Data**
* If needed, apply filters in the frontend.
* **Processing step (not a separate query, but costly in terms of UX and performance).**
#### **Estimated Calls Without an Indexer**
* **50 NFT collections** → **50 queries**
* **Transfers over 30 days** → **Potentially 1,500-3,000 queries** (assuming 30–60 transfers per collection)
* **Fetching metadata** → **500+ queries** (assuming 10 NFTs acquired per collection)
* **IPFS requests** → **500+ external calls**
💡 **Total Queries: 2,050 - 3,500+ (depending on number of NFTs and collections).**
### **How an Indexer Solves This Problem**
An indexer would pre-process and store ownership transfer events and metadata in an optimized database. This allows for a single query like:
```
GET /api/nfts?owner=xion12345...&from_date=2025-01-28&to_date=2025-02-28&limit=50&offset=0
```
💡 **Total Queries with an Indexer: 1 API Call**
* The indexer would fetch ownership records, filter by the date range, include metadata, and return structured results instantly.
This approach drastically reduces load on the blockchain, improves application performance, and enables real-time, user-friendly data retrieval.
# SubQuery
SubQuery is a leading blockchain data indexer that offers developers fast, flexible, open-source, and decentralized APIs for web3 projects. With the SubQuery SDK, developers can efficiently access rich indexed data to build intuitive and immersive decentralized applications. SubQuery supports a wide range of ecosystems, including XION, Cosmos, Ethereum, Polygon, Polkadot, Algorand, NEAR, Avalanche among others.
A key advantage of SubQuery is its ability to aggregate data across multiple blockchains within a single project. This enables developers to create advanced dashboard analytics, multi-chain block scanners, and index IBC transactions across zones.
## Useful resources:
* [SubQuery Academy (Documentation)](https://academy.subquery.network/)
* [XION Starter](https://github.com/subquery/cosmos-subql-starter/tree/main/XION/xion-testnet-starter)
* [Quick Start Guide](https://academy.subquery.network/indexer/quickstart/quickstart.html)
For technical questions and support, reach out to the SubQuery team at [**start@subquery.network**](mailto:start@subquery.network).
## Running and Hosting your XION SubQuery APIs
SubQuery is open-source, meaning you have the freedom to run it in the following ways:
* Locally on your own computer (or a cloud provider of your choosing), [view the instructions on how to run SubQuery Locally](https://academy.subquery.network/run_publish/run.html).
* You can publish it to SubQuery's enterprise-level [Managed Service](https://managedservice.subquery.network/), where we'll host your SubQuery project in production ready services for mission critical data with zero-downtime blue/green deployments. There even is a generous free tier.
* You can publish it to the decentralised [SubQuery Network](https://academy.subquery.network/subquery_network/architects/publish.html#deploying-your-project), the most open, performant, reliable, and scalable data service for app developers. The SubQuery Network indexes and services data to the global community in an incentivised and verifiable way and supports XION from launch.
# More Use Cases
### Building Guides
* [Build a Per-User Data Storage App](/en/build-on-verona/computation/use-cases/building-a-per-user-data-storage-dapp)
* [Build a TODO App using the Collection-Document Storage Smart Contract](/en/build-on-verona/computation/use-cases/build-a-todo-app-using-the-collection-document-storage-smart-contract)
### More Examples
You can find more example repositories here: <https://github.com/burnt-labs/examples>
# Build a Per-User Data Storage App
Let's build a simple yet powerful decentralized application (app) that allows users to store and retrieve t프로젝트로 돌아가기