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