-
Notifications
You must be signed in to change notification settings - Fork 0
/
smartstake-update-valset-weights.js
311 lines (281 loc) · 12.1 KB
/
smartstake-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
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 {QueryClientImpl as PstakeQuery} from "persistenceonejs/pstake/liquidstakeibc/v1beta1/query.js"
import {QueryClientImpl as StakingQuery} from "persistenceonejs/cosmos/staking/v1beta1/query.js"
import {QueryClientImpl as SlashingQuery,} from "persistenceonejs/cosmos/slashing/v1beta1/query.js"
import {AllPaginatedQuery, CreateSigningClientFromAddress, parseJson, RpcClient, stringifyJson} from "./helper.js";
import {addresses, chainInfos, FN, FNS, HOST_CHAIN, HOST_CHAINS, LIQUIDSTAKEIBC_ADMIN} from "./constants.js";
import {assertIsDeliverTxSuccess} from "@cosmjs/stargate";
import {MsgExec} from "cosmjs-types/cosmos/authz/v1beta1/tx.js";
import {MsgUpdateHostChain} from "persistenceonejs/pstake/liquidstakeibc/v1beta1/msgs.js";
import * as fs from "fs";
import {
CalculateValidatorFinalScore,
FilterDenyList,
FilterOnBlocksMissed,
FilterOnCommission,
FilterOnSlashingEvents,
FilterOnTimeActiveSet,
FilterOnValidatorBond,
FilterOnVotingPower,
SmartStakeFilterOnGov,
SmartStakeFilterOnUptime,
UpdateSigningInfosToValidators
} from "./filter.js";
import {BondStatus, bondStatusToJSON} from "cosmjs-types/cosmos/staking/v1beta1/staking.js";
async function GetHostChainValSetData(persistenceChainInfo, cosmosChainInfo) {
const [persistenceTMClient, persistenceRpcClient] = await RpcClient(persistenceChainInfo)
const pstakeQueryClient = new PstakeQuery(persistenceRpcClient)
// try for querying hostchain, if not found default with lsm false, for finding validator set
let hostChain = {hostChain: {flags: {lsm: false}}}
try {
hostChain = await pstakeQueryClient.HostChain({chainId: cosmosChainInfo.chainID})
console.log("queried host-chain")
} catch (e) {
console.log("failed to query host-chain with id:", cosmosChainInfo.chainID, "err:", e, "using default hostchain map with lsm disabled.")
}
const [cosmosTMClient, cosmosRpcClient] = await RpcClient(cosmosChainInfo)
const cosmosStakingClient = new StakingQuery(cosmosRpcClient)
const cosmosSlashingClient = new SlashingQuery(cosmosRpcClient)
let appName = cosmosChainInfo.pstakeConfig.smartStakeApiAppName
if (appName === "") {
throw new Error("appName not found for chain-id " + cosmosChainInfo.chainID)
}
// // 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,
deny: false,
denyReason: [],
commissionScore: 0,
uptimeScore: 0,
govScore: 0,
votingPowerScore: 0,
validatorBondScore: 0,
overAllValidatorScore: 0,
weight: 0,
moniker: validator.name,
}
allVals.push(valmap)
}
console.log(allVals.length)
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
if (hostChain.hostChain.flags.lsm === true) {
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 SmartStakeFilterOnGov(appName, 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 SmartStakeFilterOnUptime(appName, allVals, cosmosChainInfo.pstakeConfig.uptime)
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, hostChain.hostChain.flags.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(10)
}
const jsonString = stringifyJson(allVals)
fs.writeFileSync(cosmosChainInfo.pstakeConfig.filename, jsonString);
process.stdout.write(jsonString + "\n")
return
}
// DUPLICATE FROM stkatom-update-valset-weights
async function TxUpdateValsetWeights(persistenceChainInfo, cosmosChainInfo, granteePersistenceAddr, AuthzGranterAddr) {
const [persistenceTMClient, persistenceRpcClient] = await RpcClient(persistenceChainInfo)
const pstakeQueryClient = new PstakeQuery(persistenceRpcClient)
let hostChain = await pstakeQueryClient.HostChain({chainId: cosmosChainInfo.chainID})
let allVals = parseJson(fs.readFileSync(cosmosChainInfo.pstakeConfig.filename))
// Find validators which are not yet part of pstake validators
let add_vals = []
for (let i = 0; i < allVals.length; i++) {
if (allVals[i].deny === true) {
continue
}
let found = false
for (let j = 0; j < hostChain.hostChain.validators.length; j++) {
if (allVals[i].valoper === hostChain.hostChain.validators[j].operatorAddress) {
found = true
}
}
if (!found) {
add_vals.push(allVals[i].valoper)
}
}
let kvUpdates = []
// add kv updates to add_validators
for (let i = 0; i < add_vals.length; i++) {
kvUpdates.push({
key: "add_validator", value: JSON.stringify({
operator_address: add_vals[i],
status: "BOND_STATUS_UNSPECIFIED",
weight: "0",
delegated_amount: "0",
exchange_rate: "1",
delegable: !hostChain.hostChain.flags.lsm
})
})
kvUpdates.push({
key: "validator_update", value: add_vals[i]
})
}
// reset weights to zero
for (let i = 0; i < hostChain.hostChain.validators.length; i++) {
kvUpdates.push({
key: "validator_weight", value: `${hostChain.hostChain.validators[i].operatorAddress},0`
})
}
// 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
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
let found = false
for (let j = 0; j < kvUpdates.length; j++) {
if (kvUpdates[j].key === "validator_weight" && kvUpdates[j].value === `${nonZeroVals[i].valoper},0`) {
kvUpdates[j].value = `${nonZeroVals[i].valoper},${nonZeroVals[i].weight}`
found = true
}
}
if (!found) {
kvUpdates.push({
key: "validator_weight", value: `${nonZeroVals[i].valoper},${nonZeroVals[i].weight}`
})
}
}
if (kvUpdates.length === 0 || sum !== 1) {
console.error(`no kv updates, total kv updates:${kvUpdates.length}, sum ${sum}`)
throw "No valset update"
} else {
console.log("total kv updates:", kvUpdates.length)
}
const msgUpdateHostChain = {
typeUrl: "/pstake.liquidstakeibc.v1beta1.MsgUpdateHostChain", value: MsgUpdateHostChain.fromPartial({
authority: AuthzGranterAddr, chainId: cosmosChainInfo.chainID, updates: kvUpdates
})
}
console.log(JSON.stringify(msgUpdateHostChain))
const msg = {
typeUrl: "/cosmos.authz.v1beta1.MsgExec", value: MsgExec.fromPartial({
grantee: granteePersistenceAddr.address, msgs: [{
typeUrl: msgUpdateHostChain.typeUrl, value: MsgUpdateHostChain.encode(msgUpdateHostChain.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.cosmos) {
return await Fn(chainInfos.persistence, chainInfos.cosmos, addresses.liquidStakeIBC, LIQUIDSTAKEIBC_ADMIN)
} else if (HOST_CHAIN === HOST_CHAINS.osmosis) {
return await Fn(chainInfos.persistence, chainInfos.osmosis, addresses.liquidStakeIBC, LIQUIDSTAKEIBC_ADMIN)
} else if (HOST_CHAIN === HOST_CHAINS.dydx) {
return await Fn(chainInfos.persistence, chainInfos.dydx, addresses.liquidStakeIBC, LIQUIDSTAKEIBC_ADMIN)
} else if (HOST_CHAIN === HOST_CHAINS.stargaze) {
return await Fn(chainInfos.persistence, chainInfos.stargaze, addresses.liquidStakeIBC, LIQUIDSTAKEIBC_ADMIN)
} else if (HOST_CHAIN === HOST_CHAINS.agoric) {
return await Fn(chainInfos.persistence, chainInfos.agoric, addresses.liquidStakeIBC, LIQUIDSTAKEIBC_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"))