Skip to content

Commit

Permalink
feat: validate maxTotalBalance (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
CarmitKl authored Mar 28, 2022
1 parent a581252 commit 12295d0
Show file tree
Hide file tree
Showing 9 changed files with 96 additions and 45 deletions.
12 changes: 12 additions & 0 deletions src/api/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ export const maxDeposit = async ({decimals, contract}) => {
}
};

export const maxTotalBalance = async ({decimals, contract}) => {
try {
const maxTotalBalance = await utils.blockchain.ethereum.callContract(
contract,
'maxTotalBalance'
);
return utils.parser.parseFromDecimals(maxTotalBalance, decimals);
} catch (ex) {
return Promise.reject(ex);
}
};

export const initiateWithdraw = async ({recipient, amount, decimals, contract}) => {
try {
return utils.blockchain.starknet.sendTransaction(contract, 'initiate_withdraw', {
Expand Down
4 changes: 2 additions & 2 deletions src/components/Features/Transfer/Transfer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
} from '../../UI';
import {LoadingSize} from '../../UI/Loading/Loading.enums';
import styles from './Transfer.module.scss';
import {INSUFFICIENT_BALANCE_ERROR_MSG, MAX_AMOUNT_ERROR_MSG} from './Transfer.strings';
import {INSUFFICIENT_BALANCE_ERROR_MSG, MAX_DEPOSIT_ERROR_MSG} from './Transfer.strings';

export const Transfer = () => {
const [isL1, swapToL1] = useIsL1();
Expand Down Expand Up @@ -52,7 +52,7 @@ export const Transfer = () => {
setIsButtonDisabled(true);
} else if (isL1 && amount > maxDeposit) {
setHasInputError(true);
setErrorMsg(MAX_AMOUNT_ERROR_MSG(maxDeposit, symbol));
setErrorMsg(MAX_DEPOSIT_ERROR_MSG(maxDeposit, symbol));
setIsButtonDisabled(true);
} else {
setIsButtonDisabled(false);
Expand Down
6 changes: 3 additions & 3 deletions src/components/Features/Transfer/Transfer.strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ export const INSUFFICIENT_BALANCE_ERROR_MSG = utils.getTranslation(
'menus.transfer.insufficient_balance_error_msg'
);

export const MAX_AMOUNT_ERROR_MSG = (maxAmount, symbol) =>
utils.object.evaluate(utils.getTranslation('menus.transfer.max_amount_error_msg'), {
maxAmount,
export const MAX_DEPOSIT_ERROR_MSG = (maxDeposit, symbol) =>
utils.object.evaluate(utils.getTranslation('menus.transfer.max_deposit_error_msg'), {
maxDeposit,
symbol
});
7 changes: 5 additions & 2 deletions src/config/strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const strings = {
to_txt: 'to',
from_txt: 'from',
insufficient_balance_error_msg: 'Insufficient balance',
max_amount_error_msg:
max_deposit_error_msg:
'StarkNet Alpha Limitation: transfer to StarkNet limited to {{maxAmount}} {{symbol}}.',
max_btn_txt: 'Max',
balance_title_txt: 'Available balance',
Expand Down Expand Up @@ -84,7 +84,10 @@ const strings = {
message: 'Waiting for confirmation from {{walletName}}'
},
confirm_txt: 'Confirm this transaction in your wallet',
error_title: 'Transaction error'
max_total_balance_error_msg:
'We have reached the upper limit of the amount we allow the bridge to hold at this point so it is not possible to use the token you have chosen now.\n\nPlease try later or use another token.',
error_title: 'Transaction error',
limitation_error_title: 'Limitation error'
}
},
toasts: {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ export * from './useTransferToL1';
export * from './useTransferToL2';
export * from './useConfig';
export * from './useTransferProgress';
export * from './useMaxDeposit';
export * from './useTokenConstant';
30 changes: 0 additions & 30 deletions src/hooks/useMaxDeposit.js

This file was deleted.

39 changes: 39 additions & 0 deletions src/hooks/useTokenConstant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {useAsyncMemo} from 'use-async-memo';

import {maxDeposit, maxTotalBalance} from '../api/bridge';
import {useTransfer} from '../providers/TransferProvider';
import {useTokenBridgeContract} from './useContract';

const cache = {};

export const useMaxDeposit = () => {
return useTokenConstant('maxDeposit', maxDeposit);
};

export const useMaxTotalBalance = () => {
return useTokenConstant('maxTotalBalance', maxTotalBalance);
};

const useTokenConstant = (methodName, methodHandler) => {
const {symbol, isL1, selectedToken} = useTransfer();
const getTokenBridgeContract = useTokenBridgeContract();

const fetchTokenConstant = () => {
const {decimals, bridgeAddress} = selectedToken;
const contract = getTokenBridgeContract(bridgeAddress);
return methodHandler({decimals, contract});
};

return useAsyncMemo(async () => {
if (symbol && isL1) {
cache[methodName] = cache[methodName] || {};
if (!cache[methodName][symbol]) {
const value = await fetchTokenConstant();
cache[methodName][symbol] = value;
return value;
}
return cache[symbol];
}
return null;
}, [symbol, isL1, methodHandler, methodName]);
};
7 changes: 7 additions & 0 deletions src/hooks/useTransferProgress.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ export const useTransferProgress = () => {
type: error_title,
message: err.message
};
},
maxTotalBalanceError: () => {
const {limitation_error_title, max_total_balance_error_msg} = transferProgressStrings;
return {
type: limitation_error_title,
message: max_total_balance_error_msg
};
}
}),
[]
Expand Down
34 changes: 27 additions & 7 deletions src/hooks/useTransferToL2.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {useCallback} from 'react';

import {deposit, depositEth} from '../api/bridge';
import {allowance, approve} from '../api/erc20';
import {allowance, approve, balanceOf, ethBalanceOf} from '../api/erc20';
import {ActionType, TransactionHashPrefix} from '../enums';
import {starknet} from '../libs';
import {useLogMessageToL2Listener} from '../providers/EventManagerProvider';
Expand All @@ -10,6 +10,7 @@ import {useL1Wallet, useL2Wallet} from '../providers/WalletsProvider';
import utils from '../utils';
import {useTokenBridgeContract, useTokenContract} from './useContract';
import {useLogger} from './useLogger';
import {useMaxTotalBalance} from './useTokenConstant';
import {useTransfer} from './useTransfer';
import {useTransferProgress} from './useTransferProgress';

Expand All @@ -23,26 +24,28 @@ export const useTransferToL2 = () => {
const getTokenBridgeContract = useTokenBridgeContract();
const progressOptions = useTransferProgress();
const addLogMessageToL2Listener = useLogMessageToL2Listener();
const maxTotalBalance = useMaxTotalBalance();

return useCallback(
async amount => {
const {symbol, decimals, name, tokenAddress, bridgeAddress} = selectedToken;
const isEthToken = utils.token.isEth(symbol);
const tokenContract = getTokenContract(tokenAddress);
const bridgeContract = getTokenBridgeContract(bridgeAddress);
const isEthToken = utils.token.isEth(symbol);
const tokenBridgeAddress = bridgeAddress[l1ChainId];

const readAllowance = () => {
return allowance({
owner: l1Account,
spender: bridgeAddress[l1ChainId],
spender: tokenBridgeAddress,
decimals,
contract: tokenContract
});
};

const sendApproval = () => {
return approve({
spender: bridgeAddress[l1ChainId],
const sendApproval = async () => {
return await approve({
spender: tokenBridgeAddress,
value: starknet.constants.MASK_250,
contract: tokenContract,
options: {from: l1Account}
Expand Down Expand Up @@ -105,8 +108,24 @@ export const useTransferToL2 = () => {
};
};

const isMaxBalanceExceeded = async () => {
const tokenBridgeBalance = await (isEthToken
? ethBalanceOf(tokenBridgeAddress)
: balanceOf({
account: tokenBridgeAddress,
decimals,
contract: tokenContract
}));
return maxTotalBalance < tokenBridgeBalance + Number(amount);
};

try {
logger.log('TransferToL2 called');
if (await isMaxBalanceExceeded()) {
logger.error(`Prevented ${symbol} deposit due to max balance exceeded`);
handleError(progressOptions.maxTotalBalanceError());
return;
}
if (!isEthToken) {
logger.log('Token needs approval');
handleProgress(progressOptions.approval(symbol));
Expand Down Expand Up @@ -139,7 +158,8 @@ export const useTransferToL2 = () => {
handleError,
handleProgress,
logger,
progressOptions
progressOptions,
maxTotalBalance
]
);
};

0 comments on commit 12295d0

Please sign in to comment.