@pythnetwork/hermes-client 2.0.0 → 2.1.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.
package/README.md CHANGED
@@ -9,13 +9,13 @@ This library is a client for interacting with Hermes, allowing your application
9
9
  ### npm
10
10
 
11
11
  ```
12
- $ npm install --save @pythnetwork/hermes-client
12
+ npm install --save @pythnetwork/hermes-client
13
13
  ```
14
14
 
15
15
  ### Yarn
16
16
 
17
17
  ```
18
- $ yarn add @pythnetwork/hermes-client
18
+ yarn add @pythnetwork/hermes-client
19
19
  ```
20
20
 
21
21
  ## Quickstart
@@ -76,11 +76,12 @@ The [HermesClient](./src/examples/HermesClient.ts) example demonstrates both the
76
76
  examples above. To run the example:
77
77
 
78
78
  1. Clone [the Pyth monorepo](https://github.com/pyth-network/pyth-crosschain)
79
- 2. In the root of the monorepo, run `pnpm example:hermes-client -- <args>`. For
80
- example, to print BTC and ETH price feeds in the testnet network, run:
79
+ 2. In the root of the monorepo, run `pnpm turbo --filter
80
+ @pythnetwork/hermes-client example -- <args>`. For example, to print BTC and
81
+ ETH price feeds in the testnet network, run:
81
82
 
82
83
  ```bash
83
- pnpm example:hermes-client -- \
84
+ pnpm turbo --filter @pythnetwork/hermes-client example -- \
84
85
  --endpoint https://hermes.pyth.network \
85
86
  --price-ids \
86
87
  0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43 \
@@ -0,0 +1,220 @@
1
+ /* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/no-misused-spread */ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "HermesClient", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return HermesClient;
9
+ }
10
+ });
11
+ const _eventsource = require("eventsource");
12
+ const _utils = require("./utils.cjs");
13
+ const _zodSchemas = require("./zodSchemas.cjs");
14
+ const DEFAULT_TIMEOUT = 5000;
15
+ const DEFAULT_HTTP_RETRIES = 3;
16
+ class HermesClient {
17
+ baseURL;
18
+ timeout;
19
+ httpRetries;
20
+ headers;
21
+ /**
22
+ * Constructs a new Connection.
23
+ *
24
+ * @param endpoint - endpoint URL to the price service. Example: https://website/example/
25
+ * @param config - Optional HermesClientConfig for custom configurations.
26
+ */ constructor(endpoint, config){
27
+ this.baseURL = endpoint;
28
+ this.timeout = config?.timeout ?? DEFAULT_TIMEOUT;
29
+ this.httpRetries = config?.httpRetries ?? DEFAULT_HTTP_RETRIES;
30
+ this.headers = config?.headers ?? {};
31
+ }
32
+ async httpRequest(url, schema, options, retries = this.httpRetries, backoff = 100 + Math.floor(Math.random() * 100)) {
33
+ try {
34
+ const response = await fetch(url, {
35
+ ...options,
36
+ signal: AbortSignal.any([
37
+ ...options?.signal ? [
38
+ options.signal
39
+ ] : [],
40
+ AbortSignal.timeout(this.timeout)
41
+ ]),
42
+ headers: {
43
+ ...this.headers,
44
+ ...options?.headers
45
+ }
46
+ });
47
+ if (!response.ok) {
48
+ const errorBody = await response.text();
49
+ throw new Error(`HTTP error! status: ${response.status.toString()}${errorBody ? `, body: ${errorBody}` : ""}`);
50
+ }
51
+ const data = await response.json();
52
+ return schema.parse(data);
53
+ } catch (error) {
54
+ if (retries > 0 && !(error instanceof Error && error.name === "AbortError")) {
55
+ // Wait for a backoff period before retrying
56
+ await new Promise((resolve)=>setTimeout(resolve, backoff));
57
+ return this.httpRequest(url, schema, options, retries - 1, backoff * 2); // Exponential backoff
58
+ }
59
+ throw error;
60
+ }
61
+ }
62
+ /**
63
+ * Fetch the set of available price feeds.
64
+ * This endpoint can be filtered by asset type and query string.
65
+ * This will throw an error if there is a network problem or the price service returns a non-ok response.
66
+ *
67
+ * @param options - Optional parameters:
68
+ * - query: String to filter the price feeds. If provided, the results will be filtered to all price feeds whose symbol contains the query string. Query string is case insensitive. Example: "bitcoin".
69
+ * - assetType: String to filter the price feeds by asset type. Possible values are "crypto", "equity", "fx", "metal", "rates", "crypto_redemption_rate". Filter string is case insensitive.
70
+ *
71
+ * @returns Array of PriceFeedMetadata objects.
72
+ */ async getPriceFeeds({ fetchOptions, ...options } = {}) {
73
+ const url = this.buildURL("price_feeds");
74
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
75
+ if (options) {
76
+ const transformedOptions = (0, _utils.camelToSnakeCaseObject)(options);
77
+ this.appendUrlSearchParams(url, transformedOptions);
78
+ }
79
+ return await this.httpRequest(url.toString(), _zodSchemas.schemas.PriceFeedMetadata.array(), fetchOptions);
80
+ }
81
+ /**
82
+ * Fetch the latest publisher stake caps.
83
+ * This endpoint can be customized by specifying the encoding type and whether the results should also return the parsed publisher caps.
84
+ * This will throw an error if there is a network problem or the price service returns a non-ok response.
85
+ *
86
+ * @param options - Optional parameters:
87
+ * - encoding: Encoding type. If specified, return the publisher caps in the encoding specified by the encoding parameter. Default is hex.
88
+ * - parsed: Boolean to specify if the parsed publisher caps should be included in the response. Default is false.
89
+ *
90
+ * @returns PublisherCaps object containing the latest publisher stake caps.
91
+ */ async getLatestPublisherCaps({ fetchOptions, ...options } = {}) {
92
+ const url = this.buildURL("updates/publisher_stake_caps/latest");
93
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
94
+ if (options) {
95
+ this.appendUrlSearchParams(url, options);
96
+ }
97
+ return await this.httpRequest(url.toString(), _zodSchemas.schemas.LatestPublisherStakeCapsUpdateDataResponse, fetchOptions);
98
+ }
99
+ /**
100
+ * Fetch the latest price updates for a set of price feed IDs.
101
+ * This endpoint can be customized by specifying the encoding type and whether the results should also return the parsed price update using the options object.
102
+ * This will throw an error if there is a network problem or the price service returns a non-ok response.
103
+ *
104
+ * @param ids - Array of hex-encoded price feed IDs for which updates are requested.
105
+ * @param options - Optional parameters:
106
+ * - encoding: Encoding type. If specified, return the price update in the encoding specified by the encoding parameter. Default is hex.
107
+ * - parsed: Boolean to specify if the parsed price update should be included in the response. Default is false.
108
+ * - ignoreInvalidPriceIds: Boolean to specify if invalid price IDs should be ignored instead of returning an error. Default is false.
109
+ *
110
+ * @returns PriceUpdate object containing the latest updates.
111
+ */ async getLatestPriceUpdates(ids, options, fetchOptions) {
112
+ const url = this.buildURL("updates/price/latest");
113
+ for (const id of ids){
114
+ url.searchParams.append("ids[]", id);
115
+ }
116
+ if (options) {
117
+ const transformedOptions = (0, _utils.camelToSnakeCaseObject)(options);
118
+ this.appendUrlSearchParams(url, transformedOptions);
119
+ }
120
+ return this.httpRequest(url.toString(), _zodSchemas.schemas.PriceUpdate, fetchOptions);
121
+ }
122
+ /**
123
+ * Fetch the price updates for a set of price feed IDs at a given timestamp.
124
+ * This endpoint can be customized by specifying the encoding type and whether the results should also return the parsed price update.
125
+ * This will throw an error if there is a network problem or the price service returns a non-ok response.
126
+ *
127
+ * @param publishTime - Unix timestamp in seconds.
128
+ * @param ids - Array of hex-encoded price feed IDs for which updates are requested.
129
+ * @param options - Optional parameters:
130
+ * - encoding: Encoding type. If specified, return the price update in the encoding specified by the encoding parameter. Default is hex.
131
+ * - parsed: Boolean to specify if the parsed price update should be included in the response. Default is false.
132
+ * - ignoreInvalidPriceIds: Boolean to specify if invalid price IDs should be ignored instead of returning an error. Default is false.
133
+ *
134
+ * @returns PriceUpdate object containing the updates at the specified timestamp.
135
+ */ async getPriceUpdatesAtTimestamp(publishTime, ids, options, fetchOptions) {
136
+ const url = this.buildURL(`updates/price/${publishTime.toString()}`);
137
+ for (const id of ids){
138
+ url.searchParams.append("ids[]", id);
139
+ }
140
+ if (options) {
141
+ const transformedOptions = (0, _utils.camelToSnakeCaseObject)(options);
142
+ this.appendUrlSearchParams(url, transformedOptions);
143
+ }
144
+ return this.httpRequest(url.toString(), _zodSchemas.schemas.PriceUpdate, fetchOptions);
145
+ }
146
+ /**
147
+ * Fetch streaming price updates for a set of price feed IDs.
148
+ * This endpoint can be customized by specifying the encoding type, whether the results should include parsed updates,
149
+ * and if unordered updates or only benchmark updates are allowed.
150
+ * This will return an EventSource that can be used to listen to streaming updates.
151
+ * If an invalid hex-encoded ID is passed, it will throw an error.
152
+ *
153
+ * @param ids - Array of hex-encoded price feed IDs for which streaming updates are requested.
154
+ * @param options - Optional parameters:
155
+ * - encoding: Encoding type. If specified, updates are returned in the specified encoding. Default is hex.
156
+ * - parsed: Boolean to specify if the parsed price update should be included in the response. Default is false.
157
+ * - allowUnordered: Boolean to specify if unordered updates are allowed to be included in the stream. Default is false.
158
+ * - benchmarksOnly: Boolean to specify if only benchmark prices should be returned. Default is false.
159
+ * - ignoreInvalidPriceIds: Boolean to specify if invalid price IDs should be ignored instead of returning an error. Default is false.
160
+ *
161
+ * @returns An EventSource instance for receiving streaming updates.
162
+ */ async getPriceUpdatesStream(ids, options) {
163
+ const url = this.buildURL("updates/price/stream");
164
+ for (const id of ids){
165
+ url.searchParams.append("ids[]", id);
166
+ }
167
+ if (options) {
168
+ const transformedOptions = (0, _utils.camelToSnakeCaseObject)(options);
169
+ this.appendUrlSearchParams(url, transformedOptions);
170
+ }
171
+ return new _eventsource.EventSource(url.toString(), {
172
+ fetch: (input, init)=>fetch(input, {
173
+ ...init,
174
+ headers: {
175
+ ...init?.headers,
176
+ ...this.headers
177
+ }
178
+ })
179
+ });
180
+ }
181
+ /**
182
+ * Fetch the latest TWAP (time weighted average price) for a set of price feed IDs.
183
+ * This endpoint can be customized by specifying the encoding type and whether the results should also return the calculated TWAP using the options object.
184
+ * This will throw an error if there is a network problem or the price service returns a non-ok response.
185
+ *
186
+ * @param ids - Array of hex-encoded price feed IDs for which updates are requested.
187
+ * @param window_seconds - The time window in seconds over which to calculate the TWAP, ending at the current time.
188
+ * For example, a value of 300 would return the most recent 5 minute TWAP. Must be greater than 0 and less than or equal to 600 seconds (10 minutes).
189
+ * @param options - Optional parameters:
190
+ * - encoding: Encoding type. If specified, return the TWAP binary data in the encoding specified by the encoding parameter. Default is hex.
191
+ * - parsed: Boolean to specify if the calculated TWAP should be included in the response. Default is false.
192
+ * - ignoreInvalidPriceIds: Boolean to specify if invalid price IDs should be ignored instead of returning an error. Default is false.
193
+ *
194
+ * @returns TwapsResponse object containing the latest TWAPs.
195
+ */ async getLatestTwaps(ids, window_seconds, options, fetchOptions) {
196
+ const url = this.buildURL(`updates/twap/${window_seconds.toString()}/latest`);
197
+ for (const id of ids){
198
+ url.searchParams.append("ids[]", id);
199
+ }
200
+ if (options) {
201
+ const transformedOptions = (0, _utils.camelToSnakeCaseObject)(options);
202
+ this.appendUrlSearchParams(url, transformedOptions);
203
+ }
204
+ return this.httpRequest(url.toString(), _zodSchemas.schemas.TwapsResponse, fetchOptions);
205
+ }
206
+ appendUrlSearchParams(url, params) {
207
+ for (const [key, value] of Object.entries(params)){
208
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
209
+ if (value !== undefined) {
210
+ url.searchParams.append(key, String(value));
211
+ }
212
+ }
213
+ }
214
+ buildURL(endpoint) {
215
+ return new URL(// eslint-disable-next-line unicorn/relative-url-style
216
+ `./v2/${endpoint}`, // We ensure the `baseURL` ends with a `/` so that URL doesn't resolve the
217
+ // path relative to the parent.
218
+ `${this.baseURL}${this.baseURL.endsWith("/") ? "" : "/"}`);
219
+ }
220
+ }
@@ -1,6 +1,6 @@
1
1
  import { EventSource } from "eventsource";
2
- import { schemas } from "./zodSchemas";
3
2
  import { z } from "zod";
3
+ import { schemas } from "./zodSchemas.js";
4
4
  export type AssetType = z.infer<typeof schemas.AssetType>;
5
5
  export type BinaryPriceUpdate = z.infer<typeof schemas.BinaryUpdate>;
6
6
  export type EncodingType = z.infer<typeof schemas.EncodingType>;
@@ -35,8 +35,8 @@ export declare class HermesClient {
35
35
  /**
36
36
  * Constructs a new Connection.
37
37
  *
38
- * @param endpoint endpoint URL to the price service. Example: https://website/example/
39
- * @param config Optional HermesClientConfig for custom configurations.
38
+ * @param endpoint - endpoint URL to the price service. Example: https://website/example/
39
+ * @param config - Optional HermesClientConfig for custom configurations.
40
40
  */
41
41
  constructor(endpoint: string, config?: HermesClientConfig);
42
42
  private httpRequest;
@@ -45,7 +45,7 @@ export declare class HermesClient {
45
45
  * This endpoint can be filtered by asset type and query string.
46
46
  * This will throw an error if there is a network problem or the price service returns a non-ok response.
47
47
  *
48
- * @param options Optional parameters:
48
+ * @param options - Optional parameters:
49
49
  * - query: String to filter the price feeds. If provided, the results will be filtered to all price feeds whose symbol contains the query string. Query string is case insensitive. Example: "bitcoin".
50
50
  * - assetType: String to filter the price feeds by asset type. Possible values are "crypto", "equity", "fx", "metal", "rates", "crypto_redemption_rate". Filter string is case insensitive.
51
51
  *
@@ -61,7 +61,7 @@ export declare class HermesClient {
61
61
  * This endpoint can be customized by specifying the encoding type and whether the results should also return the parsed publisher caps.
62
62
  * This will throw an error if there is a network problem or the price service returns a non-ok response.
63
63
  *
64
- * @param options Optional parameters:
64
+ * @param options - Optional parameters:
65
65
  * - encoding: Encoding type. If specified, return the publisher caps in the encoding specified by the encoding parameter. Default is hex.
66
66
  * - parsed: Boolean to specify if the parsed publisher caps should be included in the response. Default is false.
67
67
  *
@@ -77,8 +77,8 @@ export declare class HermesClient {
77
77
  * This endpoint can be customized by specifying the encoding type and whether the results should also return the parsed price update using the options object.
78
78
  * This will throw an error if there is a network problem or the price service returns a non-ok response.
79
79
  *
80
- * @param ids Array of hex-encoded price feed IDs for which updates are requested.
81
- * @param options Optional parameters:
80
+ * @param ids - Array of hex-encoded price feed IDs for which updates are requested.
81
+ * @param options - Optional parameters:
82
82
  * - encoding: Encoding type. If specified, return the price update in the encoding specified by the encoding parameter. Default is hex.
83
83
  * - parsed: Boolean to specify if the parsed price update should be included in the response. Default is false.
84
84
  * - ignoreInvalidPriceIds: Boolean to specify if invalid price IDs should be ignored instead of returning an error. Default is false.
@@ -95,9 +95,9 @@ export declare class HermesClient {
95
95
  * This endpoint can be customized by specifying the encoding type and whether the results should also return the parsed price update.
96
96
  * This will throw an error if there is a network problem or the price service returns a non-ok response.
97
97
  *
98
- * @param publishTime Unix timestamp in seconds.
99
- * @param ids Array of hex-encoded price feed IDs for which updates are requested.
100
- * @param options Optional parameters:
98
+ * @param publishTime - Unix timestamp in seconds.
99
+ * @param ids - Array of hex-encoded price feed IDs for which updates are requested.
100
+ * @param options - Optional parameters:
101
101
  * - encoding: Encoding type. If specified, return the price update in the encoding specified by the encoding parameter. Default is hex.
102
102
  * - parsed: Boolean to specify if the parsed price update should be included in the response. Default is false.
103
103
  * - ignoreInvalidPriceIds: Boolean to specify if invalid price IDs should be ignored instead of returning an error. Default is false.
@@ -116,8 +116,8 @@ export declare class HermesClient {
116
116
  * This will return an EventSource that can be used to listen to streaming updates.
117
117
  * If an invalid hex-encoded ID is passed, it will throw an error.
118
118
  *
119
- * @param ids Array of hex-encoded price feed IDs for which streaming updates are requested.
120
- * @param options Optional parameters:
119
+ * @param ids - Array of hex-encoded price feed IDs for which streaming updates are requested.
120
+ * @param options - Optional parameters:
121
121
  * - encoding: Encoding type. If specified, updates are returned in the specified encoding. Default is hex.
122
122
  * - parsed: Boolean to specify if the parsed price update should be included in the response. Default is false.
123
123
  * - allowUnordered: Boolean to specify if unordered updates are allowed to be included in the stream. Default is false.
@@ -138,10 +138,10 @@ export declare class HermesClient {
138
138
  * This endpoint can be customized by specifying the encoding type and whether the results should also return the calculated TWAP using the options object.
139
139
  * This will throw an error if there is a network problem or the price service returns a non-ok response.
140
140
  *
141
- * @param ids Array of hex-encoded price feed IDs for which updates are requested.
142
- * @param window_seconds The time window in seconds over which to calculate the TWAP, ending at the current time.
141
+ * @param ids - Array of hex-encoded price feed IDs for which updates are requested.
142
+ * @param window_seconds - The time window in seconds over which to calculate the TWAP, ending at the current time.
143
143
  * For example, a value of 300 would return the most recent 5 minute TWAP. Must be greater than 0 and less than or equal to 600 seconds (10 minutes).
144
- * @param options Optional parameters:
144
+ * @param options - Optional parameters:
145
145
  * - encoding: Encoding type. If specified, return the TWAP binary data in the encoding specified by the encoding parameter. Default is hex.
146
146
  * - parsed: Boolean to specify if the calculated TWAP should be included in the response. Default is false.
147
147
  * - ignoreInvalidPriceIds: Boolean to specify if invalid price IDs should be ignored instead of returning an error. Default is false.
@@ -156,4 +156,3 @@ export declare class HermesClient {
156
156
  private appendUrlSearchParams;
157
157
  private buildURL;
158
158
  }
159
- //# sourceMappingURL=HermesClient.d.ts.map
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ _export_star(require("./hermes-client.cjs"), exports);
6
+ function _export_star(from, to) {
7
+ Object.keys(from).forEach(function(k) {
8
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
9
+ Object.defineProperty(to, k, {
10
+ enumerable: true,
11
+ get: function() {
12
+ return from[k];
13
+ }
14
+ });
15
+ }
16
+ });
17
+ return from;
18
+ }
@@ -0,0 +1 @@
1
+ export * from "./hermes-client.js";
@@ -0,0 +1 @@
1
+ { "type": "commonjs" }
@@ -0,0 +1,22 @@
1
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "camelToSnakeCaseObject", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return camelToSnakeCaseObject;
9
+ }
10
+ });
11
+ function camelToSnakeCase(str) {
12
+ return str.replaceAll(/[A-Z]/g, (letter)=>`_${letter.toLowerCase()}`);
13
+ }
14
+ function camelToSnakeCaseObject(obj) {
15
+ const result = {};
16
+ for (const key of Object.keys(obj)){
17
+ const newKey = camelToSnakeCase(key);
18
+ const val = obj[key];
19
+ result[newKey] = val;
20
+ }
21
+ return result;
22
+ }
@@ -1,2 +1 @@
1
1
  export declare function camelToSnakeCaseObject(obj: Record<string, string | boolean>): Record<string, string | boolean>;
2
- //# sourceMappingURL=utils.d.ts.map