Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions src/components/TradingWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ function applySlippage(amount: bigint, isBuy: boolean): bigint {

const isZapAvailable = ZAP_PLOTLINK !== "0x0000000000000000000000000000000000000000";

/** Format a raw bigint token amount for display with appropriate precision. */
function formatTokenAmount(value: bigint, decimals: number): string {
const num = Number(formatUnits(value, decimals));
if (num === 0) return "0";
if (num >= 1) {
return num.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
if (num >= 0.001) {
return num.toFixed(4);
}
if (num >= 0.000001) {
return num.toFixed(6);
}
return num.toExponential(2);
}

/** Retry a writeContractAsync call once if it fails with a nonce error. */
async function retryOnNonceError<T>(fn: () => Promise<T>): Promise<T> {
try {
Expand Down Expand Up @@ -499,7 +515,7 @@ export function TradingWidget({ tokenAddress }: { tokenAddress: Address }) {
</div>
{balance !== undefined && (
<p className="text-muted mt-1 text-[10px]">
Balance: {formatUnits(balance, balanceDecimals)} {balanceLabel}
Balance: {formatTokenAmount(balance, balanceDecimals)} {balanceLabel}
</p>
)}
{insufficientBalance && (
Expand Down Expand Up @@ -548,7 +564,7 @@ export function TradingWidget({ tokenAddress }: { tokenAddress: Address }) {
{/* Balance for sell tab and non-zap buy (PLOT direct) */}
{(tab === "sell" || !isZapAvailable) && balance !== undefined && (
<p className="text-muted mt-1 text-[10px]">
Balance: {formatUnits(balance, balanceDecimals)} {balanceLabel}
Balance: {formatTokenAmount(balance, balanceDecimals)} {balanceLabel}
</p>
)}
{(tab === "sell" || !isZapAvailable) && insufficientBalance && (
Expand All @@ -561,7 +577,7 @@ export function TradingWidget({ tokenAddress }: { tokenAddress: Address }) {
<div className="text-muted mt-2 text-xs">
Est. cost:{" "}
<span className="font-semibold text-accent">
{formatUnits(zapQuote.fromTokenAmount, estimateDecimals)} {payToken}
{formatTokenAmount(zapQuote.fromTokenAmount, estimateDecimals)} {payToken}
</span>
<span className="ml-2">(incl. 3% slippage)</span>
</div>
Expand All @@ -570,7 +586,7 @@ export function TradingWidget({ tokenAddress }: { tokenAddress: Address }) {
<div className="text-muted mt-2 text-xs">
{tab === "buy" ? "Max cost" : "Min return"}:{" "}
<span className="font-semibold text-accent">
{formatUnits(applySlippage(estimate, tab === "buy"), 18)} {RESERVE_LABEL}
{formatTokenAmount(applySlippage(estimate, tab === "buy"), 18)} {RESERVE_LABEL}
</span>
<span className="ml-2">(incl. 3% slippage)</span>
</div>
Expand Down
Loading