@human-protocol/sdk 1.1.3 → 1.1.6

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 (56) hide show
  1. package/README.md +80 -1
  2. package/dist/constants.d.ts +52 -0
  3. package/dist/constants.d.ts.map +1 -0
  4. package/dist/constants.js +222 -0
  5. package/dist/decorators.d.ts +2 -0
  6. package/dist/decorators.d.ts.map +1 -0
  7. package/dist/decorators.js +17 -0
  8. package/dist/encryption.d.ts +84 -0
  9. package/dist/encryption.d.ts.map +1 -0
  10. package/dist/encryption.js +202 -0
  11. package/dist/enums.d.ts +17 -0
  12. package/dist/enums.d.ts.map +1 -0
  13. package/dist/enums.js +20 -0
  14. package/dist/error.d.ts +196 -0
  15. package/dist/error.d.ts.map +1 -0
  16. package/dist/error.js +229 -0
  17. package/dist/escrow.d.ts +201 -0
  18. package/dist/escrow.d.ts.map +1 -0
  19. package/dist/escrow.js +651 -0
  20. package/dist/index.d.ts +10 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +29 -0
  23. package/dist/interfaces.d.ts +42 -0
  24. package/dist/interfaces.d.ts.map +1 -0
  25. package/dist/interfaces.js +2 -0
  26. package/dist/kvstore.d.ts +51 -0
  27. package/dist/kvstore.d.ts.map +1 -0
  28. package/dist/kvstore.js +135 -0
  29. package/dist/queries.d.ts +5 -0
  30. package/dist/queries.d.ts.map +1 -0
  31. package/dist/queries.js +19 -0
  32. package/dist/staking.d.ts +130 -0
  33. package/dist/staking.d.ts.map +1 -0
  34. package/dist/staking.js +409 -0
  35. package/dist/storage.d.ts +49 -0
  36. package/dist/storage.d.ts.map +1 -0
  37. package/dist/storage.js +171 -0
  38. package/dist/types.d.ts +131 -0
  39. package/dist/types.d.ts.map +1 -0
  40. package/dist/types.js +35 -0
  41. package/dist/utils.d.ts +32 -0
  42. package/dist/utils.d.ts.map +1 -0
  43. package/dist/utils.js +99 -0
  44. package/package.json +4 -1
  45. package/src/constants.ts +25 -6
  46. package/src/encryption.ts +223 -0
  47. package/src/error.ts +2 -4
  48. package/src/escrow.ts +120 -74
  49. package/src/index.ts +6 -12
  50. package/src/interfaces.ts +10 -13
  51. package/src/kvstore.ts +51 -14
  52. package/src/queries.ts +15 -7
  53. package/src/staking.ts +61 -24
  54. package/src/storage.ts +15 -3
  55. package/src/types.ts +8 -0
  56. package/src/init.ts +0 -45
@@ -0,0 +1,409 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.StakingClient = void 0;
13
+ const typechain_types_1 = require("@human-protocol/core/typechain-types");
14
+ const ethers_1 = require("ethers");
15
+ const constants_1 = require("./constants");
16
+ const decorators_1 = require("./decorators");
17
+ const error_1 = require("./error");
18
+ const queries_1 = require("./queries");
19
+ const utils_1 = require("./utils");
20
+ class StakingClient {
21
+ /**
22
+ * **StakingClient constructor**
23
+ *
24
+ * @param {Signer | Provider} signerOrProvider - The Signer or Provider object to interact with the Ethereum network
25
+ * @param {NetworkData} network - The network information required to connect to the Staking contract
26
+ */
27
+ constructor(signerOrProvider, network) {
28
+ this.stakingContract = typechain_types_1.Staking__factory.connect(network.stakingAddress, signerOrProvider);
29
+ this.escrowFactoryContract = typechain_types_1.EscrowFactory__factory.connect(network.factoryAddress, signerOrProvider);
30
+ this.tokenContract = typechain_types_1.HMToken__factory.connect(network.hmtAddress, signerOrProvider);
31
+ this.signerOrProvider = signerOrProvider;
32
+ this.network = network;
33
+ }
34
+ /**
35
+ * Creates an instance of StakingClient from a Signer or Provider.
36
+ *
37
+ * @param {Signer | Provider} signerOrProvider - The Signer or Provider object to interact with the Ethereum network
38
+ * @returns {Promise<StakingClient>} - An instance of StakingClient
39
+ * @throws {ErrorProviderDoesNotExist} - Thrown if the provider does not exist for the provided Signer
40
+ * @throws {ErrorUnsupportedChainID} - Thrown if the network's chainId is not supported
41
+ */
42
+ static async build(signerOrProvider) {
43
+ let network;
44
+ if (ethers_1.Signer.isSigner(signerOrProvider)) {
45
+ if (!signerOrProvider.provider) {
46
+ throw error_1.ErrorProviderDoesNotExist;
47
+ }
48
+ network = await signerOrProvider.provider.getNetwork();
49
+ }
50
+ else {
51
+ network = await signerOrProvider.getNetwork();
52
+ }
53
+ const chainId = network.chainId;
54
+ const networkData = constants_1.NETWORKS[chainId];
55
+ if (!networkData) {
56
+ throw error_1.ErrorUnsupportedChainID;
57
+ }
58
+ return new StakingClient(signerOrProvider, networkData);
59
+ }
60
+ /**
61
+ * **Approves the staking contract to transfer a specified amount of tokens when the user stakes.
62
+ * **It increases the allowance for the staking contract.*
63
+ *
64
+ * @param {BigNumber} amount - Amount of tokens to approve for stake
65
+ * @returns {Promise<void>}
66
+ * @throws {Error} - An error object if an error occurred, void otherwise
67
+ */
68
+ async approveStake(amount) {
69
+ if (!ethers_1.BigNumber.isBigNumber(amount)) {
70
+ throw error_1.ErrorInvalidStakingValueType;
71
+ }
72
+ if (amount.isNegative()) {
73
+ throw error_1.ErrorInvalidStakingValueSign;
74
+ }
75
+ try {
76
+ await this.tokenContract.approve(this.stakingContract.address, amount);
77
+ return;
78
+ }
79
+ catch (e) {
80
+ return (0, utils_1.throwError)(e);
81
+ }
82
+ }
83
+ /**
84
+ * **Stakes a specified amount of tokens on a specific network.*
85
+ *
86
+ * @param {BigNumber} amount - Amount of tokens to stake
87
+ * @returns {Promise<void>}
88
+ * @throws {Error} - An error object if an error occurred, void otherwise
89
+ */
90
+ async stake(amount) {
91
+ if (!ethers_1.BigNumber.isBigNumber(amount)) {
92
+ throw error_1.ErrorInvalidStakingValueType;
93
+ }
94
+ if (amount.isNegative()) {
95
+ throw error_1.ErrorInvalidStakingValueSign;
96
+ }
97
+ try {
98
+ await this.stakingContract.stake(amount);
99
+ return;
100
+ }
101
+ catch (e) {
102
+ return (0, utils_1.throwError)(e);
103
+ }
104
+ }
105
+ /**
106
+ * **Unstakes tokens from staking contract.
107
+ * **The unstaked tokens stay locked for a period of time.*
108
+ *
109
+ * @param {BigNumber} amount - Amount of tokens to unstake
110
+ * @returns {Promise<void>}
111
+ * @throws {Error} - An error object if an error occurred, void otherwise
112
+ */
113
+ async unstake(amount) {
114
+ if (!ethers_1.BigNumber.isBigNumber(amount)) {
115
+ throw error_1.ErrorInvalidStakingValueType;
116
+ }
117
+ if (amount.isNegative()) {
118
+ throw error_1.ErrorInvalidStakingValueSign;
119
+ }
120
+ try {
121
+ await this.stakingContract.unstake(amount);
122
+ return;
123
+ }
124
+ catch (e) {
125
+ return (0, utils_1.throwError)(e);
126
+ }
127
+ }
128
+ /**
129
+ * **Withdraws unstaked and non locked tokens form staking contract to the user wallet.*
130
+ *
131
+ * @returns {Promise<void>}
132
+ * @throws {Error} - An error object if an error occurred, void otherwise
133
+ */
134
+ async withdraw() {
135
+ try {
136
+ await this.stakingContract.withdraw();
137
+ return;
138
+ }
139
+ catch (e) {
140
+ return (0, utils_1.throwError)(e);
141
+ }
142
+ }
143
+ /**
144
+ * **Slash the allocated amount by an staker in an escrow and transfers those tokens to the reward pool.
145
+ * **This allows the slasher to claim them later.*
146
+ *
147
+ * @param {string} slasher - Wallet address from who requested the slash
148
+ * @param {string} staker - Wallet address from who is going to be slashed
149
+ * @param {string} escrowAddress - Address of the escrow which allocation will be slashed
150
+ * @param {BigNumber} amount - Amount of tokens to slash
151
+ * @returns {Promise<void>}
152
+ * @throws {Error} - An error object if an error occurred, void otherwise
153
+ */
154
+ async slash(slasher, staker, escrowAddress, amount) {
155
+ if (!ethers_1.BigNumber.isBigNumber(amount)) {
156
+ throw error_1.ErrorInvalidStakingValueType;
157
+ }
158
+ if (amount.isNegative()) {
159
+ throw error_1.ErrorInvalidStakingValueSign;
160
+ }
161
+ if (!ethers_1.ethers.utils.isAddress(slasher)) {
162
+ throw error_1.ErrorInvalidSlasherAddressProvided;
163
+ }
164
+ if (!ethers_1.ethers.utils.isAddress(staker)) {
165
+ throw error_1.ErrorInvalidStakerAddressProvided;
166
+ }
167
+ if (!ethers_1.ethers.utils.isAddress(escrowAddress)) {
168
+ throw error_1.ErrorInvalidEscrowAddressProvided;
169
+ }
170
+ if (!(await this.escrowFactoryContract.hasEscrow(escrowAddress))) {
171
+ throw error_1.ErrorEscrowAddressIsNotProvidedByFactory;
172
+ }
173
+ try {
174
+ await this.stakingContract.slash(slasher, staker, escrowAddress, amount);
175
+ return;
176
+ }
177
+ catch (e) {
178
+ return (0, utils_1.throwError)(e);
179
+ }
180
+ }
181
+ /**
182
+ * **Allocates a portion of the staked tokens to a specific escrow.*
183
+ *
184
+ * @param {string} escrowAddress - Address of the escrow contract
185
+ * @param {BigNumber} amount - Amount of tokens to allocate
186
+ * @returns {Promise<void>}
187
+ * @throws {Error} - An error object if an error occurred, void otherwise
188
+ */
189
+ async allocate(escrowAddress, amount) {
190
+ if (!ethers_1.BigNumber.isBigNumber(amount)) {
191
+ throw error_1.ErrorInvalidStakingValueType;
192
+ }
193
+ if (amount.isNegative()) {
194
+ throw error_1.ErrorInvalidStakingValueSign;
195
+ }
196
+ if (!ethers_1.ethers.utils.isAddress(escrowAddress)) {
197
+ throw error_1.ErrorInvalidEscrowAddressProvided;
198
+ }
199
+ if (!(await this.escrowFactoryContract.hasEscrow(escrowAddress))) {
200
+ throw error_1.ErrorEscrowAddressIsNotProvidedByFactory;
201
+ }
202
+ try {
203
+ await this.stakingContract.allocate(escrowAddress, amount);
204
+ return;
205
+ }
206
+ catch (e) {
207
+ return (0, utils_1.throwError)(e);
208
+ }
209
+ }
210
+ /**
211
+ * **Drops the allocation from a specific escrow.*
212
+ *
213
+ * @param {string} escrowAddress - Address of the escrow contract.
214
+ * @returns {Promise<void>}
215
+ * @throws {Error} - An error object if an error occurred, void otherwise
216
+ */
217
+ async closeAllocation(escrowAddress) {
218
+ if (!ethers_1.ethers.utils.isAddress(escrowAddress)) {
219
+ throw error_1.ErrorInvalidEscrowAddressProvided;
220
+ }
221
+ if (!(await this.escrowFactoryContract.hasEscrow(escrowAddress))) {
222
+ throw error_1.ErrorEscrowAddressIsNotProvidedByFactory;
223
+ }
224
+ try {
225
+ await this.stakingContract.closeAllocation(escrowAddress);
226
+ return;
227
+ }
228
+ catch (e) {
229
+ return (0, utils_1.throwError)(e);
230
+ }
231
+ }
232
+ /**
233
+ * **Pays out rewards to the slashers for the specified escrow address.*
234
+ *
235
+ * @param {string} escrowAddress - Escrow address from which rewards are distributed.
236
+ * @returns {Promise<void>}
237
+ * @throws {Error} - An error object if an error occurred, void otherwise
238
+ */
239
+ async distributeRewards(escrowAddress) {
240
+ if (!ethers_1.ethers.utils.isAddress(escrowAddress)) {
241
+ throw error_1.ErrorInvalidEscrowAddressProvided;
242
+ }
243
+ if (!(await this.escrowFactoryContract.hasEscrow(escrowAddress))) {
244
+ throw error_1.ErrorEscrowAddressIsNotProvidedByFactory;
245
+ }
246
+ try {
247
+ const rewardPoolContract = typechain_types_1.RewardPool__factory.connect(await this.stakingContract.rewardPool(), this.signerOrProvider);
248
+ await rewardPoolContract.distributeReward(escrowAddress);
249
+ return;
250
+ }
251
+ catch (e) {
252
+ return (0, utils_1.throwError)(e);
253
+ }
254
+ }
255
+ /**
256
+ * **Returns the staking information about an staker address.*
257
+ *
258
+ * @param {string} staker - Address of the staker
259
+ * @returns {Promise<IStaker>} - Return staking information of the specified address
260
+ * @throws {Error} - An error object if an error occurred, result otherwise
261
+ */
262
+ async getStaker(staker) {
263
+ if (!ethers_1.ethers.utils.isAddress(staker)) {
264
+ throw error_1.ErrorInvalidStakerAddressProvided;
265
+ }
266
+ try {
267
+ const result = await this.stakingContract.getStaker(staker);
268
+ const tokensStaked = ethers_1.BigNumber.from(result.tokensStaked), tokensAllocated = ethers_1.BigNumber.from(result.tokensAllocated), tokensLocked = ethers_1.BigNumber.from(result.tokensLocked), tokensLockedUntil = ethers_1.BigNumber.from(result.tokensLockedUntil);
269
+ const tokensAvailable = tokensStaked
270
+ .sub(tokensAllocated)
271
+ .sub(tokensLocked);
272
+ return {
273
+ tokensStaked,
274
+ tokensAllocated,
275
+ tokensLocked,
276
+ tokensLockedUntil,
277
+ tokensAvailable,
278
+ };
279
+ }
280
+ catch (e) {
281
+ return (0, utils_1.throwError)(e);
282
+ }
283
+ }
284
+ /**
285
+ * **Returns the staking information about all stakers of the protocol.*
286
+ *
287
+ * @returns {Promise<IStakerInfo>} - Return an array with all stakers information
288
+ * @throws {Error} - An error object if an error occurred, results otherwise
289
+ */
290
+ async getAllStakers() {
291
+ try {
292
+ const result = await this.stakingContract.getListOfStakers();
293
+ if (result[1].length === 0) {
294
+ throw error_1.ErrorStakingGetStakers;
295
+ }
296
+ return result[1].map((staker) => {
297
+ const tokensStaked = ethers_1.BigNumber.from(staker.tokensStaked), tokensAllocated = ethers_1.BigNumber.from(staker.tokensAllocated), tokensLocked = ethers_1.BigNumber.from(staker.tokensLocked), tokensLockedUntil = ethers_1.BigNumber.from(staker.tokensLockedUntil);
298
+ const tokensAvailable = tokensStaked
299
+ .sub(tokensAllocated)
300
+ .sub(tokensLocked);
301
+ return {
302
+ tokensStaked,
303
+ tokensAllocated,
304
+ tokensLocked,
305
+ tokensLockedUntil,
306
+ tokensAvailable,
307
+ };
308
+ });
309
+ }
310
+ catch (e) {
311
+ return (0, utils_1.throwError)(e);
312
+ }
313
+ }
314
+ /**
315
+ * **Returns information about the allocation of the specified escrow.*
316
+ *
317
+ * @param {string} escrowAddress - The escrow address for the received allocation data
318
+ * @returns {Promise<IAllocation>} - Returns allocation info if exists
319
+ * @throws {Error} - An error object if an error occurred, result otherwise
320
+ */
321
+ async getAllocation(escrowAddress) {
322
+ if (!ethers_1.ethers.utils.isAddress(escrowAddress)) {
323
+ throw error_1.ErrorInvalidEscrowAddressProvided;
324
+ }
325
+ if (!(await this.escrowFactoryContract.hasEscrow(escrowAddress))) {
326
+ throw error_1.ErrorEscrowAddressIsNotProvidedByFactory;
327
+ }
328
+ try {
329
+ const result = await this.stakingContract.getAllocation(escrowAddress);
330
+ return result;
331
+ }
332
+ catch (e) {
333
+ return (0, utils_1.throwError)(e);
334
+ }
335
+ }
336
+ /**
337
+ * **Returns information about the rewards for a given escrow address.*
338
+ *
339
+ * @param {string} slasherAddress - Address of the slasher
340
+ * @returns {Promise<IReward[]>} - Returns rewards info if exists
341
+ * @throws {Error} - An error object if an error occurred, results otherwise
342
+ */
343
+ async getRewards(slasherAddress) {
344
+ if (!ethers_1.ethers.utils.isAddress(slasherAddress)) {
345
+ throw error_1.ErrorInvalidSlasherAddressProvided;
346
+ }
347
+ try {
348
+ const { data } = await (0, utils_1.gqlFetch)(this.network.subgraphUrl, (0, queries_1.RAW_REWARDS_QUERY)(slasherAddress));
349
+ return data.rewardAddedEvents.map((reward) => {
350
+ return {
351
+ escrowAddress: reward.escrow,
352
+ amount: reward.amount,
353
+ };
354
+ });
355
+ }
356
+ catch (e) {
357
+ return (0, utils_1.throwError)(e);
358
+ }
359
+ }
360
+ }
361
+ __decorate([
362
+ decorators_1.requiresSigner,
363
+ __metadata("design:type", Function),
364
+ __metadata("design:paramtypes", [ethers_1.BigNumber]),
365
+ __metadata("design:returntype", Promise)
366
+ ], StakingClient.prototype, "approveStake", null);
367
+ __decorate([
368
+ decorators_1.requiresSigner,
369
+ __metadata("design:type", Function),
370
+ __metadata("design:paramtypes", [ethers_1.BigNumber]),
371
+ __metadata("design:returntype", Promise)
372
+ ], StakingClient.prototype, "stake", null);
373
+ __decorate([
374
+ decorators_1.requiresSigner,
375
+ __metadata("design:type", Function),
376
+ __metadata("design:paramtypes", [ethers_1.BigNumber]),
377
+ __metadata("design:returntype", Promise)
378
+ ], StakingClient.prototype, "unstake", null);
379
+ __decorate([
380
+ decorators_1.requiresSigner,
381
+ __metadata("design:type", Function),
382
+ __metadata("design:paramtypes", []),
383
+ __metadata("design:returntype", Promise)
384
+ ], StakingClient.prototype, "withdraw", null);
385
+ __decorate([
386
+ decorators_1.requiresSigner,
387
+ __metadata("design:type", Function),
388
+ __metadata("design:paramtypes", [String, String, String, ethers_1.BigNumber]),
389
+ __metadata("design:returntype", Promise)
390
+ ], StakingClient.prototype, "slash", null);
391
+ __decorate([
392
+ decorators_1.requiresSigner,
393
+ __metadata("design:type", Function),
394
+ __metadata("design:paramtypes", [String, ethers_1.BigNumber]),
395
+ __metadata("design:returntype", Promise)
396
+ ], StakingClient.prototype, "allocate", null);
397
+ __decorate([
398
+ decorators_1.requiresSigner,
399
+ __metadata("design:type", Function),
400
+ __metadata("design:paramtypes", [String]),
401
+ __metadata("design:returntype", Promise)
402
+ ], StakingClient.prototype, "closeAllocation", null);
403
+ __decorate([
404
+ decorators_1.requiresSigner,
405
+ __metadata("design:type", Function),
406
+ __metadata("design:paramtypes", [String]),
407
+ __metadata("design:returntype", Promise)
408
+ ], StakingClient.prototype, "distributeRewards", null);
409
+ exports.StakingClient = StakingClient;
@@ -0,0 +1,49 @@
1
+ import { UploadFile, StorageCredentials, StorageParams } from './types';
2
+ export declare class StorageClient {
3
+ private client;
4
+ private clientParams;
5
+ /**
6
+ * **Storage client constructor**
7
+ *
8
+ * @param {StorageCredentials} credentials - Cloud storage access data
9
+ * @param {StorageParams} params - Cloud storage params
10
+ */
11
+ constructor(credentials: StorageCredentials, params: StorageParams);
12
+ /**
13
+ * **Download files from cloud storage**
14
+ *
15
+ * @param {string} keys - Keys of files
16
+ * @returns {Promise<File>} - Downloaded file
17
+ */
18
+ downloadFiles(keys: string[], bucket: string): Promise<any[]>;
19
+ /**
20
+ * **Download files from cloud storage.*
21
+ *
22
+ * @param {string} url - URL to the file
23
+ * @returns {Promise<File>} - Downloaded file
24
+ */
25
+ static downloadFileFromUrl(url: string): Promise<any>;
26
+ /**
27
+ * **Upload file to cloud storage**
28
+ *
29
+ * @param {File[]} files - Files to upload
30
+ * @param {string} bucket - Bucket name
31
+ * @returns {Promise<UploadFile>} - Uploaded file with key/hash
32
+ */
33
+ uploadFiles(files: any[], bucket: string): Promise<UploadFile[]>;
34
+ /**
35
+ * **Checks if a bucket exists**
36
+ *
37
+ * @param {string} bucket - Name of the bucket
38
+ * @returns {Promise<boolean>} - True if bucket exists, false otherwise
39
+ */
40
+ bucketExists(bucket: string): Promise<boolean>;
41
+ /**
42
+ * **Checks if a bucket exists**
43
+ *
44
+ * @param {string} bucket - Name of the bucket
45
+ * @returns {Promise<string[]>} - A list of filenames with their extensions in the bucket
46
+ */
47
+ listObjects(bucket: string): Promise<string[]>;
48
+ }
49
+ //# sourceMappingURL=storage.d.ts.map
@@ -0,0 +1 @@
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,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,YAAY,CAAgB;IAEpC;;;;;OAKG;gBACS,WAAW,EAAE,kBAAkB,EAAE,MAAM,EAAE,aAAa;IAclE;;;;;OAKG;IACU,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAoB1E;;;;;OAKG;WACiB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAsBlE;;;;;;OAMG;IACU,WAAW,CACtB,KAAK,EAAE,GAAG,EAAE,EACZ,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,UAAU,EAAE,CAAC;IAkCxB;;;;;OAKG;IACU,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAI3D;;;;;OAKG;IACU,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;CAqB5D"}
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.StorageClient = void 0;
30
+ /* eslint-disable @typescript-eslint/no-explicit-any */
31
+ const axios_1 = __importDefault(require("axios"));
32
+ const crypto_1 = __importDefault(require("crypto"));
33
+ const Minio = __importStar(require("minio"));
34
+ const error_1 = require("./error");
35
+ const utils_1 = require("./utils");
36
+ const constants_1 = require("./constants");
37
+ class StorageClient {
38
+ /**
39
+ * **Storage client constructor**
40
+ *
41
+ * @param {StorageCredentials} credentials - Cloud storage access data
42
+ * @param {StorageParams} params - Cloud storage params
43
+ */
44
+ constructor(credentials, params) {
45
+ try {
46
+ this.clientParams = params;
47
+ this.client = new Minio.Client({
48
+ ...params,
49
+ accessKey: credentials.accessKey,
50
+ secretKey: credentials.secretKey,
51
+ });
52
+ }
53
+ catch (e) {
54
+ throw error_1.ErrorStorageClientNotInitialized;
55
+ }
56
+ }
57
+ /**
58
+ * **Download files from cloud storage**
59
+ *
60
+ * @param {string} keys - Keys of files
61
+ * @returns {Promise<File>} - Downloaded file
62
+ */
63
+ async downloadFiles(keys, bucket) {
64
+ const isBucketExists = await this.client.bucketExists(bucket);
65
+ if (!isBucketExists) {
66
+ throw error_1.ErrorStorageBucketNotFound;
67
+ }
68
+ return Promise.all(keys.map(async (key) => {
69
+ try {
70
+ const response = await this.client.getObject(bucket, key);
71
+ const content = response?.read();
72
+ return { key, content: JSON.parse(content?.toString('utf-8') || '') };
73
+ }
74
+ catch (e) {
75
+ throw error_1.ErrorStorageFileNotFound;
76
+ }
77
+ }));
78
+ }
79
+ /**
80
+ * **Download files from cloud storage.*
81
+ *
82
+ * @param {string} url - URL to the file
83
+ * @returns {Promise<File>} - Downloaded file
84
+ */
85
+ static async downloadFileFromUrl(url) {
86
+ if (!(0, utils_1.isValidUrl)(url)) {
87
+ throw error_1.ErrorInvalidUrl;
88
+ }
89
+ try {
90
+ const { data, status } = await axios_1.default.get(url, {
91
+ headers: {
92
+ 'Content-Type': 'application/json',
93
+ },
94
+ });
95
+ if (status !== constants_1.HttpStatus.OK) {
96
+ throw error_1.ErrorStorageFileNotFound;
97
+ }
98
+ return data;
99
+ }
100
+ catch (e) {
101
+ throw error_1.ErrorStorageFileNotFound;
102
+ }
103
+ }
104
+ /**
105
+ * **Upload file to cloud storage**
106
+ *
107
+ * @param {File[]} files - Files to upload
108
+ * @param {string} bucket - Bucket name
109
+ * @returns {Promise<UploadFile>} - Uploaded file with key/hash
110
+ */
111
+ async uploadFiles(files, bucket) {
112
+ const isBucketExists = await this.client.bucketExists(bucket);
113
+ if (!isBucketExists) {
114
+ throw error_1.ErrorStorageBucketNotFound;
115
+ }
116
+ return Promise.all(files.map(async (file) => {
117
+ const content = JSON.stringify(file);
118
+ const hash = crypto_1.default.createHash('sha1').update(content).digest('hex');
119
+ const key = `s3${hash}.json`;
120
+ try {
121
+ await this.client.putObject(bucket, key, content, {
122
+ 'Content-Type': 'application/json',
123
+ });
124
+ return {
125
+ key,
126
+ url: `${this.clientParams.useSSL ? 'https' : 'http'}://${this.clientParams.endPoint}${this.clientParams.port ? `:${this.clientParams.port}` : ''}/${bucket}/${key}`,
127
+ hash,
128
+ };
129
+ }
130
+ catch (e) {
131
+ throw error_1.ErrorStorageFileNotUploaded;
132
+ }
133
+ }));
134
+ }
135
+ /**
136
+ * **Checks if a bucket exists**
137
+ *
138
+ * @param {string} bucket - Name of the bucket
139
+ * @returns {Promise<boolean>} - True if bucket exists, false otherwise
140
+ */
141
+ async bucketExists(bucket) {
142
+ return this.client.bucketExists(bucket);
143
+ }
144
+ /**
145
+ * **Checks if a bucket exists**
146
+ *
147
+ * @param {string} bucket - Name of the bucket
148
+ * @returns {Promise<string[]>} - A list of filenames with their extensions in the bucket
149
+ */
150
+ async listObjects(bucket) {
151
+ const isBucketExists = await this.client.bucketExists(bucket);
152
+ if (!isBucketExists) {
153
+ throw error_1.ErrorStorageBucketNotFound;
154
+ }
155
+ try {
156
+ return new Promise((resolve, reject) => {
157
+ const keys = [];
158
+ const stream = this.client.listObjectsV2(bucket, '', true, '');
159
+ stream.on('data', (obj) => keys.push(obj.name));
160
+ stream.on('error', reject);
161
+ stream.on('end', () => {
162
+ resolve(keys);
163
+ });
164
+ });
165
+ }
166
+ catch (e) {
167
+ throw new Error(String(e));
168
+ }
169
+ }
170
+ }
171
+ exports.StorageClient = StorageClient;