-
Notifications
You must be signed in to change notification settings - Fork 29
/
staking.ts
601 lines (561 loc) · 17.6 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
import {
EscrowFactory,
EscrowFactory__factory,
HMToken,
HMToken__factory,
RewardPool,
RewardPool__factory,
Staking,
Staking__factory,
} from '@human-protocol/core/typechain-types';
import { ContractRunner, Overrides, ethers } from 'ethers';
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 } from './interfaces';
import { NetworkData } from './types';
import { throwError } from './utils';
/**
* ## 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 `runner`.
* To use this client, it is recommended to initialize it using the static `build` method.
*
* ```ts
* static async build(runner: ContractRunner);
* ```
*
* 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 {ContractRunner} runner - The Runner object to interact with the Ethereum network
* @param {NetworkData} network - The network information required to connect to the Staking contract
*/
constructor(runner: ContractRunner, networkData: NetworkData) {
super(runner, networkData);
this.stakingContract = Staking__factory.connect(
networkData.stakingAddress,
runner
);
this.escrowFactoryContract = EscrowFactory__factory.connect(
networkData.factoryAddress,
runner
);
this.tokenContract = HMToken__factory.connect(
networkData.hmtAddress,
runner
);
this.rewardPoolContract = RewardPool__factory.connect(
networkData.rewardPoolAddress,
this.runner
);
}
/**
* Creates an instance of StakingClient from a Runner.
*
* @param {ContractRunner} runner - The Runner 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(runner: ContractRunner) {
if (!runner.provider) {
throw ErrorProviderDoesNotExist;
}
const network = await runner.provider?.getNetwork();
const chainId: ChainId = Number(network?.chainId);
const networkData = NETWORKS[chainId];
if (!networkData) {
throw ErrorUnsupportedChainID;
}
return new StakingClient(runner, networkData);
}
/**
* Check if escrow exists
*
* @param escrowAddress Escrow address to check against
*/
private async checkValidEscrow(escrowAddress: string) {
if (!ethers.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 {bigint} amount Amount in WEI of tokens to approve for stake.
* @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object).
* @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.parseUnits(5, 'ether'); //convert from ETH to WEI
* await stakingClient.approveStake(amount);
* ```
*/
@requiresSigner
public async approveStake(
amount: bigint,
txOptions: Overrides = {}
): Promise<void> {
if (typeof amount !== 'bigint') {
throw ErrorInvalidStakingValueType;
}
if (amount < 0n) {
throw ErrorInvalidStakingValueSign;
}
try {
await (
await this.tokenContract.approve(
await this.stakingContract.getAddress(),
amount,
txOptions
)
).wait();
return;
} catch (e) {
return throwError(e);
}
}
/**
* This function stakes a specified amount of tokens on a specific network.
*
* > `approveStake` must be called before
*
* @param {bigint} amount Amount in WEI of tokens to stake.
* @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object).
* @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.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: bigint, txOptions: Overrides = {}): Promise<void> {
if (typeof amount !== 'bigint') {
throw ErrorInvalidStakingValueType;
}
if (amount < 0n) {
throw ErrorInvalidStakingValueSign;
}
try {
await (await this.stakingContract.stake(amount, txOptions)).wait();
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 {bigint} amount Amount in WEI of tokens to unstake.
* @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object).
* @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.parseUnits(5, 'ether'); //convert from ETH to WEI
* await stakingClient.unstake(amount);
* ```
*/
@requiresSigner
public async unstake(
amount: bigint,
txOptions: Overrides = {}
): Promise<void> {
if (typeof amount !== 'bigint') {
throw ErrorInvalidStakingValueType;
}
if (amount < 0n) {
throw ErrorInvalidStakingValueSign;
}
try {
await (await this.stakingContract.unstake(amount, txOptions)).wait();
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
*
* @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object).
* @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(txOptions: Overrides = {}): Promise<void> {
try {
await (await this.stakingContract.withdraw(txOptions)).wait();
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 {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object).
* @param {bigint} 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.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: bigint,
txOptions: Overrides = {}
): Promise<void> {
if (typeof amount !== 'bigint') {
throw ErrorInvalidStakingValueType;
}
if (amount < 0n) {
throw ErrorInvalidStakingValueSign;
}
if (!ethers.isAddress(slasher)) {
throw ErrorInvalidSlasherAddressProvided;
}
if (!ethers.isAddress(staker)) {
throw ErrorInvalidStakerAddressProvided;
}
await this.checkValidEscrow(escrowAddress);
try {
await (
await this.stakingContract.slash(
slasher,
staker,
escrowAddress,
amount,
txOptions
)
).wait();
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 {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object).
* @param {bigint} 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.parseUnits(5, 'ether'); //convert from ETH to WEI
* await stakingClient.allocate('0x62dD51230A30401C455c8398d06F85e4EaB6309f', amount);
* ```
*/
@requiresSigner
public async allocate(
escrowAddress: string,
amount: bigint,
txOptions: Overrides = {}
): Promise<void> {
if (typeof amount !== 'bigint') {
throw ErrorInvalidStakingValueType;
}
if (amount < 0n) {
throw ErrorInvalidStakingValueSign;
}
await this.checkValidEscrow(escrowAddress);
try {
await (
await this.stakingContract.allocate(escrowAddress, amount, txOptions)
).wait();
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.
* @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object).
* @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,
txOptions: Overrides = {}
): Promise<void> {
await this.checkValidEscrow(escrowAddress);
try {
await (
await this.stakingContract.closeAllocation(escrowAddress, txOptions)
).wait();
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.
* @param {Overrides} [txOptions] - Additional transaction parameters (optional, defaults to an empty object).
* @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,
txOptions: Overrides = {}
): Promise<void> {
await this.checkValidEscrow(escrowAddress);
try {
(
await this.rewardPoolContract.distributeReward(escrowAddress, txOptions)
).wait();
return;
} 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);
}
}
}