fix format decimal

This commit is contained in:
Pham Tu 2024-01-25 14:39:31 +07:00
parent bac4545dee
commit 39a718dc27
No known key found for this signature in database
GPG Key ID: 7460FD99133ADA1C
12 changed files with 89 additions and 83 deletions

View File

@ -3,6 +3,7 @@ import type { PropType } from 'vue';
import { useFormatter } from '@/stores';
import { formatSeconds, formatTitle } from '@/libs/utils';
import { fromAscii, toBase64 } from '@cosmjs/encoding';
import numeral from 'numeral';
const props = defineProps({
cardItem: {
type: Object as PropType<{ title: string; items: Array<any> }>,
@ -14,7 +15,7 @@ function calculateValue(value: any) {
if (!value) return;
if (value instanceof Uint8Array) {
return formatter.formatDecimalToPercent(fromAscii(value));
return formatter.formatDecimalToPercent(fromAscii(value), 1e18);
}
if (Array.isArray(value)) {
@ -33,7 +34,7 @@ function calculateValue(value: any) {
}
// check is correct percent format
const decimalFormat = formatter.toDecimal(value);
const decimalFormat = numeral(value);
if (decimalFormat) {
const decimalValue = decimalFormat.value();
if (decimalValue && decimalValue < 1 && decimalValue > 0) {

View File

@ -3,6 +3,7 @@ import ApexCharts from 'vue3-apexcharts';
import { computed, type PropType } from 'vue';
import { useFormatter } from '@/stores';
import type { Commission } from 'cosmjs-types/cosmos/staking/v1beta1/staking';
import numeral from 'numeral';
const props = defineProps({
commission: { type: Object as PropType<Commission> },
@ -11,18 +12,18 @@ const format = useFormatter();
let rate = computed(
() =>
(format.toDecimal(props.commission?.commissionRates.rate)?.value() || 0) *
100
(numeral(props.commission?.commissionRates.rate).divide(1e18)?.value() ||
0) * 100
);
let change = computed(
() =>
(format
.toDecimal(props.commission?.commissionRates.maxChangeRate)
(numeral(props.commission?.commissionRates.maxChangeRate)
.divide(1e18)
?.value() || 0) * 100
);
let max = computed(
() =>
(format.toDecimal(props.commission?.commissionRates.maxRate)?.value() ||
(numeral(props.commission?.commissionRates.maxRate).divide(1e18)?.value() ||
1) * 100
);

View File

@ -2,7 +2,6 @@ import type {
AuthAccount,
Block,
ClientStateWithProof,
Coin,
ConnectionWithProof,
DenomTrace,
NodeInfo,
@ -43,6 +42,7 @@ import type {
} from '@/types/staking';
import type { PaginatedTxs, Tx, TxResponse } from '@/types';
import semver from 'semver';
import type { Coin } from 'cosmjs-types/cosmos/base/v1beta1/coin';
export interface Request<T> {
url: string;
adapter: (source: any) => T;

View File

@ -1,16 +1,16 @@
import {
useBankStore,
useBaseStore,
useBlockchain,
useCoingecko,
useBaseStore,
useBankStore,
useFormatter,
useGovStore,
} from '@/stores';
import { useDistributionStore } from '@/stores/useDistributionStore';
import { useMintStore } from '@/stores/useMintStore';
import { useStakingStore } from '@/stores/useStakingStore';
import type { Coin, Tally } from '@/types';
import type { Pool } from 'cosmjs-types/cosmos/staking/v1beta1/staking';
import type { Tally } from '@/types';
import type { Coin } from '@cosmjs/stargate';
import numeral from 'numeral';
import { defineStore } from 'pinia';
@ -170,14 +170,14 @@ export const useIndexModule = defineStore('module-index', {
title: 'Supply',
color: 'success',
icon: 'mdi-currency-usd',
stats: formatter.formatTokenAmount(bank.supply!),
stats: formatter.formatToken(bank.supply!),
change: 0,
},
{
title: 'Bonded Tokens',
color: 'warning',
icon: 'mdi-lock',
stats: formatter.formatTokenAmount({
stats: formatter.formatToken({
// @ts-ignore
amount: this.pool.bondedTokens,
denom: staking.params.bondDenom,
@ -195,11 +195,15 @@ export const useIndexModule = defineStore('module-index', {
title: 'Community Pool',
color: 'primary',
icon: 'mdi-bank',
stats: formatter.formatTokens(
stats: formatter.formatToken(
// @ts-ignore
this.communityPool?.filter(
this?.communityPool?.find(
(x: Coin) => x.denom === staking.params.bondDenom
)
),
undefined,
undefined,
undefined,
1e18
),
change: 0,
},

View File

@ -18,8 +18,9 @@ import {
useStakingStore,
useTxDialog,
} from '@/stores';
import { PageRequest, type Coin } from '@/types';
import { PageRequest } from '@/types';
import { fromAscii, fromBech32, toBase64, toHex } from '@cosmjs/encoding';
import type { Coin } from '@cosmjs/stargate';
import type { Event } from '@cosmjs/tendermint-rpc';
import { Icon } from '@iconify/vue';
import type { QueryValidatorDelegationsResponse } from 'cosmjs-types/cosmos/staking/v1beta1/query';
@ -441,7 +442,10 @@ function mapDelegators(messages: any[]) {
amount: v.delegatorShares,
denom: staking.params.bondDenom,
},
false
true,
undefined,
undefined,
1e18
)
}}
</span>
@ -458,7 +462,10 @@ function mapDelegators(messages: any[]) {
amount: v.delegatorShares,
denom: staking.params.bondDenom,
},
false
true,
undefined,
undefined,
1e18
)
}}
</span>
@ -544,7 +551,7 @@ function mapDelegators(messages: any[]) {
/>
</div>
<div class="ml-3 flex flex-col justify-center">
<h4>{{ v.unbondingHeight }}</h4>
<h4>{{ Number(v.unbondingHeight) || '-' }}</h4>
<span class="text-sm">{{
$t('staking.unbonding_height')
}}</span>
@ -562,9 +569,7 @@ function mapDelegators(messages: any[]) {
<h4
v-if="
v.unbondingTime &&
!fromTimestamp(v.unbondingTime)
.toString()
.startsWith('1970')
fromTimestamp(v.unbondingTime).getFullYear() > 1970
"
>
{{ format.toDay(v.unbondingTime, 'from') }}

View File

@ -491,7 +491,8 @@ loadAvatars();
<td class="text-right text-xs">
{{
format.formatCommissionRate(
v.commission?.commissionRates?.rate
v.commission?.commissionRates?.rate,
1e18
)
}}
</td>

View File

@ -1,7 +1,7 @@
<script lang="ts" setup>
import { CosmosRestClient } from '@/libs/client';
import { useBlockchain, useDashboard, useFormatter } from '@/stores';
import type { Coin, CoinWithPrice, Delegation } from '@/types';
import type { CoinWithPrice, Delegation } from '@/types';
import { fromBech32, toBase64, toBech32, toHex } from '@cosmjs/encoding';
import { Icon } from '@iconify/vue';
import type { DelegationResponse } from 'cosmjs-types/cosmos/staking/v1beta1/staking';

View File

@ -1,6 +1,5 @@
<script lang="ts" setup>
import { CosmosRestClient } from '@/libs/client';
import type { Coin, Delegation } from '@/types';
import { ref, watchEffect } from 'vue';
import type { AccountEntry } from './utils';
import { computed } from 'vue';
@ -10,6 +9,7 @@ import ApexCharts from 'vue3-apexcharts';
import { get } from '@/libs';
import { getMarketPriceChartConfig } from '@/components/charts/apexChartConfig';
import type { DelegationResponse } from 'cosmjs-types/cosmos/staking/v1beta1/staking';
import type { Coin } from 'cosmjs-types/cosmos/base/v1beta1/coin';
const format = useFormatter();
const conf = ref(

View File

@ -1,49 +1,49 @@
import { useDashboard } from "@/stores"
import type { Coin } from "@/types"
import { fromBech32, toBech32 } from "@cosmjs/encoding"
import { useDashboard } from '@/stores';
import { fromBech32, toBech32 } from '@cosmjs/encoding';
export interface AccountEntry {
chainName: string,
logo: string,
address: string,
coinType: string,
endpoint?: string,
compatiable?: boolean,
chainName: string;
logo: string;
address: string;
coinType: string;
endpoint?: string;
compatiable?: boolean;
}
export interface LocalKey {
cosmosAddress: string, hdPath: string
cosmosAddress: string;
hdPath: string;
}
export function scanLocalKeys() {
const connected = [] as LocalKey[]
const connected = [] as LocalKey[];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (key?.startsWith("m/44")) {
const wallet = JSON.parse(localStorage.getItem(key) || "")
const key = localStorage.key(i);
if (key?.startsWith('m/44')) {
const wallet = JSON.parse(localStorage.getItem(key) || '');
if (wallet) {
connected.push(wallet)
connected.push(wallet);
}
}
}
return connected
return connected;
}
export function scanCompatibleAccounts(keys: LocalKey[]) {
const dashboard = useDashboard()
const available = [] as AccountEntry[]
keys.forEach(wallet => {
Object.values(dashboard.chains).forEach(chain => {
const { data } = fromBech32(wallet.cosmosAddress)
const dashboard = useDashboard();
const available = [] as AccountEntry[];
keys.forEach((wallet) => {
Object.values(dashboard.chains).forEach((chain) => {
const { data } = fromBech32(wallet.cosmosAddress);
available.push({
chainName: chain.chainName,
logo: chain.logo,
address: toBech32(chain.bech32Prefix, data),
coinType: chain.coinType,
compatiable: wallet.hdPath.indexOf(chain.coinType) > 0,
endpoint: chain.endpoints.rest?.at(0)?.address
})
})
})
return available
}
endpoint: chain.endpoints.rest?.at(0)?.address,
});
});
});
return available;
}

View File

@ -146,10 +146,13 @@ export const useFormatter = defineStore('formatter', {
const value = amount * this.price(token.denom);
return value;
},
formatTokenAmount(token: { denom: string; amount: string }) {
return this.formatToken(token, false);
formatTokenAmount(
token?: { denom: string; amount: string },
decimal?: number
) {
return this.formatToken(token, false, undefined, undefined, decimal);
},
formatToken2(token: { denom: string; amount: string }, decimal?: number) {
formatToken2(token?: { denom: string; amount: string }, decimal?: number) {
return this.formatToken(token, true, '0,0.[00]', undefined, decimal);
},
@ -293,10 +296,14 @@ export const useFormatter = defineStore('formatter', {
formatTokens(
tokens?: { denom: string; amount: string }[],
withDenom = true,
fmt = '0.0a'
fmt = '0,0.[0]',
mode?: string,
decimal?: number
): string {
if (!tokens) return '';
return tokens.map((x) => this.formatToken(x, withDenom, fmt)).join(', ');
return tokens
.map((x) => this.formatToken(x, withDenom, fmt, mode, decimal))
.join(', ');
},
calculateBondedRatio(
pool: { bonded_tokens: string; not_bonded_tokens: string } | undefined
@ -331,30 +338,20 @@ export const useFormatter = defineStore('formatter', {
const percent = Number(input) / Number(total);
return numeral(percent > 0.0001 ? percent : 0).format('0.[00]%');
},
formatDecimalToPercent(decimal: string) {
formatDecimalToPercent(decimal: string, divideDecimal?: number) {
if (!decimal) return '-';
return this.percent(decimal);
return this.percent(decimal, divideDecimal);
},
formatCommissionRate(rate?: string) {
formatCommissionRate(rate?: string, divideDecimal?: number) {
if (!rate) return '-';
return this.percent(rate);
return this.percent(rate, divideDecimal);
},
toDecimal(decimal?: string | number) {
if (!decimal) return;
percent(decimal?: string | number, divideDecimal?: number) {
let decimalFormat = numeral(decimal);
const decimalValue = decimalFormat.value();
if (decimalValue && decimalValue > 1e6) {
decimalFormat = decimalFormat.divide('1000000000000000000');
}
return decimalFormat;
},
percent(decimal?: string | number) {
const decimalFormat = this.toDecimal(decimal);
if (!decimalFormat) return '-';
if (divideDecimal) {
decimalFormat = decimalFormat.divide(divideDecimal);
}
return decimalFormat.format('0.[00]%');
},
formatNumber(input?: number, fmt = '0.[00]') {

View File

@ -1,6 +1,7 @@
import { fromBase64, toBase64 } from '@cosmjs/encoding';
import { longify } from '@cosmjs/stargate/build/queryclient';
import { PageRequest as CosmosPageRequest } from 'cosmjs-types/cosmos/base/query/v1beta1/pagination';
import type { Coin } from 'cosmjs-types/cosmos/base/v1beta1/coin';
export interface Key {
'@type': string;
@ -79,11 +80,6 @@ export class Response<T> {
[key: string]: T;
}
export interface Coin {
amount: string;
denom: string;
}
export interface CoinWithPrice extends Coin {
value?: number;
price?: number;

View File

@ -1,4 +1,5 @@
import type { Key, PaginatedResponse, Coin } from './common';
import type { Coin } from 'cosmjs-types/cosmos/base/v1beta1/coin';
import type { Key, PaginatedResponse } from './common';
export interface Validator {
operator_address: string;