-
Notifications
You must be signed in to change notification settings - Fork 7
/
staking.service.ts
268 lines (242 loc) · 8.77 KB
/
staking.service.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
import { BigNumber, providers, utils } from "ethers";
import { StakingPool as StakingPoolContract, StakingPoolFactory } from "../../../ethers";
import { StakingPoolFactory__factory } from "../../../ethers/factories/StakingPoolFactory__factory";
import { StakingPool__factory } from "../../../ethers/factories/StakingPool__factory";
import { ERROR_MESSAGES } from "../../errors/ErrorMessages";
import { emptyAddress } from "../../utils/constants";
import { SignerService } from "../signer/signer.service";
import { chainConfigs } from "../../config/chain.config";
import { DomainsService } from "../domains/domains.service";
const { namehash, parseUnits } = utils;
export enum StakeStatus {
NONSTAKING = 0,
STAKING = 1,
WITHDRAWING = 2,
}
export type Service = {
/** organization ENS name */
org: string;
/** pool address */
pool: string;
/** provider address */
provider: string;
};
export type Stake = {
amount: BigNumber;
depositStart: BigNumber;
depositEnd: BigNumber;
status: StakeStatus;
};
/**
* Inteneded for staking pools management
*/
export class StakingService {
private _stakingPoolFactoryAddress: string;
private _stakingPoolFactory: StakingPoolFactory;
constructor(private _signerService: SignerService, private _domainsService: DomainsService) {
this._signerService.onInit(this.init.bind(this));
}
static async create(signerService: SignerService, domainsService: DomainsService) {
const service = new StakingService(signerService, domainsService);
await service.init();
return service;
}
/**
* @description Connects to the same chain as `signer`. The signer must be connected
* @param signer Signer with connected provider
*/
async init() {
const chainId = this._signerService.chainId;
this._stakingPoolFactoryAddress = chainConfigs()[chainId].stakingPoolFactoryAddress;
this._stakingPoolFactory = new StakingPoolFactory__factory(
StakingPoolFactory__factory.createInterface(),
StakingPoolFactory__factory.bytecode,
)
.attach(this._stakingPoolFactoryAddress)
.connect(this._signerService.provider);
}
/**
* @description Deployes organization staking pool
* @emits StakingPoolFactory.StakingPoolLaunched
*/
async launchPool({
org,
minStakingPeriod,
patronRewardPortion,
patronRoles,
principal,
}: {
/** organization ENS name */
org: string;
/** minimum staking period in seconds */
minStakingPeriod: number | BigNumber;
/** patron's part of the reward in fractions of thousandth */
patronRewardPortion: number;
/** roles required to stake */
patronRoles: string[];
/** stake put by service provider when pool is launched */
principal: BigNumber;
}): Promise<void> {
const tx: providers.TransactionRequest = {
to: this._stakingPoolFactoryAddress,
data: this._stakingPoolFactory.interface.encodeFunctionData("launchStakingPool", [
namehash(org),
minStakingPeriod,
patronRewardPortion,
patronRoles.map((r) => namehash(r)),
]),
value: principal,
};
await this._signerService.send(tx);
}
/**
* @description Returns all services for which pools are launched
*/
async allServices(): Promise<Service[]> {
const orgs = await this._stakingPoolFactory.orgsList();
return Promise.all(
orgs.map((org) =>
this._stakingPoolFactory
.services(org)
.then((service) => ({ ...service, org }))
.then((service) => this._domainsService.readName(service.org).then((org) => ({ ...service, org }))),
),
);
}
/**
* @description Returns pool launched for `org` if any
* @param org ENS name of organization
*/
async getPool(org: string): Promise<StakingPool | null> {
const { pool } = await this._stakingPoolFactory.connect(this._signerService.signer).services(namehash(org));
if (pool === emptyAddress) {
return null;
}
return new StakingPool(this._signerService, pool);
}
}
/**
* Abstraction over staking pool smart contract
*/
export class StakingPool {
private overrides = {
gasPrice: parseUnits("0.01", "gwei"),
gasLimit: BigNumber.from(490000),
};
private pool: StakingPoolContract;
constructor(private signerService: SignerService, address: string) {
this.pool = new StakingPool__factory(
StakingPool__factory.createInterface(),
StakingPool__factory.bytecode,
).attach(address);
}
/**
* @description Locks stake and starts accumulating reward
* @emits StakingPool.StakePut
*/
async putStake(
/** stake amount */
stake: BigNumber | number,
): Promise<void> {
stake = BigNumber.from(stake);
const tx: providers.TransactionRequest = {
to: this.pool.address,
from: this.signerService.address,
data: this.pool.interface.encodeFunctionData("putStake"),
value: stake,
};
const [gasPrice, gas, balance] = await Promise.all([
this.signerService.signer.getGasPrice(),
this.signerService.provider.estimateGas(tx),
this.signerService.balance(),
]);
// multiplier 2 chosen arbitrarily because it is not known how reasonably to choose it
const fee = gasPrice.mul(gas).mul(2);
const maxStake = balance.sub(fee);
if (maxStake.lte(0)) {
throw new Error(ERROR_MESSAGES.INSUFFICIENT_BALANCE);
}
tx.value = stake.lt(maxStake) ? stake : maxStake;
await this.signerService.send(tx);
}
/**
* @description Returns time left to enable request withdraw
*/
async requestWithdrawDelay(): Promise<number> {
const { depositStart, status } = await this.getStake();
if (status !== StakeStatus.STAKING) {
throw new Error(ERROR_MESSAGES.STAKE_WAS_NOT_PUT);
}
const requestAvailableFrom = depositStart.add(
await this.pool.connect(this.signerService.signer).minStakingPeriod(),
);
const now = await this.now();
if (requestAvailableFrom.lte(now)) {
return 0;
} else {
return requestAvailableFrom.sub(now).toNumber();
}
}
/**
* Accumulated reward
*/
async checkReward(): Promise<BigNumber> {
return this.pool.connect(this.signerService.signer).checkReward();
}
/**
* @param patron staker address
* @returns Stake
*/
async getStake(patron?: string): Promise<Stake> {
if (!patron) {
patron = this.signerService.address;
}
return this.pool.connect(this.signerService.signer).stakes(patron);
}
/**
* @description Stops accumulating of the reward and prepars stake to withdraw after withdraw delay.
* Withdraw request unavailable until minimum staking period ends
*/
async requestWithdraw(): Promise<void> {
const tx: providers.TransactionRequest = {
to: this.pool.address,
data: this.pool.interface.encodeFunctionData("requestWithdraw"),
...this.overrides,
};
await this.signerService.send(tx);
}
/**
* @description Returns time left to enable withdraw
*/
async withdrawalDelay(): Promise<number> {
const { depositEnd, status } = await this.getStake();
if (status !== StakeStatus.WITHDRAWING) {
throw new Error(ERROR_MESSAGES.WITHDRAWAL_WAS_NOT_REQUESTED);
}
const withdrawAvailableFrom = depositEnd.add(
await this.pool.connect(this.signerService.signer).withdrawDelay(),
);
const now = await this.now();
if (withdrawAvailableFrom.lte(now)) {
return 0;
} else {
return withdrawAvailableFrom.sub(now).toNumber();
}
}
/**
* @description pays back stake with accumulated reward. Withdrawn unavailable until withdrawn delay ends
* @emits StakingPool.StakeWithdrawn
*/
async withdraw(): Promise<void> {
const tx: providers.TransactionRequest = {
to: this.pool.address,
data: this.pool.interface.encodeFunctionData("withdraw"),
...this.overrides,
};
await this.signerService.send(tx);
}
private async now(): Promise<BigNumber> {
const lastBlock = await this.signerService.provider.getBlockNumber();
return BigNumber.from((await this.signerService.provider.getBlock(lastBlock)).timestamp);
}
}