|
1 | 1 | import { AnyApi, FixedPointNumber as FN, MaybeCurrency, Token, forceToCurrencyId } from "@acala-network/sdk-core"; |
2 | 2 | import { SubstrateBlock } from '@subql/types/dist/interfaces'; |
3 | | -import { getPool, getToken } from "."; |
| 3 | +import { getBlock, getPool, getToken } from "./record"; |
4 | 4 | import { getTokenName } from './getTokenName'; |
5 | 5 | import { PriceBundle } from "../types"; |
6 | | -import { queryPriceFromOracle } from "@acala-network/subql-utils"; |
| 6 | + |
| 7 | +const getOracleValue = async (api: AnyApi, token: MaybeCurrency) => { |
| 8 | + const currencyId = forceToCurrencyId(api as any, token); |
| 9 | + const query = (api as any)?.query?.acalaOracle?.values || (api as any)?.query?.oracle?.values; |
| 10 | + |
| 11 | + if (query) { |
| 12 | + return query(currencyId); |
| 13 | + } |
| 14 | + |
| 15 | + const getValue = (api as any)?.rpc?.oracle?.getValue; |
| 16 | + |
| 17 | + if (typeof getValue === 'function') { |
| 18 | + return getValue('Aggregated', currencyId); |
| 19 | + } |
| 20 | + |
| 21 | + throw new Error(`Oracle price source is unavailable for ${getTokenName(token)}`); |
| 22 | +} |
| 23 | + |
| 24 | +const queryPriceFromOracle = async (api: AnyApi, _block: SubstrateBlock, token: MaybeCurrency) => { |
| 25 | + const result = await getOracleValue(api, token); |
| 26 | + const value = result?.unwrapOrDefault?.() || result; |
| 27 | + |
| 28 | + return FN.fromInner(value?.value?.value?.toString() || value?.value?.toString() || 0, 18); |
| 29 | +} |
| 30 | + |
| 31 | +export const ensurePriceBundleBlock = async (block: SubstrateBlock) => { |
| 32 | + const blockId = block.block.header.number.toString(); |
| 33 | + const blockRecord = await getBlock(blockId); |
| 34 | + |
| 35 | + blockRecord.hash = block.block.hash.toString(); |
| 36 | + blockRecord.number = BigInt(blockId); |
| 37 | + blockRecord.timestamp = block.timestamp; |
| 38 | + |
| 39 | + await blockRecord.save(); |
| 40 | + |
| 41 | + return blockRecord; |
| 42 | +} |
7 | 43 |
|
8 | 44 | const getOtherPrice = async (api: AnyApi, block: SubstrateBlock, token: string, stakingCurrency: string, StableCurrency: string) => { |
9 | 45 | const { rate: rateA, amount: _amountA } = await getPriceFromDexPool(token, stakingCurrency); |
@@ -154,11 +190,12 @@ export const getStablePriceBundle = async (api: AnyApi, block: SubstrateBlock, t |
154 | 190 |
|
155 | 191 | if (!record) { |
156 | 192 | const price = token === 'KUSD' ? await getKusdMarketPrice(api, block) : await getAusdMarketPrice(api, block); |
| 193 | + const blockRecord = await ensurePriceBundleBlock(block); |
157 | 194 |
|
158 | 195 | record = new PriceBundle(id); |
159 | 196 |
|
160 | 197 | record.tokenId = token |
161 | | - record.blockId = block.block.header.number.toString(); |
| 198 | + record.blockId = blockRecord.id; |
162 | 199 | record.price = BigInt((price || FN.ZERO).toChainData()) |
163 | 200 |
|
164 | 201 | await record.save(); |
|
0 commit comments