Skip to content

Commit

Permalink
Fix Small Amount Issue & Calculate Refund Fee Correctly (#1592)
Browse files Browse the repository at this point in the history
  • Loading branch information
AtelyPham authored Sep 5, 2023
1 parent 5683b24 commit f35e3f0
Show file tree
Hide file tree
Showing 9 changed files with 101 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { calculateTypedChainId } from '@webb-tools/sdk-core';
import {
DepositCard,
TokenListCard,
numberToString,
useWebbUI,
} from '@webb-tools/webb-ui-components';
import { TokenType } from '@webb-tools/webb-ui-components/components/BridgeInputs/types';
Expand All @@ -35,6 +36,7 @@ import { DepositConfirmContainerProps, DepositContainerProps } from './types';
import { CurrencyType } from '@webb-tools/dapp-types';
import { useEducationCardStep } from '../../hooks/useEducationCardStep';
import { isTokenAddedToMetamask } from '../../hooks/useAddCurrency';
import { parseUnits } from 'viem';

interface MainComponentPropsVariants {
['source-chain-list-card']: ChainListCardWrapperProps;
Expand Down Expand Up @@ -426,15 +428,17 @@ export const DepositContainer = forwardRef<
return;
}

const decimals = fungibleCurrency.getDecimals();
const amountBI = parseUnits(numberToString(amount), decimals);
const newNote = await noteManager.generateNote(
activeApi.backend,
sourceTypedChainId,
sourceId,
destTypedChainId,
destId,
fungibleCurrency.view.symbol,
fungibleCurrency.getDecimals(),
amount
decimals,
amountBI
);

setIsGeneratingNote(false);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { utxoFromVAnchorNote } from '@webb-tools/abstract-api-provider';
import { useWebContext } from '@webb-tools/api-provider-environment';
import {
ZERO_BIG_INT,
Chain,
CurrencyConfig,
ZERO_BIG_INT,
getNativeCurrencyFromConfig,
} from '@webb-tools/dapp-config';
import { isValidPublicKey } from '@webb-tools/dapp-types';
Expand All @@ -27,6 +27,7 @@ import {
TokenListCard,
TransferCard,
getRoundedAmountString,
numberToString,
useWebbUI,
} from '@webb-tools/webb-ui-components';
import { ChainType as InputChainType } from '@webb-tools/webb-ui-components/components/BridgeInputs/types';
Expand All @@ -36,21 +37,21 @@ import {
RelayerType,
} from '@webb-tools/webb-ui-components/components/ListCard/types';
import { TransferCardProps } from '@webb-tools/webb-ui-components/containers/TransferCard/types';
import { formatEther, parseUnits, formatUnits } from 'viem';
import { forwardRef, useCallback, useEffect, useMemo, useState } from 'react';
import { formatEther, formatUnits, parseUnits } from 'viem';
import { ChainListCardWrapper } from '../../components';
import {
WalletState,
useAddCurrency,
useConnectWallet,
useMaxFeeInfo,
} from '../../hooks';
import { isTokenAddedToMetamask } from '../../hooks/useAddCurrency';
import { useEducationCardStep } from '../../hooks/useEducationCardStep';
import useStatesFromNotes from '../../hooks/useStatesFromNotes';
import { TransferConfirmContainer } from './TransferConfirmContainer';
import { RecipientPublicKeyTooltipContent } from './shared';
import { TransferContainerProps } from './types';
import { isTokenAddedToMetamask } from '../../hooks/useAddCurrency';

export const TransferContainer = forwardRef<
HTMLDivElement,
Expand Down Expand Up @@ -531,7 +532,10 @@ export const TransferContainer = forwardRef<
return undefined;
}

return parseUnits(`${transferAmount}`, fungibleCurrency.view.decimals);
return parseUnits(
numberToString(transferAmount),
fungibleCurrency.view.decimals
);
}, [fungibleCurrency, transferAmount]);

// Calculate input notes for current amount
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
TokenListCard,
WithdrawCard,
getRoundedAmountString,
numberToString,
useWebbUI,
} from '@webb-tools/webb-ui-components';
import {
Expand Down Expand Up @@ -342,11 +343,14 @@ export const WithdrawContainer = forwardRef<
: currentNativeCurrency?.decimals;

if (refundAmount && isRefund) {
const parsedRefundAmount = decimals
? parseUnits(`${refundAmount}`, decimals)
: parseEther(`${refundAmount}`);
const parsedExchangeRate = Number(
formatEther(feeInfoOrBigInt.refundExchangeRate)
);
const refundFee = numberToString(refundAmount * parsedExchangeRate);

feeWei += parsedRefundAmount * feeInfoOrBigInt.refundExchangeRate;
feeWei += decimals
? parseUnits(refundFee, decimals)
: parseEther(refundFee);
}

const feeFormatted = decimals
Expand Down Expand Up @@ -419,9 +423,10 @@ export const WithdrawContainer = forwardRef<
const decimals =
wrappableCurrency?.getDecimals() ?? fungibleCurrency?.getDecimals();

const amountStr = numberToString(amount);
const amountWei = decimals
? parseUnits(`${amount}`, decimals)
: parseEther(`${amount}`);
? parseUnits(amountStr, decimals)
: parseEther(amountStr);

// If no fee or no active relayer, then return the original amount
// as the fee is not deducted from the amount
Expand Down Expand Up @@ -582,7 +587,7 @@ export const WithdrawContainer = forwardRef<
// Get the notes that will be spent for this withdraw
const inputNotes = NoteManager.getNotesFifo(
availableNotesFromManager ?? [],
parseUnits(amount.toString() as `${number}`, fungibleDecimals)
parseUnits(numberToString(amount), fungibleDecimals)
);

if (!inputNotes) {
Expand All @@ -595,8 +600,7 @@ export const WithdrawContainer = forwardRef<
}, BigInt(0));

const changeAmountBI =
sumInputNotes -
parseUnits(amount.toString() as `${number}`, fungibleDecimals);
sumInputNotes - parseUnits(numberToString(amount), fungibleDecimals);

const keypair = noteManager.getKeypair();
if (!keypair.privkey) {
Expand All @@ -620,7 +624,7 @@ export const WithdrawContainer = forwardRef<
destAddress,
fungibleCurrency.view.symbol,
fungibleDecimals,
formattedChangeAmount
changeAmountBI
);
}

Expand Down Expand Up @@ -672,7 +676,7 @@ export const WithdrawContainer = forwardRef<
}
feeInfo={transactionFeeInfo}
receivingInfo={refundInfo}
refundAmount={parseEther(`${refundAmount}`)}
refundAmount={parseEther(numberToString(refundAmount))}
refundToken={currentNativeCurrency?.symbol}
recipient={recipient}
onResetState={handleResetState}
Expand Down
5 changes: 2 additions & 3 deletions apps/bridge-dapp/src/hooks/useShieldedAssets.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Currency } from '@webb-tools/abstract-api-provider';
import { useWebContext } from '@webb-tools/api-provider-environment';
import { chainsPopulated } from '@webb-tools/dapp-config';
import { useCurrencies, useNoteAccount } from '@webb-tools/react-hooks';
import { calculateTypedChainId } from '@webb-tools/sdk-core';
import numberToString from '@webb-tools/webb-ui-components/utils/numberToString';
import React from 'react';

import { formatUnits, parseUnits } from 'viem';
import { ShieldedAssetDataType } from '../containers/note-account-tables/ShieldedAssetsTableContainer/types';

Expand Down Expand Up @@ -49,7 +48,7 @@ export const useShieldedAssets = (): ShieldedAssetDataType[] => {

if (existedChain) {
const parsedAvailableBalance = parseUnits(
`${existedChain.availableBalance}`,
numberToString(existedChain.availableBalance),
denomination
);

Expand Down
2 changes: 1 addition & 1 deletion libs/dapp-config/src/chains/chain-config.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

import { ChainType } from '@webb-tools/sdk-core';
import type { Chain } from '@wagmi/chains';
import type { Chain } from 'viem/chains';

import { AppEnvironment } from '../types';

Expand Down
92 changes: 45 additions & 47 deletions libs/dapp-config/src/chains/evm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
scrollTestnet,
sepolia,
type Chain,
} from '@wagmi/chains';
} from 'viem/chains';
import { EVMChainId, PresetTypedChainId } from '@webb-tools/dapp-types';
import { ChainType } from '@webb-tools/sdk-core/typed-chain-id';
import merge from 'lodash/merge';
Expand Down Expand Up @@ -223,15 +223,15 @@ export const chainsConfig: Record<number, ChainConfig> = {
},
},
env: ['development', 'test'],
contracts: {
multicall3: hostedOrbitMulticall3Address
? {
contracts: hostedOrbitMulticall3Address
? {
multicall3: {
address: `0x${hostedOrbitMulticall3Address.replace(/^0x/, '')}`,
blockCreated: hermesOrbitMulticall3DeploymentBlock,
}
: undefined,
},
},
},
}
: undefined,
} satisfies ChainConfig,

[PresetTypedChainId.AthenaOrbit]: {
chainType: ChainType.EVM,
Expand All @@ -256,15 +256,15 @@ export const chainsConfig: Record<number, ChainConfig> = {
},
},
env: ['development', 'test'],
contracts: {
multicall3: hostedOrbitMulticall3Address
? {
contracts: hostedOrbitMulticall3Address
? {
multicall3: {
address: `0x${hostedOrbitMulticall3Address.replace(/^0x/, '')}`,
blockCreated: athenaOrbitMulticall3DeploymentBlock,
}
: undefined,
},
},
},
}
: undefined,
} satisfies ChainConfig,

[PresetTypedChainId.DemeterOrbit]: {
chainType: ChainType.EVM,
Expand All @@ -289,15 +289,15 @@ export const chainsConfig: Record<number, ChainConfig> = {
},
},
env: ['development', 'test'],
contracts: {
multicall3: hostedOrbitMulticall3Address
? {
contracts: hostedOrbitMulticall3Address
? {
multicall3: {
address: `0x${hostedOrbitMulticall3Address.replace(/^0x/, '')}`,
blockCreated: demeterOrbitMulticall3DeploymentBlock,
}
: undefined,
},
},
},
}
: undefined,
} satisfies ChainConfig,

[PresetTypedChainId.TangleTestnet]: {
chainType: ChainType.EVM,
Expand Down Expand Up @@ -326,10 +326,8 @@ export const chainsConfig: Record<number, ChainConfig> = {
},
},
env: ['development', 'test'],
contracts: {
multicall3: undefined,
},
},
} satisfies ChainConfig,

// Localnet
[PresetTypedChainId.HermesLocalnet]: {
chainType: ChainType.EVM,
Expand All @@ -348,15 +346,15 @@ export const chainsConfig: Record<number, ChainConfig> = {
},
},
env: ['development'],
contracts: {
multicall3: localOrbitMulticall3Address
? {
contracts: localOrbitMulticall3Address
? {
multicall3: {
address: `0x${localOrbitMulticall3Address.replace(/^0x/, '')}`,
blockCreated: localHermesMulticall3DeploymentBlock,
}
: undefined,
},
},
},
}
: undefined,
} satisfies ChainConfig,

[PresetTypedChainId.AthenaLocalnet]: {
chainType: ChainType.EVM,
Expand All @@ -375,15 +373,15 @@ export const chainsConfig: Record<number, ChainConfig> = {
},
},
env: ['development'],
contracts: {
multicall3: localOrbitMulticall3Address
? {
contracts: localOrbitMulticall3Address
? {
multicall3: {
address: `0x${localOrbitMulticall3Address.replace(/^0x/, '')}`,
blockCreated: localAthenaMulticall3DeploymentBlock,
}
: undefined,
},
},
},
}
: undefined,
} satisfies ChainConfig,

[PresetTypedChainId.DemeterLocalnet]: {
chainType: ChainType.EVM,
Expand All @@ -402,13 +400,13 @@ export const chainsConfig: Record<number, ChainConfig> = {
},
},
env: ['development'],
contracts: {
multicall3: localOrbitMulticall3Address
? {
contracts: localOrbitMulticall3Address
? {
multicall3: {
address: `0x${localOrbitMulticall3Address.replace(/^0x/, '')}`,
blockCreated: localDemeterMulticall3DeploymentBlock,
}
: undefined,
},
},
},
}
: undefined,
} satisfies ChainConfig,
};
12 changes: 3 additions & 9 deletions libs/note-manager/src/note-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
resetNoteStorage,
} from '@webb-tools/browser-utils/storage';
import { ZERO_BIG_INT } from '@webb-tools/dapp-config';
import { parseUnits } from 'viem';
import Storage from '@webb-tools/dapp-types/Storage';
import {
CircomUtxo,
Expand All @@ -20,6 +19,7 @@ import {
import { hexToU8a } from '@webb-tools/utils';
import { Backend } from '@webb-tools/wasm-utils';
import { BehaviorSubject } from 'rxjs';
import { parseUnits } from 'viem';

type DefaultNoteGenInput = Pick<
NoteGenInput,
Expand Down Expand Up @@ -349,15 +349,9 @@ export class NoteManager {
destAnchorAddress: string,
tokenSymbol: string,
tokenDecimals: number,
amount: number | bigint
amount: bigint
): Promise<Note> {
let amountStr: string;

if (typeof amount === 'number') {
amountStr = parseUnits(amount.toString(), tokenDecimals).toString();
} else {
amountStr = amount.toString();
}
const amountStr = amount.toString();

const input: UtxoGenInput = {
curve: this.defaultNoteGenInput.curve,
Expand Down
Loading

0 comments on commit f35e3f0

Please sign in to comment.