solana-flux-aggregator/src/Submitter.ts

196 lines
5.4 KiB
TypeScript
Raw Normal View History

2021-02-17 05:39:03 -08:00
import { Connection } from "@solana/web3.js"
import { PublicKey, Wallet } from "solray"
import { conn } from "./context"
import { Aggregator, Submissions, Oracle } from "./schema"
import BN from "bn.js"
import { sleep } from "./utils"
import FluxAggregator from "./FluxAggregator"
import { createLogger, Logger } from "winston"
2021-02-20 02:00:17 -08:00
import { log } from "./log"
2021-02-19 05:16:33 -08:00
import { IPriceFeed } from "./feeds"
2021-02-17 05:39:03 -08:00
// allow oracle to start a new round after this many slots. each slot is about 500ms
const MAX_ROUND_STALENESS = 10
2021-02-19 05:13:56 -08:00
export interface SubmitterConfig {
// won't start a new round unless price changed this much
minValueChangeForNewRound: number
}
2021-02-17 05:39:03 -08:00
export class Submitter {
public aggregator!: Aggregator
2021-02-19 02:35:30 -08:00
public oracle!: Oracle
2021-02-17 20:15:50 -08:00
public roundSubmissions!: Submissions
public answerSubmissions!: Submissions
2021-02-17 05:39:03 -08:00
public program: FluxAggregator
public logger!: Logger
public currentValue: BN
constructor(
programID: PublicKey,
public aggregatorPK: PublicKey,
public oraclePK: PublicKey,
private oracleOwnerWallet: Wallet,
private priceFeed: IPriceFeed,
2021-02-19 02:35:30 -08:00
private cfg: SubmitterConfig
2021-02-17 05:39:03 -08:00
) {
this.program = new FluxAggregator(this.oracleOwnerWallet, programID)
this.currentValue = new BN(0)
}
// TODO: harvest rewards if > n
public async start() {
// make sure the states are initialized
this.aggregator = await Aggregator.load(this.aggregatorPK)
2021-02-17 20:15:50 -08:00
this.roundSubmissions = await Submissions.load(
this.aggregator.roundSubmissions
)
this.answerSubmissions = await Submissions.load(
this.aggregator.answerSubmissions
)
2021-02-20 02:00:17 -08:00
this.logger = log.child({
2021-02-17 05:39:03 -08:00
aggregator: this.aggregator.config.description,
})
2021-02-17 05:45:46 -08:00
await Promise.all([this.observeAggregatorState(), this.observePriceFeed()])
2021-02-17 05:39:03 -08:00
}
2021-02-19 02:35:30 -08:00
public async withdrawRewards() {
}
2021-02-17 05:39:03 -08:00
private async observeAggregatorState() {
conn.onAccountChange(this.aggregatorPK, async (info) => {
this.aggregator = Aggregator.deserialize(info.data)
2021-02-17 20:15:50 -08:00
this.roundSubmissions = await Submissions.load(
2021-02-17 05:39:03 -08:00
this.aggregator.roundSubmissions
)
2021-02-17 20:15:50 -08:00
this.answerSubmissions = await Submissions.load(
this.aggregator.answerSubmissions
)
2021-02-17 05:39:03 -08:00
// TODO: load answer
this.logger.debug("state updated", {
aggregator: this.aggregator,
2021-02-17 20:15:50 -08:00
submissions: this.roundSubmissions,
answerSubmissions: this.answerSubmissions,
2021-02-17 05:39:03 -08:00
})
this.onAggregatorStateUpdate()
})
}
2021-02-17 05:45:46 -08:00
private async observePriceFeed() {
2021-02-17 05:39:03 -08:00
for await (let price of this.priceFeed) {
if (price.decimals != this.aggregator.config.decimals) {
throw new Error(
`Expect price with decimals of ${this.aggregator.config.decimals} got: ${price.decimals}`
)
}
this.currentValue = new BN(price.value)
2021-02-19 02:35:30 -08:00
const valueDiff = this.aggregator.answer.median
.sub(this.currentValue)
.abs()
if (valueDiff.lten(this.cfg.minValueChangeForNewRound)) {
this.logger.debug("price did not change enough to start a new round", {
diff: valueDiff.toNumber(),
})
continue
}
2021-02-17 05:39:03 -08:00
await this.trySubmit()
}
}
private async trySubmit() {
// TODO: make it possible to be triggered by chainlink task
// TODO: If from chainlink node, update state before running
2021-02-19 02:35:30 -08:00
this.oracle = await Oracle.load(this.oraclePK)
this.logger.debug("oracle", { oracle: this.oracle })
2021-02-17 05:39:03 -08:00
const { round } = this.aggregator
2021-02-17 20:15:50 -08:00
if (this.canSubmitToCurrentRound) {
2021-02-17 05:39:03 -08:00
this.logger.info("Submit to current round")
await this.submitCurrentValue(round.id)
return
}
2021-02-17 20:15:50 -08:00
// or, see if oracle can start a new round
2021-02-17 05:45:46 -08:00
const epoch = await conn.getEpochInfo()
const sinceLastUpdate = new BN(epoch.absoluteSlot).sub(round.updatedAt)
// console.log("slot", epoch.absoluteSlot, sinceLastUpdate.toString())
if (sinceLastUpdate.ltn(MAX_ROUND_STALENESS)) {
2021-02-17 20:15:50 -08:00
// round is not stale yet. don't submit new round
2021-02-17 05:39:03 -08:00
return
}
2021-02-17 05:45:46 -08:00
// The round is stale. start a new round if possible, or wait for another
// oracle to start
2021-02-17 05:39:03 -08:00
const oracle = await Oracle.load(this.oraclePK)
if (oracle.canStartNewRound(round.id)) {
2021-02-20 02:00:17 -08:00
this.logger.info("Starting a new round")
2021-02-17 05:39:03 -08:00
return this.submitCurrentValue(round.id.addn(1))
}
}
private async onAggregatorStateUpdate() {
2021-02-20 02:00:17 -08:00
if (!this.canSubmitToCurrentRound) {
2021-02-17 05:39:03 -08:00
return
}
this.logger.info("Another oracle started a new round")
await this.trySubmit()
}
2021-02-17 20:15:50 -08:00
get canSubmitToCurrentRound(): boolean {
return this.roundSubmissions.canSubmit(
this.oraclePK,
this.aggregator.config
)
2021-02-17 05:39:03 -08:00
}
private async submitCurrentValue(round: BN) {
// guard zero value
const value = this.currentValue
if (value.isZero()) {
this.logger.warn("current value is zero. skip submit.")
return
}
2021-02-20 02:00:17 -08:00
this.logger.info("Submit value", {
2021-02-17 05:39:03 -08:00
round: round.toString(),
value: value.toString(),
})
2021-02-17 20:15:50 -08:00
try {
await this.program.submit({
accounts: {
aggregator: { write: this.aggregatorPK },
roundSubmissions: { write: this.aggregator.roundSubmissions },
answerSubmissions: { write: this.aggregator.answerSubmissions },
oracle: { write: this.oraclePK },
oracle_owner: this.oracleOwnerWallet.account,
},
round_id: round,
value,
})
} catch (err) {
console.log(err)
2021-02-20 02:00:17 -08:00
this.logger.error("Submit error", {
err: err.toString(),
2021-02-17 20:15:50 -08:00
})
}
2021-02-17 05:39:03 -08:00
}
}