-
Notifications
You must be signed in to change notification settings - Fork 0
/
stkxprt-update-valset-weights.js
250 lines (224 loc) · 9.08 KB
/
stkxprt-update-valset-weights.js
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
import {QueryClientImpl as StakingQuery} from "persistenceonejs/cosmos/staking/v1beta1/query.js"
import {QueryClientImpl as SlashingQuery,} from "persistenceonejs/cosmos/slashing/v1beta1/query.js"
import {QueryClientImpl as GovQuery} from "cosmjs-types/cosmos/gov/v1/query.js"
import {AllPaginatedQuery, CreateSigningClientFromAddress, parseJson, RpcClient, stringifyJson} from "./helper.js";
import {
addresses,
chainInfos,
FN,
FNS,
HOST_CHAIN,
HOST_CHAINS, LIQUIDSTAKE_ADMIN,
LIQUIDSTAKE_ADMIN_TESTNET
} from "./constants.js";
import {assertIsDeliverTxSuccess} from "@cosmjs/stargate";
import {MsgUpdateWhitelistedValidators} from "persistenceonejs/pstake/liquidstake/v1beta1/tx.js";
import {BondStatus, bondStatusToJSON} from "persistenceonejs/cosmos/staking/v1beta1/staking.js";
import * as fs from "fs";
import {
CalculateValidatorFinalScore,
FilterDenyList,
FilterOnBlocksMissed,
FilterOnCommission,
FilterOnGov,
FilterOnSlashingEvents,
FilterOnTimeActiveSet,
FilterOnUptime,
FilterOnValidatorBond,
FilterOnVotingPower,
UpdateSigningInfosToValidators
} from "./filter.js";
import {MsgExec} from "persistenceonejs/cosmos/authz/v1beta1/tx.js";
async function GetHostChainValSetData(persistenceChainInfo, cosmosChainInfo) {
const lsm = true
const [cosmosTMClient, cosmosRpcClient] = await RpcClient(cosmosChainInfo)
const cosmosStakingClient = new StakingQuery(cosmosRpcClient)
const cosmosGovClient = new GovQuery(cosmosRpcClient)
const cosmosSlashingClient = new SlashingQuery(cosmosRpcClient)
// query all bonded vals
let allValsBonded = await AllPaginatedQuery(cosmosStakingClient.Validators, {status: bondStatusToJSON(BondStatus.BOND_STATUS_BONDED)}, "validators")
// put it into struct that has all info
let allVals = []
for (let validator of allValsBonded) {
let valmap = {
valoper: validator.operatorAddress,
validator: validator,
signingInfo: {},
proposalsVoted: [],
deny: false,
denyReason: [],
commissionScore: 0,
uptimeScore: 0,
govScore: 0,
votingPowerScore: 0,
validatorBondScore: 0,
overAllValidatorScore: 0,
weight: 0,
moniker: validator.description.moniker,
}
allVals.push(valmap)
}
console.log("update all validators")
allVals = await UpdateSigningInfosToValidators(cosmosSlashingClient, allVals, cosmosChainInfo.pstakeConfig.valconsPrefix)
console.log("update validator-infos")
// Reject vals based on deny list
try {
allVals = FilterDenyList(allVals, cosmosChainInfo.pstakeConfig.denyListVals)
} catch (e) {
throw e
}
console.log("filtered denylist")
// reject/filter on commission, calculate scores
try {
allVals = FilterOnCommission(allVals, cosmosChainInfo.pstakeConfig.commission)
} catch (e) {
throw e
}
console.log("filtered commission")
// reject/filter on voting power, calculate scores
try {
allVals = FilterOnVotingPower(allVals, cosmosChainInfo.pstakeConfig.votingPower)
} catch (e) {
throw e
}
console.log("filtered voting power")
// reject/filter on blocks missed in signed_blocks_window
try {
allVals = FilterOnBlocksMissed(cosmosSlashingClient, allVals, cosmosChainInfo.pstakeConfig.blocksMissed)
} catch (e) {
throw e
}
console.log("filtered on blocks missed")
// reject/filter time in active set, calculate scores
try {
allVals = await FilterOnTimeActiveSet(cosmosTMClient, allVals, cosmosChainInfo.pstakeConfig.timeInActiveSet)
} catch (e) {
throw e
}
console.log("filtered on time in active set")
// reject/ filter on slashing events, calculate scores
try {
allVals = await FilterOnSlashingEvents(cosmosTMClient, allVals, cosmosChainInfo.pstakeConfig.slashingEvents)
} catch (e) {
throw e
}
console.log("filtered on slashing events")
// reject/ filter on validator bond, calculate scores
// persistence by default has LSM live
if (lsm) {
try {
allVals = await FilterOnValidatorBond(cosmosStakingClient, allVals, cosmosChainInfo.pstakeConfig.validatorBond)
} catch (e) {
throw e
}
console.log("filtered on validators bond")
}
// reject/filter on Gov in last N days, calculate scores, this might fail if rpc gives up ( approx 180 requests )
try {
allVals = await FilterOnGov(cosmosGovClient, cosmosTMClient, allVals, cosmosChainInfo.pstakeConfig.gov, cosmosChainInfo.prefix)
} catch (e) {
throw e
}
console.log("filtered on gov")
// reject/filter on uptime, calculate scores, this might fail if rpc gives up (approx 180 * Ndays requests )
try {
allVals = await FilterOnUptime(cosmosTMClient, allVals, cosmosChainInfo.pstakeConfig.uptime, cosmosChainInfo.pstakeConfig.valconsPrefix)
console.log("filtered on uptime")
} catch (e) {
// most likely to fail, just score them all 100 if this is the case.
for (let i = 0; i < allVals.length; i++) {
allVals[i].uptimeScore = 100
}
console.log("Failed to filter on uptime, so awarded 100%, err:", e)
}
for (let i = 0; i < allVals.length; i++) {
let valScore = CalculateValidatorFinalScore(allVals[i], cosmosChainInfo.pstakeConfig, lsm)
allVals[i].overAllValidatorScore = valScore
}
let totalDenom = 0
for (let i = 0; i < allVals.length; i++) {
if (allVals[i].deny === true) {
continue
}
totalDenom = totalDenom + allVals[i].overAllValidatorScore
}
for (let i = 0; i < allVals.length; i++) {
if (allVals[i].deny === true) {
continue
}
allVals[i].weight = +(allVals[i].overAllValidatorScore / totalDenom).toFixed(4)
}
const jsonString = stringifyJson(allVals)
fs.writeFileSync(cosmosChainInfo.pstakeConfig.filename, jsonString);
process.stdout.write(jsonString + "\n")
return
}
async function TxUpdateValsetWeights(persistenceChainInfo, cosmosChainInfo, granteePersistenceAddr, AuthzGranterAddr) {
let allVals = parseJson(fs.readFileSync(cosmosChainInfo.pstakeConfig.filename))
// add kv updates to set weight
let nonZeroVals = []
for (let i = 0; i < allVals.length; i++) {
if (allVals[i].deny === true) {
continue
}
nonZeroVals.push({
valoper: allVals[i].valoper,
weight: allVals[i].weight
})
}
// add to check if sum of weights is 1.
let sum = 0
let kvUpdates = []
for (let i = 0; i < nonZeroVals.length; i++) {
// to scratch float approximations
if (i === nonZeroVals.length - 1) {
nonZeroVals[i].weight = 1 - sum
}
sum = sum + nonZeroVals[i].weight
kvUpdates.push({
validatorAddress: nonZeroVals[i].valoper, targetWeight: (nonZeroVals[i].weight * 10000).toFixed(0)
})
}
if (kvUpdates.length <= 0) {
console.log("no kv updates, total kv updates:", kvUpdates.length)
return
} else {
console.log("total kv updates:", kvUpdates.length)
}
const msgUpdateValidators = {
typeUrl: "/pstake.liquidstake.v1beta1.MsgUpdateWhitelistedValidators",
value: MsgUpdateWhitelistedValidators.fromPartial({
authority: AuthzGranterAddr, whitelistedValidators: kvUpdates
})
}
console.log(JSON.stringify(msgUpdateValidators))
const msg = {
typeUrl: "/cosmos.authz.v1beta1.MsgExec", value: MsgExec.fromPartial({
grantee: granteePersistenceAddr.address, msgs: [{
typeUrl: msgUpdateValidators.typeUrl,
value: MsgUpdateWhitelistedValidators.encode(msgUpdateValidators.value).finish()
}]
})
}
console.log("msg: ", JSON.stringify(msg))
const signingPersistenceClient = await CreateSigningClientFromAddress(granteePersistenceAddr)
const response = await signingPersistenceClient.signAndBroadcast(granteePersistenceAddr.address, [msg], 1.5, "Auto validator update check")
console.log(stringifyJson(response))
assertIsDeliverTxSuccess(response)
}
async function UpdateValsetWeights() {
console.log(HOST_CHAIN, FN)
if (HOST_CHAIN === HOST_CHAINS.persistenceTestnet) {
return await Fn(chainInfos.persistenceTestnet, chainInfos.persistenceTestnet, addresses.liquidStakeIBCTestnet, LIQUIDSTAKE_ADMIN_TESTNET)
} else if (HOST_CHAIN === HOST_CHAINS.persistence) {
return await Fn(chainInfos.persistence, chainInfos.persistence, addresses.liquidStakeIBC, LIQUIDSTAKE_ADMIN)
}
}
async function Fn(controllerChainInfo, hostChainInfo, txnSenderAddress, adminAddress) {
if (FN === FNS.getData) {
return await GetHostChainValSetData(controllerChainInfo, hostChainInfo)
} else if (FN === FNS.doTx) {
return await TxUpdateValsetWeights(controllerChainInfo, hostChainInfo, txnSenderAddress, adminAddress)
}
}
UpdateValsetWeights().then(_ => console.log("Success"))