@daimo/pay
Version:
Seamless crypto payments. Onboard users from any chain, any coin into your app with one click.
84 lines (81 loc) • 2.85 kB
JavaScript
import { formatUnits } from 'viem';
const USD_DECIMALS = 2;
/**
* Round a number to a given number of decimal places
*
* @param round - The rounding strategy to use:
* - "up": Always rounds up to the next decimal place (ceiling)
* - "down": Always rounds down to the previous decimal place (floor)
* - "nearest": Rounds to the nearest decimal place (standard rounding)
*/
function roundDecimals(value, decimals, round) {
const factor = 10 ** decimals;
const multiplied = value * factor;
let rounded;
if (round === "up") {
rounded = Math.ceil(multiplied);
}
else if (round === "down") {
rounded = Math.floor(multiplied);
}
else {
rounded = Math.round(multiplied);
}
return (rounded / factor).toFixed(decimals);
}
/**
* Format a number as a USD amount
*
* @param usd - The USD amount to format
* @param round - The rounding strategy to use ("up", "down", or "nearest")
* @returns The formatted USD amount
*/
function formatUsd(usd, round = "down") {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(Number(roundUsd(usd, round)));
}
/**
* Round a USD amount to `USD_DECIMALS` precision
*/
function roundUsd(usd, round = "down") {
return roundDecimals(usd, USD_DECIMALS, round);
}
/**
* Round a token amount to `displayDecimals` precision
*/
function roundTokenAmount(amount, token, round = "down") {
return roundDecimals(Number(formatUnits(BigInt(amount), token.decimals)), token.displayDecimals, round);
}
/**
* Round a token amount in units to `displayDecimals` precision
*/
function roundTokenAmountUnits(amountUnits, token, round = "down") {
return roundDecimals(amountUnits, token.displayDecimals, round);
}
/**
* Convert a USD amount to a token amount with `displayDecimals` precision
*
* @param usd - The USD amount to convert
* @param token - The token to convert to
* @param round - The rounding strategy to use ("up", "down", or "nearest")
* @returns The token amount
*/
function usdToRoundedTokenAmount(usd, token, round = "down") {
return roundTokenAmountUnits(usd / token.usd, token, round);
}
/**
* Convert a token amount to a USD amount with `USD_DECIMALS` precision
*
* @param amount - The token amount to convert
* @param token - The token to convert from
* @param round - The rounding strategy to use ("up", "down", or "nearest")
* @returns The formatted USD amount
*/
function tokenAmountToRoundedUsd(amount, token, round = "nearest") {
const amountUnits = formatUnits(BigInt(amount), token.decimals);
return roundUsd(Number(amountUnits) * token.usd, round);
}
export { USD_DECIMALS, formatUsd, roundDecimals, roundTokenAmount, roundTokenAmountUnits, roundUsd, tokenAmountToRoundedUsd, usdToRoundedTokenAmount };
//# sourceMappingURL=format.js.map