forked from terra-money/oracle-feeder
-
Notifications
You must be signed in to change notification settings - Fork 7
/
vote.ts
366 lines (305 loc) · 10.1 KB
/
vote.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import * as crypto from 'crypto'
import * as Bluebird from 'bluebird'
import * as promptly from 'promptly'
import * as http from 'http'
import * as https from 'https'
import axios from 'axios'
import * as ks from './keystore'
import {
LCDClient,
RawKey,
Wallet,
isTxError,
LCDClientConfig,
OracleAPI,
MsgAggregateExchangeRateVote,
Fee,
} from '@terra-money/terra.js'
import * as packageInfo from '../package.json'
import * as logger from './logger'
import { BigNumber } from 'bignumber.js'
const ax = axios.create({
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
timeout: 10000,
headers: {
post: {
'Content-Type': 'application/json',
},
},
})
async function initKey(keyPath: string, name: string, password?: string): Promise<RawKey> {
const plainEntity = ks.load(
keyPath,
name,
password || (await promptly.password(`Enter a passphrase:`, { replace: `*` }))
)
return new RawKey(Buffer.from(plainEntity.privateKey, 'hex'))
}
interface OracleParameters {
oracleVotePeriod: number
oracleWhitelist: string[]
currentVotePeriod: number
indexInVotePeriod: number
nextBlockHeight: number
}
async function loadOracleParams(client: LCDClient, oracle: OracleAPI): Promise<OracleParameters> {
const oracleParams = await oracle.parameters()
const oracleVotePeriod = oracleParams.vote_period
const oracleWhitelist: string[] = oracleParams.whitelist.map((e) => e.name)
const latestBlock = await client.tendermint.blockInfo()
// the vote will be included in the next block
const blockHeight = parseInt(latestBlock.block.header.height, 10)
const nextBlockHeight = blockHeight + 1
const currentVotePeriod = Math.floor(blockHeight / oracleVotePeriod)
const indexInVotePeriod = nextBlockHeight % oracleVotePeriod
return {
oracleVotePeriod,
oracleWhitelist,
currentVotePeriod,
indexInVotePeriod,
nextBlockHeight,
}
}
interface Price {
denom: string
price: string
}
async function getPrices(sources: string[]): Promise<Price[]> {
const results = await Bluebird.some(
sources.map((s) => ax.get(s)),
1
).then((results) =>
results.filter(({ data }) => {
if (typeof data.created_at !== 'string' || !Array.isArray(data.prices) || !data.prices.length) {
logger.error('getPrices: invalid response')
return false
}
// Ignore prices older than 60 seconds ago
if (Date.now() - new Date(data.created_at).getTime() > 60 * 1000) {
logger.error('getPrices: too old')
return false
}
return true
})
)
if (!results.length) {
return []
}
return results[0].data.prices
}
/**
* preparePrices traverses prices array for following logics:
* 1. Removes price that cannot be found in oracle whitelist
* 2. Fill abstain prices for prices that cannot be found in price source but in oracle whitelist
*/
function preparePrices(prices: Price[], oracleWhitelist: string[]): Price[] {
const idx = prices.findIndex((p) => p.denom === 'LUNC')
if (idx === -1) {
throw new Error('cannot find LUNC price')
}
const luncusd = new BigNumber(prices[idx].price)
const newPrices = prices
.map((price) => {
if (oracleWhitelist.indexOf(`u${price.denom.toLowerCase()}`) === -1) {
return
}
return {
denom: price.denom,
price: luncusd.dividedBy(price.price).toString(),
}
})
.filter(Boolean) as Price[]
oracleWhitelist.forEach((denom) => {
const found = prices.filter((price) => denom === `u${price.denom.toLowerCase()}`).length > 0
if (!found) {
if (denom === 'uusd') {
newPrices.push({
denom: 'USD',
price: luncusd.toString(),
})
} else {
newPrices.push({
denom: denom.slice(1).toUpperCase(),
price: '0.000000',
})
}
}
})
return newPrices
}
function buildVoteMsgs(prices: Price[], valAddrs: string[], voterAddr: string): MsgAggregateExchangeRateVote[] {
const coins = prices.map(({ denom, price }) => `${price}u${denom.toLowerCase()}`).join(',')
return valAddrs.map((valAddr) => {
const salt = crypto.randomBytes(2).toString('hex')
return new MsgAggregateExchangeRateVote(coins, salt, voterAddr, valAddr)
})
}
let previousVoteMsgs: MsgAggregateExchangeRateVote[] = []
let previousVotePeriod = 0
// yarn start vote command
export async function processVote(
client: LCDClient,
wallet: Wallet,
args: VoteArgs,
valAddrs: string[],
voterAddr: string
): Promise<void> {
const oracle = new OracleAPI(client)
logger.info(`[VOTE] Requesting on chain data`)
const { oracleVotePeriod, oracleWhitelist, currentVotePeriod, indexInVotePeriod, nextBlockHeight } =
await loadOracleParams(client, oracle)
// Skip until new voting period
// Skip when index [0, oracleVotePeriod - 1] is bigger than oracleVotePeriod - 2 or index is 0
if ((previousVotePeriod && currentVotePeriod === previousVotePeriod) || oracleVotePeriod - indexInVotePeriod < 2) {
return
}
// If it failed to reveal the price,
// reset the state by throwing error
if (previousVotePeriod && currentVotePeriod - previousVotePeriod !== 1) {
throw new Error('Failed to Reveal Exchange Rates; reset to prevote')
}
// Print timestamp before start
logger.info(`[VOTE] Requesting prices from price server ${args.dataSourceUrl.join(',')}`)
const _prices = await getPrices(args.dataSourceUrl)
// Removes non-whitelisted currencies and abstain for not fetched currencies
const prices = preparePrices(_prices, oracleWhitelist)
// Build Exchange Rate Vote Msgs
const voteMsgs: any[] = buildVoteMsgs(prices, valAddrs, voterAddr)
logger.info(`[VOTE] Create transaction and sign`)
// Build Exchange Rate Prevote Msgs
const isPrevoteOnlyTx = previousVoteMsgs.length === 0
const msgs = [...previousVoteMsgs, ...voteMsgs.map((vm) => vm.getPrevote())]
logger.info(`[PREVOTE] msg: ${JSON.stringify(msgs)}\n`)
const tx = await wallet.createAndSignTx({
msgs,
fee: new Fee((1 + msgs.length) * 50000, []),
memo: `${packageInfo.name}@${packageInfo.version}`,
})
const res = await client.tx.broadcastBlock(tx).catch((err) => {
logger.error(`broadcast error: ${err.message} ${tx.toData()}`)
throw err
})
if (isTxError(res)) {
logger.error(`broadcast error: code: ${res.code}, raw_log: ${res.raw_log}`)
return
}
const txhash = res.txhash
logger.info(`[VOTE] Broadcast success ${txhash}`)
const height = await validateTx(
client,
nextBlockHeight,
txhash,
args,
// if only prevote exist, then wait 2 * vote_period blocks,
// else wait left blocks in the current vote_period
isPrevoteOnlyTx ? oracleVotePeriod * 2 : oracleVotePeriod - indexInVotePeriod
)
// Update last success VotePeriod
previousVotePeriod = Math.floor(height / oracleVotePeriod)
previousVoteMsgs = voteMsgs
}
async function validateTx(
client: LCDClient,
nextBlockHeight: number,
txhash: string,
args: VoteArgs,
timeoutHeight: number
): Promise<number> {
let inclusionHeight = 0
// wait 3 blocks
const maxBlockHeight = nextBlockHeight + timeoutHeight
// current block height
let lastCheckHeight = nextBlockHeight - 1
while (!inclusionHeight && lastCheckHeight < maxBlockHeight) {
await Bluebird.delay(1500)
const lastBlock = await client.tendermint.blockInfo()
const latestBlockHeight = parseInt(lastBlock.block.header.height, 10)
if (latestBlockHeight <= lastCheckHeight) {
continue
}
// set last check height to latest block height
lastCheckHeight = latestBlockHeight
// wait for indexing (not sure; but just for safety)
await Bluebird.delay(500)
client.tx
.txInfo(txhash)
.then((res) => {
const { height, code, raw_log } = res
if (!res.code) {
inclusionHeight = height
} else {
throw new Error(`[VOTE]: transaction failed tx: code: ${code}, raw_log: ${raw_log}`)
}
})
.catch((err) => {
if (!err.isAxiosError) {
logger.error('txInfo error', err)
}
})
}
if (!inclusionHeight) {
throw new Error('[VOTE]: transaction timeout')
}
logger.info(`[VOTE] Included at height: ${inclusionHeight}`)
return inclusionHeight
}
interface VoteArgs {
lcdUrl: string[]
prefix: string
chainID: string
validators: string[]
dataSourceUrl: string[]
password: string
keyPath: string
keyName: string
}
function buildLCDClientConfig(args: VoteArgs, lcdIndex: number): Record<string, LCDClientConfig> {
return {
[args.chainID]: {
URL: args.lcdUrl[lcdIndex],
chainID: args.chainID,
gasAdjustment: '1.5',
gasPrices: { ucandle: 0.0015 },
isClassic: true,
},
}
}
export async function vote(args: VoteArgs): Promise<void> {
const rawKey: RawKey = await initKey(args.keyPath, args.keyName, args.password)
const valAddrs: string[] = args.validators || [rawKey.valAddress]
const voterAddr = rawKey.accAddress
const lcdRotate = {
client: new LCDClient(buildLCDClientConfig(args, 0)[args.chainID]),
current: 0,
max: args.lcdUrl.length - 1,
}
while (true) {
const startTime = Date.now()
await processVote(lcdRotate.client, lcdRotate.client.wallet(rawKey), args, valAddrs, voterAddr).catch((err) => {
if (err.isAxiosError && err.response) {
logger.error(err.message, err.response.data)
} else {
logger.error(err)
}
if (err.isAxiosError) {
logger.info('vote: lcd client unavailable, rotating to next lcd client.')
rotateLCD(args, lcdRotate)
}
resetPrevote()
})
await Bluebird.delay(Math.max(500, 500 - (Date.now() - startTime)))
}
}
function rotateLCD(args: VoteArgs, lcdRotate: { client: LCDClient; current: number; max: number }) {
if (++lcdRotate.current > lcdRotate.max) {
lcdRotate.current = 0
}
lcdRotate.client = new LCDClient(buildLCDClientConfig(args, lcdRotate.current)[args.chainID])
logger.info('Switched to LCD address ' + lcdRotate.current + '(' + args.lcdUrl[lcdRotate.current] + ')')
return
}
function resetPrevote() {
previousVotePeriod = 0
previousVoteMsgs = []
}