Pyth is a pull oracle. Pyth price feeds on TON are managed through the main TON Pyth smart
contract, enabling seamless interaction with on-chain data. In TON,
these interactions are facilitated by specific functions within the
Pyth TON contract. This contract acts as an interface to Pyth
price feeds, handling the retrieval and updating of price data.
The following example uses the testnet contract. For mainnet usage, change the PYTH_CONTRACT_ADDRESS_TESTNET to PYTH_CONTRACT_ADDRESS_MAINNET accordingly.
import { TonClient, Address, WalletContractV4 } from "@ton/ton";import { mnemonicToPrivateKey } from "@ton/crypto";import { HermesClient } from "@pythnetwork/hermes-client";import { PythContract, PYTH_CONTRACT_ADDRESS_TESTNET, PYTH_CONTRACT_ADDRESS_MAINNET, calculateUpdatePriceFeedsFee,} from "@pythnetwork/pyth-ton-js";const BTC_PRICE_FEED_ID = "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43";async function main() { // Initialize TonClient const client = new TonClient({ endpoint: "https://testnet.toncenter.com/api/v2/jsonRPC", apiKey: "your-api-key-here", // Get your TON Center API key via @tonapibot or https://t.me/toncenter (optional) }); // Create PythContract instance const contractAddress = Address.parse(PYTH_CONTRACT_ADDRESS_TESTNET); const contract = client.open(PythContract.createFromAddress(contractAddress)); // Get current guardian set index const guardianSetIndex = await contract.getCurrentGuardianSetIndex(); console.log("Guardian Set Index:", guardianSetIndex); // Get BTC price from TON contract const price = await contract.getPriceUnsafe(BTC_PRICE_FEED_ID); console.log("BTC Price from TON contract:", price); // Fetch latest price updates from Hermes const hermesEndpoint = "https://hermes.pyth.network"; const hermesClient = new HermesClient(hermesEndpoint); const priceIds = [BTC_PRICE_FEED_ID]; const latestPriceUpdates = await hermesClient.getLatestPriceUpdates( priceIds, { encoding: "hex" } ); console.log("Hermes BTC price:", latestPriceUpdates.parsed?.[0].price); // Prepare update data const updateData = Buffer.from(latestPriceUpdates.binary.data[0], "hex"); console.log("Update data:", updateData); // Get update fee const updateFee = await contract.getUpdateFee(updateData); console.log("Update fee:", updateFee); const totalFee = calculateUpdatePriceFeedsFee(BigInt(updateFee)) + BigInt(updateFee); // Update price feeds const mnemonic = "your mnemonic here"; const key = await mnemonicToPrivateKey(mnemonic.split(" ")); const wallet = WalletContractV4.create({ publicKey: key.publicKey, workchain: 0, }); const provider = client.open(wallet); await contract.sendUpdatePriceFeeds( provider.sender(key.secretKey), updateData, totalFee ); console.log("Price feeds updated successfully.");}main().catch(console.error);