-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli-command-compute-validator-rewards.ts
More file actions
329 lines (284 loc) Β· 14.5 KB
/
cli-command-compute-validator-rewards.ts
File metadata and controls
329 lines (284 loc) Β· 14.5 KB
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
// Archival RPC endpoints with full historical data
const ARCHIVAL_RPCS = [
"https://near.lava.build", // Lava Network - has archival (try first for view_account)
"https://free.rpc.fastnear.com", // FastNear - has archival for validators
"https://archival-rpc.mainnet.near.org", // Official NEAR archival (fallback)
];
let currentRpcIndex = 0;
interface ValidatorInfo {
account_id: string;
stake: string;
num_produced_blocks?: number;
num_expected_blocks?: number;
is_slashed?: boolean;
}
/**
* Make an RPC call with retry and failover between providers
*/
async function rpcCall(method: string, params: any): Promise<any> {
let lastError: Error | null = null;
for (let providerAttempt = 0; providerAttempt < ARCHIVAL_RPCS.length; providerAttempt++) {
const rpcUrl = ARCHIVAL_RPCS[(currentRpcIndex + providerAttempt) % ARCHIVAL_RPCS.length];
for (let attempt = 0; attempt < 3; attempt++) {
try {
const response = await fetch(rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: '1',
method: method,
params: params
})
});
const data = await response.json() as any;
// Check for rate limit errors or garbage collected blocks
if (data.error) {
const errCode = data.error.code;
const errMsg = data.error.message || '';
const errData = data.error.data || '';
// Check for rate limiting
if (errCode === -429 || errMsg.includes('rate') || errMsg.includes('limit')) {
if (attempt < 2) {
const waitTime = 1000 * (attempt + 1);
console.log(`Rate limited on ${rpcUrl}, waiting ${waitTime / 1000}s...`);
await new Promise(r => setTimeout(r, waitTime));
continue;
}
// Try next provider
console.log(`Switching to next RPC provider...`);
break;
}
// Check for garbage collected block - try next provider
if (errData.includes('GARBAGE_COLLECTED') || errData.includes('garbage collected')) {
// Try next provider silently
break;
}
// For other errors, throw immediately
throw new Error(`RPC Error: ${JSON.stringify(data.error)}`);
}
// Success - remember this RPC for next call
currentRpcIndex = (currentRpcIndex + providerAttempt) % ARCHIVAL_RPCS.length;
return data.result;
} catch (e: any) {
lastError = e;
if (e.message?.includes('RPC Error')) {
// Try next provider for RPC errors too
break;
}
if (attempt < 2) {
await new Promise(r => setTimeout(r, 500));
}
}
}
}
throw lastError || new Error('All RPC providers failed. Please try again later.');
}
/**
* Get the epoch start block height from validators RPC call
*/
async function getEpochInfo(): Promise<{ currentEpoch: number; epochStartHeight: number }> {
const data = await rpcCall('validators', [null]);
return {
currentEpoch: parseInt(data.epoch_height),
epochStartHeight: data.epoch_start_height
};
}
/**
* Get validators at a specific block height using EXPERIMENTAL_validators_ordered
*/
async function getValidatorsAtBlock(blockHeight: number): Promise<ValidatorInfo[]> {
return await rpcCall('EXPERIMENTAL_validators_ordered', { block_id: blockHeight });
}
/**
* Get account balance at a specific block height
*/
async function getAccountBalanceAtBlock(accountId: string, blockHeight: number): Promise<string> {
const result = await rpcCall('query', {
request_type: 'view_account',
block_id: blockHeight,
account_id: accountId
});
return result.amount; // returns balance in yoctoNEAR
}
/**
* Calculate the approximate block heights for an epoch boundary
* Each epoch is approximately 43200 blocks (~12 hours)
*/
async function getEpochBoundaryBlocks(targetEpoch: number): Promise<{ epochFirstBlock: number; prevEpochLastBlock: number }> {
const { currentEpoch, epochStartHeight } = await getEpochInfo();
console.log(`Current epoch: ${currentEpoch}, current epoch start block: ${epochStartHeight}`);
const APPROX_EPOCH_BLOCKS = 43200;
const epochDiff = currentEpoch - targetEpoch;
// Calculate approximate first block of target epoch
const epochFirstBlock = epochStartHeight - (epochDiff * APPROX_EPOCH_BLOCKS);
// The last block of the previous epoch is first block of target epoch - 1
const prevEpochLastBlock = epochFirstBlock - 1;
console.log(`Approximate epoch ${targetEpoch} first block: ${epochFirstBlock}`);
console.log(`Approximate epoch ${targetEpoch - 1} last block: ${prevEpochLastBlock}`);
return { epochFirstBlock, prevEpochLastBlock };
}
/**
* Compute validator rewards for a specific epoch
* Rewards = (stake + account balance) at start of epoch - (stake + account balance) at end of previous epoch
*/
export async function computeValidatorRewards(validatorId: string, epoch: number): Promise<{
validatorId: string;
epoch: number;
prevEpochLastBlock: number;
epochFirstBlock: number;
stakeAtPrevEpochEnd: string | null;
stakeAtEpochStart: string | null;
accountBalanceAtPrevEpochEnd: string | null;
accountBalanceAtEpochStart: string | null;
totalBalanceAtPrevEpochEnd: string | null;
totalBalanceAtEpochStart: string | null;
stakeRewardsYocto: string | null;
totalRewardsYocto: string | null;
}> {
console.log(`\nπ Computing rewards for validator "${validatorId}" at epoch ${epoch}...`);
console.log(`Using archival RPC endpoints\n`);
// Get the block heights for the epoch boundary
const { epochFirstBlock, prevEpochLastBlock } = await getEpochBoundaryBlocks(epoch);
// Get validators at both points
console.log(`\nQuerying validators at block ${prevEpochLastBlock} (end of epoch ${epoch - 1})...`);
const validatorsAtPrevEnd = await getValidatorsAtBlock(prevEpochLastBlock);
console.log(`Querying validators at block ${epochFirstBlock} (start of epoch ${epoch})...`);
const validatorsAtEpochStart = await getValidatorsAtBlock(epochFirstBlock);
// Get account balances at both blocks
console.log(`Querying account balance at block ${prevEpochLastBlock}...`);
let accountBalanceAtPrevEnd: string | null = null;
let accountBalanceAtStart: string | null = null;
try {
accountBalanceAtPrevEnd = await getAccountBalanceAtBlock(validatorId, prevEpochLastBlock);
} catch (e: any) {
console.log(`Warning: Could not get account balance at prev epoch end: ${e.message}`);
}
console.log(`Querying account balance at block ${epochFirstBlock}...`);
try {
accountBalanceAtStart = await getAccountBalanceAtBlock(validatorId, epochFirstBlock);
} catch (e: any) {
console.log(`Warning: Could not get account balance at epoch start: ${e.message}`);
}
// Find the validator in both lists
const validatorAtPrevEnd = validatorsAtPrevEnd.find(v => v.account_id === validatorId);
const validatorAtEpochStart = validatorsAtEpochStart.find(v => v.account_id === validatorId);
let stakeRewardsYocto: string | null = null;
let totalRewardsYocto: string | null = null;
let totalBalanceAtPrevEpochEnd: string | null = null;
let totalBalanceAtEpochStart: string | null = null;
// Compute stake rewards
if (validatorAtPrevEnd && validatorAtEpochStart) {
const stakeAtEnd = BigInt(validatorAtPrevEnd.stake);
const stakeAtStart = BigInt(validatorAtEpochStart.stake);
const stakeRewards = stakeAtStart - stakeAtEnd;
stakeRewardsYocto = stakeRewards.toString();
}
// Compute total balance (stake + account balance) and total rewards
const stakeEnd = validatorAtPrevEnd ? BigInt(validatorAtPrevEnd.stake) : BigInt(0);
const stakeStart = validatorAtEpochStart ? BigInt(validatorAtEpochStart.stake) : BigInt(0);
const balanceEnd = accountBalanceAtPrevEnd ? BigInt(accountBalanceAtPrevEnd) : BigInt(0);
const balanceStart = accountBalanceAtStart ? BigInt(accountBalanceAtStart) : BigInt(0);
const totalEnd = stakeEnd + balanceEnd;
const totalStart = stakeStart + balanceStart;
totalBalanceAtPrevEpochEnd = totalEnd.toString();
totalBalanceAtEpochStart = totalStart.toString();
const totalRewards = totalStart - totalEnd;
totalRewardsYocto = totalRewards.toString();
return {
validatorId,
epoch,
prevEpochLastBlock,
epochFirstBlock,
stakeAtPrevEpochEnd: validatorAtPrevEnd?.stake || null,
stakeAtEpochStart: validatorAtEpochStart?.stake || null,
accountBalanceAtPrevEpochEnd: accountBalanceAtPrevEnd,
accountBalanceAtEpochStart: accountBalanceAtStart,
totalBalanceAtPrevEpochEnd,
totalBalanceAtEpochStart,
stakeRewardsYocto,
totalRewardsYocto
};
}
/**
* CLI command handler: compute-validator-rewards <validator_id> <epoch>
* Example: npm run cli compute-validator-rewards bisontrails2.poolv1.near 4016
*/
export async function cliCommandComputeValidatorRewards(args: string[]) {
if (args.length < 2) {
console.log("Usage: compute-validator-rewards <validator_id> <epoch>");
console.log("Example: compute-validator-rewards bisontrails2.poolv1.near 4016");
console.log("\nThis command computes the rewards received by a validator at a specific epoch.");
console.log("It queries the stake at the end of the previous epoch and the start of the");
console.log("specified epoch to calculate the rewards distributed at the epoch boundary.");
process.exit(1);
}
const validatorId = args[0];
const epoch = parseInt(args[1]);
if (isNaN(epoch) || epoch <= 1) {
console.error("β Invalid epoch number. Must be a positive integer greater than 1.");
process.exit(1);
}
try {
const result = await computeValidatorRewards(validatorId, epoch);
console.log("\n" + "=".repeat(90));
console.log("π VALIDATOR REWARDS COMPUTATION (all amounts in yoctoNEAR)");
console.log("=".repeat(90));
console.log(`Validator: ${result.validatorId}`);
console.log(`Epoch: ${result.epoch}`);
console.log("-".repeat(90));
console.log(`Previous Epoch End: Block #${result.prevEpochLastBlock}`);
console.log(`Epoch Start: Block #${result.epochFirstBlock}`);
console.log("-".repeat(90));
console.log("\nπ AT END OF PREVIOUS EPOCH (block #{0}):".replace("{0}", result.prevEpochLastBlock.toString()));
if (result.stakeAtPrevEpochEnd) {
console.log(` Staked Balance: ${result.stakeAtPrevEpochEnd}`);
} else {
console.log(` Staked Balance: 0 (validator not active)`);
}
console.log(` Account Balance: ${result.accountBalanceAtPrevEpochEnd || '0'}`);
console.log(` βββββββββββββββββββββββββββββββββββββββββββββββββ`);
console.log(` TOTAL BALANCE: ${result.totalBalanceAtPrevEpochEnd}`);
console.log("\nπ AT START OF EPOCH (block #{0}):".replace("{0}", result.epochFirstBlock.toString()));
if (result.stakeAtEpochStart) {
console.log(` Staked Balance: ${result.stakeAtEpochStart}`);
} else {
console.log(` Staked Balance: 0 (validator not active)`);
}
console.log(` Account Balance: ${result.accountBalanceAtEpochStart || '0'}`);
console.log(` βββββββββββββββββββββββββββββββββββββββββββββββββ`);
console.log(` TOTAL BALANCE: ${result.totalBalanceAtEpochStart}`);
console.log("\n" + "-".repeat(90));
console.log("π REWARDS BREAKDOWN:");
console.log("-".repeat(90));
if (result.stakeRewardsYocto !== null) {
const stakeSign = BigInt(result.stakeRewardsYocto) >= BigInt(0) ? "+" : "";
console.log(` Stake Rewards: ${stakeSign}${result.stakeRewardsYocto}`);
} else {
console.log(` Stake Rewards: N/A (validator not active in one or both epochs)`);
}
if (result.totalRewardsYocto !== null) {
const totalSign = BigInt(result.totalRewardsYocto) >= BigInt(0) ? "+" : "";
console.log(`\n βββββββββββββββββββββββββββββββββββββββββββββββββββ`);
console.log(` β
TOTAL REWARDS: ${totalSign}${result.totalRewardsYocto}`);
console.log(` βββββββββββββββββββββββββββββββββββββββββββββββββββ`);
// Calculate and show percentage
const totalEnd = BigInt(result.totalBalanceAtPrevEpochEnd || '0');
const totalRewards = BigInt(result.totalRewardsYocto);
if (totalEnd > BigInt(0)) {
const rewardsPct = (Number(totalRewards) / Number(totalEnd)) * 100;
const sign = rewardsPct >= 0 ? "+" : "";
console.log(` Reward Rate: ${sign}${rewardsPct.toFixed(6)}% (for ~12 hours)`);
const annualizedPct = rewardsPct * 730;
console.log(` Annualized APY: ~${annualizedPct.toFixed(2)}%`);
}
}
console.log("=".repeat(90));
} catch (error: any) {
console.error(`\nβ Error: ${error.message}`);
if (error.message.includes("UNKNOWN_BLOCK") || error.message.includes("does not exist")) {
console.log("\nπ‘ Tip: The epoch might be too old or too new for archival data.");
}
process.exit(1);
}
}