-
Notifications
You must be signed in to change notification settings - Fork 0
/
governor.ts
239 lines (207 loc) · 7.54 KB
/
governor.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
import {JsSignatureProvider} from "eosjs/dist/eosjs-jssig";
import {Api, JsonRpc, RpcError} from "eosjs";
import {PowerUpResState, PowerUpState} from "./interfaces";
import * as BN from "bn.js";
import {fetch} from "cross-fetch";
import {assetToFloat} from "./functions";
import {Configuration} from "./config";
const config = Configuration;
if (!config.intervalSecs) {
config.intervalSecs = 3600;
} else {
if (config.intervalSecs <= 30) {
config.intervalSecs = 30;
}
}
if (!config.api) {
console.log('API URL not defined!');
process.exit(1);
}
if (!config.accounts || config.accounts?.length === 0) {
console.log('No accounts defined! Please check your config.ts file.');
process.exit(1);
}
if (!config.payers || config.payers?.length === 0) {
console.log('No payers defined! Please check your config.ts file.');
process.exit(1);
}
// constants
const zero = new BN(0);
// 10e4 (EOS native)
const decimals = 10000;
const precision = new BN(decimals);
// 10e7
const precision2 = new BN(10000000);
// 10e15
const powerupFraction = new BN(1000000000000000);
export class PowerupGovernor {
signatureProvider: JsSignatureProvider;
rpc: JsonRpc;
powerupState: PowerUpState;
api: Api;
mainLoop: NodeJS.Timeout;
constructor() {
this.init();
}
init() {
this.signatureProvider = new JsSignatureProvider(config.payers.map(payer => payer.key));
this.rpc = new JsonRpc(config.api, {fetch});
this.api = new Api({
rpc: this.rpc,
signatureProvider: this.signatureProvider,
textDecoder: new TextDecoder(),
textEncoder: new TextEncoder()
});
}
startLoop() {
this.run().then(() => {
console.log('Check scheduled every ' + config.intervalSecs + ' seconds...');
this.mainLoop = setInterval(() => {
this.run().catch(console.log);
}, config.intervalSecs * 1000);
});
}
async run() {
await this.getPowerupState();
await this.checkAccounts();
console.log(`\n✅ done checking ${config.accounts.length} accounts`);
}
calculateFee(state: PowerUpResState, utilization_increase: BN): number {
if (utilization_increase.lte(zero)) return 0;
let fee = 0.0;
let start_utilization = new BN(state.utilization);
let end_utilization = start_utilization.add(utilization_increase);
const weight = new BN(state.weight);
const minPrice = assetToFloat(state.min_price);
const maxPrice = assetToFloat(state.max_price);
const exp = parseFloat(state.exponent);
const nexp = exp - 1.0;
const priceFunction = (utilization: BN): number => {
let price = minPrice;
if (nexp <= 0.0) {
return maxPrice;
} else {
const d = (maxPrice - minPrice);
const x = utilization.mul(precision).div(weight).toNumber() / precision.toNumber();
price += d * Math.pow(x, nexp);
}
return price;
};
const priceIntegralDelta = (startUtilization: BN, endUtilization: BN): number => {
const c = (maxPrice - minPrice) / exp;
const start_u = startUtilization.mul(precision2).div(weight).toNumber() / precision2.toNumber();
const end_u = endUtilization.mul(precision2).div(weight).toNumber() / precision2.toNumber();
return (minPrice * end_u) - (minPrice * start_u) + (c * Math.pow(end_u, exp)) - (c * Math.pow(start_u, exp));
};
const adjustedUtilization = new BN(state.adjusted_utilization);
if (start_utilization.lt(adjustedUtilization)) {
const priceResult = priceFunction(adjustedUtilization);
const min = BN.min(utilization_increase, adjustedUtilization.sub(start_utilization));
const k = min.mul(precision2).div(weight).toNumber() / precision2.toNumber();
fee += priceResult * k;
}
if (start_utilization < end_utilization) {
fee += priceIntegralDelta(start_utilization, end_utilization);
}
return Math.ceil(fee * decimals) / decimals;
}
async checkAccounts() {
for (const account of config.accounts) {
console.log(`\nChecking resources for ${account.name}...`);
const accountData = await this.rpc.get_account(account.name);
let requiredNetFraction: BN = zero;
let requiredCpuFraction: BN = zero;
// calculate fraction for CPU
const cpu = accountData.cpu_limit;
const cpuWeight = new BN(accountData.cpu_weight);
const weightPerUs = cpuWeight.div(new BN(cpu.max));
const pctCpuFree = (cpu.available / cpu.max) * 100;
console.log(`${accountData.account_name} has ${cpu.available} us of ${cpu.max} us CPU available (${pctCpuFree.toFixed(2)}%)`);
let requiredCpu = new BN(account.requiredCPUAvailability - cpu.max);
if (cpu.available === 0) {
const usedExtra = cpu.used - cpu.max;
if (usedExtra > 0) {
if (usedExtra > account.allowedExtraCPU) {
console.log(`${accountData.account_name} has used ${usedExtra} us and the maximum allowed to powerup is ${account.allowedExtraCPU}!`);
continue;
} else {
requiredCpu = new BN(account.allowedExtraCPU);
}
}
}
if (requiredCpu.gt(zero)) {
console.log(`${account.name} needs ${requiredCpu.toString()} us of CPU`);
requiredCpu = requiredCpu.mul(weightPerUs);
requiredCpuFraction = requiredCpu.mul(powerupFraction).div(new BN(this.powerupState.cpu.weight));
}
// calculate fraction for NET
const net = accountData.net_limit;
const netWeight = new BN(accountData.net_weight);
const weightPerByte = netWeight.div(new BN(net.max));
const pctNetFree = (net.available / net.max) * 100;
console.log(`${accountData.account_name} has ${net.available} of ${net.max} bytes of NET available (${pctNetFree.toFixed(2)}%)`);
let requiredNet = new BN(account.requiredNETAvailability - net.max);
if (net.available === 0) {
const usedExtra = net.used - net.max;
if (usedExtra > 0) {
if (usedExtra > account.allowedExtraNET) {
console.log(`${accountData.account_name} has used ${usedExtra} bytes and the maximum allowed to powerup is ${account.allowedExtraNET}!`);
continue;
} else {
requiredNet = new BN(account.allowedExtraNET);
}
}
}
if (requiredNet.gt(zero)) {
console.log(`${account.name} needs ${requiredNet.toString()} bytes of NET`);
requiredNet = requiredNet.mul(weightPerByte);
requiredNetFraction = requiredNet.mul(powerupFraction).div(new BN(this.powerupState.net.weight));
}
// calculate fee CPU + NET
const feeAmount = this.calculateFee(this.powerupState.cpu, requiredCpu) + this.calculateFee(this.powerupState.net, requiredNet);
if (feeAmount > 0) {
const powerupActionData = {
payer: account.payer,
receiver: account.name,
days: 1,
net_frac: requiredNetFraction.toString(10),
cpu_frac: requiredCpuFraction.toString(10),
max_payment: feeAmount.toFixed(4) + ' EOS'
};
const payer = config.payers.find(value => value.name === account.payer);
try {
const transaction = {
actions: [{
name: 'powerup',
account: 'eosio',
authorization: [{actor: account.payer, permission: payer.permission}],
data: powerupActionData
}]
};
console.log('Pushing transaction...');
console.log(JSON.stringify(transaction, null, 2));
const trxResponse = await this.api.transact(transaction, {
useLastIrreversible: true,
broadcast: config.broadcast,
expireSeconds: 3600,
sign: true
});
console.log(`Trx Id: ${trxResponse["transaction_id"]} on block ${trxResponse["processed"]["block_num"]}`);
} catch (e) {
console.log('\nCaught exception: ' + e);
if (e instanceof RpcError) {
console.log(JSON.stringify(e.json, null, 2));
}
}
}
}
}
async getPowerupState() {
const data = await this.rpc.get_table_rows({
json: true,
code: 'eosio',
table: 'powup.state'
});
this.powerupState = data.rows[0];
}
}