-
Notifications
You must be signed in to change notification settings - Fork 458
/
stake.ts
336 lines (292 loc) · 9.45 KB
/
stake.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
/*
* Copyright © 2021 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
import { dataStructures } from '@liskhq/lisk-utils';
import { ValidationError } from '../../../errors';
import {
CommandVerifyContext,
VerificationResult,
VerifyStatus,
CommandExecuteContext,
} from '../../../state_machine';
import { BaseCommand } from '../../base_command';
import { MODULE_NAME_POS, PoSEventResult } from '../constants';
import { ValidatorStakedEvent } from '../events/validator_staked';
import { InternalMethod } from '../internal_method';
import { stakeCommandParamsSchema } from '../schemas';
import { ValidatorStore } from '../stores/validator';
import { EligibleValidatorsStore } from '../stores/eligible_validators';
import { StakerStore } from '../stores/staker';
import { TokenMethod, TokenID, StakeTransactionParams } from '../types';
import { sortUnlocking, getValidatorWeight } from '../utils';
export class StakeCommand extends BaseCommand {
public schema = stakeCommandParamsSchema;
private _tokenMethod!: TokenMethod;
private _posTokenID!: TokenID;
private _internalMethod!: InternalMethod;
private _factorSelfStakes!: number;
private _baseStakeAmount!: bigint;
private _maxNumberPendingUnlocks!: number;
private _maxNumberSentStakes!: number;
public addDependencies(args: { tokenMethod: TokenMethod; internalMethod: InternalMethod }) {
this._tokenMethod = args.tokenMethod;
this._internalMethod = args.internalMethod;
}
public init(args: {
posTokenID: TokenID;
factorSelfStakes: number;
baseStakeAmount: bigint;
maxNumberPendingUnlocks: number;
maxNumberSentStakes: number;
}) {
this._posTokenID = args.posTokenID;
this._factorSelfStakes = args.factorSelfStakes;
this._baseStakeAmount = args.baseStakeAmount;
this._maxNumberPendingUnlocks = args.maxNumberPendingUnlocks;
this._maxNumberSentStakes = args.maxNumberSentStakes;
}
// eslint-disable-next-line @typescript-eslint/require-await
public async verify(
context: CommandVerifyContext<StakeTransactionParams>,
): Promise<VerificationResult> {
const {
params: { stakes },
} = context;
let upstakeCount = 0;
let downstakeCount = 0;
const validatorAddressSet = new dataStructures.BufferSet();
for (const stake of stakes) {
if (validatorAddressSet.has(stake.validatorAddress)) {
return {
status: VerifyStatus.FAIL,
error: new ValidationError(
'Validator address must be unique.',
stake.validatorAddress.toString('hex'),
),
};
}
validatorAddressSet.add(stake.validatorAddress);
if (stake.amount === BigInt(0)) {
return {
status: VerifyStatus.FAIL,
error: new ValidationError('Amount cannot be 0.', ''),
};
}
if (stake.amount % this._baseStakeAmount !== BigInt(0)) {
return {
status: VerifyStatus.FAIL,
error: new ValidationError(
'Amount should be multiple of 10 * 10^8.',
stake.amount.toString(),
),
};
}
if (stake.amount > BigInt(0)) {
upstakeCount += 1;
} else if (stake.amount < BigInt(0)) {
downstakeCount += 1;
}
}
if (upstakeCount > this._maxNumberSentStakes) {
return {
status: VerifyStatus.FAIL,
error: new ValidationError(
`Upstake can only be casted up to ${this._maxNumberSentStakes}.`,
upstakeCount.toString(),
),
};
}
if (downstakeCount > this._maxNumberSentStakes) {
return {
status: VerifyStatus.FAIL,
error: new ValidationError(
`Downstake can only be casted up to ${this._maxNumberSentStakes}.`,
downstakeCount.toString(),
),
};
}
return {
status: VerifyStatus.OK,
};
}
public async execute(context: CommandExecuteContext<StakeTransactionParams>): Promise<void> {
const {
transaction: { senderAddress },
params: { stakes },
getMethodContext,
header: { height },
} = context;
stakes.sort((a, b) => {
const diff = a.amount - b.amount;
if (diff > BigInt(0)) {
return 1;
}
if (diff < BigInt(0)) {
return -1;
}
return 0;
});
const stakerStore = this.stores.get(StakerStore);
const validatorStore = this.stores.get(ValidatorStore);
for (const stake of stakes) {
const stakerData = await stakerStore.getOrDefault(context, senderAddress);
const validatorExists = await validatorStore.has(context, stake.validatorAddress);
if (!validatorExists) {
this.events.get(ValidatorStakedEvent).error(
context,
{
senderAddress,
validatorAddress: stake.validatorAddress,
amount: stake.amount,
},
PoSEventResult.STAKE_FAILED_NON_REGISTERED_VALIDATOR,
);
throw new Error('Invalid stake: no registered validator with the specified address');
}
const validatorData = await validatorStore.get(context, stake.validatorAddress);
const existingStakeIndex = stakerData.stakes.findIndex(senderStake =>
senderStake.validatorAddress.equals(stake.validatorAddress),
);
// downstake
if (stake.amount < BigInt(0)) {
if (existingStakeIndex < 0) {
this.events.get(ValidatorStakedEvent).error(
context,
{
senderAddress,
validatorAddress: stake.validatorAddress,
amount: stake.amount,
},
PoSEventResult.STAKE_FAILED_INVALID_UNSTAKE_PARAMETERS,
);
throw new Error(
'Invalid unstake: Cannot cast downstake to validator who is not upstaked.',
);
}
if (stakerData.stakes[existingStakeIndex].amount + stake.amount < BigInt(0)) {
this.events.get(ValidatorStakedEvent).error(
context,
{
senderAddress,
validatorAddress: stake.validatorAddress,
amount: stake.amount,
},
PoSEventResult.STAKE_FAILED_INVALID_UNSTAKE_PARAMETERS,
);
throw new Error(
'Invalid unstake: The unstake amount exceeds the staked amount for this validator.',
);
}
await this._internalMethod.assignStakeRewards(
context,
senderAddress,
stakerData.stakes[existingStakeIndex],
validatorData,
);
stakerData.stakes[existingStakeIndex].amount += stake.amount;
stakerData.stakes[existingStakeIndex].sharingCoefficients =
validatorData.sharingCoefficients;
if (stakerData.stakes[existingStakeIndex].amount === BigInt(0)) {
stakerData.stakes = stakerData.stakes.filter(
senderStake => !senderStake.validatorAddress.equals(stake.validatorAddress),
);
}
// Create unlocking object
// Amount is converted to +BigInt for unlocking
stakerData.pendingUnlocks.push({
validatorAddress: stake.validatorAddress,
amount: BigInt(-1) * stake.amount,
unstakeHeight: height,
});
// Sort account.unlocking
sortUnlocking(stakerData.pendingUnlocks);
if (stakerData.pendingUnlocks.length > this._maxNumberPendingUnlocks) {
this.events.get(ValidatorStakedEvent).error(
context,
{
senderAddress,
validatorAddress: stake.validatorAddress,
amount: stake.amount,
},
PoSEventResult.STAKE_FAILED_TOO_MANY_PENDING_UNLOCKS,
);
throw new Error(`Pending unlocks cannot exceed ${this._maxNumberPendingUnlocks}.`);
}
}
// upstake
else {
await this._tokenMethod.lock(
getMethodContext(),
senderAddress,
MODULE_NAME_POS,
this._posTokenID,
stake.amount,
);
if (existingStakeIndex > -1) {
await this._internalMethod.assignStakeRewards(
context.getMethodContext(),
senderAddress,
stakerData.stakes[existingStakeIndex],
validatorData,
);
stakerData.stakes[existingStakeIndex].amount += stake.amount;
stakerData.stakes[existingStakeIndex].sharingCoefficients =
validatorData.sharingCoefficients;
} else {
stakerData.stakes.push({
validatorAddress: stake.validatorAddress,
amount: stake.amount,
sharingCoefficients: validatorData.sharingCoefficients,
});
}
stakerData.stakes.sort((a, b) => a.validatorAddress.compare(b.validatorAddress));
if (stakerData.stakes.length > this._maxNumberSentStakes) {
this.events.get(ValidatorStakedEvent).error(
context,
{
senderAddress,
validatorAddress: stake.validatorAddress,
amount: stake.amount,
},
PoSEventResult.STAKE_FAILED_TOO_MANY_SENT_STAKES,
);
throw new Error(`Sender can only stake upto ${this._maxNumberSentStakes}.`);
}
}
const previousValidatorWeight = getValidatorWeight(
this._factorSelfStakes,
validatorData.selfStake,
validatorData.totalStake,
);
// Change validator.selfStake if this stake is a self stake
if (senderAddress.equals(stake.validatorAddress)) {
validatorData.selfStake += stake.amount;
}
validatorData.totalStake += stake.amount;
const eligibleValidatorsStore = this.stores.get(EligibleValidatorsStore);
await eligibleValidatorsStore.update(
context,
stake.validatorAddress,
previousValidatorWeight,
validatorData,
);
await stakerStore.set(context, senderAddress, stakerData);
await validatorStore.set(context, stake.validatorAddress, validatorData);
this.events.get(ValidatorStakedEvent).log(context, {
senderAddress,
validatorAddress: stake.validatorAddress,
amount: stake.amount,
});
}
}
}