@human-protocol/sdk 5.1.0 → 6.0.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 (66) hide show
  1. package/dist/base.d.ts +4 -5
  2. package/dist/base.d.ts.map +1 -1
  3. package/dist/base.js +4 -5
  4. package/dist/constants.js +6 -6
  5. package/dist/encryption.d.ts +68 -203
  6. package/dist/encryption.d.ts.map +1 -1
  7. package/dist/encryption.js +67 -203
  8. package/dist/error.d.ts +4 -24
  9. package/dist/error.d.ts.map +1 -1
  10. package/dist/error.js +6 -26
  11. package/dist/escrow.d.ts +427 -780
  12. package/dist/escrow.d.ts.map +1 -1
  13. package/dist/escrow.js +314 -684
  14. package/dist/graphql/queries/operator.d.ts.map +1 -1
  15. package/dist/graphql/queries/operator.js +3 -1
  16. package/dist/graphql/types.d.ts.map +1 -1
  17. package/dist/index.d.ts +3 -4
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +2 -4
  20. package/dist/interfaces.d.ts +5 -0
  21. package/dist/interfaces.d.ts.map +1 -1
  22. package/dist/kvstore.d.ts +119 -181
  23. package/dist/kvstore.d.ts.map +1 -1
  24. package/dist/kvstore.js +119 -182
  25. package/dist/operator.d.ts +59 -30
  26. package/dist/operator.d.ts.map +1 -1
  27. package/dist/operator.js +59 -30
  28. package/dist/staking.d.ts +135 -134
  29. package/dist/staking.d.ts.map +1 -1
  30. package/dist/staking.js +135 -135
  31. package/dist/statistics.d.ts +104 -134
  32. package/dist/statistics.d.ts.map +1 -1
  33. package/dist/statistics.js +119 -144
  34. package/dist/transaction.d.ts +36 -15
  35. package/dist/transaction.d.ts.map +1 -1
  36. package/dist/transaction.js +36 -16
  37. package/dist/types.d.ts +0 -54
  38. package/dist/types.d.ts.map +1 -1
  39. package/dist/utils.d.ts +31 -17
  40. package/dist/utils.d.ts.map +1 -1
  41. package/dist/utils.js +57 -28
  42. package/dist/worker.d.ts +35 -14
  43. package/dist/worker.d.ts.map +1 -1
  44. package/dist/worker.js +35 -14
  45. package/package.json +13 -28
  46. package/src/base.ts +4 -5
  47. package/src/constants.ts +6 -6
  48. package/src/encryption.ts +70 -204
  49. package/src/error.ts +7 -36
  50. package/src/escrow.ts +426 -780
  51. package/src/graphql/queries/operator.ts +3 -1
  52. package/src/graphql/types.ts +4 -2
  53. package/src/index.ts +4 -5
  54. package/src/interfaces.ts +5 -0
  55. package/src/kvstore.ts +120 -183
  56. package/src/operator.ts +59 -30
  57. package/src/staking.ts +136 -135
  58. package/src/statistics.ts +125 -146
  59. package/src/transaction.ts +36 -16
  60. package/src/types.ts +0 -57
  61. package/src/utils.ts +62 -31
  62. package/src/worker.ts +35 -14
  63. package/dist/storage.d.ts +0 -186
  64. package/dist/storage.d.ts.map +0 -1
  65. package/dist/storage.js +0 -319
  66. package/src/storage.ts +0 -313
package/src/utils.ts CHANGED
@@ -8,6 +8,7 @@ import { ChainId } from './enums';
8
8
  import {
9
9
  ContractExecutionError,
10
10
  ErrorRetryParametersMissing,
11
+ ErrorRoutingRequestsToIndexerRequiresApiKey,
11
12
  EthereumError,
12
13
  InvalidArgumentError,
13
14
  NonceExpired,
@@ -20,10 +21,16 @@ import { NetworkData } from './types';
20
21
  import { SubgraphOptions } from './interfaces';
21
22
 
22
23
  /**
23
- * **Handle and throw the error.*
24
+ * Handles and throws appropriate error types based on the Ethereum error.
24
25
  *
25
- * @param {any} e
26
- * @returns
26
+ * @param e - The error to handle
27
+ * @throws {InvalidArgumentError} If the error is an invalid argument error
28
+ * @throws {ContractExecutionError} If the error is a contract execution error
29
+ * @throws {TransactionReplaced} If the transaction was replaced
30
+ * @throws {ReplacementUnderpriced} If the replacement transaction was underpriced
31
+ * @throws {NumericFault} If there's a numeric fault
32
+ * @throws {NonceExpired} If the nonce has expired
33
+ * @throws {EthereumError} For any other Ethereum-related error
27
34
  */
28
35
  export const throwError = (e: any) => {
29
36
  if (ethers.isError(e, 'INVALID_ARGUMENT')) {
@@ -44,10 +51,10 @@ export const throwError = (e: any) => {
44
51
  };
45
52
 
46
53
  /**
47
- * **URL validation.*
54
+ * Validates if a string is a valid URL.
48
55
  *
49
- * @param {string} url
50
- * @returns
56
+ * @param url - The URL string to validate
57
+ * @returns True if the URL is valid, false otherwise
51
58
  */
52
59
  export const isValidUrl = (url: string): boolean => {
53
60
  return isURL(url, {
@@ -58,10 +65,10 @@ export const isValidUrl = (url: string): boolean => {
58
65
  };
59
66
 
60
67
  /**
61
- * **Check if a string is a valid JSON.*
68
+ * Checks if a string is valid JSON.
62
69
  *
63
- * @param {string} input
64
- * @returns {boolean}
70
+ * @param input - The string to check
71
+ * @returns True if the string is valid JSON, false otherwise
65
72
  */
66
73
  export const isValidJson = (input: string): boolean => {
67
74
  try {
@@ -73,10 +80,10 @@ export const isValidJson = (input: string): boolean => {
73
80
  };
74
81
 
75
82
  /**
76
- * **Get the subgraph URL.*
83
+ * Gets the subgraph URL for the given network, using API key if available.
77
84
  *
78
- * @param {NetworkData} networkData
79
- * @returns
85
+ * @param networkData - The network data containing subgraph URLs
86
+ * @returns The subgraph URL with API key if available
80
87
  */
81
88
  export const getSubgraphUrl = (networkData: NetworkData) => {
82
89
  let subgraphUrl = networkData.subgraphUrl;
@@ -94,10 +101,10 @@ export const getSubgraphUrl = (networkData: NetworkData) => {
94
101
  };
95
102
 
96
103
  /**
97
- * **Convert a date to Unix timestamp (seconds since epoch).*
104
+ * Converts a Date object to Unix timestamp (seconds since epoch).
98
105
  *
99
- * @param {Date} date
100
- * @returns {number}
106
+ * @param date - The date to convert
107
+ * @returns Unix timestamp in seconds
101
108
  */
102
109
  export const getUnixTimestamp = (date: Date): number => {
103
110
  return Math.floor(date.getTime() / 1000);
@@ -118,9 +125,24 @@ const sleep = (ms: number): Promise<void> => {
118
125
  return new Promise((resolve) => setTimeout(resolve, ms));
119
126
  };
120
127
 
128
+ const buildIndexerUrl = (baseUrl: string, indexerId?: string): string => {
129
+ if (!indexerId) {
130
+ return baseUrl;
131
+ }
132
+ return `${baseUrl}/indexers/id/${indexerId}`;
133
+ };
134
+
121
135
  /**
122
- * Execute a GraphQL request with automatic retry logic for bad indexer errors.
123
- * Only retries if options is provided.
136
+ * Executes a GraphQL request with automatic retry logic for bad indexer errors.
137
+ * Only retries if options is provided with maxRetries and baseDelay.
138
+ *
139
+ * @param url - The GraphQL endpoint URL
140
+ * @param query - The GraphQL query to execute
141
+ * @param variables - Variables for the GraphQL query (optional)
142
+ * @param options - Optional configuration for subgraph requests including retry logic
143
+ * @returns The response data from the GraphQL query
144
+ * @throws ErrorRetryParametersMissing If only one of maxRetries or baseDelay is provided
145
+ * @throws ErrorRoutingRequestsToIndexerRequiresApiKey If indexerId is provided without API key
124
146
  */
125
147
  export const customGqlFetch = async <T = any>(
126
148
  url: string,
@@ -128,35 +150,44 @@ export const customGqlFetch = async <T = any>(
128
150
  variables?: any,
129
151
  options?: SubgraphOptions
130
152
  ): Promise<T> => {
153
+ const apiKey = process.env.SUBGRAPH_API_KEY;
154
+ const headers = apiKey
155
+ ? {
156
+ Authorization: `Bearer ${apiKey}`,
157
+ }
158
+ : undefined;
159
+
131
160
  if (!options) {
132
- return await gqlFetch<T>(url, query, variables);
161
+ return await gqlFetch<T>(url, query, variables, headers);
133
162
  }
134
163
 
135
- if (
136
- (options.maxRetries && options.baseDelay === undefined) ||
137
- (options.baseDelay && options.maxRetries === undefined)
138
- ) {
164
+ const hasMaxRetries = options.maxRetries !== undefined;
165
+ const hasBaseDelay = options.baseDelay !== undefined;
166
+
167
+ if (hasMaxRetries !== hasBaseDelay) {
139
168
  throw ErrorRetryParametersMissing;
140
169
  }
170
+ if (options.indexerId && !headers) {
171
+ throw ErrorRoutingRequestsToIndexerRequiresApiKey;
172
+ }
173
+
174
+ const targetUrl = buildIndexerUrl(url, options.indexerId);
141
175
 
176
+ const maxRetries = hasMaxRetries ? (options.maxRetries as number) : 0;
177
+ const baseDelay = hasBaseDelay ? (options.baseDelay as number) : 0;
142
178
  let lastError: any;
143
179
 
144
- for (let attempt = 0; attempt <= (options.maxRetries as number); attempt++) {
180
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
145
181
  try {
146
- const result = await gqlFetch<T>(url, query, variables);
147
- return result;
182
+ return await gqlFetch<T>(targetUrl, query, variables, headers);
148
183
  } catch (error) {
149
184
  lastError = error;
150
185
 
151
- if (attempt === options.maxRetries) {
152
- throw error;
153
- }
154
-
155
- if (!isIndexerError(error)) {
186
+ if (attempt === maxRetries || !isIndexerError(error)) {
156
187
  throw error;
157
188
  }
158
189
 
159
- const delay = (options.baseDelay as number) * attempt;
190
+ const delay = baseDelay * attempt;
160
191
  await sleep(delay);
161
192
  }
162
193
  }
package/src/worker.ts CHANGED
@@ -7,21 +7,40 @@ import { GET_WORKER_QUERY, GET_WORKERS_QUERY } from './graphql/queries/worker';
7
7
  import { IWorker, IWorkersFilter, SubgraphOptions } from './interfaces';
8
8
  import { getSubgraphUrl, customGqlFetch } from './utils';
9
9
 
10
+ /**
11
+ * Utility class for worker-related operations.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { WorkerUtils, ChainId } from '@human-protocol/sdk';
16
+ *
17
+ * const worker = await WorkerUtils.getWorker(
18
+ * ChainId.POLYGON_AMOY,
19
+ * '0x1234567890abcdef1234567890abcdef12345678'
20
+ * );
21
+ * console.log('Worker:', worker);
22
+ * ```
23
+ */
10
24
  export class WorkerUtils {
11
25
  /**
12
26
  * This function returns the worker data for the given address.
13
27
  *
14
- * @param {ChainId} chainId The chain ID.
15
- * @param {string} address The worker address.
16
- * @param {SubgraphOptions} options Optional configuration for subgraph requests.
17
- * @returns {Promise<IWorker | null>} - Returns the worker details or null if not found.
18
- *
19
- * **Code example**
28
+ * @param chainId - The chain ID.
29
+ * @param address - The worker address.
30
+ * @param options - Optional configuration for subgraph requests.
31
+ * @returns Returns the worker details or null if not found.
32
+ * @throws ErrorUnsupportedChainID If the chain ID is not supported
33
+ * @throws ErrorInvalidAddress If the address is invalid
20
34
  *
35
+ * @example
21
36
  * ```ts
22
37
  * import { WorkerUtils, ChainId } from '@human-protocol/sdk';
23
38
  *
24
- * const worker = await WorkerUtils.getWorker(ChainId.POLYGON, '0x1234567890abcdef1234567890abcdef12345678');
39
+ * const worker = await WorkerUtils.getWorker(
40
+ * ChainId.POLYGON_AMOY,
41
+ * '0x1234567890abcdef1234567890abcdef12345678'
42
+ * );
43
+ * console.log('Worker:', worker);
25
44
  * ```
26
45
  */
27
46
  public static async getWorker(
@@ -79,21 +98,23 @@ export class WorkerUtils {
79
98
  * };
80
99
  * ```
81
100
  *
82
- * @param {IWorkersFilter} filter Filter for the workers.
83
- * @param {SubgraphOptions} options Optional configuration for subgraph requests.
84
- * @returns {Promise<IWorker[]>} Returns an array with all the worker details.
85
- *
86
- * **Code example**
101
+ * @param filter - Filter for the workers.
102
+ * @param options - Optional configuration for subgraph requests.
103
+ * @returns Returns an array with all the worker details.
104
+ * @throws ErrorUnsupportedChainID If the chain ID is not supported
105
+ * @throws ErrorInvalidAddress If the filter address is invalid
87
106
  *
107
+ * @example
88
108
  * ```ts
89
109
  * import { WorkerUtils, ChainId } from '@human-protocol/sdk';
90
110
  *
91
- * const filter: IWorkersFilter = {
92
- * chainId: ChainId.POLYGON,
111
+ * const filter = {
112
+ * chainId: ChainId.POLYGON_AMOY,
93
113
  * first: 10,
94
114
  * skip: 0,
95
115
  * };
96
116
  * const workers = await WorkerUtils.getWorkers(filter);
117
+ * console.log('Workers:', workers.length);
97
118
  * ```
98
119
  */
99
120
  public static async getWorkers(
package/dist/storage.d.ts DELETED
@@ -1,186 +0,0 @@
1
- import { UploadFile, StorageCredentials, StorageParams } from './types';
2
- /**
3
- *
4
- * @deprecated StorageClient is deprecated. Use Minio.Client directly.
5
- *
6
- * ## Introduction
7
- *
8
- * This client enables interacting with S3 cloud storage services like Amazon S3 Bucket, Google Cloud Storage, and others.
9
- *
10
- * The instance creation of `StorageClient` should be made using its constructor:
11
- *
12
- * ```ts
13
- * constructor(params: StorageParams, credentials?: StorageCredentials)
14
- * ```
15
- *
16
- * > If credentials are not provided, it uses anonymous access to the bucket for downloading files.
17
- *
18
- * ## Installation
19
- *
20
- * ### npm
21
- * ```bash
22
- * npm install @human-protocol/sdk
23
- * ```
24
- *
25
- * ### yarn
26
- * ```bash
27
- * yarn install @human-protocol/sdk
28
- * ```
29
- *
30
- * ## Code example
31
- *
32
- * ```ts
33
- * import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk';
34
- *
35
- * const credentials: StorageCredentials = {
36
- * accessKey: 'ACCESS_KEY',
37
- * secretKey: 'SECRET_KEY',
38
- * };
39
- * const params: StorageParams = {
40
- * endPoint: 'http://localhost',
41
- * port: 9000,
42
- * useSSL: false,
43
- * region: 'us-east-1'
44
- * };
45
- *
46
- * const storageClient = new StorageClient(params, credentials);
47
- * ```
48
- */
49
- export declare class StorageClient {
50
- private client;
51
- private clientParams;
52
- /**
53
- * **Storage client constructor**
54
- *
55
- * @param {StorageParams} params - Cloud storage params
56
- * @param {StorageCredentials} credentials - Optional. Cloud storage access data. If credentials are not provided - use anonymous access to the bucket
57
- */
58
- constructor(params: StorageParams, credentials?: StorageCredentials);
59
- /**
60
- * This function downloads files from a bucket.
61
- *
62
- * @param {string[]} keys Array of filenames to download.
63
- * @param {string} bucket Bucket name.
64
- * @returns {Promise<any[]>} Returns an array of JSON files downloaded and parsed into objects.
65
- *
66
- * **Code example**
67
- *
68
- * ```ts
69
- * import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk';
70
- *
71
- * const params: StorageParams = {
72
- * endPoint: 'http://localhost',
73
- * port: 9000,
74
- * useSSL: false,
75
- * region: 'us-east-1'
76
- * };
77
- *
78
- * const storageClient = new StorageClient(params);
79
- *
80
- * const keys = ['file1.json', 'file2.json'];
81
- * const files = await storageClient.downloadFiles(keys, 'bucket-name');
82
- * ```
83
- */
84
- downloadFiles(keys: string[], bucket: string): Promise<any[]>;
85
- /**
86
- * This function downloads files from a URL.
87
- *
88
- * @param {string} url URL of the file to download.
89
- * @returns {Promise<any>} Returns the JSON file downloaded and parsed into an object.
90
- *
91
- * **Code example**
92
- *
93
- * ```ts
94
- * import { StorageClient } from '@human-protocol/sdk';
95
- *
96
- * const file = await StorageClient.downloadFileFromUrl('http://localhost/file.json');
97
- * ```
98
- */
99
- static downloadFileFromUrl(url: string): Promise<any>;
100
- /**
101
- * This function uploads files to a bucket.
102
- *
103
- * @param {any[]} files Array of objects to upload serialized into JSON.
104
- * @param {string} bucket Bucket name.
105
- * @returns {Promise<UploadFile[]>} Returns an array of uploaded file metadata.
106
- *
107
- * **Code example**
108
- *
109
- * ```ts
110
- * import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk';
111
- *
112
- * const credentials: StorageCredentials = {
113
- * accessKey: 'ACCESS_KEY',
114
- * secretKey: 'SECRET_KEY',
115
- * };
116
- * const params: StorageParams = {
117
- * endPoint: 'http://localhost',
118
- * port: 9000,
119
- * useSSL: false,
120
- * region: 'us-east-1'
121
- * };
122
- *
123
- * const storageClient = new StorageClient(params, credentials);
124
- * const file1 = { name: 'file1', description: 'description of file1' };
125
- * const file2 = { name: 'file2', description: 'description of file2' };
126
- * const files = [file1, file2];
127
- * const uploadedFiles = await storageClient.uploadFiles(files, 'bucket-name');
128
- * ```
129
- */
130
- uploadFiles(files: any[], bucket: string): Promise<UploadFile[]>;
131
- /**
132
- * This function checks if a bucket exists.
133
- *
134
- * @param {string} bucket Bucket name.
135
- * @returns {Promise<boolean>} Returns `true` if exists, `false` if it doesn't.
136
- *
137
- * **Code example**
138
- *
139
- * ```ts
140
- * import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk';
141
- *
142
- * const credentials: StorageCredentials = {
143
- * accessKey: 'ACCESS_KEY',
144
- * secretKey: 'SECRET_KEY',
145
- * };
146
- * const params: StorageParams = {
147
- * endPoint: 'http://localhost',
148
- * port: 9000,
149
- * useSSL: false,
150
- * region: 'us-east-1'
151
- * };
152
- *
153
- * const storageClient = new StorageClient(params, credentials);
154
- * const exists = await storageClient.bucketExists('bucket-name');
155
- * ```
156
- */
157
- bucketExists(bucket: string): Promise<boolean>;
158
- /**
159
- * This function lists all file names contained in the bucket.
160
- *
161
- * @param {string} bucket Bucket name.
162
- * @returns {Promise<string[]>} Returns the list of file names contained in the bucket.
163
- *
164
- * **Code example**
165
- *
166
- * ```ts
167
- * import { StorageClient, StorageCredentials, StorageParams } from '@human-protocol/sdk';
168
- *
169
- * const credentials: StorageCredentials = {
170
- * accessKey: 'ACCESS_KEY',
171
- * secretKey: 'SECRET_KEY',
172
- * };
173
- * const params: StorageParams = {
174
- * endPoint: 'http://localhost',
175
- * port: 9000,
176
- * useSSL: false,
177
- * region: 'us-east-1'
178
- * };
179
- *
180
- * const storageClient = new StorageClient(params, credentials);
181
- * const fileNames = await storageClient.listObjects('bucket-name');
182
- * ```
183
- */
184
- listObjects(bucket: string): Promise<string[]>;
185
- }
186
- //# sourceMappingURL=storage.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAIxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,YAAY,CAAgB;IAEpC;;;;;OAKG;gBACS,MAAM,EAAE,aAAa,EAAE,WAAW,CAAC,EAAE,kBAAkB;IAcnE;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACU,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAoB1E;;;;;;;;;;;;;OAaG;WACiB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAsBlE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6BG;IACU,WAAW,CACtB,KAAK,EAAE,GAAG,EAAE,EACZ,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,UAAU,EAAE,CAAC;IAmCxB;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACU,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAI3D;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACU,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;CAqB5D"}