Skip to content

Commit

Permalink
refactor: promise handler instead of try/catch statement (#209)
Browse files Browse the repository at this point in the history
  • Loading branch information
dan-ziv authored May 25, 2022
1 parent 685c672 commit 1f56c38
Show file tree
Hide file tree
Showing 10 changed files with 147 additions and 118 deletions.
26 changes: 12 additions & 14 deletions src/api/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
parseToDecimals,
parseToFelt,
parseToUint256,
isDai
isDai,
promiseHandler
} from '../utils';

export const deposit = async ({recipient, amount, decimals, contract, options, emitter}) => {
Expand Down Expand Up @@ -45,24 +46,21 @@ export const withdraw = async ({recipient, amount, decimals, contract, emitter})
};

export const maxDeposit = async ({decimals, contract}) => {
try {
const maxDeposit = await callL1Contract(contract, 'maxDeposit');
return parseFromDecimals(maxDeposit, decimals);
} catch (ex) {
return Promise.reject(ex);
const [maxDeposit, error] = await promiseHandler(callL1Contract(contract, 'maxDeposit'));
if (error) {
return Promise.reject(error);
}
return parseFromDecimals(maxDeposit, decimals);
};

export const maxTotalBalance = async ({decimals, symbol, contract}) => {
try {
const maxTotalBalance = await callL1Contract(
contract,
isDai(symbol) ? 'ceiling' : 'maxTotalBalance'
);
return parseFromDecimals(maxTotalBalance, decimals);
} catch (ex) {
return Promise.reject(ex);
const [maxTotalBalance, error] = await promiseHandler(
callL1Contract(contract, isDai(symbol) ? 'ceiling' : 'maxTotalBalance')
);
if (error) {
return Promise.reject(error);
}
return parseFromDecimals(maxTotalBalance, decimals);
};

const initiateWithdrawCall = ({bridge, recipient, amount, decimals}) => {
Expand Down
59 changes: 35 additions & 24 deletions src/api/erc20.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,54 @@ import {
callL1Contract,
callL2Contract,
parseFromDecimals,
parseFromUint256
parseFromUint256,
promiseHandler
} from '../utils';

export const approve = async ({spender, value, contract, options}) => {
return sendL1Transaction(contract, 'approve', [spender, value], options);
};

export const allowance = async ({owner, spender, decimals, contract}) => {
try {
const allow = await callL1Contract(contract, 'allowance', [owner, spender]);
return parseFromDecimals(allow, decimals);
} catch (ex) {
return Promise.reject(ex);
const [allow, error] = await promiseHandler(
callL1Contract(contract, 'allowance', [owner, spender])
);
if (error) {
return Promise.reject(error);
}
return parseFromDecimals(allow, decimals);
};

export const balanceOf = async ({account, decimals, contract}, isL1 = true) => {
try {
if (isL1) {
const balance = await callL1Contract(contract, 'balanceOf', [account]);
return parseFromDecimals(balance, decimals);
} else {
const {balance} = await callL2Contract(contract, 'balanceOf', account, {
blockIdentifier: TransactionStatus.PENDING.toLowerCase()
});
return parseFromUint256(balance, decimals);
}
} catch (ex) {
return Promise.reject(ex);
}
return isL1
? balanceOfL1({account, decimals, contract})
: balanceOfL2({account, decimals, contract});
};

export const ethBalanceOf = async account => {
try {
const balance = await web3.eth.getBalance(account);
return parseFromDecimals(balance);
} catch (ex) {
return Promise.reject(ex);
const [balance, error] = await promiseHandler(web3.eth.getBalance(account));
if (error) {
return Promise.reject(error);
}
return parseFromDecimals(balance);
};

const balanceOfL1 = async ({account, decimals, contract}) => {
const [balance, error] = await promiseHandler(callL1Contract(contract, 'balanceOf', [account]));
if (error) {
return Promise.reject(error);
}
return parseFromDecimals(balance, decimals);
};

const balanceOfL2 = async ({account, decimals, contract}) => {
const [{balance}, error] = await promiseHandler(
callL2Contract(contract, 'balanceOf', account, {
blockIdentifier: TransactionStatus.PENDING.toLowerCase()
})
);
if (error) {
return Promise.reject(error);
}
return parseFromUint256(balance, decimals);
};
16 changes: 8 additions & 8 deletions src/hooks/useFetchData.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import {useEffect, useState} from 'react';

import {promiseHandler} from '../utils';

export const useFetchData = (func, deps = []) => {
const [isLoading, setIsLoading] = useState(true);
const [data, setData] = useState(null);
Expand All @@ -9,16 +11,14 @@ export const useFetchData = (func, deps = []) => {
async function fetch() {
setIsLoading(true);
setError(null);
try {
const data = await func();
if (!mounted) return;
setData(data);
setIsLoading(false);
} catch (ex) {
if (!mounted) return;
setError(ex);
const [data, error] = await promiseHandler(func());
if (!mounted) return;
if (error) {
setError(error);
setIsLoading(false);
}
setData(data);
setIsLoading(false);
}
let mounted = true;
fetch();
Expand Down
9 changes: 4 additions & 5 deletions src/hooks/useTransferToL2.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {useDepositListener} from '../providers/EventManagerProvider';
import {useL2Token} from '../providers/TokensProvider';
import {useSelectedToken} from '../providers/TransferProvider';
import {useL1Wallet, useL2Wallet} from '../providers/WalletsProvider';
import {addToken, isEth} from '../utils';
import {addToken, isEth, promiseHandler} from '../utils';
import {useTokenBridgeContract, useTokenContract} from './useContract';
import {useIsMaxTotalBalanceExceeded} from './useIsMaxTotalBalanceExceeded';
import {useLogger} from './useLogger';
Expand Down Expand Up @@ -100,10 +100,9 @@ export const useTransferToL2 = () => {
};

const maybeAddToken = async () => {
try {
await addToken(l2TokenAddress);
} catch (ex) {
logger.warn(ex.message);
const [, error] = await promiseHandler(addToken(l2TokenAddress));
if (error) {
logger.warn(error.message);
}
};

Expand Down
7 changes: 5 additions & 2 deletions src/providers/BlockHashProvider/BlockHashProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@ import React, {useCallback, useEffect, useState} from 'react';

import {useEnvs} from '../../hooks';
import {getStarknet} from '../../libs';
import {promiseHandler} from '../../utils';
import {BlockHashContext} from './block-hash-context';

export const BlockHashProvider = ({children}) => {
const {pollBlockNumberInterval} = useEnvs();
const [blockHash, setBlockHash] = useState();

const fetchBlockHash = useCallback(async () => {
const {block_hash} = await getStarknet().provider.getBlock();
setBlockHash(block_hash);
const [{block_hash}, error] = await promiseHandler(getStarknet().provider.getBlock());
if (!error) {
setBlockHash(block_hash);
}
}, []);

useEffect(() => {
Expand Down
14 changes: 6 additions & 8 deletions src/providers/TokensProvider/TokensProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React, {useReducer} from 'react';

import {useAccountChange, useConstants, useLogger} from '../../hooks';
import {useL1TokenBalance, useL2TokenBalance} from '../../hooks/useTokenBalance';
import {promiseHandler} from '../../utils';
import {useL1Wallet, useL2Wallet} from '../WalletsProvider';
import {TokensContext} from './tokens-context';
import {actions, initialState, reducer} from './tokens-reducer';
Expand Down Expand Up @@ -37,19 +38,16 @@ export const TokensProvider = ({children}) => {
};

const fetchBalance = async (fn, token, retry = 1) => {
try {
const balance = await fn(token);
logger.log(`New ${token.isL1 ? 'L1' : 'L2'} ${token.symbol} token balance is ${balance}`);
return updateToken(token.index, {balance, isLoading: false});
} catch (ex) {
logger.error(`Failed to fetch token ${token.symbol} balance: ${ex.message}, retry again`, {
ex
});
const [balance, error] = await promiseHandler(fn(token));
if (error) {
logger.error(`Failed to fetch token ${token.symbol} balance: ${error.message}, retry again`);
if (retry === FETCH_TOKEN_BALANCE_MAX_RETRY) {
return updateToken(token.index, {balance: null, isLoading: false});
}
return fetchBalance(fn, token, retry + 1);
}
logger.log(`New ${token.isL1 ? 'L1' : 'L2'} ${token.symbol} token balance is ${balance}`);
return updateToken(token.index, {balance, isLoading: false});
};

const updateToken = (index, props) => {
Expand Down
45 changes: 26 additions & 19 deletions src/providers/TransfersLogProvider/TransfersLogProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import useDeepCompareEffect from 'use-deep-compare-effect';
import {isCompleted, isConsumed, TransactionHashPrefix} from '../../enums';
import {useEnvs, useLogger} from '../../hooks';
import {getStarknet} from '../../libs';
import {calcAccountHash, getStorageItem, setStorageItem, getTransactionHash} from '../../utils';
import {
calcAccountHash,
getStorageItem,
setStorageItem,
getTransactionHash,
promiseHandler
} from '../../utils';
import {useBlockHash} from '../BlockHashProvider';
import {useDepositMessageToL2Event} from '../EventManagerProvider';
import {useTokens} from '../TokensProvider';
Expand Down Expand Up @@ -53,26 +59,27 @@ export const TransfersLogProvider = ({children}) => {
if (isCompleted(transfer.status) || transfer.lastChecked === blockHash) {
return transfer;
}
try {
logger.log(`Checking tx status ${transfer.l2hash}`);
const {tx_status} = await getStarknet().provider.getTransactionStatus(transfer.l2hash);
if (transfer.status !== tx_status) {
logger.log(`Status changed from ${transfer.status}->${tx_status}`);
if (isConsumed(tx_status)) {
updateTokenBalance(transfer.symbol);
}
} else {
logger.log(`Status is still ${tx_status}`);
}
return {
...transfer,
status: tx_status,
lastChecked: blockHash
};
} catch (error) {
logger.log(`Checking tx status ${transfer.l2hash}`);
const [{tx_status}, error] = await promiseHandler(
getStarknet().provider.getTransactionStatus(transfer.l2hash)
);
if (error) {
logger.error(`Failed to check transaction status: ${transfer.l2hash}`);
return transfer;
}
return transfer;
if (transfer.status !== tx_status) {
logger.log(`Status changed from ${transfer.status}->${tx_status}`);
if (isConsumed(tx_status)) {
updateTokenBalance(transfer.symbol);
}
} else {
logger.log(`Status is still ${tx_status}`);
}
return {
...transfer,
status: tx_status,
lastChecked: blockHash
};
};

const calcL2TransactionHash = async transfer => {
Expand Down
19 changes: 11 additions & 8 deletions src/utils/ethereum.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import {web3} from '../libs';
import {promiseHandler} from './index';

export const createL1Contract = (address, ABI) => {
return new web3.eth.Contract(ABI, address);
};

export const callL1Contract = async (contract, method, args = []) => {
try {
return await contract.methods?.[method](...args).call();
} catch (ex) {
return Promise.reject(ex);
const [response, error] = await promiseHandler(contract.methods?.[method](...args).call());
if (error) {
return Promise.reject(error);
}
return response;
};

export const sendL1Transaction = async (
Expand All @@ -19,9 +20,11 @@ export const sendL1Transaction = async (
options = {},
cb = () => {}
) => {
try {
return contract.methods?.[method](...args).send(options, cb);
} catch (ex) {
return Promise.reject(ex);
const [response, error] = await promiseHandler(
contract.methods?.[method](...args).send(options, cb)
);
if (error) {
return Promise.reject(error);
}
return response;
};
8 changes: 8 additions & 0 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,11 @@ export const printPackageInfo = (name, version, color) => {
getLogger().info(`%c ${name} v${version}`, `color: ${color || '#ff98f9'}; font-size: large`);
setLogLevel(currentLogLevel);
};

export const promiseHandler = async promise => {
try {
return [await promise, null];
} catch (err) {
return [null, err];
}
};
Loading

0 comments on commit 1f56c38

Please sign in to comment.