-
Notifications
You must be signed in to change notification settings - Fork 29
/
staking.ts
713 lines (665 loc) · 20.8 KB
/
staking.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Provider } from '@ethersproject/abstract-provider';
import { Network } from '@ethersproject/networks';
import {
EscrowFactory,
EscrowFactory__factory,
HMToken,
HMToken__factory,
RewardPool,
RewardPool__factory,
Staking,
Staking__factory,
} from '@human-protocol/core/typechain-types';
import { BigNumber, Signer, ethers } from 'ethers';
import gqlFetch from 'graphql-request';
import { BaseEthersClient } from './base';
import { NETWORKS } from './constants';
import { requiresSigner } from './decorators';
import { ChainId } from './enums';
import {
ErrorEscrowAddressIsNotProvidedByFactory,
ErrorInvalidEscrowAddressProvided,
ErrorInvalidSlasherAddressProvided,
ErrorInvalidStakerAddressProvided,
ErrorInvalidStakingValueSign,
ErrorInvalidStakingValueType,
ErrorProviderDoesNotExist,
ErrorUnsupportedChainID,
} from './error';
import { IAllocation, ILeader, ILeadersFilter, IReward } from './interfaces';
import { NetworkData } from './types';
import { throwError } from './utils';
import { GET_REWARD_ADDED_EVENTS_QUERY } from './graphql/queries/reward';
import { RewardAddedEventData } from './graphql';
import { GET_LEADER_QUERY, GET_LEADERS_QUERY } from './graphql/queries/staking';
/**
* ## Introduction
*
* This client enables to perform actions on staking contracts and obtain staking information from both the contracts and subgraph.
*
* Internally, the SDK will use one network or another according to the network ID of the `signerOrProvider`.
* To use this client, it is recommended to initialize it using the static `build` method.
*
* ```ts
* static async build(signerOrProvider: Signer | Provider);
* ```
*
* A `Signer` or a `Provider` should be passed depending on the use case of this module:
*
* - **Signer**: when the user wants to use this model in order to send transactions caling the contract functions.
* - **Provider**: when the user wants to use this model in order to get information from the contracts or subgraph.
*
* ## Installation
*
* ### npm
* ```bash
* npm install @human-protocol/sdk
* ```
*
* ### yarn
* ```bash
* yarn install @human-protocol/sdk
* ```
*
* ## Code example
*
* ### Signer
*
* **Using private key(backend)**
*
* ```ts
* import { StakingClient } from '@human-protocol/sdk';
* import { Wallet, providers } from 'ethers';
*
* const rpcUrl = 'YOUR_RPC_URL';
* const privateKey = 'YOUR_PRIVATE_KEY'
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const signer = new Wallet(privateKey, provider);
* const stakingClient = await StakingClient.build(signer);
* ```
*
* **Using Wagmi(frontend)**
*
* ```ts
* import { useSigner, useChainId } from 'wagmi';
* import { StakingClient } from '@human-protocol/sdk';
*
* const { data: signer } = useSigner();
* const stakingClient = await StakingClient.build(signer);
* ```
*
* ### Provider
*
* ```ts
* import { StakingClient } from '@human-protocol/sdk';
* import { providers } from 'ethers';
*
* const rpcUrl = 'YOUR_RPC_URL';
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const stakingClient = await StakingClient.build(provider);
* ```
*/
export class StakingClient extends BaseEthersClient {
public tokenContract: HMToken;
public stakingContract: Staking;
public escrowFactoryContract: EscrowFactory;
public rewardPoolContract: RewardPool;
/**
* **StakingClient constructor**
*
* @param {Signer | Provider} signerOrProvider - The Signer or Provider object to interact with the Ethereum network
* @param {NetworkData} network - The network information required to connect to the Staking contract
* @param {number | undefined} gasPriceMultiplier - The multiplier to apply to the gas price
*/
constructor(
signerOrProvider: Signer | Provider,
networkData: NetworkData,
gasPriceMultiplier?: number
) {
super(signerOrProvider, networkData, gasPriceMultiplier);
this.stakingContract = Staking__factory.connect(
networkData.stakingAddress,
signerOrProvider
);
this.escrowFactoryContract = EscrowFactory__factory.connect(
networkData.factoryAddress,
signerOrProvider
);
this.tokenContract = HMToken__factory.connect(
networkData.hmtAddress,
signerOrProvider
);
this.rewardPoolContract = RewardPool__factory.connect(
networkData.rewardPoolAddress,
this.signerOrProvider
);
}
/**
* Creates an instance of StakingClient from a Signer or Provider.
*
* @param {Signer | Provider} signerOrProvider - The Signer or Provider object to interact with the Ethereum network
* @param {number | undefined} gasPriceMultiplier - The multiplier to apply to the gas price
*
* @returns {Promise<StakingClient>} - An instance of StakingClient
* @throws {ErrorProviderDoesNotExist} - Thrown if the provider does not exist for the provided Signer
* @throws {ErrorUnsupportedChainID} - Thrown if the network's chainId is not supported
*/
public static async build(
signerOrProvider: Signer | Provider,
gasPriceMultiplier?: number
) {
let network: Network;
if (Signer.isSigner(signerOrProvider)) {
if (!signerOrProvider.provider) {
throw ErrorProviderDoesNotExist;
}
network = await signerOrProvider.provider.getNetwork();
} else {
network = await signerOrProvider.getNetwork();
}
const chainId: ChainId = network.chainId;
const networkData = NETWORKS[chainId];
if (!networkData) {
throw ErrorUnsupportedChainID;
}
return new StakingClient(signerOrProvider, networkData, gasPriceMultiplier);
}
/**
* Check if escrow exists
*
* @param escrowAddress Escrow address to check against
*/
private async checkValidEscrow(escrowAddress: string) {
if (!ethers.utils.isAddress(escrowAddress)) {
throw ErrorInvalidEscrowAddressProvided;
}
if (!(await this.escrowFactoryContract.hasEscrow(escrowAddress))) {
throw ErrorEscrowAddressIsNotProvidedByFactory;
}
}
/**
* This function approves the staking contract to transfer a specified amount of tokens when the user stakes. It increases the allowance for the staking contract.
*
* @param {BigNumber} amount Amount in WEI of tokens to approve for stake.
* @returns Returns void if successful. Throws error if any.
*
*
* **Code example**
*
* ```ts
* import { ethers, Wallet, providers } from 'ethers';
* import { StakingClient } from '@human-protocol/sdk';
*
* const rpcUrl = 'YOUR_RPC_URL';
* const privateKey = 'YOUR_PRIVATE_KEY'
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const signer = new Wallet(privateKey, provider);
* const stakingClient = await StakingClient.build(signer);
*
* const amount = ethers.utils.parseUnits(5, 'ether'); //convert from ETH to WEI
* await stakingClient.approveStake(amount);
* ```
*/
@requiresSigner
public async approveStake(amount: BigNumber): Promise<void> {
if (!BigNumber.isBigNumber(amount)) {
throw ErrorInvalidStakingValueType;
}
if (amount.isNegative()) {
throw ErrorInvalidStakingValueSign;
}
try {
await this.tokenContract.approve(this.stakingContract.address, amount, {
...(await this.gasPriceOptions()),
});
return;
} catch (e) {
return throwError(e);
}
}
/**
* This function stakes a specified amount of tokens on a specific network.
*
* > `approveStake` must be called before
*
* @param {BigNumber} amount Amount in WEI of tokens to stake.
* @returns Returns void if successful. Throws error if any.
*
*
* **Code example**
*
* ```ts
* import { ethers, Wallet, providers } from 'ethers';
* import { StakingClient } from '@human-protocol/sdk';
*
* const rpcUrl = 'YOUR_RPC_URL';
* const privateKey = 'YOUR_PRIVATE_KEY'
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const signer = new Wallet(privateKey, provider);
* const stakingClient = await StakingClient.build(signer);
*
* const amount = ethers.utils.parseUnits(5, 'ether'); //convert from ETH to WEI
* await stakingClient.approveStake(amount); // if it was already approved before, this is not necessary
* await stakingClient.approveStake(amount);
* ```
*/
@requiresSigner
public async stake(amount: BigNumber): Promise<void> {
if (!BigNumber.isBigNumber(amount)) {
throw ErrorInvalidStakingValueType;
}
if (amount.isNegative()) {
throw ErrorInvalidStakingValueSign;
}
try {
await this.stakingContract.stake(amount, {
...(await this.gasPriceOptions()),
});
return;
} catch (e) {
return throwError(e);
}
}
/**
* This function unstakes tokens from staking contract. The unstaked tokens stay locked for a period of time.
*
* > Must have tokens available to unstake
*
* @param {BigNumber} amount Amount in WEI of tokens to unstake.
* @returns Returns void if successful. Throws error if any.
*
*
* **Code example**
*
* ```ts
* import { ethers, Wallet, providers } from 'ethers';
* import { StakingClient } from '@human-protocol/sdk';
*
* const rpcUrl = 'YOUR_RPC_URL';
* const privateKey = 'YOUR_PRIVATE_KEY'
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const signer = new Wallet(privateKey, provider);
* const stakingClient = await StakingClient.build(signer);
*
* const amount = ethers.utils.parseUnits(5, 'ether'); //convert from ETH to WEI
* await stakingClient.unstake(amount);
* ```
*/
@requiresSigner
public async unstake(amount: BigNumber): Promise<void> {
if (!BigNumber.isBigNumber(amount)) {
throw ErrorInvalidStakingValueType;
}
if (amount.isNegative()) {
throw ErrorInvalidStakingValueSign;
}
try {
await this.stakingContract.unstake(amount, {
...(await this.gasPriceOptions()),
});
return;
} catch (e) {
return throwError(e);
}
}
/**
* This function withdraws unstaked and non locked tokens form staking contract to the user wallet.
*
* > Must have tokens available to withdraw
*
* @returns Returns void if successful. Throws error if any.
*
*
* **Code example**
*
* ```ts
* import { Wallet, providers } from 'ethers';
* import { StakingClient } from '@human-protocol/sdk';
*
* const rpcUrl = 'YOUR_RPC_URL';
* const privateKey = 'YOUR_PRIVATE_KEY'
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const signer = new Wallet(privateKey, provider);
* const stakingClient = await StakingClient.build(signer);
*
* await stakingClient.withdraw();
* ```
*/
@requiresSigner
public async withdraw(): Promise<void> {
try {
await this.stakingContract.withdraw({
...(await this.gasPriceOptions()),
});
return;
} catch (e) {
return throwError(e);
}
}
/**
* This function reduces the allocated amount by an staker in an escrow and transfers those tokens to the reward pool. This allows the slasher to claim them later.
*
* @param {string} slasher Wallet address from who requested the slash
* @param {string} staker Wallet address from who is going to be slashed
* @param {string} escrowAddress Address of the escrow which allocation will be slashed
* @param {BigNumber} amount Amount in WEI of tokens to unstake.
* @returns Returns void if successful. Throws error if any.
*
*
* **Code example**
*
* ```ts
* import { ethers, Wallet, providers } from 'ethers';
* import { StakingClient } from '@human-protocol/sdk';
*
* const rpcUrl = 'YOUR_RPC_URL';
* const privateKey = 'YOUR_PRIVATE_KEY'
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const signer = new Wallet(privateKey, provider);
* const stakingClient = await StakingClient.build(signer);
*
* const amount = ethers.utils.parseUnits(5, 'ether'); //convert from ETH to WEI
* await stakingClient.slash('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount);
* ```
*/
@requiresSigner
public async slash(
slasher: string,
staker: string,
escrowAddress: string,
amount: BigNumber
): Promise<void> {
if (!BigNumber.isBigNumber(amount)) {
throw ErrorInvalidStakingValueType;
}
if (amount.isNegative()) {
throw ErrorInvalidStakingValueSign;
}
if (!ethers.utils.isAddress(slasher)) {
throw ErrorInvalidSlasherAddressProvided;
}
if (!ethers.utils.isAddress(staker)) {
throw ErrorInvalidStakerAddressProvided;
}
await this.checkValidEscrow(escrowAddress);
try {
await this.stakingContract.slash(slasher, staker, escrowAddress, amount, {
...(await this.gasPriceOptions()),
});
return;
} catch (e) {
return throwError(e);
}
}
/**
* This function allocates a portion of the staked tokens to a specific escrow.
*
* > Must have tokens staked
*
* @param {string} escrowAddress Address of the escrow contract to allocate in.
* @param {BigNumber} amount Amount in WEI of tokens to allocate.
* @returns Returns void if successful. Throws error if any.
*
*
* **Code example**
*
* ```ts
* import { ethers, Wallet, providers } from 'ethers';
* import { StakingClient } from '@human-protocol/sdk';
*
* const rpcUrl = 'YOUR_RPC_URL';
* const privateKey = 'YOUR_PRIVATE_KEY'
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const signer = new Wallet(privateKey, provider);
* const stakingClient = await StakingClient.build(signer);
*
* const amount = ethers.utils.parseUnits(5, 'ether'); //convert from ETH to WEI
* await stakingClient.allocate('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount);
* ```
*/
@requiresSigner
public async allocate(
escrowAddress: string,
amount: BigNumber
): Promise<void> {
if (!BigNumber.isBigNumber(amount)) {
throw ErrorInvalidStakingValueType;
}
if (amount.isNegative()) {
throw ErrorInvalidStakingValueSign;
}
await this.checkValidEscrow(escrowAddress);
try {
await this.stakingContract.allocate(escrowAddress, amount, {
...(await this.gasPriceOptions()),
});
return;
} catch (e) {
return throwError(e);
}
}
/**
* This function drops the allocation from a specific escrow.
*
* > The escrow must have allocation
* > The escrow must be cancelled or completed.
*
* @param {string} escrowAddress Address of the escrow contract to close allocation from.
* @returns Returns void if successful. Throws error if any.
*
*
* **Code example**
*
* ```ts
* import { Wallet, providers } from 'ethers';
* import { StakingClient } from '@human-protocol/sdk';
*
* const rpcUrl = 'YOUR_RPC_URL';
* const privateKey = 'YOUR_PRIVATE_KEY'
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const signer = new Wallet(privateKey, provider);
* const stakingClient = await StakingClient.build(signer);
*
* await stakingClient.closeAllocation('0x62dD51230A30401C455c8398d06F85e4EaB6309f');
* ```
*/
@requiresSigner
public async closeAllocation(escrowAddress: string): Promise<void> {
await this.checkValidEscrow(escrowAddress);
try {
await this.stakingContract.closeAllocation(escrowAddress, {
...(await this.gasPriceOptions()),
});
return;
} catch (e) {
return throwError(e);
}
}
/**
* This function drops the allocation from a specific escrow.
*
* > The escrow must have rewards added
*
* @param {string} escrowAddress Escrow address from which rewards are distributed.
* @returns Returns void if successful. Throws error if any.
*
*
* **Code example**
*
* ```ts
* import { Wallet, providers } from 'ethers';
* import { StakingClient } from '@human-protocol/sdk';
*
* const rpcUrl = 'YOUR_RPC_URL';
* const privateKey = 'YOUR_PRIVATE_KEY'
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const signer = new Wallet(privateKey, provider);
* const stakingClient = await StakingClient.build(signer);
*
* await stakingClient.distributeReward('0x62dD51230A30401C455c8398d06F85e4EaB6309f');
* ```
*/
@requiresSigner
public async distributeReward(escrowAddress: string): Promise<void> {
await this.checkValidEscrow(escrowAddress);
try {
this.rewardPoolContract.distributeReward(escrowAddress, {
...(await this.gasPriceOptions()),
});
return;
} catch (e) {
return throwError(e);
}
}
/**
* This function returns all the leader details of the protocol.
*
* @param {ILeadersFilter} filter Filter for the leaders.
* @returns {ILeader[]} Returns an array with all the leader details.
*
*
* **Code example**
*
* ```ts
* import { StakingClient } from '@human-protocol/sdk';
* import { providers } from 'ethers';
*
* const rpcUrl = 'YOUR_RPC_URL';
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const stakingClient = await StakingClient.build(provider);
*
* const leaders = await stakingClient.getLeaders();
* ```
*/
public async getLeader(address: string): Promise<ILeader> {
if (!ethers.utils.isAddress(address)) {
throw ErrorInvalidStakerAddressProvided;
}
try {
const { leader } = await gqlFetch<{
leader: ILeader;
}>(this.networkData.subgraphUrl, GET_LEADER_QUERY, {
address: address.toLowerCase(),
});
return leader;
} catch (e) {
return throwError(e);
}
}
/**
* This function returns the leader data for the given address.
*
* @param {string} address Leader address.
* @returns {ILeader} Returns the leader details.
*
*
* **Code example**
*
* ```ts
* import { StakingClient } from '@human-protocol/sdk';
* import { providers } from 'ethers';
*
* const rpcUrl = 'YOUR_RPC_URL';
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const stakingClient = await StakingClient.build(provider);
*
* const leader = await stakingClient.getLeader('0x62dD51230A30401C455c8398d06F85e4EaB6309f');
* ```
*/
public async getLeaders(filter: ILeadersFilter = {}): Promise<ILeader[]> {
try {
const { leaders } = await gqlFetch<{
leaders: ILeader[];
}>(this.networkData.subgraphUrl, GET_LEADERS_QUERY(filter), {
role: filter.role,
});
return leaders;
} catch (e) {
return throwError(e);
}
}
/**
* This function returns information about the allocation of the specified escrow.
*
* @param {string} escrowAddress Escrow address from which we want to get allocation information.
* @returns {IAllocation} Returns allocation info if exists.
*
*
* **Code example**
*
* ```ts
* import { StakingClient } from '@human-protocol/sdk';
* import { providers } from 'ethers';
*
* const rpcUrl = 'YOUR_RPC_URL';
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const stakingClient = await StakingClient.build(provider);
*
* const allocationInfo = await stakingClient.getAllocation('0x62dD51230A30401C455c8398d06F85e4EaB6309f');
* ```
*/
public async getAllocation(escrowAddress: string): Promise<IAllocation> {
await this.checkValidEscrow(escrowAddress);
try {
const result = await this.stakingContract.getAllocation(escrowAddress);
return result;
} catch (e) {
return throwError(e);
}
}
/**
* This function returns information about the rewards for a given slasher address.
*
* @param {string} slasherAddress Slasher address.
* @returns {IReward[]} Returns an array of Reward objects that contain the rewards earned by the user through slashing other users.
*
*
* **Code example**
*
* ```ts
* import { StakingClient } from '@human-protocol/sdk';
* import { providers } from 'ethers';
*
* const rpcUrl = 'YOUR_RPC_URL';
*
* const provider = new providers.JsonRpcProvider(rpcUrl);
* const stakingClient = await StakingClient.build(provider);
*
* const rewards = await stakingClient.getRewards('0x62dD51230A30401C455c8398d06F85e4EaB6309f');
* ```
*/
public async getRewards(slasherAddress: string): Promise<IReward[]> {
if (!ethers.utils.isAddress(slasherAddress)) {
throw ErrorInvalidSlasherAddressProvided;
}
try {
const { rewardAddedEvents } = await gqlFetch<{
rewardAddedEvents: RewardAddedEventData[];
}>(this.networkData.subgraphUrl, GET_REWARD_ADDED_EVENTS_QUERY, {
slasherAddress: slasherAddress.toLowerCase(),
});
return rewardAddedEvents.map((reward: any) => {
return {
escrowAddress: reward.escrow,
amount: reward.amount,
};
});
} catch (e) {
return throwError(e);
}
}
}