feat: Interface data processing

This commit is contained in:
alisa 2023-04-27 00:18:50 +08:00
parent e1c62c086f
commit 062d8b81b5
3 changed files with 81 additions and 38 deletions

48
src/libs/utils.ts Normal file
View File

@ -0,0 +1,48 @@
export function getLocalObject(name: string) {
const text = localStorage.getItem(name)
if (text) {
return JSON.parse(text)
}
return null
}
export function getLocalChains() {
return 'osmosis'
}
export const percent = (num: number) => {
return parseFloat((num * 100).toFixed(2))
}
const COUNT_ABBRS = ['', 'K', 'M', 'B', 't', 'q', 's', 'S', 'o', 'n', 'd', 'U', 'D', 'T', 'Qt', 'Qd', 'Sd', 'St']
export function formatNumber(count:number, withAbbr = false, decimals = 2) {
const i = count === 0 ? count : Math.floor(Math.log(count) / Math.log(1000))
let result: any = parseFloat((count / (1000 ** i)).toFixed(decimals))
if (withAbbr && COUNT_ABBRS[i]) {
result += `${COUNT_ABBRS[i]}`
}
return result
}
export function formatTokenAmount(assets: any ,tokenAmount: any, decimals = 2, tokenDenom = 'uatom', format = true) {
const denom = tokenDenom?.denom_trace ? tokenDenom?.denom_trace?.base_denom : tokenDenom
let amount = 0
const asset = assets.find((a:any) => (a.base === denom))
let exp = asset? asset.exponent: String(denom).startsWith('gravity') ? 18 : 6
const config = Object.values(getLocalChains())
amount = Number(Number(tokenAmount)) / (10 ** exp)
if (amount > 10) {
if (format) { return numberWithCommas(parseFloat(amount.toFixed(decimals))) }
return parseFloat(amount.toFixed(decimals))
}
return parseFloat(amount.toFixed(exp))
}
export function numberWithCommas(x: any) {
const parts = x.toString().split('.')
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
return parts.join('.')
}

View File

@ -70,6 +70,7 @@ export interface ChainConfig {
cosmosSdk?: string, cosmosSdk?: string,
tendermint?: string, tendermint?: string,
}, },
exponent: string,
} }
export interface LocalConfig { export interface LocalConfig {
@ -109,7 +110,8 @@ export function fromLocal(lc: LocalConfig ): ChainConfig {
display: x.symbol, display: x.symbol,
symbol: x.symbol, symbol: x.symbol,
logo_URIs: { svg: x.logo }, logo_URIs: { svg: x.logo },
coingecko_id: x.coingecko_id, coingecko_id: x.coingecko_id,
exponent: x.exponent,
denom_units: [{denom: x.base, exponent: 0}, {denom: x.symbol.toLowerCase(), exponent: Number(x.exponent)}] denom_units: [{denom: x.base, exponent: 0}, {denom: x.symbol.toLowerCase(), exponent: Number(x.exponent)}]
})) }))
conf.bech32Prefix = lc.addr_prefix conf.bech32Prefix = lc.addr_prefix

View File

@ -1,6 +1,6 @@
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { useBlockchain } from "./useBlockchain"; import { useBlockchain } from "./useBlockchain";
import { percent,formatNumber,formatTokenAmount } from '@/libs/utils'
export interface stakingItem { export interface stakingItem {
unbonding_time: string unbonding_time: string
max_validators: number max_validators: number
@ -24,25 +24,25 @@ export const useParamStore = defineStore("paramstore", {
{ subtitle: 'inflation', icon: 'TrendingUpIcon', color: 'light-primary', value: '' }, { subtitle: 'inflation', icon: 'TrendingUpIcon', color: 'light-primary', value: '' },
], ],
}, },
mint: {
title: 'Mint Parameters',
items: [] as Array<any>,
},
staking: { staking: {
title: 'Staking Parameters', title: 'Staking Parameters',
items: [] as Array<any>, items: [] as Array<any>,
}, },
distribution: { distribution: {
title: 'Distribution Parameters', title: 'Distribution Parameters',
items: [], items: [] as Array<any>,
}, },
slashing: { slashing: {
title: 'Slashing Parameters', title: 'Slashing Parameters',
items: null, items: [] as Array<any>,
},
mint: {
title: 'Mint Parameters',
items: null,
}, },
gov: { gov: {
title: 'Governance Parameters', title: 'Governance Parameters',
items: [], items: [] as Array<any>,
}, },
}), }),
getters: { getters: {
@ -53,6 +53,7 @@ export const useParamStore = defineStore("paramstore", {
actions: { actions: {
initial() { initial() {
this.handleBaseBlockLatest() this.handleBaseBlockLatest()
this.handleMintParam()
this.handleStakingParams() this.handleStakingParams()
}, },
async handleBaseBlockLatest() { async handleBaseBlockLatest() {
@ -61,7 +62,7 @@ export const useParamStore = defineStore("paramstore", {
const height = this.chain.items.findIndex(x => x.subtitle === 'height') const height = this.chain.items.findIndex(x => x.subtitle === 'height')
this.chain.title = `Chain ID: ${res.block.header.chain_id}` this.chain.title = `Chain ID: ${res.block.header.chain_id}`
this.chain.items[height].value = res.block.header.height this.chain.items[height].value = res.block.header.height
console.log(this.chain.items[height].value, 999) console.log(res, 999)
// if (timeIn(res.block.header.time, 3, 'm')) { // if (timeIn(res.block.header.time, 3, 'm')) {
// this.syncing = true // this.syncing = true
// } else { // } else {
@ -74,42 +75,34 @@ export const useParamStore = defineStore("paramstore", {
} }
}, },
async handleStakingParams() { async handleStakingParams() {
console.log('handleStakingParams', 99999)
const res = await this.getStakingParams() const res = await this.getStakingParams()
const bond_denom = res?.params.bond_denom
this.staking.items = Object.entries(res.params).map(([key, value]) => ({ subtitle:key, this.staking.items = Object.entries(res.params).map(([key, value]) => ({ subtitle:key,
value: value })) value: value })).filter((item: any) => {
if (!['min_commission_rate','min_self_delegation'].includes(item.subtitle)) return item
Promise.all([this.getStakingPool(), this.getBankTotal(res?.params.bond_denom)]) })
Promise.all([this.getStakingPool(), this.getBankTotal(bond_denom)])
.then(resArr => { .then(resArr => {
console.log(resArr, 'ddd') const pool = resArr[0]?.pool
const amount =resArr[1]?.amount?.amount
const assets = this.blockchain.current?.assets
const bondedAndSupply = this.chain.items.findIndex(x => x.subtitle === 'bonded_and_supply')
this.chain.items[bondedAndSupply].value = `${formatNumber(formatTokenAmount(assets,pool.bonded_tokens, 2, bond_denom, false), true, 0)}/${formatNumber(formatTokenAmount(assets,amount, 2, bond_denom, false), true, 0)}`
const bondedRatio = this.chain.items.findIndex(x => x.subtitle === 'bonded_ratio')
this.chain.items[bondedRatio].value = `${percent(Number(pool.bonded_tokens) /Number(amount)) }%`
}) })
// const totalRes = await this.getBankTotal(res?.params.bond_denom)
// console.log(res, 9999, totalRes)
}, },
// normalize(data: {}, title:string) { async handleMintParam() {
// if (!data) return null const res = await this.getMintParam()
// const items = this.makeItems(data) console.log(res, 'mint')
// return {
// title, },
// items,
// }
// },
// makeItems(data) {
// return Object.keys(data).map(k => {
// if (isToken(data[k])) {
// return { title: tokenFormatter(data[k]), subtitle: k }
// }
// if (typeof data[k] === 'boolean') {
// return { title: data[k], subtitle: k }
// }
// return { title: this.convert(data[k]), subtitle: k }
// })
// },
async getBaseTendermintBlockLatest() { async getBaseTendermintBlockLatest() {
return await this.blockchain.rpc.getBaseBlockLatest() return await this.blockchain.rpc.getBaseBlockLatest()
}, },
async getMintParam() {
return await this.blockchain.rpc.getMintParam()
},
async getStakingParams() { async getStakingParams() {
return await this.blockchain.rpc.getStakingParams() return await this.blockchain.rpc.getStakingParams()
}, },