Skip to content

feat(evm/sdk/js): add pyth filler #2832

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
435 changes: 89 additions & 346 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

10 changes: 0 additions & 10 deletions target_chains/ethereum/sdk/js/.eslintrc.js

This file was deleted.

209 changes: 55 additions & 154 deletions target_chains/ethereum/sdk/js/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
# Pyth EVM JS (DEPRECATED)

> [!WARNING]
> **DEPRECATION NOTICE:** This package is deprecated and no longer maintained. Please use [hermes-client](https://github.com/pyth-network/pyth-crosschain/tree/main/apps/hermes/client/js) instead.
# Pyth EVM JS

[Pyth](https://pyth.network/) 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 EVM-based networks.
Expand All @@ -22,156 +19,60 @@ $ yarn add @pythnetwork/pyth-evm-js

## Quickstart

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](https://docs.pyth.network/documentation/pythnet-price-feeds/on-demand) for more
information about this approach. In order to use Pyth prices on chain, they must be fetched from an off-chain Hermes
instance. The `EvmPriceServiceConnection` 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:

```typescript
const connection = new EvmPriceServiceConnection("https://hermes.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#pyth-evm-stable
"0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43", // BTC/USD price id
"0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace", // ETH/USD price id
];

// In order to use Pyth prices in your protocol you need to submit the price update data to Pyth contract in your target
// chain. `getPriceFeedsUpdateData` creates the update data which can be submitted to your contract. Then your contract should
// call the Pyth Contract with this data.
const priceUpdateData = await connection.getPriceFeedsUpdateData(priceIds);

// If the user is paying the price update fee, you need to fetch it from the Pyth contract.
// Please refer to https://docs.pyth.network/documentation/pythnet-price-feeds/on-demand#fees for more information.
//
// `pythContract` below is a web3.js contract; if you wish to use ethers, you need to change it accordingly.
// You can find the Pyth interface ABI in @pythnetwork/pyth-sdk-solidity npm package.
const updateFee = await pythContract.methods
.getUpdateFee(priceUpdateData)
.call();

// Calling someContract method
// `someContract` below is a web3.js contract; if you wish to use ethers, you need to change it accordingly.
// Note: In Hedera you need to pass updateFee * 10^10 as value to the send method as there is an
// inconsistency in the way the value is handled in Hedera RPC and the way it is handled on-chain.
await someContract.methods
.doSomething(someArg, otherArg, priceUpdateData)
.send({ value: updateFee });
```

`SomeContract` looks like so:

```solidity
pragma solidity ^0.8.0;

import "@pythnetwork/pyth-sdk-solidity/IPyth.sol";
import "@pythnetwork/pyth-sdk-solidity/PythStructs.sol";
### Filling Pyth Data for Transactions

contract SomeContract {
IPyth pyth;

constructor(address pythContract) {
pyth = IPyth(pythContract);
}

function doSomething(
uint someArg,
string memory otherArg,
bytes[] calldata priceUpdateData
) public payable {
// Update the prices to be set to the latest values
uint fee = pyth.getUpdateFee(priceUpdateData);
pyth.updatePriceFeeds{ value: fee }(priceUpdateData);

// Doing other things that uses prices
bytes32 priceId = 0xf9c0172ba10dfa4d19088d94f5bf61d3b54d5bd7483a322a982e1373ee8ea31b;
// Get the price if it is not older than 10 seconds from the current time.
PythStructs.Price price = pyth.getPriceNoOlderThan(priceId, 10);
}
}

```

We strongly recommend reading our guide which explains [how to work with Pyth price feeds](https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices).

### Off-chain prices

Many applications additionally need to display Pyth prices off-chain, for example, in their frontend application.
The `EvmPriceServiceConnection` 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:
The `fillPythUpdate` function helps you automatically determine what Pyth price updates are needed for a transaction and creates the necessary update call.
This function uses the `trace_callMany` method by default but can be used with `debug_traceCall` and a bundler as well. See the example below for more information.

```typescript
// `getLatestPriceFeeds` returns a `PriceFeed` for each price id. It contains all information about a price and has
// utility functions to get the current and exponentially-weighted moving average price, and other functionality.
const priceFeeds = await connection.getLatestPriceFeeds(priceIds);
// Get the price if it is not older than 60 seconds from the current time.
console.log(priceFeeds[0].getPriceNoOlderThan(60)); // Price { conf: '1234', expo: -8, price: '12345678' }
// Get the exponentially-weighted moving average price if it is not older than 60 seconds from the current time.
console.log(priceFeeds[1].getEmaPriceNoOlderThan(60));
```

The object also supports a streaming websocket 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:

```typescript
// Subscribe to the price feeds given by `priceId`. The callback will be invoked every time the requested feed
// gets a price update.
connection.subscribePriceFeedUpdates(priceIds, (priceFeed) => {
console.log(
`Received update for ${priceFeed.id}: ${priceFeed.getPriceNoOlderThan(60)}`
);
});

// When using the subscription, make sure to close the websocket upon termination to finish the process gracefully.
setTimeout(() => {
connection.closeWebSocket();
}, 60000);
```

### Examples

There are two examples in [examples](./src/examples/).

#### EvmPriceServiceClient

[This example](./src/examples/EvmPriceServiceClient.ts) fetches `PriceFeed` updates using both a HTTP-request API and a streaming websocket API. You can run it with `npm run example-client`. A full command that prints BTC and ETH price feeds, in the testnet network, looks like so:

```bash
npm run example-client -- \
--endpoint https://hermes.pyth.network \
--price-ids \
0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43 \
0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace
```

#### EvmRelay

[This example](./src/examples/EvmRelay.ts) shows how to update prices on an EVM network. It does the following:

1. Gets update data to update given price feeds.
2. Calls the pyth contract with the update data.
3. Submits it to the network and prints the txhash if successful.

You can run this example with `npm run example-relay`. A full command that updates BTC and ETH prices on the BNB Chain
testnet network looks like so:

```bash
npm run example-relay -- \
--network "https://data-seed-prebsc-1-s1.binance.org:8545" \
--pyth-contract "0x5744Cbf430D99456a0A8771208b674F27f8EF0Fb"\
--mnemonic "my good mnemonic" \
--endpoint https://hermes.pyth.network \
--price-ids \
"0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43" \
"0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace"
```

## Hermes endpoints

Pyth offers a free public endpoint at [https://hermes.pyth.network](https://hermes.pyth.network). However, it is
recommended to obtain a private endpoint from one of the Hermes RPC providers for more reliability. You can find more
information about Hermes RPC providers
[here](https://docs.pyth.network/documentation/pythnet-price-feeds/hermes#public-endpoint).
import { fillPythUpdate, multicall3Bundler } from "@pythnetwork/pyth-evm-js";
import { createPublicClient, http } from "viem";
import { optimismSepolia } from "viem/chains";

async function example() {
const client = createPublicClient({
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor thing but since top-level await exists, you don't need the code here to live in a function, and it kind of distracted me a bit when I was reading through the docs here -- when I saw this my immediate thought was "what is the example function returning and where do I use it" -- I'd just put the body at the top level to minimize the distraction.

chain: optimismSepolia,
transport: http("YOUR_RPC_ENDPOINT"),
});

// Fill Pyth update data using "trace_callMany"
const pythUpdate = await fillPythUpdate(
client,
{
to: "0x3252c2F7962689fA17f892C52555613f36056f22",
data: "0xd09de08a", // Your transaction calldata
from: "0x78357316239040e19fC823372cC179ca75e64b81",
},
"0x0708325268df9f66270f1401206434524814508b", // Pyth contract address
"https://hermes.pyth.network", // Hermes endpoint
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we export this as a const? I know that contract manager isn't in a great state but even just manually copying it over seems to be a better experience for now

{
Copy link
Collaborator

@cprussin cprussin Jul 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we make this a const too? Or better yet, can we make this function just automatically derive these two fields from the client, but allow overriding them in the options?

method: "trace_callMany"
maxIter: 5,
},
);

// Fill Pyth update data using "debug_traceCall"
const pythUpdateWithDebugTrace = await fillPythUpdate(
client,
{
to: "0x3252c2F7962689fA17f892C52555613f36056f22",
data: "0xd09de08a", // Your transaction calldata
from: "0x78357316239040e19fC823372cC179ca75e64b81",
},
"0x0708325268df9f66270f1401206434524814508b", // Pyth contract address
"https://hermes.pyth.network", // Hermes endpoint
{
method: "debug_traceCall",
bundler: multicall3Bundler // or any function that takes a PythUpdate and a CallRequest and produces a CallRequest
maxIter: 5,
},
);

if (pythUpdate) {
console.log("Pyth update needed:", pythUpdate);
// Bundle the calls together, or pass the pythUpdate.updateData to your contract.
} else {
console.log("No Pyth data needed for this transaction");
}
}
```
1 change: 1 addition & 0 deletions target_chains/ethereum/sdk/js/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { base as default } from "@cprussin/eslint-config";
21 changes: 8 additions & 13 deletions target_chains/ethereum/sdk/js/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@pythnetwork/pyth-evm-js",
"version": "1.83.0",
"version": "2.0.0-alpha",
"description": "Pyth Network EVM Utils in JS",
"homepage": "https://pyth.network",
"author": {
Expand All @@ -21,42 +21,37 @@
},
"scripts": {
"build": "tsc",
"example-client": "pnpm run build && node lib/examples/EvmPriceServiceClient.js",
"example-relay": "pnpm run build && node lib/examples/EvmRelay.js",
"example-benchmark": "pnpm run build && node lib/examples/EvmBenchmark.js",
"test:format": "prettier --check \"src/**/*.ts\"",
"test:lint": "eslint src/ --max-warnings 0",
"fix:format": "prettier --write \"src/**/*.ts\"",
"fix:lint": "eslint src/ --fix --max-warnings 0",
"prepublishOnly": "pnpm run build && pnpm run test:lint",
"preversion": "pnpm run test:lint",
"version": "pnpm run format && git add -A src"
"version": "pnpm run test:format && git add -A src"
},
"keywords": [
"pyth",
"oracle"
],
"license": "Apache-2.0",
"devDependencies": {
"@cprussin/eslint-config": "catalog:",
"@pythnetwork/pyth-sdk-solidity": "workspace:*",
"@truffle/hdwallet-provider": "^2.1.5",
"@types/ethereum-protocol": "^1.0.2",
"@types/jest": "^29.4.0",
"@types/node": "^18.11.18",
"@types/web3-provider-engine": "^14.0.1",
"@types/yargs": "^17.0.10",
"@typescript-eslint/eslint-plugin": "^5.21.0",
"@typescript-eslint/parser": "^5.21.0",
"eslint": "^8.14.0",
"eslint": "catalog:",
"jest": "^29.4.1",
"prettier": "catalog:",
"ts-jest": "^29.0.5",
"typescript": "^4.6.3",
"web3": "^1.8.2",
"yargs": "^17.4.1"
"ts-node": "catalog:",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this dependency used anywhere?

"typescript": "catalog:"
},
"dependencies": {
"@pythnetwork/price-service-client": "workspace:*",
"buffer": "^6.0.3"
"@pythnetwork/hermes-client": "workspace:*",
"viem": "catalog:"
}
}
21 changes: 0 additions & 21 deletions target_chains/ethereum/sdk/js/src/EvmPriceServiceConnection.ts

This file was deleted.

Loading
Loading