Skip to content

Commit

Permalink
fix: improve data consistency and parsing (amounts)
Browse files Browse the repository at this point in the history
  • Loading branch information
ps1dr3x committed Aug 17, 2023
1 parent 5b50dee commit 572d144
Show file tree
Hide file tree
Showing 16 changed files with 56 additions and 80 deletions.
11 changes: 3 additions & 8 deletions src/core/getSingleBalance.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
getSplitFromLoggedUser,
displayableAmount,
displayableAmountBI,
} from "../helpers";
import { getSplitFromLoggedUser, formatAmount } from "../helpers";
import { IBalanceDetailed } from "../typing";
import { getEscrowData } from "./getEscrowData";

Expand All @@ -26,9 +22,8 @@ export const getSingleBalance = async (
decimals: escrowData.token.decimals,
},
status: escrowData.status,
amount: amount.toString(),
amountBI: displayableAmountBI(amount, escrowData.token.decimals),
displayableAmount: displayableAmount(amount, escrowData.token.decimals),
solidityAmount: amount,
displayableAmount: formatAmount(amount, escrowData.token.decimals),
connectedUser: escrowData.connectedUser,
walletAddress: escrowData.walletAddress,
};
Expand Down
4 changes: 2 additions & 2 deletions src/helpers/__tests__/validPayment.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const params: IValidateProps = {
buyer: "0x484Ee4Eb8CB165F4FBFd897f84283142C8f1fD3a",
arbitrator: "0x7bD733DBc10A1cD04e1e51cC89450941c928ee62",
marketplace: "0x7bD733DBc10A1cD04e1e51cC89450941c928ee62",
amount: 1n,
amount: "1",
challengePeriod: 1,
challengePeriodExtension: 1,
arbitratorFee: 1,
Expand Down Expand Up @@ -67,7 +67,7 @@ describe("Valid payments function", () => {
await expect(async () =>
validateParameters({
...params,
amount: 0n,
amount: "0",
}),
).rejects.toThrow(/Invalid amount/);
});
Expand Down
19 changes: 0 additions & 19 deletions src/helpers/displayAmount.ts

This file was deleted.

24 changes: 18 additions & 6 deletions src/helpers/formatAmount.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,27 @@
import { displayableAmountBI } from "./displayAmount";
import { ethers } from "ethers";

export const formatAmount = (
amount: string | number | bigint,
precision: number,
amount: bigint,
precision: number | bigint,
): string => {
try {
const uxAmount = displayableAmountBI(BigInt(amount), precision);
return uxAmount.toString();
return ethers.formatUnits(amount, precision);
} catch (error) {
throw new Error(
`Invalid amount: '${amount}'. It should be a valid number.`,
`Invalid amount: '${amount}'. It should be a valid bigint.`,
);
}
};

export const parseAmount = (
amount: string,
precision: number | bigint,
): bigint => {
try {
return ethers.parseUnits(amount, precision);
} catch (error) {
throw new Error(
`Invalid amount: '${amount}'. It should be a valid string.`,
);
}
};
3 changes: 1 addition & 2 deletions src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
export { countdownChallengePeriod } from "./countdownChallengePeriod";
export { isValidAddress } from "./isValidAddress";
export { displayChallengePeriod } from "./displayChallengePeriod";
export { displayableAmount, displayableAmountBI } from "./displayAmount";
export { formatAmountToUSD } from "./formatAmountToUSD";
export { percentageToBips } from "./percentageToBips";
export { bipsToPercentage } from "./bipsToPercentage";
Expand All @@ -19,4 +18,4 @@ export { validateAddress } from "./validateAddress";
export { validateParameters } from "./validateParameters";
export { getSplitFromLoggedUser } from "./calculateSplit";
export { tag } from "./tag";
export { formatAmount } from "./formatAmount";
export { formatAmount, parseAmount } from "./formatAmount";
2 changes: 1 addition & 1 deletion src/helpers/validateParameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const validateParameters = async (data: IValidateProps) => {
}

try {
const _amount = BigInt(amount);
const _amount = parseFloat(amount);
if (_amount <= 0) {
throw new Error(`Invalid amount (${amount}<=0)`);
}
Expand Down
19 changes: 6 additions & 13 deletions src/indexer/internal/getUserBalance.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
calculateSplit,
groupBy,
displayableAmount,
displayableAmountBI,
} from "../../helpers";
import { calculateSplit, groupBy, formatAmount } from "../../helpers";
import { GraphQLClient } from "graphql-request";
import { getTokenInfo } from "../../core";
import {
Expand All @@ -27,31 +22,29 @@ const fetchTokenInfo = async (balances: IBalance[]) => {
};

const prepareResponseData = (balance: any, tokens: IToken[]) => {
const _amount = BigInt(balance.amount);
const tokenInfo = tokens.find((t) => t.address === balance.token.address);

return {
...balance,
token: { ...tokenInfo },
total: _amount,
displayableAmount: displayableAmount(_amount, tokenInfo.decimals),
amountBI: displayableAmountBI(_amount, tokenInfo.decimals),
solidityAmount: balance.solidityAmount,
displayableAmount: formatAmount(balance.solidityAmount, tokenInfo.decimals),
};
};

const mapData = (_group, status: IEscrowStatus, walletUserAddress: string) =>
Object.keys(_group)
.map((key) => {
const total = calculateSplit(_group[key], walletUserAddress);
const amount = calculateSplit(_group[key], walletUserAddress);
return {
amount: total.toString(),
solidityAmount: amount,
token: {
address: key,
},
status,
};
})
.filter((item: any) => BigInt(item.amount) > 0) as IBalance[];
.filter((item: any) => BigInt(item.solidityAmount) > 0) as IBalance[];

/**
* Read how much balance does the provided account have in the contract
Expand Down
9 changes: 3 additions & 6 deletions src/typing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export interface IToken {
*/
export interface IPaymentProps {
/** Amount in token */
amount: bigint;
amount: string;
/** Whom is the payment for */
seller: string;
/** Initial challenge period (in seconds) */
Expand Down Expand Up @@ -882,7 +882,7 @@ export type tConnectedUser =
*/
export interface IBalance {
/** Amount in ETH's or token's WEI */
amount: string;
solidityAmount: bigint;

/** Amount converted to USD (using Coingecko's API on the client side) */
amountInUSD?: string;
Expand All @@ -899,10 +899,7 @@ export interface IBalance {
*/
export interface IBalanceDetailed extends IBalance {
/** Amount converted to human readable form */
displayableAmount: string | bigint;

/** Helper field used when calculating with other bigint fields */
amountBI: number;
displayableAmount: string;

/** User's role in the escrow ('buyer' | 'seller' | 'arbitrator' | 'marketplace' | 'other') */
connectedUser: tConnectedUser;
Expand Down
4 changes: 2 additions & 2 deletions src/ui/internal/components/Amount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const Style = styled.div`

// TODO pass the entire tokenInfo instead of each prop
export interface IAmountProps {
amount: bigint;
amount: string;
tokenSymbol: string;
tokenAddress?: string; // todo remove this prop
status?: string;
Expand All @@ -54,7 +54,7 @@ export const Amount = ({
return (
<Style>
<div>
<strong>{formatAmount(amount, precision || 18)}</strong>
<strong>{amount}</strong>
{tokenSymbol && <span>{tokenSymbol}</span>}

{
Expand Down
7 changes: 4 additions & 3 deletions src/ui/internal/components/BalancesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const TableRow = (
const isStableCoin = STABLE_COINS.includes(balance?.token?.symbol);

const [formattedAmountInUSD, setFormattedAmountInUSD] =
React.useState<string>(isStableCoin && balance.amountBI.toFixed(2));
React.useState<string>(balance.displayableAmount);

const { data: exchangeValues, error: errorExchange } = useExchangeRates(
balance?.token?.symbol,
Expand All @@ -84,7 +84,7 @@ const TableRow = (

if (exchangeValue) {
setFormattedAmountInUSD(
formatAmountToUSD(balance.amountBI, exchangeValue),
formatAmountToUSD(balance.displayableAmount, exchangeValue),
);
}
}
Expand All @@ -105,7 +105,8 @@ const TableRow = (
{balance.token.symbol && (
<>
<td>
{balance.amountBI} <TokenSymbol>{balance.token.symbol}</TokenSymbol>
{balance.displayableAmount}{" "}
<TokenSymbol>{balance.token.symbol}</TokenSymbol>
</td>
<td>
<ExchangeCell>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { IToken } from "../../../typing";
import { displayableAmountBI } from "../../../helpers";
import { formatAmount } from "../../../helpers";
import { calculatePercentageInt } from "../../../core/calculateAmounts";
import React from "react";

Expand All @@ -20,10 +20,10 @@ export const FormattedPercentageAmountAdornment = ({
return null;
}

const value = displayableAmountBI(
const value = formatAmount(
calculatePercentageInt(_percentage, amount),
tokenInfo.decimals,
).toFixed(2);
);

return (
<div style={{ whiteSpace: "nowrap" }}>
Expand Down
9 changes: 4 additions & 5 deletions src/ui/internal/modals/ApproveSettlement.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
DataDisplayer,
} from "../components/DataDisplayer";
import { renderModal } from "../config/render";
import { displayableAmount, BUYER, SELLER } from "../../../helpers";
import { formatAmount, BUYER, SELLER } from "../../../helpers";
import { SettlementOfferModal } from "./SettlementOffer";

import { MARKER } from "../../../config/marker";
Expand Down Expand Up @@ -83,12 +83,12 @@ export function ApproveSettlementModal(props: ISettlementApproveModalProps) {
escrowData.amount,
);

const _amountBuyerDisplayable = displayableAmount(
const _amountBuyerDisplayable = formatAmount(
_amountBuyer,
escrowData.token.decimals,
);

const _sellerBuyerDisplayable = displayableAmount(
const _sellerBuyerDisplayable = formatAmount(
_amountSeller,
escrowData.token.decimals,
);
Expand All @@ -99,7 +99,6 @@ export function ApproveSettlementModal(props: ISettlementApproveModalProps) {
symbol: escrowData.token.symbol,
percentage: escrowData.settlement.latestSettlementOfferBuyer,
},

seller: {
amount: _sellerBuyerDisplayable,
symbol: escrowData.token.symbol,
Expand Down Expand Up @@ -213,7 +212,7 @@ export function ApproveSettlementModal(props: ISettlementApproveModalProps) {
return (
<>
<Amount
amount={escrowData.amount}
amount={formatAmount(escrowData.amount, escrowData.token.decimals)}
precision={escrowData.token.decimals}
tokenSymbol={
escrowData.token?.symbol ? escrowData.token.symbol : "..."
Expand Down
4 changes: 2 additions & 2 deletions src/ui/internal/modals/Challenge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { useModalStates } from "../../../ui/internal/hooks/useModalStates";
import {
addressWithYou,
reduceAddress,
displayableAmount,
formatAmount,
BUYER,
SELLER,
displayChallengePeriod,
Expand Down Expand Up @@ -142,7 +142,7 @@ export function ChallengeModal(props: IChallengeModalProps) {
return (
<>
<Amount
amount={escrowData.amount}
amount={formatAmount(escrowData.amount, escrowData.token.decimals)}
precision={escrowData.token.decimals}
tokenSymbol={escrowData.token.symbol}
status={paymentStatus}
Expand Down
7 changes: 3 additions & 4 deletions src/ui/internal/modals/Pay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,9 @@ export function PayModal(props: IPaymentModalProps) {
let buttonOnClick;

if (!(error || success)) {
buttonChildren = `Pay ${formatAmount(
props.paymentProps.amount,
tokenInfo?.decimals || 18,
)} ${tokenInfo ? tokenInfo.symbol : "ETH"}`;
buttonChildren = `Pay ${props.paymentProps.amount} ${
tokenInfo ? tokenInfo.symbol : "ETH"
}`;
buttonOnClick = onPayClick;
} else if (success) {
buttonChildren = "Close";
Expand Down
4 changes: 2 additions & 2 deletions src/ui/internal/modals/Refund.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from "../../../ui/internal/components";
import {
reduceAddress,
displayableAmount,
formatAmount,
SELLER,
addressWithYou,
} from "../../../helpers";
Expand Down Expand Up @@ -129,7 +129,7 @@ export function RefundModal(props: IRefundModalProps) {
return (
<>
<Amount
amount={escrowData.amount}
amount={formatAmount(escrowData.amount, escrowData.token.decimals)}
precision={escrowData.token.decimals}
tokenSymbol={escrowData.token.symbol}
status={paymentStatus}
Expand Down
4 changes: 2 additions & 2 deletions src/ui/internal/modals/Release.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { useModalStates } from "../../../ui/internal/hooks/useModalStates";
import { toast } from "../notification/toast";
import { release } from "../../../core/release";
import { MARKER } from "../../../config/marker";
import { addressWithYou, reduceAddress, displayableAmount } from "helpers";
import { addressWithYou, reduceAddress, formatAmount } from "helpers";
import { useCountdownChallengePeriod } from "../hooks/useCountdownChallengePeriod";
import { ModalAction } from "../components/Modal";
import { useModalCloseHandler } from "../hooks/useModalCloseHandler";
Expand Down Expand Up @@ -126,7 +126,7 @@ export function ReleaseModal(props: IReleaseModalProps) {
return (
<>
<Amount
amount={escrowData.amount}
amount={formatAmount(escrowData.amount, escrowData.token.decimals)}
precision={escrowData.token.decimals}
tokenSymbol={escrowData.token.symbol}
status={paymentStatus}
Expand Down

0 comments on commit 572d144

Please sign in to comment.