-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.ts
382 lines (343 loc) · 11.8 KB
/
index.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
import TokenStaking from "@threshold-network/solidity-contracts/artifacts/TokenStaking.json"
import KeepTokenStaking from "@keep-network/keep-core/artifacts/TokenStaking.json"
import { BigNumber, BigNumberish, Contract, ContractTransaction } from "ethers"
import { ContractCall, IMulticall } from "../multicall"
import { EthereumConfig } from "../types"
import {
getArtifact,
getContract,
getContractAddressFromTruffleArtifact,
getContractPastEvents,
isAddress,
isSameETHAddress,
ZERO,
} from "../utils"
import { IVendingMachines } from "../vending-machine"
// Note: Must be in the same order as here:
// /~https://github.com/threshold-network/solidity-contracts/blob/main/contracts/staking/IStaking.sol#L30-L
// because solidity eg. for `StakeType.NU` returns 0.
export enum StakeType {
NU,
KEEP,
T,
}
export interface Stake<NumberType extends BigNumberish = BigNumber> {
stakeType?: StakeType
owner: string
stakingProvider: string
beneficiary: string
authorizer: string
nuInTStake: NumberType
keepInTStake: NumberType
tStake: NumberType
totalInTStake: NumberType
possibleKeepTopUpInT: NumberType
possibleNuTopUpInT: NumberType
}
export interface RolesOf {
owner: string
beneficiary: string
authorizer: string
}
interface OwnerRefreshedResult {
current: string[]
outdated: string[]
}
export interface IStaking {
stakingContract: Contract
legacyNuStakingContract: Contract
STAKING_CONTRACT_DEPLOYMENT_BLOCK: number
/**
* Returns the authorized stake amount of the staking provider for the application.
* @param stakingProvider Staking provider address.
* @param application Application address.
* @returns Authorized stake amount.
*/
authorizedStake(
stakingProvider: string,
application: string
): Promise<BigNumber>
/**
* Increases the authorization of the given staking provider for the given
* application by the given amount. Can only be called by the given staking
* provider’s authorizer.
* @param stakingProvider Staking provider address.
* @param application Application address.
* @param amount Amount to authrozie.
* @returns Ethers `ContractTransaction` instance.
*/
increaseAuthorization(
stakingProvider: string,
application: string,
amount: BigNumberish
): Promise<ContractTransaction>
/**
* Returns the stake data by given staking provider address.
* @param stakingProvider Staking provider address.
* @returns Stake data.
*/
getStakeByStakingProvider(stakingProvider: string): Promise<Stake>
requestAuthorizationDecrease(
stakingProvider: string,
application: string,
amount: BigNumberish
): Promise<ContractTransaction>
/**
* Gets the stake owner, the beneficiary and the authorizer for the specified
* staking provider address.
* @param stakingProvider Staking provider address
* @returns Object containing owner, beneficiary and authorizer of the given
* stake. If the staking provider is not used in any stake then it returns
* zero address for each role.
*/
rolesOf(stakingProvider: string): Promise<RolesOf>
/**
* Returns all stakes for the given owner address.
* @param owner The stake owner address.
* @returns All stakes for a given owner address.
*/
getOwnerStakes(owner: string): Promise<Array<Stake>>
/**
* Returns the current and outdated staking providers for a givne owner
* address. The outdated array is necessary while fetching all owner stakes.
* We need to filter out outdated staking providers eg. the `Staked` event was
* emitted with the owner address that we are looking for but then the owner
* was changed(`OwnerRefreshed` event emitted with `oldOwner = owner`) meaning the
* owner is not the owner of this staking- we should skip that address.
* @param owner The stake owner address.
* @returns Two arrays: current and outdated staking providers.
*/
findRefreshedKeepStakes(owner: string): Promise<OwnerRefreshedResult>
}
export class Staking implements IStaking {
private _staking: Contract
private _multicall: IMulticall
private _legacyKeepStaking: Contract
private _legacyNuStaking: Contract
private _vendingMachines: IVendingMachines
public readonly STAKING_CONTRACT_DEPLOYMENT_BLOCK: number
constructor(
config: EthereumConfig,
multicall: IMulticall,
vendingMachines: IVendingMachines
) {
this.STAKING_CONTRACT_DEPLOYMENT_BLOCK = config.chainId === 1 ? 14113768 : 0
this._staking = getContract(
TokenStaking.address,
TokenStaking.abi,
config.providerOrSigner,
config.account
)
this._legacyKeepStaking = getContract(
getContractAddressFromTruffleArtifact(KeepTokenStaking),
KeepTokenStaking.abi,
config.providerOrSigner,
config.account
)
const NuCypherStakingEscrowArtifact = getArtifact(
"NuCypherStakingEscrow",
config.chainId,
config.shouldUseTestnetDevelopmentContracts
)
this._legacyNuStaking = getContract(
NuCypherStakingEscrowArtifact.address,
NuCypherStakingEscrowArtifact.abi,
config.providerOrSigner,
config.account
)
this._multicall = multicall
this._vendingMachines = vendingMachines
}
async authorizedStake(
stakingProvider: string,
application: string
): Promise<BigNumber> {
return this._staking.authorizedStake(stakingProvider, application)
}
get stakingContract() {
return this._staking
}
get legacyNuStakingContract() {
return this._legacyNuStaking
}
increaseAuthorization = async (
stakingProvider: string,
application: string,
amount: BigNumberish
): Promise<ContractTransaction> => {
return await this._staking.increaseAuthorization(
stakingProvider,
application,
amount
)
}
getStakeByStakingProvider = async (
stakingProvider: string,
stakeType?: StakeType
): Promise<Stake> => {
const multicalls: ContractCall[] = [
{
interface: this._staking.interface,
address: this._staking.address,
method: "rolesOf",
args: [stakingProvider],
},
{
interface: this._staking.interface,
address: this._staking.address,
method: "stakes",
args: [stakingProvider],
},
{
interface: this._legacyKeepStaking.interface,
address: this._legacyKeepStaking.address,
method: "eligibleStake",
args: [stakingProvider, this._staking.address],
},
]
const [rolesOf, stakes, { balance: eligibleKeepStake }] =
await this._multicall.aggregate(multicalls)
const { owner, authorizer, beneficiary } = rolesOf
const { tStake, keepInTStake, nuInTStake } = stakes
// The NU staker can have only one stake.
const { stakingProvider: nuStakingProvider, value: nuStake } =
await this._legacyNuStaking.stakerInfo(owner)
const possibleNuTopUpInT =
isAddress(nuStakingProvider) &&
isSameETHAddress(stakingProvider, nuStakingProvider)
? BigNumber.from(
(await this._vendingMachines.nu.convertToT(nuStake.toString()))
.tAmount
).sub(BigNumber.from(nuInTStake.toString()))
: ZERO
const keepEligableStakeInT = (
await this._vendingMachines.keep.convertToT(eligibleKeepStake.toString())
).tAmount
const possibleKeepTopUpInT = BigNumber.from(keepEligableStakeInT).sub(
BigNumber.from(keepInTStake)
)
const totalInTStake = tStake.add(keepInTStake).add(nuInTStake)
return {
stakeType,
owner,
authorizer,
beneficiary,
stakingProvider,
tStake,
keepInTStake,
nuInTStake,
totalInTStake,
possibleKeepTopUpInT,
possibleNuTopUpInT,
}
}
requestAuthorizationDecrease = async (
stakingProvider: string,
application: string,
amount: BigNumberish
): Promise<ContractTransaction> => {
return await this._staking[
"requestAuthorizationDecrease(address,address,uint96)"
](stakingProvider, application, amount)
}
rolesOf = async (stakingProvider: string): Promise<RolesOf> => {
const rolesOf = await this._staking.rolesOf(stakingProvider)
return {
owner: rolesOf.owner,
beneficiary: rolesOf.beneficiary,
authorizer: rolesOf.authorizer,
}
}
getOwnerStakes = async (owner: string): Promise<Array<Stake>> => {
const stakes = (
await getContractPastEvents(this._staking, {
eventName: "Staked",
fromBlock: this.STAKING_CONTRACT_DEPLOYMENT_BLOCK,
filterParams: [undefined, owner],
})
)
.map((event) => ({
stakingProvider: event.args?.stakingProvider,
stakeType: event.args?.stakeType,
}))
.reverse()
const { current, outdated } = await this.findRefreshedKeepStakes(owner)
const stakingProviders = stakes
.filter(({ stakingProvider }) => !outdated.includes(stakingProvider))
.concat(
current.map((stakingProvider) => ({
stakingProvider,
stakeType: StakeType.KEEP,
}))
)
return await Promise.all(
stakingProviders.map(({ stakingProvider, stakeType }) =>
this.getStakeByStakingProvider(stakingProvider, stakeType)
)
)
}
findRefreshedKeepStakes = async (
owner: string
): Promise<OwnerRefreshedResult> => {
// Find all events where the `owner` was set as a new owner or old owner of
// the stake.
const ownerRefreshedEventsFilteredByNewOwner = await getContractPastEvents(
this._staking,
{
eventName: "OwnerRefreshed",
filterParams: [null, null, owner],
fromBlock: this.STAKING_CONTRACT_DEPLOYMENT_BLOCK,
}
)
const ownerRefreshedEventsFilteredByOldOwner = await getContractPastEvents(
this._staking,
{
eventName: "OwnerRefreshed",
filterParams: [null, owner, null],
fromBlock: this.STAKING_CONTRACT_DEPLOYMENT_BLOCK,
}
)
const ownerRefreshedEvents = [
...ownerRefreshedEventsFilteredByNewOwner,
...ownerRefreshedEventsFilteredByOldOwner,
].sort((a, b) => a.blockNumber - b.blockNumber)
// Convert to `Set` to remove duplicated staking provider addresses(the
// owner can be changed multiple times for the same staking provider) and
// then to an array so we can use `map`, `filter` and other array methods.
const possibleStakingProviders: string[] = Array.from(
new Set(ownerRefreshedEvents.map((event) => event?.args?.stakingProvider))
)
const multicalls: ContractCall[] = possibleStakingProviders.map(
(stakingProvider) => ({
address: this._staking.address,
interface: this._staking.interface,
method: "rolesOf",
args: [stakingProvider],
})
)
// For each staking provider, we need to verify that the current owner of
// the stake is indeed the one we are looking for (the `owner` argument).
// It's possible that the owner can be changed multiple times. Instead of
// iterating through the `OwnerRefreshed` events and comparing the
// `oldOwner` and `newOwner` params from that event, we can just check the
// current owner for a given staking provider by calling `rolesOf`.
const rolesOf: RolesOf[] = await this._multicall.aggregate(multicalls)
// The current staking providers for a given `owner` address.
const stakingProviders: string[] = rolesOf
.map((_, index) => ({
..._,
stakingProvider: possibleStakingProviders[index],
}))
.filter((rolesOf) => isSameETHAddress(rolesOf.owner, owner))
.map((_) => _.stakingProvider)
// Outdated staking providers - the `owner` address is no longer an owner of
// these stakes.
const outdatedStakingProviders: string[] = possibleStakingProviders.filter(
(stakingProvider) => !stakingProviders.includes(stakingProvider)
)
return {
current: stakingProviders,
outdated: outdatedStakingProviders,
}
}
}