@gearbox-protocol/sdk 12.9.9 → 12.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/cjs/permissionless/utils/price-update/get-prices.js +0 -3
  2. package/dist/cjs/permissionless/utils/price-update/get-updatable-feeds.js +2 -9
  3. package/dist/cjs/sdk/GearboxSDK.js +7 -17
  4. package/dist/cjs/sdk/market/pricefeeds/PriceFeedsRegister.js +1 -4
  5. package/dist/cjs/sdk/market/pricefeeds/PythPriceFeed.js +3 -27
  6. package/dist/cjs/sdk/market/pricefeeds/index.js +0 -2
  7. package/dist/cjs/sdk/market/pricefeeds/updates/index.js +0 -7
  8. package/dist/cjs/sdk/options.js +0 -4
  9. package/dist/esm/permissionless/utils/price-update/get-prices.js +0 -3
  10. package/dist/esm/permissionless/utils/price-update/get-updatable-feeds.js +2 -10
  11. package/dist/esm/sdk/GearboxSDK.js +7 -17
  12. package/dist/esm/sdk/market/pricefeeds/PriceFeedsRegister.js +2 -5
  13. package/dist/esm/sdk/market/pricefeeds/PythPriceFeed.js +4 -28
  14. package/dist/esm/sdk/market/pricefeeds/index.js +0 -2
  15. package/dist/esm/sdk/market/pricefeeds/updates/index.js +0 -4
  16. package/dist/esm/sdk/options.js +1 -8
  17. package/dist/types/sdk/market/pricefeeds/PriceFeedsRegister.d.ts +1 -2
  18. package/dist/types/sdk/market/pricefeeds/PythPriceFeed.d.ts +2 -25
  19. package/dist/types/sdk/market/pricefeeds/index.d.ts +1 -1
  20. package/dist/types/sdk/market/pricefeeds/updates/index.d.ts +0 -2
  21. package/dist/types/sdk/options.d.ts +0 -6
  22. package/package.json +5 -2
  23. package/dist/cjs/sdk/market/pricefeeds/updates/PythAccumulatorUpdateData.js +0 -195
  24. package/dist/cjs/sdk/market/pricefeeds/updates/PythUpdater.js +0 -183
  25. package/dist/cjs/sdk/market/pricefeeds/updates/fetchPythPayloads.js +0 -135
  26. package/dist/esm/sdk/market/pricefeeds/updates/PythAccumulatorUpdateData.js +0 -157
  27. package/dist/esm/sdk/market/pricefeeds/updates/PythUpdater.js +0 -158
  28. package/dist/esm/sdk/market/pricefeeds/updates/fetchPythPayloads.js +0 -115
  29. package/dist/types/sdk/market/pricefeeds/updates/PythAccumulatorUpdateData.d.ts +0 -41
  30. package/dist/types/sdk/market/pricefeeds/updates/PythUpdater.d.ts +0 -26
  31. package/dist/types/sdk/market/pricefeeds/updates/fetchPythPayloads.d.ts +0 -45
@@ -1,195 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var PythAccumulatorUpdateData_exports = {};
30
- __export(PythAccumulatorUpdateData_exports, {
31
- isAccumulatorUpdateData: () => isAccumulatorUpdateData,
32
- parseAccumulatorUpdateData: () => parseAccumulatorUpdateData,
33
- parsePriceFeedMessage: () => parsePriceFeedMessage,
34
- parseTwapMessage: () => parseTwapMessage,
35
- sliceAccumulatorUpdateData: () => sliceAccumulatorUpdateData
36
- });
37
- module.exports = __toCommonJS(PythAccumulatorUpdateData_exports);
38
- var import_bn = __toESM(require("bn.js"));
39
- var import_buffer = require("buffer");
40
- const ACCUMULATOR_MAGIC = "504e4155";
41
- const MAJOR_VERSION = 1;
42
- const MINOR_VERSION = 0;
43
- const KECCAK160_HASH_SIZE = 20;
44
- const PRICE_FEED_MESSAGE_VARIANT = 0;
45
- const TWAP_MESSAGE_VARIANT = 1;
46
- function isAccumulatorUpdateData(updateBytes) {
47
- return updateBytes.toString("hex").slice(0, 8) === ACCUMULATOR_MAGIC && updateBytes[4] === MAJOR_VERSION && updateBytes[5] === MINOR_VERSION;
48
- }
49
- function parsePriceFeedMessage(message) {
50
- let cursor = 0;
51
- const variant = message.readUInt8(cursor);
52
- if (variant !== PRICE_FEED_MESSAGE_VARIANT) {
53
- throw new Error("Not a price feed message");
54
- }
55
- cursor += 1;
56
- const feedId = message.subarray(cursor, cursor + 32);
57
- cursor += 32;
58
- const price = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
59
- cursor += 8;
60
- const confidence = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
61
- cursor += 8;
62
- const exponent = message.readInt32BE(cursor);
63
- cursor += 4;
64
- const publishTime = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
65
- cursor += 8;
66
- const prevPublishTime = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
67
- cursor += 8;
68
- const emaPrice = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
69
- cursor += 8;
70
- const emaConf = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
71
- cursor += 8;
72
- return {
73
- feedId,
74
- price,
75
- confidence,
76
- exponent,
77
- publishTime,
78
- prevPublishTime,
79
- emaPrice,
80
- emaConf
81
- };
82
- }
83
- function parseTwapMessage(message) {
84
- let cursor = 0;
85
- const variant = message.readUInt8(cursor);
86
- if (variant !== TWAP_MESSAGE_VARIANT) {
87
- throw new Error("Not a twap message");
88
- }
89
- cursor += 1;
90
- const feedId = message.subarray(cursor, cursor + 32);
91
- cursor += 32;
92
- const cumulativePrice = new import_bn.default(message.subarray(cursor, cursor + 16), "be");
93
- cursor += 16;
94
- const cumulativeConf = new import_bn.default(message.subarray(cursor, cursor + 16), "be");
95
- cursor += 16;
96
- const numDownSlots = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
97
- cursor += 8;
98
- const exponent = message.readInt32BE(cursor);
99
- cursor += 4;
100
- const publishTime = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
101
- cursor += 8;
102
- const prevPublishTime = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
103
- cursor += 8;
104
- const publishSlot = new import_bn.default(message.subarray(cursor, cursor + 8), "be");
105
- cursor += 8;
106
- return {
107
- feedId,
108
- cumulativePrice,
109
- cumulativeConf,
110
- numDownSlots,
111
- exponent,
112
- publishTime,
113
- prevPublishTime,
114
- publishSlot
115
- };
116
- }
117
- function sliceAccumulatorUpdateData(data, start, end) {
118
- if (!isAccumulatorUpdateData(data)) {
119
- throw new Error("Invalid accumulator message");
120
- }
121
- let cursor = 6;
122
- const trailingPayloadSize = data.readUint8(cursor);
123
- cursor += 1 + trailingPayloadSize;
124
- cursor += 1;
125
- const vaaSize = data.readUint16BE(cursor);
126
- cursor += 2;
127
- cursor += vaaSize;
128
- const endOfVaa = cursor;
129
- const updates = [];
130
- const numUpdates = data.readUInt8(cursor);
131
- cursor += 1;
132
- for (let i = 0; i < numUpdates; i++) {
133
- const updateStart = cursor;
134
- const messageSize = data.readUint16BE(cursor);
135
- cursor += 2;
136
- cursor += messageSize;
137
- const numProofs = data.readUInt8(cursor);
138
- cursor += 1;
139
- cursor += KECCAK160_HASH_SIZE * numProofs;
140
- updates.push(data.subarray(updateStart, cursor));
141
- }
142
- if (cursor !== data.length) {
143
- throw new Error("Didn't reach the end of the message");
144
- }
145
- const sliceUpdates = updates.slice(start, end);
146
- return import_buffer.Buffer.concat([
147
- data.subarray(0, endOfVaa),
148
- import_buffer.Buffer.from([sliceUpdates.length]),
149
- ...updates.slice(start, end)
150
- ]);
151
- }
152
- function parseAccumulatorUpdateData(data) {
153
- if (!isAccumulatorUpdateData(data)) {
154
- throw new Error("Invalid accumulator message");
155
- }
156
- let cursor = 6;
157
- const trailingPayloadSize = data.readUint8(cursor);
158
- cursor += 1 + trailingPayloadSize;
159
- cursor += 1;
160
- const vaaSize = data.readUint16BE(cursor);
161
- cursor += 2;
162
- const vaa = data.subarray(cursor, cursor + vaaSize);
163
- cursor += vaaSize;
164
- const numUpdates = data.readUInt8(cursor);
165
- const updates = [];
166
- cursor += 1;
167
- for (let i = 0; i < numUpdates; i++) {
168
- const messageSize = data.readUint16BE(cursor);
169
- cursor += 2;
170
- const message = data.subarray(cursor, cursor + messageSize);
171
- cursor += messageSize;
172
- const numProofs = data.readUInt8(cursor);
173
- cursor += 1;
174
- const proof = [];
175
- for (let j = 0; j < numProofs; j++) {
176
- proof.push(
177
- Array.from(data.subarray(cursor, cursor + KECCAK160_HASH_SIZE))
178
- );
179
- cursor += KECCAK160_HASH_SIZE;
180
- }
181
- updates.push({ message, proof });
182
- }
183
- if (cursor !== data.length) {
184
- throw new Error("Didn't reach the end of the message");
185
- }
186
- return { vaa, updates };
187
- }
188
- // Annotate the CommonJS export names for ESM import in node:
189
- 0 && (module.exports = {
190
- isAccumulatorUpdateData,
191
- parseAccumulatorUpdateData,
192
- parsePriceFeedMessage,
193
- parseTwapMessage,
194
- sliceAccumulatorUpdateData
195
- });
@@ -1,183 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var PythUpdater_exports = {};
20
- __export(PythUpdater_exports, {
21
- PythOptions: () => PythOptions,
22
- PythUpdater: () => PythUpdater
23
- });
24
- module.exports = __toCommonJS(PythUpdater_exports);
25
- var import_v4 = require("zod/v4");
26
- var import_base = require("../../../base/index.js");
27
- var import_fetchPythPayloads = require("./fetchPythPayloads.js");
28
- var import_PriceUpdatesCache = require("./PriceUpdatesCache.js");
29
- var import_PriceUpdateTx = require("./PriceUpdateTx.js");
30
- class PythUpdateTx extends import_PriceUpdateTx.PriceUpdateTx {
31
- name = "pyth";
32
- }
33
- const PythOptions = import_v4.z.object({
34
- /**
35
- * Fixed pyth historic timestamp in seconds
36
- * Set to true to enable pyth historical mode using timestamp from attach block
37
- */
38
- historicTimestamp: import_v4.z.union([import_v4.z.number().nonnegative(), import_v4.z.literal(true)]).optional(),
39
- /**
40
- * Override Hermes API with this proxy. Can be used to set caching proxies, to avoid rate limiting
41
- */
42
- apiProxy: import_v4.z.url().optional(),
43
- /**
44
- * TTL for pyth cache in milliseconds
45
- * If 0, disables caching
46
- * If not set, uses some default value
47
- * Cache is always enabled in historical mode
48
- */
49
- cacheTTL: import_v4.z.number().nonnegative().optional(),
50
- /**
51
- * When true, no error will be thrown when pyth is unable to fetch data for some feeds
52
- */
53
- ignoreMissingFeeds: import_v4.z.boolean().optional()
54
- });
55
- class PythUpdater extends import_base.SDKConstruct {
56
- #cache;
57
- #historicalTimestamp;
58
- #apiProxy;
59
- #ignoreMissingFeeds;
60
- constructor(sdk, opts = {}) {
61
- super(sdk);
62
- const { apiProxy, cacheTTL, ignoreMissingFeeds, historicTimestamp } = opts;
63
- this.#ignoreMissingFeeds = ignoreMissingFeeds;
64
- this.#apiProxy = apiProxy;
65
- if (historicTimestamp) {
66
- this.#historicalTimestamp = historicTimestamp === true ? Number(this.sdk.timestamp) : historicTimestamp;
67
- this.logger?.debug(
68
- `using historical timestamp ${this.#historicalTimestamp}`
69
- );
70
- }
71
- this.#cache = import_PriceUpdatesCache.PriceUpdatesCache.get("pyth", {
72
- // currently staleness period is 240 seconds on all networks, add some buffer
73
- // this period of 4 minutes is selected based on time that is required for user to sign transaction with wallet
74
- // so it's unlikely to decrease
75
- ttl: cacheTTL ?? 225 * 1e3,
76
- historical: !!historicTimestamp
77
- });
78
- }
79
- async getUpdateTxs(feeds) {
80
- if (feeds.length === 0) {
81
- return [];
82
- }
83
- this.logger?.debug(
84
- `generating update transactions for ${feeds.length} pyth price feeds`
85
- );
86
- const pythFeeds = new Map(
87
- feeds.filter(isPyth).map((f) => [f.priceFeedId, f])
88
- );
89
- const payloads = await this.#getPayloads(new Set(pythFeeds.keys()));
90
- let [minTimestamp, maxTimestamp] = [Number.POSITIVE_INFINITY, 0];
91
- const results = [];
92
- for (const p of payloads) {
93
- const priceFeed = pythFeeds.get(p.dataFeedId);
94
- if (!priceFeed) {
95
- throw new Error(`cannot find price feed for ${p.dataFeedId}`);
96
- }
97
- const { dataFeedId, timestamp, cached, data } = p;
98
- minTimestamp = Math.min(minTimestamp, timestamp);
99
- maxTimestamp = Math.max(maxTimestamp, timestamp);
100
- results.push(
101
- new PythUpdateTx(priceFeed.createPriceUpdateTx(data), {
102
- dataFeedId,
103
- priceFeed: priceFeed.address,
104
- timestamp,
105
- cached
106
- })
107
- );
108
- }
109
- let tsRange = "";
110
- if (results.length) {
111
- const minDelta = BigInt(minTimestamp) - this.sdk.timestamp;
112
- tsRange = `, timestamps ${minTimestamp} (${minDelta})`;
113
- if (minTimestamp !== maxTimestamp) {
114
- const maxDelta = BigInt(maxTimestamp) - this.sdk.timestamp;
115
- tsRange = `${tsRange} - ${maxTimestamp} (${maxDelta})`;
116
- }
117
- }
118
- this.logger?.debug(
119
- `generated ${results.length} update transactions for pyth price feeds: ${Array.from(pythFeeds.keys()).join(", ")}${tsRange}`
120
- );
121
- return results;
122
- }
123
- /**
124
- * Gets pyth payloads
125
- * @param dataFeedsIds
126
- * @returns
127
- */
128
- async #getPayloads(dataFeedsIds) {
129
- this.logger?.debug(
130
- `getting pyth payloads for ${dataFeedsIds.size} price feeds: ${Array.from(dataFeedsIds).join(", ")}`
131
- );
132
- const fromCache = [];
133
- const uncached = [];
134
- for (const priceFeedsId of dataFeedsIds) {
135
- const cached = this.#cache.get(priceFeedsId);
136
- if (cached) {
137
- fromCache.push({ ...cached, cached: true });
138
- } else {
139
- uncached.push(priceFeedsId);
140
- }
141
- }
142
- const fromPyth = await this.#fetchPayloads(
143
- new Set(uncached)
144
- );
145
- for (const resp of fromPyth) {
146
- this.#cache.set(resp, resp.dataFeedId);
147
- }
148
- this.logger?.debug(
149
- `got ${fromPyth.length} new pyth updates and ${fromCache.length} from cache`
150
- );
151
- return [...fromCache, ...fromPyth];
152
- }
153
- /**
154
- * Fetches pyth payloads from Hermes API
155
- * @param dataFeedsIds
156
- * @returns
157
- */
158
- async #fetchPayloads(dataFeedsIds) {
159
- if (dataFeedsIds.size === 0) {
160
- return [];
161
- }
162
- const ids = Array.from(dataFeedsIds);
163
- const tsStr = this.#historicalTimestamp ? ` with historical timestamp ${this.#historicalTimestamp}` : "";
164
- this.logger?.debug(
165
- `fetching pyth payloads for ${dataFeedsIds.size} price feeds: ${ids.join(", ")}${tsStr}`
166
- );
167
- return (0, import_fetchPythPayloads.fetchPythPayloads)({
168
- dataFeedsIds,
169
- historicalTimestampSeconds: this.#historicalTimestamp,
170
- apiProxy: this.#apiProxy,
171
- ignoreMissingFeeds: this.#ignoreMissingFeeds,
172
- logger: this.logger
173
- });
174
- }
175
- }
176
- function isPyth(pf) {
177
- return pf.contractType === "PRICE_FEED::PYTH";
178
- }
179
- // Annotate the CommonJS export names for ESM import in node:
180
- 0 && (module.exports = {
181
- PythOptions,
182
- PythUpdater
183
- });
@@ -1,135 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var fetchPythPayloads_exports = {};
20
- __export(fetchPythPayloads_exports, {
21
- fetchPythPayloads: () => fetchPythPayloads
22
- });
23
- module.exports = __toCommonJS(fetchPythPayloads_exports);
24
- var import_buffer = require("buffer");
25
- var import_viem = require("viem");
26
- var import_utils = require("../../../utils/index.js");
27
- var import_PythAccumulatorUpdateData = require("./PythAccumulatorUpdateData.js");
28
- async function fetchPythPayloads(options) {
29
- const {
30
- dataFeedsIds,
31
- ignoreMissingFeeds,
32
- historicalTimestampSeconds,
33
- logger,
34
- apiProxy,
35
- customFetch = fetch,
36
- returnPrices
37
- } = options;
38
- const ids = Array.from(new Set(dataFeedsIds)).sort();
39
- if (ids.length === 0) {
40
- return [];
41
- }
42
- let api = apiProxy ?? "https://hermes.pyth.network/v2/updates/price/";
43
- api = api.endsWith("/") ? api : `${api}/`;
44
- const url = new URL(api + (historicalTimestampSeconds ?? "latest"));
45
- url.searchParams.append("parsed", returnPrices ? "true" : "false");
46
- if (ignoreMissingFeeds) {
47
- url.searchParams.append("ignore_invalid_price_ids", "true");
48
- }
49
- for (const id of ids) {
50
- url.searchParams.append("ids[]", id);
51
- }
52
- const resp = await (0, import_utils.retry)(
53
- async () => {
54
- const resp2 = await customFetch(url.toString());
55
- if (!resp2.ok) {
56
- const body = await resp2.text();
57
- throw new Error(
58
- `failed to fetch pyth payloads: ${resp2.statusText}: ${body}`
59
- );
60
- }
61
- const data = await resp2.json();
62
- return data;
63
- },
64
- { attempts: 3, exponent: 2, interval: 200 }
65
- );
66
- const result = respToCalldata(resp, returnPrices);
67
- if (result.length !== ids.length) {
68
- if (ignoreMissingFeeds) {
69
- logger?.warn(`expected ${ids.length} price feeds, got ${result.length}`);
70
- } else {
71
- throw new Error(
72
- `expected ${ids.length} price feeds, got ${result.length}`
73
- );
74
- }
75
- }
76
- return result;
77
- }
78
- function respToCalldata(resp, returnPrices) {
79
- if (resp.binary.data.length === 0) {
80
- return [];
81
- }
82
- const updates = splitAccumulatorUpdates(resp.binary.data[0]);
83
- const priceMap = /* @__PURE__ */ new Map();
84
- if (returnPrices && resp.parsed) {
85
- for (const feed of resp.parsed) {
86
- const feedId = feed.id.startsWith("0x") ? feed.id : `0x${feed.id}`;
87
- priceMap.set(feedId.toLowerCase(), {
88
- price: BigInt(feed.price.price),
89
- decimals: Math.abs(feed.price.expo)
90
- });
91
- }
92
- }
93
- return updates.map(({ data, dataFeedId, timestamp }) => {
94
- const base = {
95
- dataFeedId,
96
- data: (0, import_viem.encodeAbiParameters)(
97
- [{ type: "uint256" }, { type: "bytes[]" }],
98
- [BigInt(timestamp), [data]]
99
- ),
100
- timestamp,
101
- cached: false
102
- };
103
- if (returnPrices) {
104
- const priceInfo = priceMap.get(dataFeedId.toLowerCase());
105
- if (!priceInfo) {
106
- throw new Error(`Price info not found for feed ${dataFeedId}`);
107
- }
108
- return {
109
- ...base,
110
- price: priceInfo.price,
111
- decimals: priceInfo.decimals
112
- };
113
- }
114
- return base;
115
- });
116
- }
117
- function splitAccumulatorUpdates(binary) {
118
- const data = import_buffer.Buffer.from(binary, "hex");
119
- const parsed = (0, import_PythAccumulatorUpdateData.parseAccumulatorUpdateData)(data);
120
- const results = [];
121
- for (let i = 0; i < parsed.updates.length; i++) {
122
- const upd = parsed.updates[i].message;
123
- const msg = (0, import_PythAccumulatorUpdateData.parsePriceFeedMessage)(upd);
124
- results.push({
125
- dataFeedId: (0, import_viem.toHex)(msg.feedId),
126
- timestamp: msg.publishTime.toNumber(),
127
- data: (0, import_viem.toHex)((0, import_PythAccumulatorUpdateData.sliceAccumulatorUpdateData)(data, i, i + 1))
128
- });
129
- }
130
- return results;
131
- }
132
- // Annotate the CommonJS export names for ESM import in node:
133
- 0 && (module.exports = {
134
- fetchPythPayloads
135
- });
@@ -1,157 +0,0 @@
1
- import BN from "bn.js";
2
- import { Buffer } from "buffer";
3
- const ACCUMULATOR_MAGIC = "504e4155";
4
- const MAJOR_VERSION = 1;
5
- const MINOR_VERSION = 0;
6
- const KECCAK160_HASH_SIZE = 20;
7
- const PRICE_FEED_MESSAGE_VARIANT = 0;
8
- const TWAP_MESSAGE_VARIANT = 1;
9
- function isAccumulatorUpdateData(updateBytes) {
10
- return updateBytes.toString("hex").slice(0, 8) === ACCUMULATOR_MAGIC && updateBytes[4] === MAJOR_VERSION && updateBytes[5] === MINOR_VERSION;
11
- }
12
- function parsePriceFeedMessage(message) {
13
- let cursor = 0;
14
- const variant = message.readUInt8(cursor);
15
- if (variant !== PRICE_FEED_MESSAGE_VARIANT) {
16
- throw new Error("Not a price feed message");
17
- }
18
- cursor += 1;
19
- const feedId = message.subarray(cursor, cursor + 32);
20
- cursor += 32;
21
- const price = new BN(message.subarray(cursor, cursor + 8), "be");
22
- cursor += 8;
23
- const confidence = new BN(message.subarray(cursor, cursor + 8), "be");
24
- cursor += 8;
25
- const exponent = message.readInt32BE(cursor);
26
- cursor += 4;
27
- const publishTime = new BN(message.subarray(cursor, cursor + 8), "be");
28
- cursor += 8;
29
- const prevPublishTime = new BN(message.subarray(cursor, cursor + 8), "be");
30
- cursor += 8;
31
- const emaPrice = new BN(message.subarray(cursor, cursor + 8), "be");
32
- cursor += 8;
33
- const emaConf = new BN(message.subarray(cursor, cursor + 8), "be");
34
- cursor += 8;
35
- return {
36
- feedId,
37
- price,
38
- confidence,
39
- exponent,
40
- publishTime,
41
- prevPublishTime,
42
- emaPrice,
43
- emaConf
44
- };
45
- }
46
- function parseTwapMessage(message) {
47
- let cursor = 0;
48
- const variant = message.readUInt8(cursor);
49
- if (variant !== TWAP_MESSAGE_VARIANT) {
50
- throw new Error("Not a twap message");
51
- }
52
- cursor += 1;
53
- const feedId = message.subarray(cursor, cursor + 32);
54
- cursor += 32;
55
- const cumulativePrice = new BN(message.subarray(cursor, cursor + 16), "be");
56
- cursor += 16;
57
- const cumulativeConf = new BN(message.subarray(cursor, cursor + 16), "be");
58
- cursor += 16;
59
- const numDownSlots = new BN(message.subarray(cursor, cursor + 8), "be");
60
- cursor += 8;
61
- const exponent = message.readInt32BE(cursor);
62
- cursor += 4;
63
- const publishTime = new BN(message.subarray(cursor, cursor + 8), "be");
64
- cursor += 8;
65
- const prevPublishTime = new BN(message.subarray(cursor, cursor + 8), "be");
66
- cursor += 8;
67
- const publishSlot = new BN(message.subarray(cursor, cursor + 8), "be");
68
- cursor += 8;
69
- return {
70
- feedId,
71
- cumulativePrice,
72
- cumulativeConf,
73
- numDownSlots,
74
- exponent,
75
- publishTime,
76
- prevPublishTime,
77
- publishSlot
78
- };
79
- }
80
- function sliceAccumulatorUpdateData(data, start, end) {
81
- if (!isAccumulatorUpdateData(data)) {
82
- throw new Error("Invalid accumulator message");
83
- }
84
- let cursor = 6;
85
- const trailingPayloadSize = data.readUint8(cursor);
86
- cursor += 1 + trailingPayloadSize;
87
- cursor += 1;
88
- const vaaSize = data.readUint16BE(cursor);
89
- cursor += 2;
90
- cursor += vaaSize;
91
- const endOfVaa = cursor;
92
- const updates = [];
93
- const numUpdates = data.readUInt8(cursor);
94
- cursor += 1;
95
- for (let i = 0; i < numUpdates; i++) {
96
- const updateStart = cursor;
97
- const messageSize = data.readUint16BE(cursor);
98
- cursor += 2;
99
- cursor += messageSize;
100
- const numProofs = data.readUInt8(cursor);
101
- cursor += 1;
102
- cursor += KECCAK160_HASH_SIZE * numProofs;
103
- updates.push(data.subarray(updateStart, cursor));
104
- }
105
- if (cursor !== data.length) {
106
- throw new Error("Didn't reach the end of the message");
107
- }
108
- const sliceUpdates = updates.slice(start, end);
109
- return Buffer.concat([
110
- data.subarray(0, endOfVaa),
111
- Buffer.from([sliceUpdates.length]),
112
- ...updates.slice(start, end)
113
- ]);
114
- }
115
- function parseAccumulatorUpdateData(data) {
116
- if (!isAccumulatorUpdateData(data)) {
117
- throw new Error("Invalid accumulator message");
118
- }
119
- let cursor = 6;
120
- const trailingPayloadSize = data.readUint8(cursor);
121
- cursor += 1 + trailingPayloadSize;
122
- cursor += 1;
123
- const vaaSize = data.readUint16BE(cursor);
124
- cursor += 2;
125
- const vaa = data.subarray(cursor, cursor + vaaSize);
126
- cursor += vaaSize;
127
- const numUpdates = data.readUInt8(cursor);
128
- const updates = [];
129
- cursor += 1;
130
- for (let i = 0; i < numUpdates; i++) {
131
- const messageSize = data.readUint16BE(cursor);
132
- cursor += 2;
133
- const message = data.subarray(cursor, cursor + messageSize);
134
- cursor += messageSize;
135
- const numProofs = data.readUInt8(cursor);
136
- cursor += 1;
137
- const proof = [];
138
- for (let j = 0; j < numProofs; j++) {
139
- proof.push(
140
- Array.from(data.subarray(cursor, cursor + KECCAK160_HASH_SIZE))
141
- );
142
- cursor += KECCAK160_HASH_SIZE;
143
- }
144
- updates.push({ message, proof });
145
- }
146
- if (cursor !== data.length) {
147
- throw new Error("Didn't reach the end of the message");
148
- }
149
- return { vaa, updates };
150
- }
151
- export {
152
- isAccumulatorUpdateData,
153
- parseAccumulatorUpdateData,
154
- parsePriceFeedMessage,
155
- parseTwapMessage,
156
- sliceAccumulatorUpdateData
157
- };