Skip to content

Commit d959cdf

Browse files
authored
feat(sui): Add contract example code (#313)
1 parent 38e8915 commit d959cdf

File tree

1 file changed

+38
-2
lines changed
  • pages/price-feeds/use-real-time-data

1 file changed

+38
-2
lines changed

pages/price-feeds/use-real-time-data/sui.mdx

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ const tx = new TransactionBlock();
8686
const priceInfoObjectIds = await client.updatePriceFeeds(tx, priceFeedUpdateData, priceIds);
8787

8888
tx.moveCall({
89-
target: `YOUR_PACKAGE::YOUR_MODULE::use_pyth_for_defi`,
89+
target: `pyth_example::main::use_pyth_price`,
9090
arguments: [
9191
..., // other arguments needed for your contract
9292
tx.object(pythStateId),
@@ -106,7 +106,43 @@ const result = await wallet.signAndExecuteTransactionBlock(txBlock);
106106
```
107107

108108
By calling the `updatePriceFeeds` function, the `SuiPythClient` adds the necessary transactions to the transaction block to update the price feeds.
109-
Now in your contract you can consume the price by calling `pyth::get_price` or other utility functions on the `PriceInfoObject`.
109+
Now in your contract you can consume the price by calling `pyth::get_price` or other utility functions on the `PriceInfoObject`:
110+
111+
```rust copy
112+
module pyth_example::main {
113+
use sui::clock::Clock;
114+
use pyth::price_info;
115+
use pyth::price_identifier;
116+
use pyth::price;
117+
use pyth::state::{State as PythState};
118+
use pyth::pyth;
119+
use pyth::price_info::PriceInfoObject;
120+
121+
const E_INVALID_ID: u64 = 1;
122+
123+
public fun use_pyth_price(
124+
// other arguments
125+
clock: &Clock,
126+
pyth_state: &PythState,
127+
price_info_object: &PriceInfoObject,
128+
){
129+
let max_age = 60;
130+
// make sure the price is not older than max_age seconds
131+
let price_struct = pyth::get_price(pyth_state,price_info_object, clock);
132+
133+
// check the price feed id
134+
let price_info = price_info::get_price_info_from_price_info_object(price_info_object);
135+
let price_id = price_identifier::get_bytes(&price_info::get_price_identifier(&price_info));
136+
// ETH/USD price feed id
137+
assert!(price_id!=x"ff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace", E_INVALID_ID);
138+
139+
// extract the price, decimal, and timestamp from the price struct and use them
140+
let decimal_i64 = price::get_expo(&price_struct);
141+
let price_i64 = price::get_price(&price_struct);
142+
let timestamp_sec = price::get_timestamp(&price_struct);
143+
}
144+
}
145+
```
110146

111147
### Pyth Dependency
112148

0 commit comments

Comments
 (0)