|
|
2 weeks ago | |
|---|---|---|
| .. | ||
| src | 3 weeks ago | |
| .gitignore | 3 weeks ago | |
| .prettierignore | 2 weeks ago | |
| README.md | 1 month ago | |
| eslint.config.js | 3 weeks ago | |
| jest.config.js | 2 years ago | |
| package.json | 2 weeks ago | |
| tsconfig.build.json | 3 weeks ago | |
| tsconfig.json | 3 weeks ago | |
| turbo.json | 8 months ago | |
Pyth provides real-time pricing data in a variety of asset classes, including cryptocurrency, equities, FX and commodities. This library allows you to use these real-time prices on the Sui network.
cd to crosschain root
$ pnpm install
Pyth stores prices off-chain to minimize gas fees, which allows us to offer a wider selection of products and faster update times.
See On-Demand Updates for more information about this approach.
Typically, to use Pyth prices on chain,
they must be fetched from an off-chain Hermes instance. The SuiPriceServiceConnection class can be used to interact with these services,
providing a way to fetch these prices directly in your code. The following example wraps an existing RPC provider and shows how to obtain
Pyth prices and submit them to the network:
const connection = new SuiPriceServiceConnection(
"https://hermes-beta.pyth.network",
); // See Hermes endpoints section below for other endpoints
const priceIds = [
// You can find the ids of prices at https://pyth.network/developers/price-feed-ids#sui-testnet
"0xf9c0172ba10dfa4d19088d94f5bf61d3b54d5bd7483a322a982e1373ee8ea31b", // BTC/USD price id in testnet
"0xca80ba6dc32e08d06f1aa886011eed1d77c77be9eb761cc10d72b7d0a2fd57a6", // ETH/USD price id in testnet
];
// In order to use Pyth prices in your protocol you need to submit the price update data to Pyth contract in your target
// chain. `getPriceUpdateData` creates the update data which can be submitted to your contract.
const priceUpdateData = await connection.getPriceFeedsUpdateData(priceIds);
Your Sui Move module should NOT have a hard-coded call to pyth::update_single_price_feed. In other words, the Sui Pyth pyth::update_single_price_feed entry point should never be called by a contract, instead it should be called directly from client code (e.g. Typescript or Rust).
This is because when a Sui contract is upgraded, the new address is different from the original. If your module has a hard-coded call to pyth::update_single_price_feed living at a fixed call-site, it may eventually get bricked due to the way Pyth upgrades are implemented. (We only allows users to interact with the most recent package version for security reasons).
Therefore, you should build a Sui programmable transaction that first updates the price by calling pyth::update_single_price_feed at the latest call-site from the client-side and then call a function in your contract that invokes pyth::get_price on the PriceInfoObject to get the recently updated price.
You can use SuiPythClient to build such transactions.
import { SuiPythClient } from "@pythnetwork/pyth-sui-js";
import { Transaction } from "@mysten/sui/transactions";
import { SuiClient } from "@mysten/sui/client";
const priceUpdateData = await connection.getPriceFeedsUpdateData(priceIds); // see quickstart section
// It is either injected from browser or instantiated in backend via some private key
const wallet: SignerWithProvider = getWallet();
// Get the state ids of the Pyth and Wormhole contracts from
// https://docs.pyth.network/price-feeds/contract-addresses/sui
const wormholeStateId = " 0xFILL_ME";
const pythStateId = "0xFILL_ME";
const provider = new SuiClient({ url: "https://fill-sui-endpoint" });
const client = new SuiPythClient(wallet.provider, pythStateId, wormholeStateId);
const tx = new Transaction();
const priceInfoObjectIds = await client.updatePriceFeeds(tx, priceFeedUpdateData, priceIds);
tx.moveCall({
target: `YOUR_PACKAGE::YOUR_MODULE::use_pyth_for_defi`,
arguments: [
..., // other arguments needed for your contract
tx.object(pythStateId),
tx.object(priceInfoObjectIds[0]),
],
});
const result = await provider.signAndExecuteTransaction({
signer: wallet,
transaction: tx,
options: {
showEffects: true,
showEvents: true,
},
});
Now in your contract you can consume the price by calling pyth::get_price or other utility functions on the PriceInfoObject.
This example shows how to update prices on an Sui network. It does the following:
In order to run the commands, a SUI private key is needed. The commands expects the key to be in the form of hex. You can use sui keytool convert to get the hex version of the key, to be used below, if your private key is in the form "suiprivkey...".
You can run this example with pnpm turbo --filter @pythnetwork/pyth-sui-js run example-relay from the root of crosschain. Turbo will automatically build any detected dependencies including local ones, and filter is needed to tell it which sub-package to use (Such as this one). A full command that updates prices on Sui testnet looks like:
export SUI_KEY=YOUR_PRIV_KEY;
pnpm turbo run example-relay --filter @pythnetwork/pyth-sui-js -- \
--feed-id "5a035d5440f5c163069af66062bac6c79377bf88396fa27e6067bfca8096d280" \
--hermes "https://hermes-beta.pyth.network" \
--full-node "https://fullnode.testnet.sui.io:443" \
--pyth-state-id "0xd3e79c2c083b934e78b3bd58a490ec6b092561954da6e7322e1e2b3c8abfddc0" \
--wormhole-state-id "0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790"
Many applications additionally need to display Pyth prices off-chain, for example, in their frontend application.
The SuiPriceServiceConnection is an extension of the Hermes client
and provides two different ways to fetch the current Pyth price.
The code blocks below assume that the connection and priceIds objects have been initialized as shown above.
The first method is a single-shot query:
// `getLatestPriceFeeds` returns a `PriceUpdate`; see the [hermes-client](https://github.com/pyth-network/pyth-crosschain/tree/main/apps/hermes/client/js) documentation for details.
const priceUpdate: PriceUpdate = await connection.getLatestPriceUpdates(priceIds, { parsed: true });
if (priceUpdate.parsed) {
console.log("ParsedPriceUpdate:", priceUpdate.parsed);
}
The object also supports a streaming Server-Sent Events (SSE) connection that allows you to subscribe to every new price update for a given feed. This method is useful if you want to show continuously updating real-time prices in your frontend:
// Streaming price updates
const eventSource = await connection.getPriceUpdatesStream(priceIds, { parsed: true });
eventSource.onmessage = (event) => {
console.log("Received price update:", event.data);
};
eventSource.onerror = (error) => {
console.error("Error receiving updates:", error);
eventSource.close();
};
await sleep(5000);
// To stop listening to the updates, you can call eventSource.close();
console.log("Closing event source.");
eventSource.close();
You can find the list of Hermes public endpoints here.