subOraclePrices

Subscribes to price feed updates for specified tokens.

Parameters

  • tokens (string[]): An array of token identifiers.

  • callback ((price: PriceFeed) => void): A function to be called with each price update.

Returns

  • Promise<void>: A promise that resolves when the subscription is set up.

Description

This method establishes a subscription to price feed updates for the specified tokens. It maps the token identifiers to their corresponding Pyth object IDs and price feed IDs, then sets up a subscription using the Sui Price Service Connection.

When a price update is received, the method modifies the price.id to match the token identifier format used in the system, then calls the provided callback function with the updated price information.

Example Usage

export function useTokenPrice(network: string) {
  const [tokenPrice, setTokenPrice] = useState<{ [key: string]: number }>({});
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (isLoading) return;

    setIsLoading(true);
    const oracleAPI = new OracleAPI(network);

    Promise.all([
      oracleAPI.subOraclePrices(
        Array.from(
          new Set([...Object.keys(oracleAPI.consts.pythFeeder.feeder)]),
        ),
        priceInfo => {
          setTokenPrice(prevPrice => ({
            ...prevPrice,
            [priceInfo.id]: priceInfo
              .getPriceUnchecked()
              .getPriceAsNumberUnchecked(),
          }));
        },
      ),
    ])
      .then(() => {
        setIsLoading(false);
      })
      .catch(err => {
        console.error(err);
        setError(err.message);
        setIsLoading(false);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [network]);

  return {
    tokenPrice,
    isLoading,
    error,
  };
}

Last updated