Skip to content

Commit d60c5c8

Browse files
committed
chore(dev-hub) Second batch migrated
1 parent a2e8e43 commit d60c5c8

30 files changed

+1845
-21
lines changed

apps/developer-hub/content/docs/entropy/generate-random-numbers-evm.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ function requestRandomNumber() external payable {
8484

8585
This method returns a sequence number and emits a [`Requested`](https://github.com/pyth-network/pyth-crosschain/blob/main/target_chains/ethereum/entropy_sdk/solidity/EntropyEventsV2.sol#L30) event. You can store this sequence number to identify the request in next step.
8686

87-
Note that there are several variants of `requestV2` that allow the caller to configure the provider fulfilling the request and the gas limit for the callback. Refer [request callback variants](./entropy/request-callback-variants.mdx) for more details.
87+
Note that there are several variants of `requestV2` that allow the caller to configure the provider fulfilling the request and the gas limit for the callback. Refer [request callback variants](./entropy/request-callback-variants) for more details.
8888

8989
Please see the method documentation in the [IEntropyV2 interface](https://github.com/pyth-network/pyth-crosschain/blob/main/target_chains/ethereum/entropy_sdk/solidity/IEntropyV2.sol).
9090

apps/developer-hub/content/docs/entropy/set-custom-gas-limits.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Custom gas limits are useful when your callback function requires more gas than
1010

1111
## Prerequisites
1212

13-
Before following this guide, you should first complete the basic setup from the [Generate Random Numbers in EVM Contracts](./entropy/generate-random-numbers-evm.mdx) guide. This guide builds upon that foundation and assumes you have:
13+
Before following this guide, you should first complete the basic setup from the [Generate Random Numbers in EVM Contracts](./entropy/generate-random-numbers-evm) guide. This guide builds upon that foundation and assumes you have:
1414

1515
- Installed the Pyth Entropy Solidity SDK
1616
- Set up your contract with the `IEntropyConsumer` interface

apps/developer-hub/content/docs/price-feeds/core/api-instances-and-providers.mdx

Lines changed: 0 additions & 14 deletions
This file was deleted.

apps/developer-hub/content/docs/price-feeds/core/api-instances-and-providers/benchmarks.mdx

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
title: Benchmarks API Instances
2+
title: Benchmarks
33
description: Access Benchmarks API instances for Pyth Price Feeds
44
slug: /price-feeds/core/api-instances-and-providers/benchmarks
55
---
@@ -11,4 +11,3 @@ The Pyth Data Association hosts a public instance of the Benchmarks API at the f
1111
| Stable | https://benchmarks.pyth.network |
1212

1313
There is currently no Benchmarks instance for the Beta channel.
14-

apps/developer-hub/content/docs/price-feeds/core/api-instances-and-providers/hermes.mdx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,3 @@ The Pyth Data Association provides a Helm chart for running Hermes in
5050
[charts](https://github.com/pyth-network/charts/tree/main/charts/hermes) repository. Please refer to the chart's readme
5151
for the configuration values.
5252
You will need a Pythnet RPC to run Hermes; see the [guide for accessing a Pythnet RPC](pythnet-rpc.mdx).
53-

apps/developer-hub/content/docs/price-feeds/core/api-instances-and-providers/index.mdx

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,3 @@ See the following guides to learn more about how to access each service:
1010
- [Hermes](api-instances-and-providers/hermes.mdx)
1111
- [Pythnet RPC](api-instances-and-providers/pythnet-rpc.mdx)
1212
- [Benchmarks/Historical Price](api-instances-and-providers/benchmarks.mdx)
13-
14-
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
title: Pythnet RPC
3+
description: Access Pythnet RPC providers for Pyth price feeds
4+
slug: /price-feeds/core/api-instances-and-providers/pythnet-rpc
5+
---
6+
7+
You will need a Pythnet RPC to run Hermes, which you can obtain from any of the Pythnet RPC
8+
providers below:
9+
10+
- [Triton](https://triton.one)
11+
- [P2P](https://p2p.org)
12+
- [Blockdaemon](https://blockdaemon.com/)
13+
- [Figment](https://figment.io)
14+
15+
Alternatively, you can host Pythnet RPC yourself, but this is discouraged due to the potential high cost and maintenance
16+
involved in operating it. If you still wish to run it, please contact the Pyth team for more information.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
title: API Reference
3+
description: Explore interactive Pyth API references for on-chain and off-chain integrations
4+
slug: /price-feeds/core/api-reference
5+
---
6+
7+
The API reference is a comprehensive guide to the various APIs -- both on- and off-chain -- that developers can use in their applications.
8+
Developers can consult this reference to better understand what methods exist and what they do.
9+
The API reference is interactive, so developers can try out the APIs from the website to better understand their behavior.
10+
11+
The following on-chain contracts are documented in the API reference:
12+
13+
- [EVM](https://api-reference.pyth.network/price-feeds/evm/getPriceNoOlderThan)
14+
15+
Hermes also has interactive API documentation hosted by the service itself:
16+
17+
- [Hermes](https://hermes.pyth.network/docs/)
18+
- [Benchmarks / Historical Prices](https://benchmarks.pyth.network/docs)
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
---
2+
title: Best Practices
3+
description: Learn how to integrate Pyth price feeds safely and effectively
4+
slug: /price-feeds/core/best-practices
5+
---
6+
7+
This page provides some technical details about Pyth price feeds that are necessary to use them safely and correctly.
8+
Please read this page before using Pyth price feeds in your application.
9+
10+
## Fixed-Point Numeric Representation
11+
12+
Price feeds represent numbers in a fixed-point format. The same exponent is used for both the price and confidence interval. The integer representation of these values can be computed by multiplying by `10^exponent`. As an example, imagine Pyth reported the following values for AAPL/USD:
13+
14+
| Field | Value |
15+
| ---------- | -------- |
16+
| `exponent` | -5 |
17+
| `conf` | 1500 |
18+
| `price` | 12276250 |
19+
20+
The confidence interval is `1500 * 10^(-5) = $0.015`, and the price is `12276250 * 10^(-5) = $122.7625`.
21+
22+
## Price Availability
23+
24+
Sometimes, Pyth will not be able to provide a current price for a product.
25+
This situation can happen for various reasons.
26+
For example, US equity markets only trade during certain hours, and outside those hours, it's not clear what an equity's price is.
27+
Pyth price feeds follow the traditional market hours for each asset class. \
28+
Consult [Market Hours](./market-hours) to know the market hours for each asset class.
29+
30+
Alternatively, a network outage (at the internet level, blockchain level, or at multiple data providers) may prevent the protocol from producing new price updates.
31+
(Such outages are unlikely, but integrators should still be prepared for the possibility.)
32+
In such cases, Pyth may return a stale price for the product.
33+
34+
Integrators should be careful to avoid accidentally using a stale price.
35+
The Pyth SDKs guard against this failure mode by incorporating a staleness check by default.
36+
Querying the current price will fail if too much time has elapsed since the last update.
37+
The SDKs expose this failure condition in an idiomatic way: for example, the Rust SDK may return `None`, and the Solidity SDK may revert the transaction.
38+
The SDK provides a sane default for the staleness threshold, but users may configure it to suit their use case.
39+
40+
## Adversarial selection
41+
42+
Pull updates give users of Pyth Network some ability to select which price to use in a transaction.
43+
This ability is highly circumscribed by various constraints: on-chain prices must move forward in time and cannot be from too far in the past.
44+
However, users can still choose any price update that satisfies these constraints.
45+
This ability is functionally equivalent to latency: it allows users to see the price in the future before using a price from the past.
46+
47+
The simplest way to guard against this attack vector is to incorporate a **staleness check** to ensure that the price used in a transaction is sufficiently recent.
48+
49+
The Pyth SDK provides the [`getPriceNoOlderThan()`](https://api-reference.pyth.network/price-feeds/evm/getPriceNoOlderThan) method to help users guard against this attack vector. This method returns the most recent price update that is not older than a specified threshold.
50+
Highly latency-sensitive protocols may wish to reduce the threshold to a few seconds to better suit their needs.
51+
Please also see the section below on [latency mitigations](#latency) for additional ideas on how latency-sensitive protocols can minimize the impact of oracle latency.
52+
53+
## Latency
54+
55+
Developers integrating Pyth Network price feeds should account for the difference in latency between on-chain oracles and off-chain sources (e.g. centralized exchanges).
56+
Although Pyth Network is designed with low latency in mind, no on-chain oracle can match the latency of an off-chain source due to the added overhead for consensus and security.
57+
The threat model for integrating protocols should assume that adversaries see price changes a short time before the protocol does.
58+
In this threat model, protocol designers should avoid situations where a Pyth price update must race against an adversary's transaction.
59+
Adversaries are highly likely to win these races, as they have a head start, and sophisticated adversaries can additionally optimize their network latencies or pay miners for priority blockspace.
60+
61+
### Latency Mitigations for Derivative Protocols[^1]
62+
63+
Derivative protocols are encouraged to consider the following strategies to mitigate the impact of oracle latency:
64+
65+
1. **Use Delayed Settlement**: Derivative protocols can introduce a delay between the time an order is created and the time it is executed. This delay gives the protocol time to observe price changes and reject trades/transactions that profit over latency.
66+
Suppose a user submits a trade transaction at a time `t`. The protocol should execute the trade by using the price at the time `t`, which will be available to the protocol after a short delay.
67+
The protocol can fetch this price update of a specific timestamp from [Hermes](https://hermes.pyth.network/docs/#/rest/timestamp_price_updates) and can use [`parsePriceFeedUpdates()`](https://api-reference.pyth.network/price-feeds/evm/parsePriceFeedUpdates) to parse the prices and submit to prevent price frontrunning.
68+
69+
1. **Use a Spread**: Pyth provides a confidence interval for each price update. Derivative protocols can use this confidence interval to determine the range in which the true price probably lies.
70+
By using the lower bound of the confidence interval, derivative protocols can protect themselves from price manipulation that drives the price down. By using the upper bound of the confidence interval, derivative protocols can protect themselves from price manipulation that drives the price up.
71+
72+
1. **Enforce Position Holding**: Derivative protocols can enforce hold times on positions to prevent users from exploiting oracle latency.
73+
For example, a protocol could require users to hold an asset or a position for a certain period before they can trade or close it.
74+
This hold time gives the protocol time to observe price changes and reject trades that profit over latency.
75+
76+
## Confidence Intervals
77+
78+
At every point in time, Pyth publishes both a price and a confidence interval for each product. For example, Pyth may publish the current price of bitcoin as \$50000 ± \$10. Pyth publishes a confidence interval because, in real markets, there is _no one single price for a product_. For example, at any given time, bitcoin trades at different prices at different venues around the world. While these prices are typically similar, they can diverge for a number of reasons, such as when a cryptocurrency exchange blocks withdrawals on an asset. If this happens, prices diverge because arbitrageurs can no longer bring prices across exchanges into line. Alternatively, prices on different venues can differ simply because an asset is highly volatile at a particular point in time. At such times, bid/ask spreads tend to be wider, and trades on different markets at around the same time tend to occur at a wider range of prices.
79+
80+
In a Pyth feed, each publisher specifies an interval `(p_i-c_i, p_i+c_i)` in the form of their price and confidence submission. This interval is intended to achieve 95% coverage, i.e. the publisher expresses the belief that this interval contains the “true” price with 95% probability. The resulting aggregate interval `(μ-σ, μ+σ)`, where `μ` represents the aggregate price and `σ` represents the aggregate confidence, is a good estimate of a range in which the true price lies.
81+
82+
To explain this, consider two cases of publisher estimates. In the first case, there is 100% overlap of all the publishers’ intervals, i.e. each publisher submits the same interval `(p-c, p+c)`. In this case, the aggregate confidence interval is exactly that interval, so the aggregate confidence interval provides 100% coverage of the publishers’ intervals. This first case represents normal operating conditions, where most publishers agree about the price of an asset.
83+
84+
In the second case, each publisher specifies an interval that is disjoint from each of the other publishers’ intervals. In this case, the aggregate confidence interval can be seen to contain at least the 25th percentile and at least the 75th percentile of the set of points consisting of each of the publisher’s price, price plus confidence, and price plus confidence. As a result, the aggregate confidence interval is somewhat analogous to an interquartile range of the data, which is a reasonable measure of the spread of a set of points. Note that this is not an IQR of the prices alone of the publishers but rather of the set composed of the 3 points that each publisher submits. Moreover, note that the IQR does not include the most extreme publishers’ prices on either side; this property is necessary to ensure that a small group of publishers cannot manipulate the aggregate confidence interval. This second case represents an atypical scenario where publishers all disagree. Such circumstances are rare but can occur during market volatility or unusual events.
85+
86+
The aggregate confidence interval interpolates between the two cases above as publishers’ prices begin to diverge. In situations closer to case 1 where there is significant overlap of the individual publishers’ intervals, the aggregate interval `(μ-σ, μ+σ)` will capture most of the spread of the individual publishers. In the situation where the prices look more like case 2 with greater disjointness due to different views of the price across different venues, that aggregate interval may be in some eyes an imperfect measure of spread because there may be a number of individual price intervals that lie outside the aggregate interval. In this case, a protocol has a couple of options:
87+
88+
1. It can use a discounted price in the direction favorable to it. For example, a lending protocol valuing a user’s collateral can use the lower valuation price `μ-σ`. When valuing an outstanding loan position consisting of tokens a user has borrowed from the protocol, it can use the higher end of the interval by using the price `μ+σ`. This allows the protocol to be conservative with regard to its own health and safety when making valuations.
89+
2. It can decide that there is too much uncertainty when `σ/μ` exceeds some threshold and choose to pause any new activity that depends on the price of this asset.
90+
91+
To expand upon the first option, it is recommended to use the confidence interval to protect your users from these unusual market conditions. The simplest way to do so is to use Pyth's confidence interval to compute a _range_ in which the true price probably lies. This principle is common sense. Imagine that you are lending money to a friend, and your friend pledges a bitcoin as collateral. Also imagine that Pyth says the bitcoin price is \$50000 +- \$1000. (Note that \$1000 is an unusually large confidence interval for bitcoin; the confidence interval is typically \$50 dollars). You therefore calculate that the true price is between \$49000 and \$51000. When originating the loan, you would value the bitcoin at \$49000. The lower price is conservative in this instance because it limits the amount of borrowing that is possible while the price is uncertain. On the other hand, if you were to issue a loan of bitcoin, you would value the borrowed bitcoin at \$51000. The higher price is conservative, as it protects you from allowing someone to borrow in excess during times of increased volatility.
92+
93+
The same principle would apply if you wrote a derivative contract. If someone wants to open a derivative contract with you, you would value their collateral at the lower price. However, if you were deciding whether someone's margin limits were violated, you could value their outstanding leveraged position at the higher price. If a contract needs to be settled at a price, you could take approaches such as the following:
94+
95+
1. Using Pyth's exponential moving average price, which represents estimates of the average price of the asset over a specified time period (e.g., over the past 1 hour). The exponential moving average price is computed such that it lessens the influence of prices with wide confidence intervals. You may find more details in [EMA Price Aggregation](./how-pyth-works/ema-price-aggregation.mdx).
96+
2. Using the aggregate price, which is Pyth's best estimate of the price at a single point in time. The quality of this estimate depends on the width of the confidence interval at settlement time and on occasion, it may be imprecise. However, it is the best you can do with Pyth data if you need a single price at that exact point in time.
97+
3. Defining the contract to depend on confidence. For example, you could create an option that refunds the option premium to the buyer (so both sides of the transaction are even) if the strike price is within the confidence interval at settlement time. You could also create a contract that delayed settlement until the confidence interval was sufficiently small. If you choose this second option, you should ensure that your contract is guaranteed to eventually settle even if the confidence interval never narrows.
98+
99+
## Pricing Futures-Based Assets
100+
101+
For assets like commodities, interest rates, and even volatility indices, pricing is primarily derived from futures contracts. These contracts form a series of prices for different delivery dates, collectively known as the futures curve. While the **front-month contract** is the most actively traded and often seen as the benchmark, it **doesn't** represent the current price of the asset but rather a proxy of the near-term price of the asset at the time of delivery.
102+
103+
This reliance on futures, in the absence of a native spot price, means that market expectations, logistical constraints, amongst other factors can heavily influence the front-month price.
104+
For example, in times of extreme market stress, the front-month contract turn **negative** when traders avoid delivery, distorting its usefulness as a representative market signal. This happened in the case of the 2020 oil crash, where the front-month price of WTI Crude oil turned negative due to a lack of storage capacity, making applications that rely exclusively on the front-month price unreliable.
105+
106+
Thus it is important that each contract **should have a weighted stratergy** based on the their expiration dates. As the front month approaches expiry, least weight should be allocated on this contract and the weights of the other contracts are determined proportionally. A daily re-adjusted strategy should be applied by the end user of the price feeds.
107+
108+
##
109+
110+
[^1]:
111+
_The strategies and methodologies outlined in this page, including those addressing price latency mitigation, are provided solely for informational purposes and might not fully eliminate the discussed problems. Do your own research before using them. \
112+
Refer to [Terms of Use](https://www.pyth.network/terms-of-use) for more information._

0 commit comments

Comments
 (0)