optke3 2 éve
szülő
commit
661a3f901e

+ 1 - 1
target_chains/sui/scripts/pyth_create_price_feed.ts

@@ -21,7 +21,7 @@ const walletPrivateKey = process.env.SUI_TESTNET_BASE_64;
 
 async function main() {
     if (walletPrivateKey === undefined) {
-      throw new Error("SUI_TESTNET unset in environment");
+      throw new Error("SUI KEY unset in environment");
     }
     const wallet = new RawSigner(
         Ed25519Keypair.fromSecretKey(

+ 9 - 0
target_chains/sui/sdk/.eslintrc.js

@@ -0,0 +1,9 @@
+module.exports = {
+  root: true,
+  parser: "@typescript-eslint/parser",
+  plugins: ["@typescript-eslint"],
+  extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
+  rules: {
+    "@typescript-eslint/no-explicit-any": "off",
+  },
+};

+ 1 - 0
target_chains/sui/sdk/.gitignore

@@ -0,0 +1 @@
+lib

+ 140 - 0
target_chains/sui/sdk/README.md

@@ -0,0 +1,140 @@
+# Pyth Aptos 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 Aptos networks.
+
+## Installation
+
+### npm
+
+```
+$ npm install --save @pythnetwork/pyth-aptos-js
+```
+
+### Yarn
+
+```
+$ yarn add @pythnetwork/pyth-aptos-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/consume-data/on-demand) for more information about this approach.
+To use Pyth prices on chain,
+they must be fetched from an off-chain price service. The `AptosPriceServiceConnection` 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 AptosPriceServiceConnection(
+  "https://xc-testnet.pyth.network"
+); // See Price Service endpoints section below for other endpoints
+
+const priceIds = [
+  // You can find the ids of prices at https://pyth.network/developers/price-feed-ids#aptos-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. Then your contract should
+// call the Pyth Contract with this data.
+const priceUpdateData = await connection.getPriceFeedsUpdateData(priceIds);
+
+// Create a transaction and submit to your contract using the price update data
+const client = new AptosClient(endpoint);
+let result = await client.generateSignSubmitWaitForTransaction(
+  sender,
+  new TxnBuilderTypes.TransactionPayloadEntryFunction(
+    TxnBuilderTypes.EntryFunction.natural(
+      "0x..::your_module",
+      "do_something",
+      [],
+      [priceUpdateData]
+    )
+  )
+);
+```
+
+`your_module::do_something` should then call `pyth::update_price_feeds` before querying the data using `pyth::get_price`:
+
+```move
+module example::your_module {
+    use pyth::pyth;
+    use pyth::price_identifier;
+    use aptos_framework::coin;
+
+    public fun do_something(user: &signer, pyth_update_data: vector<vector<u8>>) {
+        // First update the Pyth price feeds. The user pays the fee for the update.
+        let coins = coin::withdraw(user, pyth::get_update_fee(pyth_update_data));
+
+        pyth::update_price_feeds(pyth_update_data, coins);
+
+        // Now we can use the prices which we have just updated
+        let btc_usd_price_id = price_identifier::from_byte_vec(
+            x"e62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43");
+        let price = pyth::get_price(btc_usd_price_id);
+
+    }
+}
+```
+
+We strongly recommend reading our guide which explains [how to work with Pyth price feeds](https://docs.pyth.network/consume-data/best-practices).
+
+### Off-chain prices
+
+Many applications additionally need to display Pyth prices off-chain, for example, in their frontend application.
+The `AptosPriceServiceConnection` 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:
+
+```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);
+```
+
+### Example
+
+[This example](./src/examples/AptosRelay.ts) shows how to update prices on an Aptos network. It does the following:
+
+1. Fetches update data from the Price Service for the given price feeds.
+2. Calls the Pyth Aptos contract with the update data.
+
+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 this:
+
+```bash
+export APTOS_KEY = "0x...";
+npm run example-relay -- --endpoint https://xc-testnet.pyth.network --price-ids 0xf9c0172ba10dfa4d19088d94f5bf61d3b54d5bd7483a322a982e1373ee8ea31b 0xca80ba6dc32e08d06f1aa886011eed1d77c77be9eb761cc10d72b7d0a2fd57a6 --full-node https://fullnode.testnet.aptoslabs.com/v1 --pyth-contract 0xaa706d631cde8c634fe1876b0c93e4dec69d0c6ccac30a734e9e257042e81541
+```
+
+## Price Service endpoints
+
+We provide public endpoints for the price service, although it is strongly recommended to host your own instance.
+
+| Aptos Network | Price Service URL               |
+| ------------- | ------------------------------- |
+| Testnet       | https://xc-testnet.pyth.network |
+| Mainnet       | https://xc-mainnet.pyth.network |

+ 5 - 0
target_chains/sui/sdk/jest.config.js

@@ -0,0 +1,5 @@
+/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
+module.exports = {
+  preset: "ts-jest",
+  testEnvironment: "node",
+};

+ 59 - 0
target_chains/sui/sdk/package.json

@@ -0,0 +1,59 @@
+{
+  "name": "@pythnetwork/pyth-sui-js",
+  "version": "1.0.2",
+  "description": "Pyth Network Sui Utilities",
+  "homepage": "https://pyth.network",
+  "author": {
+    "name": "Pyth Data Association"
+  },
+  "main": "lib/index.js",
+  "types": "lib/index.d.ts",
+  "files": [
+    "lib/**/*"
+  ],
+  "repository": {
+    "type": "git",
+    "url": "https://github.com/pyth-network/pyth-crosschain",
+    "directory": "target_chains/sui/sdk/js"
+  },
+  "publishConfig": {
+    "access": "public"
+  },
+  "scripts": {
+    "test": "jest --passWithNoTests",
+    "build": "tsc",
+    "example-relay": "npm run build && node lib/examples/AptosRelay.js",
+    "format": "prettier --write \"src/**/*.ts\"",
+    "lint": "eslint src/",
+    "prepublishOnly": "npm run build && npm test && npm run lint",
+    "preversion": "npm run lint",
+    "version": "npm run format && git add -A src"
+  },
+  "keywords": [
+    "pyth",
+    "oracle"
+  ],
+  "license": "Apache-2.0",
+  "devDependencies": {
+    "@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",
+    "jest": "^29.4.1",
+    "prettier": "^2.6.2",
+    "ts-jest": "^29.0.5",
+    "typescript": "^4.6.3",
+    "web3": "^1.8.2",
+    "yargs": "^17.4.1"
+  },
+  "dependencies": {
+    "@pythnetwork/price-service-client": "*",
+    "aptos": "^1.3.14",
+    "buffer": "^6.0.3"
+  }
+}

+ 21 - 0
target_chains/sui/sdk/src/SuiPriceServiceConnection.ts

@@ -0,0 +1,21 @@
+import {
+  PriceServiceConnection,
+  HexString,
+} from "@pythnetwork/price-service-client";
+import { Buffer } from "buffer";
+
+export class AptosPriceServiceConnection extends PriceServiceConnection {
+  /**
+   * Gets price update data which then can be submitted to the Pyth contract to update the prices.
+   * This will throw an axios error if there is a network problem or the price service returns a non-ok response (e.g: Invalid price ids)
+   *
+   * @param priceIds Array of hex-encoded price ids.
+   * @returns Array of price update data.
+   */
+  async getPriceFeedsUpdateData(priceIds: HexString[]): Promise<number[][]> {
+    // Fetch the latest price feed update VAAs from the price service
+    const latestVaas = await this.getLatestVaas(priceIds);
+    return latestVaas.map((vaa) => Array.from(Buffer.from(vaa, "base64")));
+  }
+
+}

+ 10 - 0
target_chains/sui/sdk/src/index.ts

@@ -0,0 +1,10 @@
+export { AptosPriceServiceConnection } from "./SuiPriceServiceConnection";
+
+export {
+  DurationInMs,
+  HexString,
+  Price,
+  PriceFeed,
+  PriceServiceConnectionConfig,
+  UnixTimestamp,
+} from "@pythnetwork/price-service-client";

+ 12 - 0
target_chains/sui/sdk/tsconfig.json

@@ -0,0 +1,12 @@
+{
+  "compilerOptions": {
+    "target": "esnext",
+    "module": "commonjs",
+    "declaration": true,
+    "outDir": "./lib",
+    "strict": true,
+    "esModuleInterop": true
+  },
+  "include": ["src"],
+  "exclude": ["node_modules", "**/__tests__/*"]
+}