mirror of
https://github.com/cosmos/cosmjs.git
synced 2025-03-10 21:49:15 +00:00
Implement Amount debugging using Decimal class
This commit is contained in:
parent
55700b2157
commit
d52f69afff
@ -1,38 +1,18 @@
|
||||
import { Account, Amount } from "@iov/bcp";
|
||||
import { Decimal } from "@iov/encoding";
|
||||
import { MultiChainSigner } from "@iov/multichain";
|
||||
|
||||
import { SendJob } from "./types";
|
||||
|
||||
export function amountToNumber(amount: Amount): number {
|
||||
const { quantity, fractionalDigits } = amount;
|
||||
if (!quantity.match(/^[0-9]+$/)) {
|
||||
throw new Error(`quantity must be a number, got ${quantity}`);
|
||||
}
|
||||
if (fractionalDigits < 0) {
|
||||
throw new Error(`invalid fractional digits: ${fractionalDigits}`);
|
||||
}
|
||||
// let's remove those leading zeros...
|
||||
const temp = quantity.replace(/^0+/, "");
|
||||
// unless we need them to reach a decimal point
|
||||
const pad = fractionalDigits - temp.length;
|
||||
const trimmed = pad > 0 ? "0".repeat(pad) + temp : temp;
|
||||
|
||||
const cut = trimmed.length - fractionalDigits;
|
||||
const whole = cut === 0 ? "0" : trimmed.slice(0, cut);
|
||||
const decimal = fractionalDigits === 0 ? "" : `.${trimmed.slice(cut)}`;
|
||||
const value = `${whole}${decimal}`;
|
||||
|
||||
return Number(value);
|
||||
}
|
||||
|
||||
/** A string representation of a coin in a human-readable format that can change at any time */
|
||||
export function debugCoin(coin: Amount): string {
|
||||
return `${amountToNumber(coin)} ${coin.tokenTicker}`;
|
||||
function debugAmount(amount: Amount): string {
|
||||
const value = Decimal.fromAtomics(amount.quantity, amount.fractionalDigits).toString();
|
||||
return `${value} ${amount.tokenTicker}`;
|
||||
}
|
||||
|
||||
/** A string representation of a balance in a human-readable format that can change at any time */
|
||||
export function debugBalance(data: ReadonlyArray<Amount>): string {
|
||||
return `[${data.map(debugCoin).join(", ")}]`;
|
||||
return `[${data.map(debugAmount).join(", ")}]`;
|
||||
}
|
||||
|
||||
/** A string representation of an account in a human-readable format that can change at any time */
|
||||
@ -53,6 +33,6 @@ export function logAccountsState(accounts: ReadonlyArray<Account>): void {
|
||||
export function logSendJob(signer: MultiChainSigner, job: SendJob): void {
|
||||
const from = signer.identityToAddress(job.sender);
|
||||
const to = job.recipient;
|
||||
const amount = debugCoin(job.amount);
|
||||
const amount = debugAmount(job.amount);
|
||||
console.info(`Sending ${amount} from ${from} to ${to} ...`);
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user