Skip to content

Commit

Permalink
Hot Fixes #2 for the Bridge (#1198)
Browse files Browse the repository at this point in the history
  • Loading branch information
AtelyPham authored May 11, 2023
1 parent 89f54d2 commit 538fd88
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ export const TransferContainer = forwardRef<
const balancesFromNotes = useBalancesFromNotes(destChain);

// State for amount input value
const [amount, setAmount] = useState<number | undefined>(undefined);
const [transferAmount, setTransferAmount] = useState<number | undefined>(
undefined
);

// State for error message when user input amount is invalid
const [amountError, setAmountError] = useState<string>('');
Expand Down Expand Up @@ -418,7 +420,7 @@ export const TransferContainer = forwardRef<
return;
}

setAmount(parsedAmount);
setTransferAmount(parsedAmount);
setAmountError('');
},
[selectedBridgingAsset?.balance]
Expand Down Expand Up @@ -483,35 +485,35 @@ export const TransferContainer = forwardRef<
// Boolean indicating whether the amount value is valid or not
const isValidAmount = useMemo(() => {
return (
typeof amount === 'number' &&
amount > 0 &&
amount <= (selectedBridgingAsset?.balance ?? 0)
typeof transferAmount === 'number' &&
transferAmount > 0 &&
transferAmount <= (selectedBridgingAsset?.balance ?? 0)
);
}, [amount, selectedBridgingAsset?.balance]);
}, [transferAmount, selectedBridgingAsset?.balance]);

// The actual amount to be transferred
const receivingAmount = useMemo(() => {
// If no relayer selected, return the amount
if (!activeRelayer) {
return amount;
return transferAmount;
}

if (!feeInWei || !amount) {
return amount;
if (!feeInWei || !transferAmount) {
return transferAmount;
}

// If relayer selected, return the amount minus the relayer fee
const fee = Number(ethers.utils.formatEther(feeInWei));
return amount - fee;
}, [activeRelayer, amount, feeInWei]);
return transferAmount - fee;
}, [activeRelayer, transferAmount, feeInWei]);

// Boolean indicating whether inputs are valid to transfer
const isValidToTransfer = useMemo<boolean>(() => {
const totalFee = Number(
ethers.utils.formatEther(feeInWei ?? ethers.constants.Zero)
);

const amountOrZero = amount ?? 0;
const amountOrZero = transferAmount ?? 0;

return [
Boolean(fungibleCurrency), // No fungible currency selected
Expand All @@ -531,7 +533,7 @@ export const TransferContainer = forwardRef<
recipientPubKey,
isValidRecipient,
activeRelayer,
amount,
transferAmount,
]);

// All available notes
Expand Down Expand Up @@ -578,15 +580,15 @@ export const TransferContainer = forwardRef<
NoteManager.getNotesFifo(
availableNotes,
ethers.utils.parseUnits(
amount?.toString() ?? '0',
transferAmount?.toString() ?? '0',
fungibleCurrency.view.decimals
)
) ?? []
);
}, [amount, availableNotes, fungibleCurrency]);
}, [transferAmount, availableNotes, fungibleCurrency]);

// Calculate the info for UI display
const infoCalculated = useMemo(() => {
const infoFormatted = useMemo(() => {
const spentValue = inputNotes.reduce<ethers.BigNumber>(
(acc, note) => acc.add(ethers.BigNumber.from(note.note.amount)),
ethers.BigNumber.from(0)
Expand All @@ -595,13 +597,13 @@ export const TransferContainer = forwardRef<
const changeAmountBigNumber = fungibleCurrency
? spentValue.sub(
ethers.utils.parseUnits(
amount?.toString() ?? '0',
transferAmount?.toString() ?? '0',
fungibleCurrency.view.decimals
)
)
: ethers.BigNumber.from(0);

const transferAmount = isValidAmount
const formattedTransferAmount = isValidAmount
? getRoundedAmountString(receivingAmount)
: undefined;

Expand All @@ -618,7 +620,7 @@ export const TransferContainer = forwardRef<
: undefined;

return {
transferAmount,
transferAmount: formattedTransferAmount,
changeAmount,
transferTokenSymbol: selectedBridgingAsset?.symbol ?? '',
rawChangeAmount: fungibleCurrency
Expand All @@ -629,7 +631,7 @@ export const TransferContainer = forwardRef<
: 0,
};
}, [
amount,
transferAmount,
fungibleCurrency,
inputNotes,
isValidAmount,
Expand All @@ -644,11 +646,11 @@ export const TransferContainer = forwardRef<
return currentNativeCurrency?.symbol ?? '';
}

return infoCalculated?.transferTokenSymbol ?? '';
return infoFormatted?.transferTokenSymbol ?? '';
}, [
activeRelayer,
currentNativeCurrency?.symbol,
infoCalculated?.transferTokenSymbol,
infoFormatted?.transferTokenSymbol,
]);

const handleSwitchChain = useCallback(
Expand Down Expand Up @@ -688,7 +690,7 @@ export const TransferContainer = forwardRef<
setAmountError('');
setRecipientPubKey('');
setIsValidRecipient(false);
setAmount(undefined);
setTransferAmount(undefined);
setRelayer(null);
resetMaxFeeInfo();
}, [resetMaxFeeInfo, setRelayer]);
Expand Down Expand Up @@ -720,7 +722,12 @@ export const TransferContainer = forwardRef<
throw new Error('No note manager or active bridge');
}

if (!fungibleCurrency || !destChain || !amount || !currentTypedChainId) {
if (
!fungibleCurrency ||
!destChain ||
!transferAmount ||
!currentTypedChainId
) {
throw new Error(
"Can't transfer without a fungible currency or dest chain"
);
Expand All @@ -735,11 +742,11 @@ export const TransferContainer = forwardRef<
return;
}

const changeAmount = infoCalculated.rawChangeAmount;
const changeAmount = infoFormatted.rawChangeAmount;
const fungibleCurrencyDecimals = fungibleCurrency.getDecimals();

const amountBigNumber = ethers.utils.parseUnits(
amount.toString(),
const transferAmountBN = ethers.utils.parseUnits(
transferAmount.toString(),
fungibleCurrencyDecimals
);

Expand All @@ -761,8 +768,8 @@ export const TransferContainer = forwardRef<
const fee = feeInWei ?? BigNumber.from(0);

const utxoAmount = activeRelayer
? amountBigNumber.sub(fee)
: amountBigNumber;
? transferAmountBN.sub(fee)
: transferAmountBN;

const transferUtxo = await activeApi.generateUtxo({
curve: noteManager.defaultNoteGenInput.curve,
Expand Down Expand Up @@ -840,11 +847,11 @@ export const TransferContainer = forwardRef<
api,
fungibleCurrency,
destChain,
amount,
transferAmount,
currentTypedChainId,
inputNotes,
activeChain?.chainId,
infoCalculated.rawChangeAmount,
infoFormatted.rawChangeAmount,
recipientPubKey,
feeInWei,
activeRelayer,
Expand Down Expand Up @@ -897,7 +904,7 @@ export const TransferContainer = forwardRef<
return;
}

if (!fungibleCurrency || !amount) {
if (!fungibleCurrency || !transferAmount) {
setEducationCardStep(2);
return;
}
Expand All @@ -912,7 +919,7 @@ export const TransferContainer = forwardRef<
destChain,
setEducationCardStep,
fungibleCurrency,
amount,
transferAmount,
recipientPubKey,
]);

Expand All @@ -921,11 +928,11 @@ export const TransferContainer = forwardRef<
return false;
}

if (!amount || !isValidAmount) {
if (!transferAmount || !isValidAmount) {
return false;
}

if (balancesFromNotes[fungibleCurrency.id] < amount) {
if (balancesFromNotes[fungibleCurrency.id] < transferAmount) {
return false;
}

Expand All @@ -950,7 +957,7 @@ export const TransferContainer = forwardRef<
return true;
}, [
activeChain,
amount,
transferAmount,
balancesFromNotes,
destChain,
fungibleCurrency,
Expand Down Expand Up @@ -988,13 +995,20 @@ export const TransferContainer = forwardRef<

const amountInputProps = useMemo(() => {
return {
amount: amount ? amount.toString() : undefined,
amount: transferAmount ? transferAmount.toString() : undefined,
onAmountChange,
errorMessage: amountError,
isDisabled: !selectedBridgingAsset || !destChain,
onMaxBtnClick: () => setAmount(selectedBridgingAsset?.balance ?? 0),
onMaxBtnClick: () =>
setTransferAmount(selectedBridgingAsset?.balance ?? 0),
};
}, [amount, amountError, destChain, onAmountChange, selectedBridgingAsset]);
}, [
transferAmount,
amountError,
destChain,
onAmountChange,
selectedBridgingAsset,
]);

const relayerInputProps = useMemo(() => {
return {
Expand Down Expand Up @@ -1054,10 +1068,10 @@ export const TransferContainer = forwardRef<
return acc + formated;
}, 0);

const { transferAmount, transferTokenSymbol } = infoCalculated;
const { transferTokenSymbol } = infoFormatted;

const formatedRemainingBalance = getRoundedAmountString(
total - (amount ?? 0),
total - (transferAmount ?? 0),
3,
Math.round
);
Expand All @@ -1068,16 +1082,16 @@ export const TransferContainer = forwardRef<
title: 'Receiving',
info: 'Receiving',
},
rightContent: transferAmount
? `${transferAmount} ${transferTokenSymbol}`
rightContent: infoFormatted.transferAmount
? `${infoFormatted.transferAmount} ${transferTokenSymbol}`
: '--',
},
{
leftTextProps: {
title: 'Remaining balance',
info: 'Remaining balance',
},
rightContent: amount
rightContent: transferAmount
? `${formatedRemainingBalance} ${transferTokenSymbol}`
: '--',
},
Expand All @@ -1088,25 +1102,30 @@ export const TransferContainer = forwardRef<
rightContent: maxFeeText,
},
];
}, [amount, availableNotes, infoCalculated, maxFeeText]);
}, [transferAmount, availableNotes, infoFormatted, maxFeeText]);

// Transfer button props
const buttonDesc = useMemo(() => {
if (!feeInWei || !amount) {
if (!feeInWei || !transferAmount) {
return;
}

const totalFee = Number(ethers.utils.formatEther(feeInWei));
const formattedFee = getRoundedAmountString(totalFee, 3, Math.round);
const tkSymbol = infoCalculated?.transferTokenSymbol ?? '';
const tkSymbol = infoFormatted?.transferTokenSymbol ?? '';
const feeText = `${formattedFee} ${tkSymbol}`.trim();

if (activeRelayer && amount < totalFee) {
if (activeRelayer && transferAmount < totalFee) {
return `Insufficient funds. You need more than ${feeText} to cover the fee`;
}

return;
}, [activeRelayer, amount, feeInWei, infoCalculated?.transferTokenSymbol]);
}, [
activeRelayer,
transferAmount,
feeInWei,
infoFormatted?.transferTokenSymbol,
]);

const isDisabled = useMemo(() => {
return isWalletConnected && hasNoteAccount && isValidToTransfer;
Expand Down
2 changes: 2 additions & 0 deletions apps/bridge-dapp/src/containers/WithdrawContainer/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Currency } from '@webb-tools/abstract-api-provider';
import { CurrencyConfig } from '@webb-tools/dapp-config';
import { Note, Utxo } from '@webb-tools/sdk-core';
import { TitleWithInfo } from '@webb-tools/webb-ui-components';
import { TokenType } from '@webb-tools/webb-ui-components/components/BridgeInputs/types';
import { PropsOf } from '@webb-tools/webb-ui-components/types';
import { BigNumber } from 'ethers';
import { ComponentProps } from 'react';
import { BridgeTabContainerProps } from '../types';

export interface WithdrawContainerProps
Expand Down
5 changes: 4 additions & 1 deletion libs/web3-api-provider/src/webb-provider/vanchor-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,15 @@ export class Web3VAnchorActions extends VAnchorActions<WebbWeb3Provider> {
const relayer =
this.inner.relayerManager.activeRelayer?.beneficiary ?? ZERO_ADDRESS;

// If no relayer is set, then the fee is 0, otherwise it is the fee amount
const feeVal = relayer === ZERO_ADDRESS ? BigNumber.from(0) : feeAmount;

return Promise.resolve([
tx, // tx
notes[0].note.targetIdentifyingData, // contractAddress
inputUtxos, // inputs
[changeUtxo], // outputs
feeAmount, // fee
feeVal, // fee
refundAmount, // refund
recipient, // recipient
relayer, // relayer
Expand Down

0 comments on commit 538fd88

Please sign in to comment.