Skip to content

Commit

Permalink
Merge pull request #14 from terraswap/hotfix/classic-oracle
Browse files Browse the repository at this point in the history
Hotfix: classic oracle
  • Loading branch information
jbamlee authored Sep 18, 2023
2 parents ef14894 + 4a5ff07 commit 4507865
Showing 1 changed file with 38 additions and 6 deletions.
44 changes: 38 additions & 6 deletions src/lib/terra/oracle/classic.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,46 @@
import { delay } from 'bluebird'
import { num } from 'lib/num'
import fetch from 'node-fetch'
import { ExchangeRate } from 'types'
import { Oracle } from './interfaces'
import axios, { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders } from 'axios'
import * as http from 'http';
import * as https from 'https';

export class ClassicOracle implements Oracle {
private url = process.env.TERRA_LCD ?? "http://localhost:1317"
private client: AxiosInstance

constructor(url?: string, config?: AxiosRequestConfig) {
if (url) {
this.url = url
}
const defaultConfig = {
baseURL: this.url,
httpAgent: new http.Agent({ keepAlive: true, maxTotalSockets: 5, keepAliveMsecs: 5 * 1000 }),
httpsAgent: new https.Agent({ keepAlive: true, maxTotalSockets: 5 }),
timeout: 10 * 1000,
}
this.client = axios.create({
...defaultConfig,
...config,
})
}

async getExchangeRate(height: number): Promise<ExchangeRate> {
let headers: AxiosRequestHeaders = {}
if (height) {
headers = {
'x-cosmos-block-height': `${height}`,
}
}
if (Number(process.env.START_BLOCK_HEIGHT) + 100 > height) height += 100
let res = await this.getFromLCD('/oracle/denoms/exchange_rates?height=' + height.toString())
let res = await this.getFromLCD('/terra/oracle/v1beta1/denoms/exchange_rates', headers)
if (res && !res.result) {
let index = 1
while (!res.result) {
headers['x-cosmos-block-height'] = `${(height - index * 100)}`
res = await this.getFromLCD(
'/oracle/denoms/exchange_rates?height=' + (height - index * 100).toString()
'/terra/oracle/v1beta1/denoms/exchange_rates', headers
)
index++
}
Expand Down Expand Up @@ -41,17 +69,21 @@ export class ClassicOracle implements Oracle {
return num(uusdRate).div(targetDenomRate).toString()
}

private async getFromLCD(leftover: string, baseURL = process.env.TERRA_LCD): Promise<ExchangeRate> {
private async getFromLCD(path: string, headers?: AxiosRequestHeaders): Promise<ExchangeRate> {
let got = false
while (!got) {
try {
const res = await fetch(baseURL + leftover, {
const res = await this.client.get(this.url + path, {
headers: {
accept: 'application/json',
...headers
},
}).catch()
got = true
return res.json()
return {
height: headers['x-cosmos-block-height'],
result: res.data.exchange_rates
}
} catch (error) {
delay(1000)
throw error
Expand Down

0 comments on commit 4507865

Please sign in to comment.