From d52f69afffdd5885c9b18b23c81336914e4fa05a Mon Sep 17 00:00:00 2001 From: Simon Warta Date: Thu, 30 Jan 2020 08:43:08 +0100 Subject: [PATCH] Implement Amount debugging using Decimal class --- packages/faucet/src/debugging.ts | 32 ++++++-------------------------- 1 file changed, 6 insertions(+), 26 deletions(-) diff --git a/packages/faucet/src/debugging.ts b/packages/faucet/src/debugging.ts index 5b5adc09ab..1fb4c9ab17 100644 --- a/packages/faucet/src/debugging.ts +++ b/packages/faucet/src/debugging.ts @@ -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): 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): 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} ...`); }