forked from paradox-tt/SPC_Bounty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclasses.ts
311 lines (244 loc) · 11.6 KB
/
classes.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
import { BlockInfo, CollatorData, ExtrinsicInfo, Identity, ManualPayment } from "./types";
import * as Constants from './constants';
import { ApiPromise, WsProvider } from '@polkadot/api';
import { Codec } from '@polkadot/types-codec/types/codec';
import "@polkadot/api-augment";
import fs from 'fs';
const { encodeAddress } = require("@polkadot/keyring");
export class ParachainData {
private collators: CollatorData[];
private previous_blocks: number[];
private _invulnerables: string[];
public constructor() {
this.collators = [];
this.previous_blocks = [];
this._invulnerables = [];
};
public setInvulnerables(value: string[]) {
this._invulnerables = value;
}
public getInvulnerables(): string[] {
return this._invulnerables;
}
public addData(info: BlockInfo) {
//Double check to ensure blocks aren't counted twice
//Also don't reward collators in the no reward table
if (this.previous_blocks.indexOf(info.number) < 0
&& Constants.NO_REWARD_COLLATORS.indexOf(info.author) == -1) {
//Find collator and increment block
//If the collator does not exist then create it with a block count of 1
var collator = this.collators.find(x => x.collator == info.author);
if (collator) {
collator.number_of_blocks++;
} else {
this.collators.push(
{
collator: info.author,
number_of_blocks: 1
}
);
}
}
this.previous_blocks.push(info.number);
}
public getMaxBlocks(): number {
var max = 0;
for (var i = 0; i < this.collators.length; i++) {
if (this.collators[i].number_of_blocks > max) {
max = this.collators[i].number_of_blocks;
}
}
return max;
}
public getCollators(): CollatorData[] {
return this.collators;
}
}
export interface Parachain {
}
export class EraReward {
private _era: number;
private _total_stake: number;
private _reward: number;
private _chain: Constants.RELAY;
public constructor(era: number, total_stake: number, reward: number, chain: Constants.RELAY) {
this._era = era;
this._total_stake = total_stake;
this._reward = reward;
this._chain = chain;
}
/*
Gets the total reward for the era and divides it equally over the total staked for the era
and then multiplies it by 50 (KSM) / 1000 DOT to determine the average reward for every DOT/KSM staked.
*/
public getStakingReward(): number {
const permissionless = this._chain == Constants.RELAY.POLKADOT ? Constants.DOT_PERMISSIONLESS : Constants.KSM_PERMISSIONLESS;
return (this._reward / this._total_stake) * permissionless;
}
public getEra(): number {
return this._era;
}
}
export class RewardCollector {
private ema7: number;
private staking_info: EraReward[];
private manual_entries: ManualPayment[];
private parachain_data: ParachainData;
public constructor(ema7: number, staking_info: EraReward[], manual_entries: ManualPayment[], parachain_data: ParachainData) {
this.ema7 = ema7;
this.staking_info = staking_info;
this.manual_entries = manual_entries;
this.parachain_data = parachain_data;
}
public async getExtrinsicInfo(chain: Constants.RELAY): Promise<ExtrinsicInfo[]> {
var results: ExtrinsicInfo[] = [];
const wsProvider = new WsProvider(chain == Constants.RELAY.POLKADOT ? Constants.DOT_WSS : Constants.KSM_WSS);
const api = await ApiPromise.create({ provider: wsProvider, noInitWarn: true });
const PLANKS = (chain == Constants.RELAY.POLKADOT) ? Constants.POLKADOT_PLANKS : Constants.KUSAMA_PLANKS;
const HOSTING_RECIPIENT = (chain == Constants.RELAY.POLKADOT) ? Constants.HOSTING_RECIPIENT_DOT : Constants.HOSTING_RECIPIENT_KSM;
//Add manual entries
this.manual_entries.map(x => results.push(
{
recipient: x.recipient,
description: x.description,
value: (x.isToken ? x.value : x.value / this.ema7) * PLANKS
}
));
if (this.parachain_data) {
//Hosting reward
results.push(
{
recipient: HOSTING_RECIPIENT,
description: `Hosting fee for Curator RPC instance @ $${Constants.HOSTING_FEE.toFixed(Constants.NUM_DECIMALS)} + 1/${Constants.PARACHAINS} hosting fee for supporting relay chain RPC instances @ $${(Constants.RELAY_HOSTING_FEE * 2).toFixed(Constants.NUM_DECIMALS)} + 1/${Constants.PARACHAINS.toString()} hosting fee for curator instance @ $${Constants.CURATOR_HOSTING_FEE.toFixed(Constants.NUM_DECIMALS)}`,
value: ((Constants.HOSTING_FEE / this.ema7) + (((Constants.RELAY_HOSTING_FEE * 2) / this.ema7) / Constants.PARACHAINS) + ((Constants.CURATOR_HOSTING_FEE / this.ema7) / Constants.PARACHAINS)) * PLANKS
}
);
//System Parachain Coordinator
if (chain == Constants.COORDINATOR_CHAIN) {
results.push(
{
recipient: Constants.COORDINATOR,
description: `Partial fee for System Coordinator @ $${Constants.COORDINATOR_FEE.toFixed(Constants.NUM_DECIMALS)} split over $${(Constants.KSM_PARACHAINS)} parachains.`,
value: ((Constants.COORDINATOR_FEE / this.ema7) / Constants.KSM_PARACHAINS) * PLANKS
}
)
}
//Calculate collator rewards
const staking_reward = this.staking_info.map(x => x.getStakingReward()).reduce((a, b) => a + b);
const max = this.parachain_data.getMaxBlocks();
const collators = this.parachain_data.getCollators();
for (var i = 0; i < collators.length; i++) {
var collator = collators[i];
var ratio = collator.number_of_blocks / max;
var collator_name = await this.getIdentity(collator.collator, chain);
var adjusted_staking_reward = ratio * staking_reward;
const adjusted_collator_reward = ratio * (Constants.COLLATOR_REWARD / this.ema7);
var invulnerable = this.parachain_data.getInvulnerables().indexOf(collator.collator) > -1;
adjusted_staking_reward = invulnerable ? 0 : adjusted_staking_reward;
results.push(
{
recipient: collator.collator,
description: `${collator_name} produced ${collator.number_of_blocks}/${max} blocks; SR: ${invulnerable ? '0 (Invulnerable)' : adjusted_staking_reward.toFixed(Constants.NUM_DECIMALS)}, CR: ${adjusted_collator_reward.toFixed(Constants.NUM_DECIMALS)}`,
value: (adjusted_collator_reward + adjusted_staking_reward) * PLANKS
}
);
}
}
//Calculate curator rewards
var total_reward_map = results.map(x => x.value);
var total_reward = 0;
if (total_reward_map.length > 0) {
total_reward = total_reward_map.reduce((a, b) => a + b);
}
var curators = chain == Constants.RELAY.POLKADOT ? Constants.DOT_CURATORS : Constants.KSM_CURATORS;
for (var i = 0; i < curators.length; i++) {
var curator = await this.getIdentity(curators[i], chain);
results.push(
{
recipient: curators[i],
description: `Reward for curator (${curator}) as a portion from total ${(total_reward / PLANKS).toFixed(Constants.NUM_DECIMALS)}`,
value: ((total_reward * Constants.CURATOR_REWARD) / curators.length)
}
)
}
return results;
}
public async getExtrinsic(chain: Constants.RELAY): Promise<string> {
const extrinsic_info = await this.getExtrinsicInfo(chain);
const wsProviderRelay = new WsProvider(chain == Constants.RELAY.POLKADOT ? Constants.DOT_WSS : Constants.KSM_WSS);
const api = await ApiPromise.create({ provider: wsProviderRelay, noInitWarn: true });
//Gets the current child bounty counter
var cb_count_codec = await api.query.childBounties.childBountyCount();
var cb_count = parseInt(cb_count_codec.toString());
var parent_batch = [];
//Loop through each payout item
for (var i = 0; i < extrinsic_info.length; i++) {
//Transaction to add a child bounty
const add_cb_tx = api.tx.childBounties.addChildBounty(
chain == Constants.RELAY.POLKADOT ? Constants.POLKADOT_PARENT_BOUNTY_ID : Constants.KUSAMA_PARENT_BOUNTY_ID,
parseInt(extrinsic_info[i].value.toFixed(0)),
extrinsic_info[i].description
);
//Transaction to propose a curator for the bounty that was just created
const prop_cur_tx = api.tx.childBounties.proposeCurator(
chain == Constants.RELAY.POLKADOT ? Constants.POLKADOT_PARENT_BOUNTY_ID : Constants.KUSAMA_PARENT_BOUNTY_ID,
cb_count,
{ Id: chain == Constants.RELAY.POLKADOT ? Constants.DOT_CURATOR_ACCOUNT : Constants.KSM_CURATOR_ACCOUNT },
0
)
//Accept curation of the bounty
const acc_cb_tx = api.tx.childBounties.acceptCurator(
chain == Constants.RELAY.POLKADOT ? Constants.POLKADOT_PARENT_BOUNTY_ID : Constants.KUSAMA_PARENT_BOUNTY_ID,
cb_count
);
//Award the bounty to the recipient
const award_cb_tx = api.tx.childBounties.awardChildBounty(
chain == Constants.RELAY.POLKADOT ? Constants.POLKADOT_PARENT_BOUNTY_ID : Constants.KUSAMA_PARENT_BOUNTY_ID,
cb_count,
{ Id: extrinsic_info[i].recipient }
)
//Increment count
cb_count++;
//Add the four transactions above in a batchAll, each must be executed together
const inner_batch = api.tx.utility.batchAll([add_cb_tx, prop_cur_tx, acc_cb_tx, award_cb_tx]);
//Add the batchAll to the parent batch
parent_batch.push(inner_batch);
}
//Execute each individual batch, if one inner batch fails continue with the others.
const final_batch = api.tx.utility.forceBatch(parent_batch);
return final_batch.toHex();
}
private getIdentity(addr: string, chain: Constants.RELAY): string {
var identities: Identity[] = [];
if (chain == Constants.RELAY.POLKADOT) {
identities = JSON.parse(fs.readFileSync('polkadot-identities.json', 'utf-8'));
} else {
identities = JSON.parse(fs.readFileSync('kusama-identities.json', 'utf-8'));
}
var identity: Identity = identities.find(x => x.address == encodeAddress(addr, 42));
if (identity) {
if (identity.sub) {
return `${identity.name}\\${identity.sub}`;
} else {
return identity.name
}
} else {
return addr
}
};
private hex2a(hex: string): string {
var str;
try {
str = decodeURIComponent(hex.replace(/(..)/g, '%$1'))
}
catch (e) {
str = hex
console.log('invalid hex input: ' + hex)
}
return str
}
private CodecToObject(item: Codec) {
const res = JSON.parse(item.toString());
return res;
}
}