From 0256631154a6c6130c1d6f8f614d932b6bc0420e Mon Sep 17 00:00:00 2001 From: Dan Ziv Date: Wed, 16 Mar 2022 13:34:16 +0200 Subject: [PATCH 1/5] refactor --- src/api/bridge.js | 12 +- src/api/erc20.js | 11 +- src/{libs => blockchain}/index.js | 0 src/blockchain/starknet.js | 64 +++++++++++ src/blockchain/web3.js | 31 +++++ .../Containers/Footer/Footer.strings.js | 4 +- .../Containers/Header/Header.strings.js | 4 +- src/components/Features/Account/Account.js | 4 +- .../Features/Account/Account.strings.js | 4 +- .../Features/Login/Login.strings.js | 4 +- .../ModalProvider/ModalProvider.strings.js | 6 +- .../SelectToken/SelectToken.strings.js | 4 +- .../ToastProvider/ToastProvider.strings.js | 4 +- .../Features/Transfer/Transfer.strings.js | 6 +- .../Features/TransferLog/TransferLog.js | 4 +- .../TransferLog/TransferLog.strings.js | 4 +- .../AccountAddress/AccountAddress.strings.js | 4 +- .../UI/BackButton/BackButton.strings.js | 4 +- .../UI/LogoutButton/LogoutButton.strings.js | 4 +- .../UI/MaxButton/MaxButton.strings.js | 4 +- .../TransactionSubmittedModal.js | 10 +- .../TransactionSubmittedModal.strings.js | 4 +- .../UI/NetworkMenu/NetworkMenu.strings.js | 4 +- .../UI/SearchToken/SearchToken.strings.js | 4 +- .../CompleteTransferToL1Toast.strings.js | 4 +- .../Toast/ToastFooter/ToastFooter.strings.js | 4 +- .../TransferToast/TransferToast.strings.js | 4 +- .../UI/TokenBalance/TokenBalance.strings.js | 4 +- .../UI/TokenInput/TokenInput.strings.js | 4 +- .../TransferButton/TransferButton.strings.js | 4 +- .../TransferLogContainer.strings.js | 4 +- .../UI/WalletButton/WalletButton.strings.js | 4 +- src/config/constants.js | 38 +++++++ src/config/{config.js => envs.js} | 4 +- src/config/strings.js | 107 ++++++++++++++++++ src/config/strings.json | 101 ----------------- src/config/wallets.js | 4 +- src/constants.js | 34 ------ src/enums/ChainType.js | 4 +- src/hooks/useConfig.js | 2 +- src/hooks/useContract.js | 8 +- src/hooks/useEventListener.js | 2 +- src/hooks/useTransfer.js | 7 +- src/hooks/useTransferProgress.js | 4 +- src/libs/starknet.js | 4 - src/libs/web3.js | 10 -- .../BlockHashProvider/BlockHashProvider.js | 2 +- .../TransfersProvider/TransfersProvider.js | 6 +- .../WalletsProvider/WalletsProvider.js | 2 +- .../wallet-handlers/argent-handler.js | 2 +- src/utils/contract.js | 81 ------------- src/utils/hash.js | 2 +- src/utils/helpers.js | 4 +- src/utils/index.js | 2 +- src/utils/{number.js => parser.js} | 21 ++-- 55 files changed, 357 insertions(+), 330 deletions(-) rename src/{libs => blockchain}/index.js (100%) create mode 100644 src/blockchain/starknet.js create mode 100644 src/blockchain/web3.js create mode 100644 src/config/constants.js rename src/config/{config.js => envs.js} (89%) create mode 100644 src/config/strings.js delete mode 100644 src/config/strings.json delete mode 100644 src/constants.js delete mode 100644 src/libs/starknet.js delete mode 100644 src/libs/web3.js delete mode 100644 src/utils/contract.js rename src/utils/{number.js => parser.js} (55%) diff --git a/src/api/bridge.js b/src/api/bridge.js index 7b038543..06a0874b 100644 --- a/src/api/bridge.js +++ b/src/api/bridge.js @@ -1,9 +1,9 @@ +import {web3, starknet} from '../blockchain'; import {parseFromDecimals, parseToDecimals, parseToFelt, parseToUint256} from '../utils'; -import {l1_callContract, l1_sendTransaction, l2_sendTransaction} from '../utils/contract'; export const deposit = async ({recipient, amount, decimals, contract, options, emitter}) => { try { - return l1_sendTransaction( + return web3.sendTransaction( contract, 'deposit', [parseToDecimals(amount, decimals), recipient], @@ -17,7 +17,7 @@ export const deposit = async ({recipient, amount, decimals, contract, options, e export const depositEth = async ({recipient, amount, contract, options, emitter}) => { try { - return l1_sendTransaction( + return web3.sendTransaction( contract, 'deposit', [recipient], @@ -34,7 +34,7 @@ export const depositEth = async ({recipient, amount, contract, options, emitter} export const withdraw = async ({recipient, amount, decimals, contract, emitter}) => { try { - return l1_sendTransaction( + return web3.sendTransaction( contract, 'withdraw', [parseToDecimals(amount, decimals), recipient], @@ -50,7 +50,7 @@ export const withdraw = async ({recipient, amount, decimals, contract, emitter}) export const maxDeposit = async ({decimals, contract}) => { try { - const maxDeposit = await l1_callContract(contract, 'maxDeposit'); + const maxDeposit = await web3.callContract(contract, 'maxDeposit'); return parseFromDecimals(maxDeposit, decimals); } catch (ex) { return Promise.reject(ex); @@ -59,7 +59,7 @@ export const maxDeposit = async ({decimals, contract}) => { export const initiateWithdraw = async ({recipient, amount, decimals, contract}) => { try { - return l2_sendTransaction(contract, 'initiate_withdraw', { + return starknet.sendTransaction(contract, 'initiate_withdraw', { l1Recipient: parseToFelt(recipient), amount: parseToUint256(amount, decimals) }); diff --git a/src/api/erc20.js b/src/api/erc20.js index 7a7ec91b..92624975 100644 --- a/src/api/erc20.js +++ b/src/api/erc20.js @@ -1,11 +1,10 @@ +import {web3, starknet} from '../blockchain'; import {TransactionStatus} from '../enums'; -import {web3} from '../libs'; import {parseFromDecimals, parseFromUint256} from '../utils'; -import {l1_callContract, l1_sendTransaction, l2_callContract} from '../utils/contract'; export const approve = async ({spender, value, contract, options}) => { try { - return await l1_sendTransaction(contract, 'approve', [spender, value], options); + return await web3.sendTransaction(contract, 'approve', [spender, value], options); } catch (ex) { return Promise.reject(ex); } @@ -13,7 +12,7 @@ export const approve = async ({spender, value, contract, options}) => { export const allowance = async ({owner, spender, decimals, contract}) => { try { - const allow = await l1_callContract(contract, 'allowance', [owner, spender]); + const allow = await web3.callContract(contract, 'allowance', [owner, spender]); return parseFromDecimals(allow, decimals); } catch (ex) { return Promise.reject(ex); @@ -23,10 +22,10 @@ export const allowance = async ({owner, spender, decimals, contract}) => { export const balanceOf = async ({account, decimals, contract}, isL1 = true) => { try { if (isL1) { - const balance = await l1_callContract(contract, 'balanceOf', [account]); + const balance = await web3.callContract(contract, 'balanceOf', [account]); return parseFromDecimals(balance, decimals); } else { - const {balance} = await l2_callContract( + const {balance} = await starknet.callContract( contract, 'balanceOf', [{account}], diff --git a/src/libs/index.js b/src/blockchain/index.js similarity index 100% rename from src/libs/index.js rename to src/blockchain/index.js diff --git a/src/blockchain/starknet.js b/src/blockchain/starknet.js new file mode 100644 index 00000000..025c19f8 --- /dev/null +++ b/src/blockchain/starknet.js @@ -0,0 +1,64 @@ +import {getStarknet} from '@argent/get-starknet'; +import * as starknetJS from 'starknet'; +import {compileCalldata, Contract, defaultProvider, stark} from 'starknet'; + +import {TransactionConsumedStatuses} from '../enums'; +import {getLogger} from '../services'; + +const starknet = { + createContract: (address, ABI) => { + return new Contract(ABI, address); + }, + callContract: async (contract, method, args = [], blockIdentifier = null) => { + try { + return await contract.call(method, ...args, blockIdentifier); + } catch (ex) { + return Promise.reject(ex); + } + }, + sendTransaction: async (contract, method, args = {}) => { + try { + const methodSelector = stark.getSelectorFromName(method); + const compiledCalldata = compileCalldata(args); + return getStarknet().signer.invokeFunction( + contract.connectedTo, + methodSelector, + compiledCalldata + ); + } catch (ex) { + return Promise.reject(ex); + } + }, + waitForTransaction: async (hash, customStatus, retryInterval = 5000) => { + const logger = getLogger('l2_waitForTransaction'); + return new Promise(resolve => { + let processing = false; + const waitingForStatuses = customStatus ? [customStatus] : TransactionConsumedStatuses; + logger.debug(`Waiting for transaction with statuses ${waitingForStatuses.join(' ')}`); + const intervalId = setInterval(async () => { + if (processing) return; + logger.debug(`Checking transaction again`); + const statusPromise = defaultProvider.getTransactionStatus(hash); + processing = true; + try { + const {tx_status} = await statusPromise; + logger.debug(`Transaction status is ${tx_status}`); + if (waitingForStatuses.includes(tx_status)) { + logger.debug(`We got our desired status!`); + clearInterval(intervalId); + resolve(); + } else { + logger.debug(`We haven't got our desired status, trying again.`); + processing = false; + } + } catch (ex) { + logger.error(`Error while calling get status: ${ex.message}, trying again.`); + processing = false; + } + }, retryInterval); + }); + }, + ...starknetJS +}; + +export {starknet, getStarknet}; diff --git a/src/blockchain/web3.js b/src/blockchain/web3.js new file mode 100644 index 00000000..2d515b3d --- /dev/null +++ b/src/blockchain/web3.js @@ -0,0 +1,31 @@ +import Web3 from 'web3'; + +let web3; +if (typeof window.ethereum !== 'undefined' || typeof window.web3 !== 'undefined') { + web3 = new Web3(window.ethereum || window.web3.currentProvider); +} else { + web3 = new Web3(); +} + +web3 = { + createContract: (address, ABI) => { + return new web3.eth.Contract(ABI, address); + }, + callContract: async (contract, method, args = []) => { + try { + return await contract.methods?.[method](...args).call(); + } catch (ex) { + return Promise.reject(ex); + } + }, + sendTransaction: async (contract, method, args = [], options = {}, cb = () => {}) => { + try { + return contract.methods?.[method](...args).send(options, cb); + } catch (ex) { + return Promise.reject(ex); + } + }, + ...web3 +}; + +export {web3}; diff --git a/src/components/Containers/Footer/Footer.strings.js b/src/components/Containers/Footer/Footer.strings.js index 96622db6..18d709b7 100644 --- a/src/components/Containers/Footer/Footer.strings.js +++ b/src/components/Containers/Footer/Footer.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const RIGHTS_TXT = getString('containers.footer.rights_txt'); +export const RIGHTS_TXT = getTranslation('containers.footer.rights_txt'); diff --git a/src/components/Containers/Header/Header.strings.js b/src/components/Containers/Header/Header.strings.js index aa80fd9f..08eac976 100644 --- a/src/components/Containers/Header/Header.strings.js +++ b/src/components/Containers/Header/Header.strings.js @@ -1,4 +1,4 @@ -import {capitalize, evaluate, getString} from '../../../utils'; +import {capitalize, evaluate, getTranslation} from '../../../utils'; export const CHAIN_TXT = chainName => - capitalize(evaluate(getString('containers.header.chain_txt'), {chainName})); + capitalize(evaluate(getTranslation('containers.header.chain_txt'), {chainName})); diff --git a/src/components/Features/Account/Account.js b/src/components/Features/Account/Account.js index 851178ec..da8125a0 100644 --- a/src/components/Features/Account/Account.js +++ b/src/components/Features/Account/Account.js @@ -1,7 +1,7 @@ import PropTypes from 'prop-types'; import React from 'react'; -import {LINKS} from '../../../constants'; +import constants from '../../../config/constants'; import {useCompleteTransferToL1} from '../../../hooks'; import {useAccountTransfers} from '../../../providers/TransfersProvider'; import {useWallets} from '../../../providers/WalletsProvider'; @@ -21,6 +21,8 @@ import {TransferLog} from '../TransferLog/TransferLog'; import styles from './Account.module.scss'; import {TITLE_TXT} from './Account.strings'; +const {LINKS} = constants; + export const Account = ({transferId}) => { const {showTransferMenu} = useBridgeActions(); const {account, chainId, resetWallet} = useWallets(); diff --git a/src/components/Features/Account/Account.strings.js b/src/components/Features/Account/Account.strings.js index 75437b99..d2ea9d22 100644 --- a/src/components/Features/Account/Account.strings.js +++ b/src/components/Features/Account/Account.strings.js @@ -1,3 +1,3 @@ -import {evaluate, getString} from '../../../utils'; +import {evaluate, getTranslation} from '../../../utils'; -export const TITLE_TXT = network => evaluate(getString('menus.account.title_txt'), {network}); +export const TITLE_TXT = network => evaluate(getTranslation('menus.account.title_txt'), {network}); diff --git a/src/components/Features/Login/Login.strings.js b/src/components/Features/Login/Login.strings.js index 16b95243..83248e2d 100644 --- a/src/components/Features/Login/Login.strings.js +++ b/src/components/Features/Login/Login.strings.js @@ -1,6 +1,6 @@ -import {evaluate, getString} from '../../../utils'; +import {evaluate, getTranslation} from '../../../utils'; -const {title_txt, subtitle_txt, download_txt, modal_txt} = getString('menus.login'); +const {title_txt, subtitle_txt, download_txt, modal_txt} = getTranslation('menus.login'); export const TITLE_TXT = title_txt; export const DOWNLOAD_TEXT = download_txt; diff --git a/src/components/Features/ModalProvider/ModalProvider.strings.js b/src/components/Features/ModalProvider/ModalProvider.strings.js index 340c2566..bd02a0ff 100644 --- a/src/components/Features/ModalProvider/ModalProvider.strings.js +++ b/src/components/Features/ModalProvider/ModalProvider.strings.js @@ -1,3 +1,5 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const TRANSACTION_SUBMITTED_TITLE_TXT = getString('modals.transactionSubmitted.title_txt'); +export const TRANSACTION_SUBMITTED_TITLE_TXT = getTranslation( + 'modals.transactionSubmitted.title_txt' +); diff --git a/src/components/Features/SelectToken/SelectToken.strings.js b/src/components/Features/SelectToken/SelectToken.strings.js index 4fef0f93..c3ac8bcd 100644 --- a/src/components/Features/SelectToken/SelectToken.strings.js +++ b/src/components/Features/SelectToken/SelectToken.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const TITLE_TXT = getString('menus.selectToken.title_txt'); +export const TITLE_TXT = getTranslation('menus.selectToken.title_txt'); diff --git a/src/components/Features/ToastProvider/ToastProvider.strings.js b/src/components/Features/ToastProvider/ToastProvider.strings.js index dcb2a054..d4c23aa8 100644 --- a/src/components/Features/ToastProvider/ToastProvider.strings.js +++ b/src/components/Features/ToastProvider/ToastProvider.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const ALPHA_DISCLAIMER_MSG = getString('toasts.alpha_disclaimer_msg'); +export const ALPHA_DISCLAIMER_MSG = getTranslation('toasts.alpha_disclaimer_msg'); diff --git a/src/components/Features/Transfer/Transfer.strings.js b/src/components/Features/Transfer/Transfer.strings.js index 392f5ff4..2f73c068 100644 --- a/src/components/Features/Transfer/Transfer.strings.js +++ b/src/components/Features/Transfer/Transfer.strings.js @@ -1,8 +1,8 @@ -import {evaluate, getString} from '../../../utils'; +import {evaluate, getTranslation} from '../../../utils'; -export const INSUFFICIENT_BALANCE_ERROR_MSG = getString( +export const INSUFFICIENT_BALANCE_ERROR_MSG = getTranslation( 'menus.transfer.insufficient_balance_error_msg' ); export const MAX_AMOUNT_ERROR_MSG = (maxAmount, symbol) => - evaluate(getString('menus.transfer.max_amount_error_msg'), {maxAmount, symbol}); + evaluate(getTranslation('menus.transfer.max_amount_error_msg'), {maxAmount, symbol}); diff --git a/src/components/Features/TransferLog/TransferLog.js b/src/components/Features/TransferLog/TransferLog.js index a1182408..628d3e29 100644 --- a/src/components/Features/TransferLog/TransferLog.js +++ b/src/components/Features/TransferLog/TransferLog.js @@ -1,7 +1,7 @@ import PropTypes from 'prop-types'; import React, {useEffect, useState} from 'react'; -import {LINKS} from '../../../constants'; +import constants from '../../../config/constants'; import { isOnChain, isPending, @@ -19,6 +19,8 @@ import {useTransferData} from '../Transfer/Transfer.hooks'; import styles from './TransferLog.module.scss'; import {COMPLETE_TRANSFER_BTN_TXT} from './TransferLog.strings'; +const {LINKS} = constants; + export const TransferLog = ({transfer, onCompleteTransferClick}) => { const {symbol, timestamp, name, amount, status, l1hash, l2hash} = transfer; const [sign, setSign] = useState(''); diff --git a/src/components/Features/TransferLog/TransferLog.strings.js b/src/components/Features/TransferLog/TransferLog.strings.js index d06afed9..251234d1 100644 --- a/src/components/Features/TransferLog/TransferLog.strings.js +++ b/src/components/Features/TransferLog/TransferLog.strings.js @@ -1,5 +1,5 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const COMPLETE_TRANSFER_BTN_TXT = getString( +export const COMPLETE_TRANSFER_BTN_TXT = getTranslation( 'menus.account.transferLogContainer.transferLog.complete_transfer_btn_txt' ); diff --git a/src/components/UI/AccountAddress/AccountAddress.strings.js b/src/components/UI/AccountAddress/AccountAddress.strings.js index 00595350..7798d6b4 100644 --- a/src/components/UI/AccountAddress/AccountAddress.strings.js +++ b/src/components/UI/AccountAddress/AccountAddress.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const COPIED_MSG_TXT = getString('menus.account.copied_msg_txt'); +export const COPIED_MSG_TXT = getTranslation('menus.account.copied_msg_txt'); diff --git a/src/components/UI/BackButton/BackButton.strings.js b/src/components/UI/BackButton/BackButton.strings.js index 46bc48a2..5893b227 100644 --- a/src/components/UI/BackButton/BackButton.strings.js +++ b/src/components/UI/BackButton/BackButton.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const BTN_TXT = getString('menus.back_btn_txt'); +export const BTN_TXT = getTranslation('menus.back_btn_txt'); diff --git a/src/components/UI/LogoutButton/LogoutButton.strings.js b/src/components/UI/LogoutButton/LogoutButton.strings.js index da81090d..4cdd5d87 100644 --- a/src/components/UI/LogoutButton/LogoutButton.strings.js +++ b/src/components/UI/LogoutButton/LogoutButton.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const BTN_TXT = getString('menus.account.logout_btn_txt'); +export const BTN_TXT = getTranslation('menus.account.logout_btn_txt'); diff --git a/src/components/UI/MaxButton/MaxButton.strings.js b/src/components/UI/MaxButton/MaxButton.strings.js index d9e25a3c..6b264845 100644 --- a/src/components/UI/MaxButton/MaxButton.strings.js +++ b/src/components/UI/MaxButton/MaxButton.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const BTN_TXT = getString('menus.transfer.max_btn_txt'); +export const BTN_TXT = getTranslation('menus.transfer.max_btn_txt'); diff --git a/src/components/UI/Modal/TransactionSubmittedModal/TransactionSubmittedModal.js b/src/components/UI/Modal/TransactionSubmittedModal/TransactionSubmittedModal.js index 95d1cc23..0d01470f 100644 --- a/src/components/UI/Modal/TransactionSubmittedModal/TransactionSubmittedModal.js +++ b/src/components/UI/Modal/TransactionSubmittedModal/TransactionSubmittedModal.js @@ -3,7 +3,7 @@ import React, {useEffect, useState} from 'react'; import {ReactComponent as EtherscanLogo} from '../../../../assets/svg/etherscan.svg'; import {ReactComponent as L2Logo} from '../../../../assets/svg/tokens/starknet.svg'; -import {LINKS} from '../../../../constants'; +import constants from '../../../../config/constants'; import {ActionType} from '../../../../enums'; import {useColors} from '../../../../hooks'; import {useWallets} from '../../../../providers/WalletsProvider'; @@ -12,12 +12,14 @@ import {Button} from '../../Button/Button'; import {Circle} from '../../Circle/Circle'; import { BTN_TEXT, - TRANSFER_TO_L2_TXT, - TRANSFER_TO_L1_TXT, COMPLETE_TRANSFER_TO_L1_TXT, - STATUS_TXT + STATUS_TXT, + TRANSFER_TO_L1_TXT, + TRANSFER_TO_L2_TXT } from './TransactionSubmittedModal.strings'; +const {LINKS} = constants; + const TransactionSubmittedModal = ({transfer}) => { const {chainId} = useWallets(); const [networkData, setNetworkData] = useState({}); diff --git a/src/components/UI/Modal/TransactionSubmittedModal/TransactionSubmittedModal.strings.js b/src/components/UI/Modal/TransactionSubmittedModal/TransactionSubmittedModal.strings.js index 5ec85c37..0b6eb861 100644 --- a/src/components/UI/Modal/TransactionSubmittedModal/TransactionSubmittedModal.strings.js +++ b/src/components/UI/Modal/TransactionSubmittedModal/TransactionSubmittedModal.strings.js @@ -1,7 +1,7 @@ -import {evaluate, getString} from '../../../../utils'; +import {evaluate, getTranslation} from '../../../../utils'; const {btn_txt, transfer_to_l1_txt, complete_transfer_to_l1_txt, transfer_to_l2_txt, status_txt} = - getString('modals.transactionSubmitted'); + getTranslation('modals.transactionSubmitted'); export const COMPLETE_TRANSFER_TO_L1_TXT = complete_transfer_to_l1_txt; export const TRANSFER_TO_L1_TXT = transfer_to_l1_txt; diff --git a/src/components/UI/NetworkMenu/NetworkMenu.strings.js b/src/components/UI/NetworkMenu/NetworkMenu.strings.js index 12b6303d..101c07bd 100644 --- a/src/components/UI/NetworkMenu/NetworkMenu.strings.js +++ b/src/components/UI/NetworkMenu/NetworkMenu.strings.js @@ -1,6 +1,6 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -const {to_txt, from_txt} = getString('menus.transfer'); +const {to_txt, from_txt} = getTranslation('menus.transfer'); export const TO = to_txt; export const FROM = from_txt; diff --git a/src/components/UI/SearchToken/SearchToken.strings.js b/src/components/UI/SearchToken/SearchToken.strings.js index 4dc182ee..2588e1f9 100644 --- a/src/components/UI/SearchToken/SearchToken.strings.js +++ b/src/components/UI/SearchToken/SearchToken.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const SEARCH_PLACEHOLDER = getString('menus.selectToken.search_placeholder'); +export const SEARCH_PLACEHOLDER = getTranslation('menus.selectToken.search_placeholder'); diff --git a/src/components/UI/Toast/CompleteTransferToL1Toast/CompleteTransferToL1Toast.strings.js b/src/components/UI/Toast/CompleteTransferToL1Toast/CompleteTransferToL1Toast.strings.js index 261b14bd..f6a1b1b2 100644 --- a/src/components/UI/Toast/CompleteTransferToL1Toast/CompleteTransferToL1Toast.strings.js +++ b/src/components/UI/Toast/CompleteTransferToL1Toast/CompleteTransferToL1Toast.strings.js @@ -1,7 +1,7 @@ -import {getString} from '../../../../utils'; +import {getTranslation} from '../../../../utils'; const {title_txt, body_txt, dismiss_btn_txt, complete_transfer_btn_txt} = - getString('toasts.completeTransfer'); + getTranslation('toasts.completeTransfer'); export const TITLE_TXT = title_txt; export const BODY_TXT = body_txt; diff --git a/src/components/UI/Toast/ToastFooter/ToastFooter.strings.js b/src/components/UI/Toast/ToastFooter/ToastFooter.strings.js index b99257f9..5871eae5 100644 --- a/src/components/UI/Toast/ToastFooter/ToastFooter.strings.js +++ b/src/components/UI/Toast/ToastFooter/ToastFooter.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../../utils'; +import {getTranslation} from '../../../../utils'; -export const TRANSFER_LOG_LINK_BTN_TXT = getString('toasts.transfer_log_link'); +export const TRANSFER_LOG_LINK_BTN_TXT = getTranslation('toasts.transfer_log_link'); diff --git a/src/components/UI/Toast/TransferToast/TransferToast.strings.js b/src/components/UI/Toast/TransferToast/TransferToast.strings.js index 55df0c99..eb8d4f2a 100644 --- a/src/components/UI/Toast/TransferToast/TransferToast.strings.js +++ b/src/components/UI/Toast/TransferToast/TransferToast.strings.js @@ -1,6 +1,6 @@ -import {getString} from '../../../../utils'; +import {getTranslation} from '../../../../utils'; -const {pending_txt, consumed_txt, rejected_txt} = getString('toasts.pendingTransfer'); +const {pending_txt, consumed_txt, rejected_txt} = getTranslation('toasts.pendingTransfer'); export const REJECTED_TXT = rejected_txt; export const PENDING_TXT = pending_txt; diff --git a/src/components/UI/TokenBalance/TokenBalance.strings.js b/src/components/UI/TokenBalance/TokenBalance.strings.js index 818489b7..fdc080fe 100644 --- a/src/components/UI/TokenBalance/TokenBalance.strings.js +++ b/src/components/UI/TokenBalance/TokenBalance.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const TITLE_TXT = getString('menus.transfer.balance_title_txt'); +export const TITLE_TXT = getTranslation('menus.transfer.balance_title_txt'); diff --git a/src/components/UI/TokenInput/TokenInput.strings.js b/src/components/UI/TokenInput/TokenInput.strings.js index b4811d09..00569d0e 100644 --- a/src/components/UI/TokenInput/TokenInput.strings.js +++ b/src/components/UI/TokenInput/TokenInput.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const INPUT_PLACEHOLDER = getString('menus.transfer.input_placeholder_txt'); +export const INPUT_PLACEHOLDER = getTranslation('menus.transfer.input_placeholder_txt'); diff --git a/src/components/UI/TransferButton/TransferButton.strings.js b/src/components/UI/TransferButton/TransferButton.strings.js index 8f523a7b..6dae2c10 100644 --- a/src/components/UI/TransferButton/TransferButton.strings.js +++ b/src/components/UI/TransferButton/TransferButton.strings.js @@ -1,3 +1,3 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -export const BTN_TXT = getString('menus.transfer.transfer_btn_txt'); +export const BTN_TXT = getTranslation('menus.transfer.transfer_btn_txt'); diff --git a/src/components/UI/TransferLogContainer/TransferLogContainer.strings.js b/src/components/UI/TransferLogContainer/TransferLogContainer.strings.js index dc2244d5..2596f336 100644 --- a/src/components/UI/TransferLogContainer/TransferLogContainer.strings.js +++ b/src/components/UI/TransferLogContainer/TransferLogContainer.strings.js @@ -1,6 +1,6 @@ -import {getString} from '../../../utils'; +import {getTranslation} from '../../../utils'; -const {title_txt, overview_txt, empty_msg_txt, view_more_txt} = getString( +const {title_txt, overview_txt, empty_msg_txt, view_more_txt} = getTranslation( 'menus.account.transferLogContainer' ); diff --git a/src/components/UI/WalletButton/WalletButton.strings.js b/src/components/UI/WalletButton/WalletButton.strings.js index c8711844..e7481ed3 100644 --- a/src/components/UI/WalletButton/WalletButton.strings.js +++ b/src/components/UI/WalletButton/WalletButton.strings.js @@ -1,4 +1,4 @@ -import {evaluate, getString} from '../../../utils'; +import {evaluate, getTranslation} from '../../../utils'; export const BTN_TXT = address => - evaluate(getString('containers.header.wallet_btn_txt'), {address}); + evaluate(getTranslation('containers.header.wallet_btn_txt'), {address}); diff --git a/src/config/constants.js b/src/config/constants.js new file mode 100644 index 00000000..b60fcaec --- /dev/null +++ b/src/config/constants.js @@ -0,0 +1,38 @@ +import {byChainId} from '../enums'; +import {evaluate} from '../utils'; + +const constants = { + LOCAL_STORAGE_TRANSFERS_KEY: 'STARKGATE_TRANSFERS', + ETHERSCAN_URL: 'etherscan.io', + VOYAGER_URL: 'voyager.online', + LINKS: { + ETHERSCAN: { + text: 'etherscan', + txUrl: (chainId, hash) => + evaluate('{{url}}/tx/{{hash}}', { + url: byChainId(chainId).blockExplorerUrl, + hash + }), + accountUrl: (chainId, account) => + evaluate('{{url}}/address/{{account}}', { + url: byChainId(chainId).blockExplorerUrl, + account + }) + }, + VOYAGER: { + text: 'voyager', + txUrl: (chainId, hash) => + evaluate('{{url}}/tx/{{hash}}', { + url: byChainId(chainId).l2BlockExplorerUrl, + hash + }), + accountUrl: (chainId, account) => + evaluate('{{url}}/contract/{{account}}', { + url: byChainId(chainId).l2BlockExplorerUrl, + account + }) + } + } +}; + +export default constants; diff --git a/src/config/config.js b/src/config/envs.js similarity index 89% rename from src/config/config.js rename to src/config/envs.js index c4a7f234..d59939e9 100644 --- a/src/config/config.js +++ b/src/config/envs.js @@ -1,6 +1,8 @@ -export default { +const envs = { autoConnect: Boolean(process.env.REACT_APP_AUTO_CONNECT), pollBalanceInterval: Number(process.env.REACT_APP_POLL_BALANCE_INTERVAL), pollBlockNumberInterval: Number(process.env.REACT_APP_POLL_BLOCK_NUMBER_INTERVAL), supportedChainIds: process.env.REACT_APP_SUPPORTED_CHAIN_IDS.split(' ').map(id => Number(id)) }; + +export default envs; diff --git a/src/config/strings.js b/src/config/strings.js new file mode 100644 index 00000000..286e7804 --- /dev/null +++ b/src/config/strings.js @@ -0,0 +1,107 @@ +const strings = { + containers: { + header: { + chain_txt: '{{chainName}} testnet', + wallet_btn_txt: 'Account | {{address}}' + }, + footer: { + rights_txt: '© 2022 StarkWare Industries Ltd. All Rights Reserved' + } + }, + menus: { + back_btn_txt: 'Back', + login: { + title_txt: 'Login', + subtitle_txt: 'Please select {{networkName}} wallet to connect with this dApp:', + download_txt: ['Don’t have a wallet?', 'Download Here'], + modal_txt: 'Waiting for confirmation from {{walletName}}' + }, + account: { + title_txt: '{{network}} Account', + copied_msg_txt: 'Copied!', + logout_btn_txt: 'Logout', + transferLogContainer: { + title_txt: 'Transfers log', + overview_txt: 'recent transfers', + empty_msg_txt: 'Transfers will appear here...', + view_more_txt: 'View more', + transferLog: { + complete_transfer_btn_txt: 'Complete transfer' + } + } + }, + selectToken: { + title_txt: 'Select token from:', + search_placeholder: 'Token name, symbol, or address' + }, + transfer: { + to_txt: 'to', + from_txt: 'from', + insufficient_balance_error_msg: 'Insufficient balance', + max_amount_error_msg: + 'StarkNet Alpha Limitation: transfer to StarkNet limited to {{maxAmount}} {{symbol}}.', + max_btn_txt: 'Max', + balance_title_txt: 'Available balance', + input_placeholder_txt: '0.00', + transfer_btn_txt: 'Transfer' + } + }, + modals: { + transactionSubmitted: { + title_txt: 'Transaction sent', + btn_txt: 'View on {{explorer}}', + transfer_to_l1_txt: + 'Your transaction is now being processing on L2. When it will be accepted on-chain, we will promote you to complete your transfer.', + transfer_to_l2_txt: 'Your transaction has been sent to L2!', + complete_transfer_to_l1_txt: 'Your transaction is completed on L1!', + status_txt: 'Follow the transaction status on the right side of the browser.' + }, + transferProgress: { + approval: { + type: 'Approval required', + message: 'Requesting permission to access your {{symbol}} funds.' + }, + deposit: { + type: 'Transfer in progress', + message: 'Transferring {{amount}} {{symbol}} to L2...' + }, + initiateWithdraw: { + type: 'Initiate transfer', + message: 'Initiating transfer of {{amount}} {{symbol}} from L2...' + }, + waitForAccept: { + type: 'Transaction sent', + message: 'Waiting for transaction to be accepted on L2...' + }, + withdraw: { + type: 'Transfer in progress', + message: 'Transferring {{amount}} {{symbol}} to L1...' + }, + waitForConfirm: { + type: '{{walletName}}', + message: 'Waiting for confirmation from {{walletName}}' + }, + confirm_txt: 'Confirm this transaction in your wallet', + error_title: 'Transaction error' + } + }, + toasts: { + alpha_disclaimer_msg: + 'This is an ALPHA version of StarkNet, and its Bridge. As such, deyals may occur, and catastrophic bugs may lurk. Thanks, OGs, for trying it at this early stage.', + transfer_log_link: 'View on Transfer Log', + pendingTransfer: { + pending_txt: 'Waiting for transaction to be accepted on L2', + consumed_txt: 'Transaction accepted on L2', + rejected_txt: 'Transaction rejected on L2' + }, + completeTransfer: { + title_txt: 'L2 finished processing your transfer!', + body_txt: + 'Click on Complete Transfer to transfer the funds from L2 Bridge to your L1 address.', + dismiss_btn_txt: 'Dismiss', + complete_transfer_btn_txt: 'Complete Transfer' + } + } +}; + +export default strings; diff --git a/src/config/strings.json b/src/config/strings.json deleted file mode 100644 index 551dbc74..00000000 --- a/src/config/strings.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "containers": { - "header": { - "chain_txt": "{{chainName}} testnet", - "wallet_btn_txt": "Account | {{address}}" - }, - "footer": { - "rights_txt": "© 2022 StarkWare Industries Ltd. All Rights Reserved" - } - }, - "menus": { - "back_btn_txt": "Back", - "login": { - "title_txt": "Login", - "subtitle_txt": "Please select {{networkName}} wallet to connect with this dApp:", - "download_txt": ["Don’t have a wallet?", "Download Here"], - "modal_txt": "Waiting for confirmation from {{walletName}}" - }, - "account": { - "title_txt": "{{network}} Account", - "copied_msg_txt": "Copied!", - "logout_btn_txt": "Logout", - "transferLogContainer": { - "title_txt": "Transfers log", - "overview_txt": "recent transfers", - "empty_msg_txt": "Transfers will appear here...", - "view_more_txt": "View more", - "transferLog": { - "complete_transfer_btn_txt": "Complete transfer" - } - } - }, - "selectToken": { - "title_txt": "Select token from:", - "search_placeholder": "Token name, symbol, or address" - }, - "transfer": { - "to_txt": "to", - "from_txt": "from", - "insufficient_balance_error_msg": "Insufficient balance", - "max_amount_error_msg": "StarkNet Alpha Limitation: transfer to StarkNet limited to {{maxAmount}} {{symbol}}.", - "max_btn_txt": "Max", - "balance_title_txt": "Available balance", - "input_placeholder_txt": "0.00", - "transfer_btn_txt": "Transfer" - } - }, - "modals": { - "transactionSubmitted": { - "title_txt": "Transaction sent", - "btn_txt": "View on {{explorer}}", - "transfer_to_l1_txt": "Your transaction is now being processing on L2. When it will be accepted on-chain, we will promote you to complete your transfer.", - "transfer_to_l2_txt": "Your transaction has been sent to L2!", - "complete_transfer_to_l1_txt": "Your transaction is completed on L1!", - "status_txt": "Follow the transaction status on the right side of the browser." - }, - "transferProgress": { - "approval": { - "type": "Approval required", - "message": "Requesting permission to access your {{symbol}} funds." - }, - "deposit": { - "type": "Transfer in progress", - "message": "Transferring {{amount}} {{symbol}} to L2..." - }, - "initiateWithdraw": { - "type": "Initiate transfer", - "message": "Initiating transfer of {{amount}} {{symbol}} from L2..." - }, - "waitForAccept": { - "type": "Transaction sent", - "message": "Waiting for transaction to be accepted on L2..." - }, - "withdraw": { - "type": "Transfer in progress", - "message": "Transferring {{amount}} {{symbol}} to L1..." - }, - "waitForConfirm": { - "type": "{{walletName}}", - "message": "Waiting for confirmation from {{walletName}}" - }, - "confirm_txt": "Confirm this transaction in your wallet", - "error_title": "Transaction error" - } - }, - "toasts": { - "alpha_disclaimer_msg": "This is an ALPHA version of StarkNet, and its Bridge. As such, deyals may occur, and catastrophic bugs may lurk. Thanks, OGs, for trying it at this early stage.", - "transfer_log_link": "View on Transfer Log", - "pendingTransfer": { - "pending_txt": "Waiting for transaction to be accepted on L2", - "consumed_txt": "Transaction accepted on L2", - "rejected_txt": "Transaction rejected on L2" - }, - "completeTransfer": { - "title_txt": "L2 finished processing your transfer!", - "body_txt": "Click on Complete Transfer to transfer the funds from L2 Bridge to your L1 address.", - "dismiss_btn_txt": "Dismiss", - "complete_transfer_btn_txt": "Complete Transfer" - } - } -} diff --git a/src/config/wallets.js b/src/config/wallets.js index b7889711..7aded763 100644 --- a/src/config/wallets.js +++ b/src/config/wallets.js @@ -1,6 +1,6 @@ import {WalletType} from '../enums'; -export default [ +const wallets = [ { id: 'metamask', name: 'MetaMask', @@ -17,3 +17,5 @@ export default [ logoPath: 'wallets/argent/logo.svg' } ]; + +export default wallets; diff --git a/src/constants.js b/src/constants.js deleted file mode 100644 index f2311527..00000000 --- a/src/constants.js +++ /dev/null @@ -1,34 +0,0 @@ -import {byChainId} from './enums'; -import {evaluate} from './utils'; - -export const LOCAL_STORAGE_TRANSFERS_KEY = 'STARKGATE_TRANSFERS'; -export const ETHERSCAN_URL = 'etherscan.io'; -export const VOYAGER_URL = 'voyager.online'; -export const LINKS = { - ETHERSCAN: { - text: 'etherscan', - txUrl: (chainId, hash) => - evaluate('{{url}}/tx/{{hash}}', { - url: byChainId(chainId).blockExplorerUrl, - hash - }), - accountUrl: (chainId, account) => - evaluate('{{url}}/address/{{account}}', { - url: byChainId(chainId).blockExplorerUrl, - account - }) - }, - VOYAGER: { - text: 'voyager', - txUrl: (chainId, hash) => - evaluate('{{url}}/tx/{{hash}}', { - url: byChainId(chainId).l2BlockExplorerUrl, - hash - }), - accountUrl: (chainId, account) => - evaluate('{{url}}/contract/{{account}}', { - url: byChainId(chainId).l2BlockExplorerUrl, - account - }) - } -}; diff --git a/src/enums/ChainType.js b/src/enums/ChainType.js index c7df6276..6c7b0201 100644 --- a/src/enums/ChainType.js +++ b/src/enums/ChainType.js @@ -1,4 +1,6 @@ -import {ETHERSCAN_URL, VOYAGER_URL} from '../constants'; +import constants from '../config/constants'; + +const {ETHERSCAN_URL, VOYAGER_URL} = constants; export const ChainType = { MAIN: { diff --git a/src/hooks/useConfig.js b/src/hooks/useConfig.js index df179418..0f7728e1 100644 --- a/src/hooks/useConfig.js +++ b/src/hooks/useConfig.js @@ -1,5 +1,5 @@ import {useMemo} from 'react'; -import config from '../config/config.js'; +import config from '../config/envs.js'; export const useConfig = () => useMemo(() => config, []); diff --git a/src/hooks/useContract.js b/src/hooks/useContract.js index 471b0faa..4758b56d 100644 --- a/src/hooks/useContract.js +++ b/src/hooks/useContract.js @@ -2,16 +2,16 @@ import {useCallback, useMemo} from 'react'; import {L1_ERC20_ABI, L1_ERC20_BRIDGE_ABI, L1_ETH_BRIDGE_ABI, L1_MESSAGING_ABI} from '../abis/l1'; import {L2_BRIDGE_ABI, L2_ERC20_ABI} from '../abis/l2'; +import {web3, starknet} from '../blockchain'; import {useTransferData} from '../components/Features/Transfer/Transfer.hooks'; import {MESSAGING_CONTRACT_ADDRESS} from '../config/addresses'; import {NetworkType} from '../enums'; import {useL1Token} from '../providers/TokensProvider'; import {useL1Wallet, useWallets} from '../providers/WalletsProvider'; -import {l1_getContract, l2_getContract} from '../utils/contract'; const cache = {}; -export const useContract = (ABI, getContractHandler = l1_getContract) => { +export const useContract = (ABI, getContractHandler = web3.createContract) => { const {chainId} = useWallets(); return useCallback( addresses => { @@ -55,7 +55,7 @@ export const useTokenBridgeContract = () => { }; export const useL2TokenContract = () => { - const getContract = useContract(L2_ERC20_ABI, l2_getContract); + const getContract = useContract(L2_ERC20_ABI, starknet.createContract); return useCallback(tokenAddresses => getContract(tokenAddresses), [getContract]); }; @@ -70,7 +70,7 @@ export const useMessagingContract = () => { }; export const useL2TokenBridgeContract = () => { - const getContract = useContract(L2_BRIDGE_ABI, l2_getContract); + const getContract = useContract(L2_BRIDGE_ABI, starknet.createContract); return useCallback(bridgeAddress => getContract(bridgeAddress), [getContract]); }; diff --git a/src/hooks/useEventListener.js b/src/hooks/useEventListener.js index 542abd00..5768a7ce 100644 --- a/src/hooks/useEventListener.js +++ b/src/hooks/useEventListener.js @@ -1,8 +1,8 @@ import {useCallback} from 'react'; +import {starknet} from '../blockchain'; import {useSelectedToken} from '../components/Features/Transfer/Transfer.hooks'; import {TransactionHashPrefix} from '../enums'; -import {starknet} from '../libs'; import {useL1Token, useL2Token} from '../providers/TokensProvider'; import {useL1Wallet, useL2Wallet} from '../providers/WalletsProvider'; import {txHash} from '../utils'; diff --git a/src/hooks/useTransfer.js b/src/hooks/useTransfer.js index 632ed5ff..95f4db9b 100644 --- a/src/hooks/useTransfer.js +++ b/src/hooks/useTransfer.js @@ -2,6 +2,7 @@ import {useCallback} from 'react'; import {deposit, depositEth, initiateWithdraw, withdraw} from '../api/bridge'; import {allowance, approve} from '../api/erc20'; +import {starknet} from '../blockchain'; import { useErrorModal, useHideModal, @@ -10,12 +11,10 @@ import { } from '../components/Features/ModalProvider/ModalProvider.hooks'; import {useAmount, useSelectedToken} from '../components/Features/Transfer/Transfer.hooks'; import {ActionType, TransactionStatus} from '../enums'; -import {starknet} from '../libs'; import {useL1Token, useTokens} from '../providers/TokensProvider'; import {useTransfers} from '../providers/TransfersProvider'; import {useL1Wallet, useL2Wallet} from '../providers/WalletsProvider'; import {isEth} from '../utils'; -import {l2_waitForTransaction} from '../utils/contract'; import {useL1TokenBridgeContract, useTokenBridgeContract, useTokenContract} from './useContract'; import {useLogMessageToL2Listener} from './useEventListener'; import {useLogger} from './useLogger'; @@ -145,10 +144,10 @@ export const useTransferToL1 = () => { logger.log('Tx hash received', {transaction_hash}); handleProgress(progressOptions.initiateWithdraw(amount, symbol)); logger.log('Waiting for tx to be received on L2'); - await l2_waitForTransaction(transaction_hash, TransactionStatus.RECEIVED); + await starknet.waitForTransaction(transaction_hash, TransactionStatus.RECEIVED); handleProgress(progressOptions.waitForAccept()); logger.log('Waiting for tx to be accepted on L2'); - await l2_waitForTransaction(transaction_hash); + await starknet.waitForTransaction(transaction_hash); logger.log('Done', {transaction_hash}); handleData({ type: ActionType.TRANSFER_TO_L1, diff --git a/src/hooks/useTransferProgress.js b/src/hooks/useTransferProgress.js index f64dea2e..40e23f2e 100644 --- a/src/hooks/useTransferProgress.js +++ b/src/hooks/useTransferProgress.js @@ -1,9 +1,9 @@ import {useMemo} from 'react'; -import {evaluate, getString} from '../utils'; +import {evaluate, getTranslation} from '../utils'; export const useTransferProgress = () => { - const transferProgressStrings = getString('modals.transferProgress'); + const transferProgressStrings = getTranslation('modals.transferProgress'); return useMemo( () => ({ approval: symbol => { diff --git a/src/libs/starknet.js b/src/libs/starknet.js deleted file mode 100644 index 98040233..00000000 --- a/src/libs/starknet.js +++ /dev/null @@ -1,4 +0,0 @@ -import {getStarknet} from '@argent/get-starknet'; -import * as starknet from 'starknet'; - -export {starknet, getStarknet}; diff --git a/src/libs/web3.js b/src/libs/web3.js deleted file mode 100644 index 7b01ddee..00000000 --- a/src/libs/web3.js +++ /dev/null @@ -1,10 +0,0 @@ -import Web3 from 'web3'; - -let web3; -if (typeof window.ethereum !== 'undefined' || typeof window.web3 !== 'undefined') { - web3 = new Web3(window.ethereum || window.web3.currentProvider); -} else { - web3 = new Web3(); -} - -export {web3}; diff --git a/src/providers/BlockHashProvider/BlockHashProvider.js b/src/providers/BlockHashProvider/BlockHashProvider.js index 5c48229b..5bbb0fee 100644 --- a/src/providers/BlockHashProvider/BlockHashProvider.js +++ b/src/providers/BlockHashProvider/BlockHashProvider.js @@ -1,8 +1,8 @@ import PropTypes from 'prop-types'; import React, {useCallback, useEffect, useState} from 'react'; +import {starknet} from '../../blockchain'; import {useConfig} from '../../hooks'; -import {starknet} from '../../libs'; import {BlockHashContext} from './block-hash-context'; export const BlockHashProvider = ({children}) => { diff --git a/src/providers/TransfersProvider/TransfersProvider.js b/src/providers/TransfersProvider/TransfersProvider.js index 6af38379..1998c3d2 100644 --- a/src/providers/TransfersProvider/TransfersProvider.js +++ b/src/providers/TransfersProvider/TransfersProvider.js @@ -2,15 +2,17 @@ import PropTypes from 'prop-types'; import React, {useEffect, useReducer} from 'react'; import useDeepCompareEffect from 'use-deep-compare-effect'; -import {LOCAL_STORAGE_TRANSFERS_KEY} from '../../constants'; +import {starknet} from '../../blockchain'; +import constants from '../../config/constants'; import {isCompleted} from '../../enums'; import {useLogger} from '../../hooks'; -import {starknet} from '../../libs'; import {StorageManager} from '../../services'; import {useBlockHash} from '../BlockHashProvider'; import {TransfersContext} from './transfers-context'; import {actions, initialState, reducer} from './transfers-reducer'; +const {LOCAL_STORAGE_TRANSFERS_KEY} = constants; + export const TransfersProvider = ({children}) => { const logger = useLogger(TransfersProvider.displayName); const [transfers, dispatch] = useReducer(reducer, initialState); diff --git a/src/providers/WalletsProvider/WalletsProvider.js b/src/providers/WalletsProvider/WalletsProvider.js index 28bdae4f..43e0d674 100644 --- a/src/providers/WalletsProvider/WalletsProvider.js +++ b/src/providers/WalletsProvider/WalletsProvider.js @@ -2,10 +2,10 @@ import PropTypes from 'prop-types'; import React, {useEffect, useReducer} from 'react'; import {useWallet} from 'use-wallet'; +import {getStarknet} from '../../blockchain'; import {useIsL1, useIsL2} from '../../components/Features/Transfer/Transfer.hooks'; import {WalletStatus} from '../../enums'; import {useConfig} from '../../hooks'; -import {getStarknet} from '../../libs'; import {WalletsContext} from './wallets-context'; import {actions, initialState, reducer} from './wallets-reducer'; diff --git a/src/services/wallet-handlers/argent-handler.js b/src/services/wallet-handlers/argent-handler.js index f4c530df..3be9cea7 100644 --- a/src/services/wallet-handlers/argent-handler.js +++ b/src/services/wallet-handlers/argent-handler.js @@ -1,4 +1,4 @@ -import {getStarknet} from '../../libs'; +import {getStarknet} from '../../blockchain'; export class ArgentHandler { constructor(config) { diff --git a/src/utils/contract.js b/src/utils/contract.js deleted file mode 100644 index 288cdd44..00000000 --- a/src/utils/contract.js +++ /dev/null @@ -1,81 +0,0 @@ -import {TransactionConsumedStatuses} from '../enums'; -import {getStarknet, starknet, web3} from '../libs'; -import {getLogger} from '../services'; - -export const l1_getContract = (address, ABI) => new web3.eth.Contract(ABI, address); - -export const l1_callContract = async (contract, method, args = []) => { - try { - return await contract.methods?.[method](...args).call(); - } catch (ex) { - return Promise.reject(ex); - } -}; - -export const l1_sendTransaction = async ( - contract, - method, - args = [], - options = {}, - cb = () => {} -) => { - try { - return contract.methods?.[method](...args).send(options, cb); - } catch (ex) { - return Promise.reject(ex); - } -}; - -export const l2_getContract = (address, ABI) => new starknet.Contract(ABI, address); - -export const l2_callContract = async (contract, method, args = [], blockIdentifier = null) => { - try { - return await contract.call(method, ...args, blockIdentifier); - } catch (ex) { - return Promise.reject(ex); - } -}; - -export const l2_sendTransaction = async (contract, method, args = {}) => { - try { - const methodSelector = starknet.stark.getSelectorFromName(method); - const compiledCalldata = starknet.compileCalldata(args); - return getStarknet().signer.invokeFunction( - contract.connectedTo, - methodSelector, - compiledCalldata - ); - } catch (ex) { - return Promise.reject(ex); - } -}; - -export const l2_waitForTransaction = async (hash, customStatus, retryInterval = 5000) => { - const logger = getLogger('l2_waitForTransaction'); - return new Promise(resolve => { - let processing = false; - const waitingForStatuses = customStatus ? [customStatus] : TransactionConsumedStatuses; - logger.debug(`Waiting for transaction with statuses ${waitingForStatuses.join(' ')}`); - const intervalId = setInterval(async () => { - if (processing) return; - logger.debug(`Checking transaction again`); - const statusPromise = starknet.defaultProvider.getTransactionStatus(hash); - processing = true; - try { - const {tx_status} = await statusPromise; - logger.debug(`Transaction status is ${tx_status}`); - if (waitingForStatuses.includes(tx_status)) { - logger.debug(`We got our desired status!`); - clearInterval(intervalId); - resolve(); - } else { - logger.debug(`We haven't got our desired status, trying again.`); - processing = false; - } - } catch (ex) { - logger.error(`Error while calling get status: ${ex.message}, trying again.`); - processing = false; - } - }, retryInterval); - }); -}; diff --git a/src/utils/hash.js b/src/utils/hash.js index f17bce92..d3a149b0 100644 --- a/src/utils/hash.js +++ b/src/utils/hash.js @@ -1,5 +1,5 @@ +import {starknet} from '../blockchain'; import {byChainId} from '../enums'; -import {starknet} from '../libs'; export const txHash = ( txHashPrefix, diff --git a/src/utils/helpers.js b/src/utils/helpers.js index 39da649b..9492ffae 100644 --- a/src/utils/helpers.js +++ b/src/utils/helpers.js @@ -1,4 +1,4 @@ -import strings from '../config/strings.json'; +import strings from '../config/strings.js'; import {getLogger, getLogLevel, setLogLevel} from '../services'; import {getPropertyPath} from './object'; @@ -9,4 +9,4 @@ export const printPackageInfo = (name, version, color) => { setLogLevel(currentLogLevel); }; -export const getString = path => getPropertyPath(strings, path); +export const getTranslation = path => getPropertyPath(strings, path); diff --git a/src/utils/index.js b/src/utils/index.js index 9be9adf3..896165a8 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -2,7 +2,7 @@ export * from './wallet'; export * from './browser'; export * from './string'; export * from './token'; -export * from './number'; +export * from './parser'; export * from './hash'; export * from './date'; export * from './object'; diff --git a/src/utils/number.js b/src/utils/parser.js similarity index 55% rename from src/utils/number.js rename to src/utils/parser.js index 7061ae51..4164789a 100644 --- a/src/utils/number.js +++ b/src/utils/parser.js @@ -1,32 +1,35 @@ -import {web3, starknet} from '../libs'; +import {web3, starknet} from '../blockchain'; + +const {number, uint256} = starknet; +const {utils} = web3; const TEN = 10; const DEFAULT_DECIMALS = 18; export const UNIT_MAP = {}; -for (let key in web3.utils.unitMap) { - UNIT_MAP[web3.utils.unitMap[key]] = key; +for (let key in utils.unitMap) { + UNIT_MAP[utils.unitMap[key]] = key; } export const parseToDecimals = (value, decimals = DEFAULT_DECIMALS) => { - return web3.utils.toWei(value, UNIT_MAP[Math.pow(TEN, decimals)]); + return utils.toWei(value, UNIT_MAP[Math.pow(TEN, decimals)]); }; export const parseFromDecimals = (value, decimals = DEFAULT_DECIMALS) => { - return Number(web3.utils.fromWei(value, UNIT_MAP[Math.pow(TEN, decimals)])); + return Number(utils.fromWei(value, UNIT_MAP[Math.pow(TEN, decimals)])); }; export const parseFromFelt = value => { - return starknet.number.toBN(value).toNumber(); + return number.toBN(value).toNumber(); }; export const parseToFelt = value => { - return starknet.number.toBN(value).toString(); + return number.toBN(value).toString(); }; export const parseToUint256 = (value, decimals = DEFAULT_DECIMALS) => { const decimalsValue = parseToDecimals(value, decimals); - const uint256 = starknet.uint256.bnToUint256(starknet.number.toBN(decimalsValue)); + const uint256 = uint256.bnToUint256(number.toBN(decimalsValue)); return { type: 'struct', ...uint256 @@ -34,6 +37,6 @@ export const parseToUint256 = (value, decimals = DEFAULT_DECIMALS) => { }; export const parseFromUint256 = (value, decimals = DEFAULT_DECIMALS) => { - const bnString = starknet.uint256.uint256ToBN(value).toString(); + const bnString = uint256.uint256ToBN(value).toString(); return parseFromDecimals(bnString, decimals); }; From abeb82f267b045e8d1f8f02012d2910826c6534e Mon Sep 17 00:00:00 2001 From: Dan Ziv Date: Wed, 16 Mar 2022 14:14:04 +0200 Subject: [PATCH 2/5] Fixes --- src/__tests__/utils/{number.spec.js => parser.spec.js} | 0 src/blockchain/starknet.js | 4 ++-- src/utils/helpers.js | 2 +- src/utils/parser.js | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) rename src/__tests__/utils/{number.spec.js => parser.spec.js} (100%) diff --git a/src/__tests__/utils/number.spec.js b/src/__tests__/utils/parser.spec.js similarity index 100% rename from src/__tests__/utils/number.spec.js rename to src/__tests__/utils/parser.spec.js diff --git a/src/blockchain/starknet.js b/src/blockchain/starknet.js index 025c19f8..406a5da9 100644 --- a/src/blockchain/starknet.js +++ b/src/blockchain/starknet.js @@ -1,10 +1,10 @@ import {getStarknet} from '@argent/get-starknet'; import * as starknetJS from 'starknet'; -import {compileCalldata, Contract, defaultProvider, stark} from 'starknet'; -import {TransactionConsumedStatuses} from '../enums'; import {getLogger} from '../services'; +const {compileCalldata, Contract, defaultProvider, stark} = starknetJS; + const starknet = { createContract: (address, ABI) => { return new Contract(ABI, address); diff --git a/src/utils/helpers.js b/src/utils/helpers.js index 9492ffae..7753dfa2 100644 --- a/src/utils/helpers.js +++ b/src/utils/helpers.js @@ -1,4 +1,4 @@ -import strings from '../config/strings.js'; +import strings from '../config/strings'; import {getLogger, getLogLevel, setLogLevel} from '../services'; import {getPropertyPath} from './object'; diff --git a/src/utils/parser.js b/src/utils/parser.js index 4164789a..aaf93002 100644 --- a/src/utils/parser.js +++ b/src/utils/parser.js @@ -29,10 +29,10 @@ export const parseToFelt = value => { export const parseToUint256 = (value, decimals = DEFAULT_DECIMALS) => { const decimalsValue = parseToDecimals(value, decimals); - const uint256 = uint256.bnToUint256(number.toBN(decimalsValue)); + const uint256Value = uint256.bnToUint256(number.toBN(decimalsValue)); return { type: 'struct', - ...uint256 + ...uint256Value }; }; From 4a1bd1b85e11a25b1cf4e18f574ebaaf01c97bfa Mon Sep 17 00:00:00 2001 From: Dan Ziv Date: Wed, 16 Mar 2022 16:44:24 +0200 Subject: [PATCH 3/5] fix --- src/api/bridge.js | 12 ++-- src/api/erc20.js | 19 ++++-- src/blockchain/web3.js | 31 ---------- src/enums/TransactionStatus.js | 9 +++ src/hooks/useContract.js | 8 +-- src/hooks/useEventListener.js | 2 +- src/hooks/useTransfer.js | 13 ++++- src/{blockchain => libs}/index.js | 0 src/libs/starknet.js | 4 ++ src/libs/web3.js | 10 ++++ .../BlockHashProvider/BlockHashProvider.js | 2 +- .../TransfersProvider/TransfersProvider.js | 2 +- .../WalletsProvider/WalletsProvider.js | 2 +- .../wallet-handlers/argent-handler.js | 2 +- .../starknet.js => utils/blockchain.js} | 58 ++++++++++++------- src/utils/hash.js | 2 +- src/utils/index.js | 1 + src/utils/parser.js | 2 +- 18 files changed, 103 insertions(+), 76 deletions(-) delete mode 100644 src/blockchain/web3.js rename src/{blockchain => libs}/index.js (100%) create mode 100644 src/libs/starknet.js create mode 100644 src/libs/web3.js rename src/{blockchain/starknet.js => utils/blockchain.js} (50%) diff --git a/src/api/bridge.js b/src/api/bridge.js index 06a0874b..7b757199 100644 --- a/src/api/bridge.js +++ b/src/api/bridge.js @@ -1,9 +1,9 @@ -import {web3, starknet} from '../blockchain'; import {parseFromDecimals, parseToDecimals, parseToFelt, parseToUint256} from '../utils'; +import blockchainUtils from '../utils/blockchain'; export const deposit = async ({recipient, amount, decimals, contract, options, emitter}) => { try { - return web3.sendTransaction( + return blockchainUtils.ethereum.sendTransaction( contract, 'deposit', [parseToDecimals(amount, decimals), recipient], @@ -17,7 +17,7 @@ export const deposit = async ({recipient, amount, decimals, contract, options, e export const depositEth = async ({recipient, amount, contract, options, emitter}) => { try { - return web3.sendTransaction( + return blockchainUtils.ethereum.sendTransaction( contract, 'deposit', [recipient], @@ -34,7 +34,7 @@ export const depositEth = async ({recipient, amount, contract, options, emitter} export const withdraw = async ({recipient, amount, decimals, contract, emitter}) => { try { - return web3.sendTransaction( + return blockchainUtils.ethereum.sendTransaction( contract, 'withdraw', [parseToDecimals(amount, decimals), recipient], @@ -50,7 +50,7 @@ export const withdraw = async ({recipient, amount, decimals, contract, emitter}) export const maxDeposit = async ({decimals, contract}) => { try { - const maxDeposit = await web3.callContract(contract, 'maxDeposit'); + const maxDeposit = await blockchainUtils.ethereum.callContract(contract, 'maxDeposit'); return parseFromDecimals(maxDeposit, decimals); } catch (ex) { return Promise.reject(ex); @@ -59,7 +59,7 @@ export const maxDeposit = async ({decimals, contract}) => { export const initiateWithdraw = async ({recipient, amount, decimals, contract}) => { try { - return starknet.sendTransaction(contract, 'initiate_withdraw', { + return blockchainUtils.starknet.sendTransaction(contract, 'initiate_withdraw', { l1Recipient: parseToFelt(recipient), amount: parseToUint256(amount, decimals) }); diff --git a/src/api/erc20.js b/src/api/erc20.js index 92624975..7782680f 100644 --- a/src/api/erc20.js +++ b/src/api/erc20.js @@ -1,10 +1,16 @@ -import {web3, starknet} from '../blockchain'; import {TransactionStatus} from '../enums'; +import {web3} from '../libs'; import {parseFromDecimals, parseFromUint256} from '../utils'; +import blockchainUtils from '../utils/blockchain'; export const approve = async ({spender, value, contract, options}) => { try { - return await web3.sendTransaction(contract, 'approve', [spender, value], options); + return await blockchainUtils.ethereum.sendTransaction( + contract, + 'approve', + [spender, value], + options + ); } catch (ex) { return Promise.reject(ex); } @@ -12,7 +18,10 @@ export const approve = async ({spender, value, contract, options}) => { export const allowance = async ({owner, spender, decimals, contract}) => { try { - const allow = await web3.callContract(contract, 'allowance', [owner, spender]); + const allow = await blockchainUtils.ethereum.callContract(contract, 'allowance', [ + owner, + spender + ]); return parseFromDecimals(allow, decimals); } catch (ex) { return Promise.reject(ex); @@ -22,10 +31,10 @@ export const allowance = async ({owner, spender, decimals, contract}) => { export const balanceOf = async ({account, decimals, contract}, isL1 = true) => { try { if (isL1) { - const balance = await web3.callContract(contract, 'balanceOf', [account]); + const balance = await blockchainUtils.ethereum.callContract(contract, 'balanceOf', [account]); return parseFromDecimals(balance, decimals); } else { - const {balance} = await starknet.callContract( + const {balance} = await blockchainUtils.starknet.callContract( contract, 'balanceOf', [{account}], diff --git a/src/blockchain/web3.js b/src/blockchain/web3.js deleted file mode 100644 index 2d515b3d..00000000 --- a/src/blockchain/web3.js +++ /dev/null @@ -1,31 +0,0 @@ -import Web3 from 'web3'; - -let web3; -if (typeof window.ethereum !== 'undefined' || typeof window.web3 !== 'undefined') { - web3 = new Web3(window.ethereum || window.web3.currentProvider); -} else { - web3 = new Web3(); -} - -web3 = { - createContract: (address, ABI) => { - return new web3.eth.Contract(ABI, address); - }, - callContract: async (contract, method, args = []) => { - try { - return await contract.methods?.[method](...args).call(); - } catch (ex) { - return Promise.reject(ex); - } - }, - sendTransaction: async (contract, method, args = [], options = {}, cb = () => {}) => { - try { - return contract.methods?.[method](...args).send(options, cb); - } catch (ex) { - return Promise.reject(ex); - } - }, - ...web3 -}; - -export {web3}; diff --git a/src/enums/TransactionStatus.js b/src/enums/TransactionStatus.js index 6932592d..3f21e6be 100644 --- a/src/enums/TransactionStatus.js +++ b/src/enums/TransactionStatus.js @@ -31,6 +31,15 @@ export const TransactionConsumedStatuses = [ TransactionStatus.PENDING ]; +export const TransactionStatusStep = { + NOT_RECEIVED: 0, + RECEIVED: 1, + PENDING: 2, + ACCEPTED_ON_L2: 3, + ACCEPTED_ON_L1: 4, + REJECTED: 5 +}; + export const isPending = status => TransactionPendingStatuses.includes(status); export const isConsumed = status => TransactionConsumedStatuses.includes(status); diff --git a/src/hooks/useContract.js b/src/hooks/useContract.js index 4758b56d..4a3754ef 100644 --- a/src/hooks/useContract.js +++ b/src/hooks/useContract.js @@ -2,16 +2,16 @@ import {useCallback, useMemo} from 'react'; import {L1_ERC20_ABI, L1_ERC20_BRIDGE_ABI, L1_ETH_BRIDGE_ABI, L1_MESSAGING_ABI} from '../abis/l1'; import {L2_BRIDGE_ABI, L2_ERC20_ABI} from '../abis/l2'; -import {web3, starknet} from '../blockchain'; import {useTransferData} from '../components/Features/Transfer/Transfer.hooks'; import {MESSAGING_CONTRACT_ADDRESS} from '../config/addresses'; import {NetworkType} from '../enums'; import {useL1Token} from '../providers/TokensProvider'; import {useL1Wallet, useWallets} from '../providers/WalletsProvider'; +import blockchainUtils from '../utils/blockchain'; const cache = {}; -export const useContract = (ABI, getContractHandler = web3.createContract) => { +export const useContract = (ABI, getContractHandler = blockchainUtils.ethereum.createContract) => { const {chainId} = useWallets(); return useCallback( addresses => { @@ -55,7 +55,7 @@ export const useTokenBridgeContract = () => { }; export const useL2TokenContract = () => { - const getContract = useContract(L2_ERC20_ABI, starknet.createContract); + const getContract = useContract(L2_ERC20_ABI, blockchainUtils.starknet.createContract); return useCallback(tokenAddresses => getContract(tokenAddresses), [getContract]); }; @@ -70,7 +70,7 @@ export const useMessagingContract = () => { }; export const useL2TokenBridgeContract = () => { - const getContract = useContract(L2_BRIDGE_ABI, starknet.createContract); + const getContract = useContract(L2_BRIDGE_ABI, blockchainUtils.starknet.createContract); return useCallback(bridgeAddress => getContract(bridgeAddress), [getContract]); }; diff --git a/src/hooks/useEventListener.js b/src/hooks/useEventListener.js index 5768a7ce..542abd00 100644 --- a/src/hooks/useEventListener.js +++ b/src/hooks/useEventListener.js @@ -1,8 +1,8 @@ import {useCallback} from 'react'; -import {starknet} from '../blockchain'; import {useSelectedToken} from '../components/Features/Transfer/Transfer.hooks'; import {TransactionHashPrefix} from '../enums'; +import {starknet} from '../libs'; import {useL1Token, useL2Token} from '../providers/TokensProvider'; import {useL1Wallet, useL2Wallet} from '../providers/WalletsProvider'; import {txHash} from '../utils'; diff --git a/src/hooks/useTransfer.js b/src/hooks/useTransfer.js index 95f4db9b..02162e95 100644 --- a/src/hooks/useTransfer.js +++ b/src/hooks/useTransfer.js @@ -2,7 +2,6 @@ import {useCallback} from 'react'; import {deposit, depositEth, initiateWithdraw, withdraw} from '../api/bridge'; import {allowance, approve} from '../api/erc20'; -import {starknet} from '../blockchain'; import { useErrorModal, useHideModal, @@ -11,10 +10,12 @@ import { } from '../components/Features/ModalProvider/ModalProvider.hooks'; import {useAmount, useSelectedToken} from '../components/Features/Transfer/Transfer.hooks'; import {ActionType, TransactionStatus} from '../enums'; +import {starknet} from '../libs'; import {useL1Token, useTokens} from '../providers/TokensProvider'; import {useTransfers} from '../providers/TransfersProvider'; import {useL1Wallet, useL2Wallet} from '../providers/WalletsProvider'; import {isEth} from '../utils'; +import blockchainUtils from '../utils/blockchain'; import {useL1TokenBridgeContract, useTokenBridgeContract, useTokenContract} from './useContract'; import {useLogMessageToL2Listener} from './useEventListener'; import {useLogger} from './useLogger'; @@ -144,10 +145,16 @@ export const useTransferToL1 = () => { logger.log('Tx hash received', {transaction_hash}); handleProgress(progressOptions.initiateWithdraw(amount, symbol)); logger.log('Waiting for tx to be received on L2'); - await starknet.waitForTransaction(transaction_hash, TransactionStatus.RECEIVED); + await blockchainUtils.starknet.waitForTransaction( + transaction_hash, + TransactionStatus.RECEIVED + ); handleProgress(progressOptions.waitForAccept()); logger.log('Waiting for tx to be accepted on L2'); - await starknet.waitForTransaction(transaction_hash); + await blockchainUtils.starknet.waitForTransaction( + transaction_hash, + TransactionStatus.PENDING + ); logger.log('Done', {transaction_hash}); handleData({ type: ActionType.TRANSFER_TO_L1, diff --git a/src/blockchain/index.js b/src/libs/index.js similarity index 100% rename from src/blockchain/index.js rename to src/libs/index.js diff --git a/src/libs/starknet.js b/src/libs/starknet.js new file mode 100644 index 00000000..98040233 --- /dev/null +++ b/src/libs/starknet.js @@ -0,0 +1,4 @@ +import {getStarknet} from '@argent/get-starknet'; +import * as starknet from 'starknet'; + +export {starknet, getStarknet}; diff --git a/src/libs/web3.js b/src/libs/web3.js new file mode 100644 index 00000000..7b01ddee --- /dev/null +++ b/src/libs/web3.js @@ -0,0 +1,10 @@ +import Web3 from 'web3'; + +let web3; +if (typeof window.ethereum !== 'undefined' || typeof window.web3 !== 'undefined') { + web3 = new Web3(window.ethereum || window.web3.currentProvider); +} else { + web3 = new Web3(); +} + +export {web3}; diff --git a/src/providers/BlockHashProvider/BlockHashProvider.js b/src/providers/BlockHashProvider/BlockHashProvider.js index 5bbb0fee..5c48229b 100644 --- a/src/providers/BlockHashProvider/BlockHashProvider.js +++ b/src/providers/BlockHashProvider/BlockHashProvider.js @@ -1,8 +1,8 @@ import PropTypes from 'prop-types'; import React, {useCallback, useEffect, useState} from 'react'; -import {starknet} from '../../blockchain'; import {useConfig} from '../../hooks'; +import {starknet} from '../../libs'; import {BlockHashContext} from './block-hash-context'; export const BlockHashProvider = ({children}) => { diff --git a/src/providers/TransfersProvider/TransfersProvider.js b/src/providers/TransfersProvider/TransfersProvider.js index 1998c3d2..d1d40662 100644 --- a/src/providers/TransfersProvider/TransfersProvider.js +++ b/src/providers/TransfersProvider/TransfersProvider.js @@ -2,10 +2,10 @@ import PropTypes from 'prop-types'; import React, {useEffect, useReducer} from 'react'; import useDeepCompareEffect from 'use-deep-compare-effect'; -import {starknet} from '../../blockchain'; import constants from '../../config/constants'; import {isCompleted} from '../../enums'; import {useLogger} from '../../hooks'; +import {starknet} from '../../libs'; import {StorageManager} from '../../services'; import {useBlockHash} from '../BlockHashProvider'; import {TransfersContext} from './transfers-context'; diff --git a/src/providers/WalletsProvider/WalletsProvider.js b/src/providers/WalletsProvider/WalletsProvider.js index 43e0d674..28bdae4f 100644 --- a/src/providers/WalletsProvider/WalletsProvider.js +++ b/src/providers/WalletsProvider/WalletsProvider.js @@ -2,10 +2,10 @@ import PropTypes from 'prop-types'; import React, {useEffect, useReducer} from 'react'; import {useWallet} from 'use-wallet'; -import {getStarknet} from '../../blockchain'; import {useIsL1, useIsL2} from '../../components/Features/Transfer/Transfer.hooks'; import {WalletStatus} from '../../enums'; import {useConfig} from '../../hooks'; +import {getStarknet} from '../../libs'; import {WalletsContext} from './wallets-context'; import {actions, initialState, reducer} from './wallets-reducer'; diff --git a/src/services/wallet-handlers/argent-handler.js b/src/services/wallet-handlers/argent-handler.js index 3be9cea7..f4c530df 100644 --- a/src/services/wallet-handlers/argent-handler.js +++ b/src/services/wallet-handlers/argent-handler.js @@ -1,4 +1,4 @@ -import {getStarknet} from '../../blockchain'; +import {getStarknet} from '../../libs'; export class ArgentHandler { constructor(config) { diff --git a/src/blockchain/starknet.js b/src/utils/blockchain.js similarity index 50% rename from src/blockchain/starknet.js rename to src/utils/blockchain.js index 406a5da9..d10bf011 100644 --- a/src/blockchain/starknet.js +++ b/src/utils/blockchain.js @@ -1,9 +1,7 @@ -import {getStarknet} from '@argent/get-starknet'; -import * as starknetJS from 'starknet'; +import {isRejected, TransactionStatusStep} from '../enums'; +import {getStarknet, starknet as starknetjs, web3} from '../libs'; -import {getLogger} from '../services'; - -const {compileCalldata, Contract, defaultProvider, stark} = starknetJS; +const {compileCalldata, Contract, defaultProvider, stark} = starknetjs; const starknet = { createContract: (address, ABI) => { @@ -29,36 +27,56 @@ const starknet = { return Promise.reject(ex); } }, - waitForTransaction: async (hash, customStatus, retryInterval = 5000) => { - const logger = getLogger('l2_waitForTransaction'); - return new Promise(resolve => { + waitForTransaction: async (transactionHash, requiredStatus, retryInterval = 5000) => { + return new Promise((resolve, reject) => { let processing = false; - const waitingForStatuses = customStatus ? [customStatus] : TransactionConsumedStatuses; - logger.debug(`Waiting for transaction with statuses ${waitingForStatuses.join(' ')}`); const intervalId = setInterval(async () => { if (processing) return; - logger.debug(`Checking transaction again`); - const statusPromise = defaultProvider.getTransactionStatus(hash); + const statusPromise = defaultProvider.getTransactionStatus(transactionHash); processing = true; try { const {tx_status} = await statusPromise; - logger.debug(`Transaction status is ${tx_status}`); - if (waitingForStatuses.includes(tx_status)) { - logger.debug(`We got our desired status!`); + if ( + tx_status === requiredStatus || + (TransactionStatusStep[tx_status] > TransactionStatusStep[requiredStatus] && + !isRejected(tx_status)) + ) { + clearInterval(intervalId); + resolve(tx_status); + } else if (isRejected(tx_status)) { clearInterval(intervalId); - resolve(); + reject(); } else { - logger.debug(`We haven't got our desired status, trying again.`); processing = false; } } catch (ex) { - logger.error(`Error while calling get status: ${ex.message}, trying again.`); processing = false; } }, retryInterval); }); + } +}; + +const ethereum = { + createContract: (address, ABI) => { + return new web3.eth.Contract(ABI, address); }, - ...starknetJS + callContract: async (contract, method, args = []) => { + try { + return await contract.methods?.[method](...args).call(); + } catch (ex) { + return Promise.reject(ex); + } + }, + sendTransaction: async (contract, method, args = [], options = {}, cb = () => {}) => { + try { + return contract.methods?.[method](...args).send(options, cb); + } catch (ex) { + return Promise.reject(ex); + } + } }; -export {starknet, getStarknet}; +const blockchain = {starknet, ethereum}; + +export default blockchain; diff --git a/src/utils/hash.js b/src/utils/hash.js index d3a149b0..f17bce92 100644 --- a/src/utils/hash.js +++ b/src/utils/hash.js @@ -1,5 +1,5 @@ -import {starknet} from '../blockchain'; import {byChainId} from '../enums'; +import {starknet} from '../libs'; export const txHash = ( txHashPrefix, diff --git a/src/utils/index.js b/src/utils/index.js index 896165a8..ce67ef28 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -7,3 +7,4 @@ export * from './hash'; export * from './date'; export * from './object'; export * from './helpers'; +export * from './blockchain'; diff --git a/src/utils/parser.js b/src/utils/parser.js index aaf93002..e122a489 100644 --- a/src/utils/parser.js +++ b/src/utils/parser.js @@ -1,4 +1,4 @@ -import {web3, starknet} from '../blockchain'; +import {web3, starknet} from '../libs'; const {number, uint256} = starknet; const {utils} = web3; From 6aa3b88d76764516ab942d8c9805639e85b1fb78 Mon Sep 17 00:00:00 2001 From: Dan Ziv Date: Mon, 21 Mar 2022 14:51:57 +0200 Subject: [PATCH 4/5] utils --- .../utils/blockchain/starknet.spec.js | 32 ++++++++ src/__tests__/utils/date.spec.js | 4 +- src/__tests__/utils/hash.spec.js | 30 +------ src/__tests__/utils/object.spec.js | 4 +- src/__tests__/utils/parser.spec.js | 6 +- .../storage.spec.js} | 32 ++++---- src/__tests__/utils/string.spec.js | 4 +- src/__tests__/utils/token.spec.js | 4 +- src/__tests__/utils/wallet.spec.js | 4 +- src/api/bridge.js | 25 +++--- src/api/erc20.js | 21 ++--- .../Containers/Footer/Footer.strings.js | 4 +- src/components/Containers/Header/Header.js | 12 +-- .../Containers/Header/Header.strings.js | 6 +- src/components/Features/Account/Account.js | 4 +- .../Features/Account/Account.strings.js | 5 +- src/components/Features/Login/Login.js | 8 +- .../Features/Login/Login.strings.js | 8 +- .../ModalProvider/ModalProvider.strings.js | 4 +- .../SelectToken/SelectToken.strings.js | 4 +- .../Features/ToastProvider/ToastProvider.js | 8 +- .../ToastProvider/ToastProvider.strings.js | 4 +- .../Features/Transfer/Transfer.strings.js | 9 +- .../Features/TransferLog/TransferLog.js | 6 +- .../TransferLog/TransferLog.strings.js | 4 +- .../UI/AccountAddress/AccountAddress.js | 4 +- .../AccountAddress/AccountAddress.strings.js | 4 +- .../UI/BackButton/BackButton.strings.js | 4 +- src/components/UI/Button/Button.js | 4 +- src/components/UI/Icon/Icon.js | 4 +- src/components/UI/Input/Input.js | 4 +- src/components/UI/LinkButton/LinkButton.js | 6 +- .../UI/LogoutButton/LogoutButton.strings.js | 4 +- .../UI/MaxButton/MaxButton.strings.js | 4 +- src/components/UI/Menu/Menu.js | 4 +- src/components/UI/Modal/Modal/Modal.js | 6 +- .../UI/Modal/ModalBody/ModalBody.js | 4 +- .../UI/Modal/ModalHeader/ModalHeader.js | 4 +- .../TransactionSubmittedModal.constants.js | 4 +- .../TransactionSubmittedModal.js | 4 +- .../TransactionSubmittedModal.strings.js | 6 +- .../UI/NetworkMenu/NetworkMenu.strings.js | 4 +- src/components/UI/NetworkSwap/NetworkSwap.js | 7 +- .../UI/SearchToken/SearchToken.strings.js | 4 +- .../UI/SelectTokenRow/SelectTokenRow.js | 6 +- .../CompleteTransferToL1Toast.strings.js | 4 +- .../Toast/ToastFooter/ToastFooter.strings.js | 4 +- .../TransferToast/TransferToast.strings.js | 4 +- .../UI/TokenBalance/TokenBalance.js | 4 +- .../UI/TokenBalance/TokenBalance.strings.js | 4 +- src/components/UI/TokenInput/TokenInput.js | 4 +- .../UI/TokenInput/TokenInput.strings.js | 4 +- .../TransferButton/TransferButton.strings.js | 4 +- .../TransferLogContainer.js | 4 +- .../TransferLogContainer.strings.js | 4 +- .../UI/TransferMenuTab/TransferMenuTab.js | 7 +- .../UI/WalletButton/WalletButton.js | 4 +- .../UI/WalletButton/WalletButton.strings.js | 4 +- src/components/UI/WalletLogin/WalletLogin.js | 6 +- .../addresses/contracts/contracts.l1.js | 2 +- src/config/constants.js | 10 +-- src/hooks/useContract.js | 14 ++-- src/hooks/useEventListener.js | 12 +-- src/hooks/useLogger.js | 4 +- src/hooks/useTokenBalance.js | 4 +- src/hooks/useTransfer.js | 9 +- src/hooks/useTransferProgress.js | 16 ++-- src/hooks/useWalletHandlerProvider.js | 6 +- src/index.js | 9 +- .../TransfersProvider/TransfersProvider.js | 6 +- src/services/index.js | 3 - src/services/wallet-handlers/index.js | 2 - src/utils/blockchain.js | 82 ------------------- src/utils/blockchain/ethereum.js | 21 +++++ src/utils/blockchain/index.js | 2 + src/utils/blockchain/starknet.js | 81 ++++++++++++++++++ src/utils/hash.js | 23 ------ src/utils/helpers.js | 12 --- src/utils/index.js | 51 +++++++++--- src/{services => utils}/logger.js | 0 .../storage-manager.js => utils/storage.js} | 31 ++++--- .../argent-handler.js => wallets/argent-x.js} | 4 +- src/wallets/index.js | 2 + .../metamask.js} | 2 +- 84 files changed, 428 insertions(+), 384 deletions(-) create mode 100644 src/__tests__/utils/blockchain/starknet.spec.js rename src/__tests__/{services/storage-manager.spec.js => utils/storage.spec.js} (66%) delete mode 100644 src/services/index.js delete mode 100644 src/services/wallet-handlers/index.js delete mode 100644 src/utils/blockchain.js create mode 100644 src/utils/blockchain/ethereum.js create mode 100644 src/utils/blockchain/index.js create mode 100644 src/utils/blockchain/starknet.js delete mode 100644 src/utils/helpers.js rename src/{services => utils}/logger.js (100%) rename src/{services/storage-manager.js => utils/storage.js} (72%) rename src/{services/wallet-handlers/argent-handler.js => wallets/argent-x.js} (72%) create mode 100644 src/wallets/index.js rename src/{services/wallet-handlers/metamask-handler.js => wallets/metamask.js} (91%) diff --git a/src/__tests__/utils/blockchain/starknet.spec.js b/src/__tests__/utils/blockchain/starknet.spec.js new file mode 100644 index 00000000..ca875df9 --- /dev/null +++ b/src/__tests__/utils/blockchain/starknet.spec.js @@ -0,0 +1,32 @@ +import {ChainType, TransactionHashPrefix} from '../../../enums'; +import utils from '../../../utils'; + +describe('starknet', () => { + describe('getTransactionHash', () => { + it('should calc tx hash', () => { + const from_address = '0xcf98f0a8edc6a730e1ca6b64a2528c6be031cb12'; + const to_address = + '1384622289134235426972866085149619554404298343372540338336104355150443775597'; + const selector = + '1285101517810983806491589552491143496277809242732141897358598292095611420389'; + const nonce = '55'; + const payload = [ + '17466514784613283928575916580398045172482824287888203092305238190565527099', + '52145000000000', + '0' + ]; + + expect( + utils.blockchain.starknet.getTransactionHash( + TransactionHashPrefix.L1_HANDLER, + from_address, + to_address, + selector, + payload, + ChainType.GOERLI.id, + nonce + ) + ).toEqual('0x35ab0e4de971ac0736844ef36a05796dc41490c165373923c423f4b995983e8'); + }); + }); +}); diff --git a/src/__tests__/utils/date.spec.js b/src/__tests__/utils/date.spec.js index c33f6de0..eb37c374 100644 --- a/src/__tests__/utils/date.spec.js +++ b/src/__tests__/utils/date.spec.js @@ -1,4 +1,6 @@ -import {get24Time, getDate} from '../../utils'; +import utils from '../../utils'; + +const {get24Time, getDate} = utils.date; describe('getDate', () => { it('should get date', () => { diff --git a/src/__tests__/utils/hash.spec.js b/src/__tests__/utils/hash.spec.js index af417a88..a24e9303 100644 --- a/src/__tests__/utils/hash.spec.js +++ b/src/__tests__/utils/hash.spec.js @@ -1,32 +1,6 @@ -import {ChainType, TransactionHashPrefix} from '../../enums'; -import {hashEquals, txHash} from '../../utils'; +import utils from '../../utils'; -describe('txHash', () => { - it('should calc tx hash', () => { - const from_address = '0xcf98f0a8edc6a730e1ca6b64a2528c6be031cb12'; - const to_address = - '1384622289134235426972866085149619554404298343372540338336104355150443775597'; - const selector = '1285101517810983806491589552491143496277809242732141897358598292095611420389'; - const nonce = '55'; - const payload = [ - '17466514784613283928575916580398045172482824287888203092305238190565527099', - '52145000000000', - '0' - ]; - - expect( - txHash( - TransactionHashPrefix.L1_HANDLER, - from_address, - to_address, - selector, - payload, - ChainType.GOERLI.id, - nonce - ) - ).toEqual('0x35ab0e4de971ac0736844ef36a05796dc41490c165373923c423f4b995983e8'); - }); -}); +const {hashEquals} = utils.hash; describe('hashEquals', () => { it('should compare hashes', () => { diff --git a/src/__tests__/utils/object.spec.js b/src/__tests__/utils/object.spec.js index 2611e903..8f96cde9 100644 --- a/src/__tests__/utils/object.spec.js +++ b/src/__tests__/utils/object.spec.js @@ -1,4 +1,6 @@ -import {evaluate, findIndexById, getPropertyPath, toClasses} from '../../utils'; +import utils from '../../utils'; + +const {evaluate, findIndexById, getPropertyPath, toClasses} = utils.object; describe('getPropertyPath', () => { const obj = { diff --git a/src/__tests__/utils/parser.spec.js b/src/__tests__/utils/parser.spec.js index 1f2c1f28..37ef3626 100644 --- a/src/__tests__/utils/parser.spec.js +++ b/src/__tests__/utils/parser.spec.js @@ -1,11 +1,13 @@ -import { +import utils from '../../utils'; + +const { parseFromDecimals, parseFromFelt, parseFromUint256, parseToDecimals, parseToUint256, UNIT_MAP -} from '../../utils'; +} = utils.parser; describe('UNIT_MAP', () => { it('should init unit map', () => { diff --git a/src/__tests__/services/storage-manager.spec.js b/src/__tests__/utils/storage.spec.js similarity index 66% rename from src/__tests__/services/storage-manager.spec.js rename to src/__tests__/utils/storage.spec.js index 9eefc3ba..fdfb97fb 100644 --- a/src/__tests__/services/storage-manager.spec.js +++ b/src/__tests__/utils/storage.spec.js @@ -1,4 +1,6 @@ -import {StorageManager} from '../../services'; +import utils from '../../utils'; + +const {getItem, setItem} = utils.storage; class LocalStorageMock { constructor() { @@ -33,14 +35,14 @@ describe('StorageManager', () => { }); it('should return null for empty key', () => { - expect(StorageManager.getItem('test')).toBeNull(); + expect(getItem('test')).toBeNull(); }); it('should get item hash from local storage', () => { - StorageManager.setItem('testObject', testObject); - StorageManager.setItem('testArray', testArray); - StorageManager.setItem('testNumber', testNumber); - StorageManager.setItem('testString', testString); + setItem('testObject', testObject); + setItem('testArray', testArray); + setItem('testNumber', testNumber); + setItem('testString', testString); expect(localStorage.getItem('testObject')).toEqual( 'eyIwIjoiZXc9PSIsIjEiOiJJZz09IiwiMiI6IllRPT0iLCIzIjoiSWc9PSIsIjQiOiJPZz09IiwiNSI6Ik1RPT0iLCI2IjoiZlE9PSJ9' ); @@ -54,21 +56,21 @@ describe('StorageManager', () => { }); it('should get item from storage manager', () => { - StorageManager.setItem('testObject', testObject); - StorageManager.setItem('testArray', testArray); - StorageManager.setItem('testNumber', testNumber); - StorageManager.setItem('testString', testString); - expect(StorageManager.getItem('testObject')).toEqual(testObject); - expect(StorageManager.getItem('testArray')).toEqual(testArray); - expect(StorageManager.getItem('testNumber')).toEqual(testNumber); - expect(StorageManager.getItem('testString')).toEqual(testString); + setItem('testObject', testObject); + setItem('testArray', testArray); + setItem('testNumber', testNumber); + setItem('testString', testString); + expect(getItem('testObject')).toEqual(testObject); + expect(getItem('testArray')).toEqual(testArray); + expect(getItem('testNumber')).toEqual(testNumber); + expect(getItem('testString')).toEqual(testString); }); it('should backward compatible for saved arrays', () => { const jsonArray = JSON.stringify(testArray); localStorage.setItem('test', jsonArray); expect(localStorage.getItem('test')).toEqual(jsonArray); - expect(StorageManager.getItem('test')).toEqual(testArray); + expect(getItem('test')).toEqual(testArray); expect(localStorage.getItem('test')).toEqual( 'eyIwIjoiV3c9PSIsIjEiOiJldz09IiwiMiI6IklnPT0iLCIzIjoiWVE9PSIsIjQiOiJJZz09IiwiNSI6Ik9nPT0iLCI2IjoiTVE9PSIsIjciOiJmUT09IiwiOCI6IlhRPT0ifQ==' ); diff --git a/src/__tests__/utils/string.spec.js b/src/__tests__/utils/string.spec.js index ce74fb5e..e8ac381d 100644 --- a/src/__tests__/utils/string.spec.js +++ b/src/__tests__/utils/string.spec.js @@ -1,4 +1,6 @@ -import {capitalize} from '../../utils'; +import utils from '../../utils'; + +const {capitalize} = utils.string; describe('capitalize', () => { it('should capitalize string', () => { diff --git a/src/__tests__/utils/token.spec.js b/src/__tests__/utils/token.spec.js index f7470b0b..a6de7b7c 100644 --- a/src/__tests__/utils/token.spec.js +++ b/src/__tests__/utils/token.spec.js @@ -1,4 +1,6 @@ -import {isEth} from '../../utils'; +import utils from '../../utils'; + +const {isEth} = utils.token; describe('isEth', () => { it('should return true for eth symbol as string', () => { diff --git a/src/__tests__/utils/wallet.spec.js b/src/__tests__/utils/wallet.spec.js index 148116f8..2011a6e0 100644 --- a/src/__tests__/utils/wallet.spec.js +++ b/src/__tests__/utils/wallet.spec.js @@ -1,4 +1,6 @@ -import {formatBalance, shortenAddress} from '../../utils'; +import utils from '../../utils'; + +const {formatBalance, shortenAddress} = utils.wallet; describe('formatBalance', () => { it('should format balance to 5 digits precision', () => { diff --git a/src/api/bridge.js b/src/api/bridge.js index 7b757199..2934e38c 100644 --- a/src/api/bridge.js +++ b/src/api/bridge.js @@ -1,12 +1,11 @@ -import {parseFromDecimals, parseToDecimals, parseToFelt, parseToUint256} from '../utils'; -import blockchainUtils from '../utils/blockchain'; +import utils from '../utils'; export const deposit = async ({recipient, amount, decimals, contract, options, emitter}) => { try { - return blockchainUtils.ethereum.sendTransaction( + return utils.blockchain.ethereum.sendTransaction( contract, 'deposit', - [parseToDecimals(amount, decimals), recipient], + [utils.parser.parseToDecimals(amount, decimals), recipient], options, emitter ); @@ -17,13 +16,13 @@ export const deposit = async ({recipient, amount, decimals, contract, options, e export const depositEth = async ({recipient, amount, contract, options, emitter}) => { try { - return blockchainUtils.ethereum.sendTransaction( + return utils.blockchain.ethereum.sendTransaction( contract, 'deposit', [recipient], { ...options, - value: parseToDecimals(amount) + value: utils.parser.parseToDecimals(amount) }, emitter ); @@ -34,10 +33,10 @@ export const depositEth = async ({recipient, amount, contract, options, emitter} export const withdraw = async ({recipient, amount, decimals, contract, emitter}) => { try { - return blockchainUtils.ethereum.sendTransaction( + return utils.blockchain.ethereum.sendTransaction( contract, 'withdraw', - [parseToDecimals(amount, decimals), recipient], + [utils.parser.parseToDecimals(amount, decimals), recipient], { from: recipient }, @@ -50,8 +49,8 @@ export const withdraw = async ({recipient, amount, decimals, contract, emitter}) export const maxDeposit = async ({decimals, contract}) => { try { - const maxDeposit = await blockchainUtils.ethereum.callContract(contract, 'maxDeposit'); - return parseFromDecimals(maxDeposit, decimals); + const maxDeposit = await utils.blockchain.ethereum.callContract(contract, 'maxDeposit'); + return utils.parser.parseFromDecimals(maxDeposit, decimals); } catch (ex) { return Promise.reject(ex); } @@ -59,9 +58,9 @@ export const maxDeposit = async ({decimals, contract}) => { export const initiateWithdraw = async ({recipient, amount, decimals, contract}) => { try { - return blockchainUtils.starknet.sendTransaction(contract, 'initiate_withdraw', { - l1Recipient: parseToFelt(recipient), - amount: parseToUint256(amount, decimals) + return utils.blockchain.starknet.sendTransaction(contract, 'initiate_withdraw', { + l1Recipient: utils.parser.parseToFelt(recipient), + amount: utils.parser.parseToUint256(amount, decimals) }); } catch (ex) { return Promise.reject(ex); diff --git a/src/api/erc20.js b/src/api/erc20.js index 7782680f..5f1336fa 100644 --- a/src/api/erc20.js +++ b/src/api/erc20.js @@ -1,11 +1,10 @@ import {TransactionStatus} from '../enums'; import {web3} from '../libs'; -import {parseFromDecimals, parseFromUint256} from '../utils'; -import blockchainUtils from '../utils/blockchain'; +import utils from '../utils'; export const approve = async ({spender, value, contract, options}) => { try { - return await blockchainUtils.ethereum.sendTransaction( + return await utils.blockchain.ethereum.sendTransaction( contract, 'approve', [spender, value], @@ -18,11 +17,11 @@ export const approve = async ({spender, value, contract, options}) => { export const allowance = async ({owner, spender, decimals, contract}) => { try { - const allow = await blockchainUtils.ethereum.callContract(contract, 'allowance', [ + const allow = await utils.blockchain.ethereum.callContract(contract, 'allowance', [ owner, spender ]); - return parseFromDecimals(allow, decimals); + return utils.parser.parseFromDecimals(allow, decimals); } catch (ex) { return Promise.reject(ex); } @@ -31,16 +30,18 @@ export const allowance = async ({owner, spender, decimals, contract}) => { export const balanceOf = async ({account, decimals, contract}, isL1 = true) => { try { if (isL1) { - const balance = await blockchainUtils.ethereum.callContract(contract, 'balanceOf', [account]); - return parseFromDecimals(balance, decimals); + const balance = await utils.blockchain.ethereum.callContract(contract, 'balanceOf', [ + account + ]); + return utils.parser.parseFromDecimals(balance, decimals); } else { - const {balance} = await blockchainUtils.starknet.callContract( + const {balance} = await utils.blockchain.starknet.callContract( contract, 'balanceOf', [{account}], TransactionStatus.PENDING.toLowerCase() ); - return parseFromUint256(balance, decimals); + return utils.parser.parseFromUint256(balance, decimals); } } catch (ex) { return Promise.reject(ex); @@ -50,7 +51,7 @@ export const balanceOf = async ({account, decimals, contract}, isL1 = true) => { export const ethBalanceOf = async account => { try { const balance = await web3.eth.getBalance(account); - return parseFromDecimals(balance); + return utils.parser.parseFromDecimals(balance); } catch (ex) { return Promise.reject(ex); } diff --git a/src/components/Containers/Footer/Footer.strings.js b/src/components/Containers/Footer/Footer.strings.js index 18d709b7..47454e13 100644 --- a/src/components/Containers/Footer/Footer.strings.js +++ b/src/components/Containers/Footer/Footer.strings.js @@ -1,3 +1,3 @@ -import {getTranslation} from '../../../utils'; +import utils from '../../../utils'; -export const RIGHTS_TXT = getTranslation('containers.footer.rights_txt'); +export const RIGHTS_TXT = utils.getTranslation('containers.footer.rights_txt'); diff --git a/src/components/Containers/Header/Header.js b/src/components/Containers/Header/Header.js index db863b52..442a3719 100644 --- a/src/components/Containers/Header/Header.js +++ b/src/components/Containers/Header/Header.js @@ -2,7 +2,7 @@ import React from 'react'; import {ReactComponent as StarkGateLogo} from '../../../assets/img/starkgate.svg'; import {useL1Wallet, useL2Wallet, useWallets} from '../../../providers/WalletsProvider'; -import {toClasses} from '../../../utils'; +import utils from '../../../utils'; import {useBridgeActions} from '../../Features/Bridge/Bridge.hooks'; import {useIsL1, useIsL2} from '../../Features/Transfer/Transfer.hooks'; import {WalletButton} from '../../UI'; @@ -32,17 +32,17 @@ export const Header = () => { }; return ( -
-
-
+
+
+
{isConnected && ( -
{CHAIN_TXT(chainName)}
+
{CHAIN_TXT(chainName)}
)}
-
+
{isL1AccountConnected && ( - capitalize(evaluate(getTranslation('containers.header.chain_txt'), {chainName})); + utils.string.capitalize( + utils.object.evaluate(utils.getTranslation('containers.header.chain_txt'), {chainName}) + ); diff --git a/src/components/Features/Account/Account.js b/src/components/Features/Account/Account.js index da8125a0..0b0de498 100644 --- a/src/components/Features/Account/Account.js +++ b/src/components/Features/Account/Account.js @@ -5,7 +5,7 @@ import constants from '../../../config/constants'; import {useCompleteTransferToL1} from '../../../hooks'; import {useAccountTransfers} from '../../../providers/TransfersProvider'; import {useWallets} from '../../../providers/WalletsProvider'; -import {findIndexById} from '../../../utils'; +import utils from '../../../utils'; import { AccountAddress, BackButton, @@ -57,7 +57,7 @@ export const Account = ({transferId}) => { {isL2 && ( )} - + {renderTransfers()} diff --git a/src/components/Features/Account/Account.strings.js b/src/components/Features/Account/Account.strings.js index d2ea9d22..4e104e7e 100644 --- a/src/components/Features/Account/Account.strings.js +++ b/src/components/Features/Account/Account.strings.js @@ -1,3 +1,4 @@ -import {evaluate, getTranslation} from '../../../utils'; +import utils from '../../../utils'; -export const TITLE_TXT = network => evaluate(getTranslation('menus.account.title_txt'), {network}); +export const TITLE_TXT = network => + utils.object.evaluate(utils.getTranslation('menus.account.title_txt'), {network}); diff --git a/src/components/Features/Login/Login.js b/src/components/Features/Login/Login.js index 0430fedb..ebfec0dd 100644 --- a/src/components/Features/Login/Login.js +++ b/src/components/Features/Login/Login.js @@ -3,7 +3,7 @@ import React, {useEffect, useRef, useState} from 'react'; import {NetworkType, toChainName, WalletStatus, WalletType} from '../../../enums'; import {useConfig, useWalletHandlerProvider} from '../../../hooks'; import {useL1Wallet, useL2Wallet, useWallets} from '../../../providers/WalletsProvider'; -import {capitalize, toClasses} from '../../../utils'; +import utils from '../../../utils'; import {Menu, WalletLogin} from '../../UI'; import {useHideModal, useProgressModal} from '../ModalProvider/ModalProvider.hooks'; import {AUTO_CONNECT_TIMEOUT_DURATION, MODAL_TIMEOUT_DURATION} from './Login.constants'; @@ -82,9 +82,9 @@ export const Login = () => { if (error.name === 'ChainUnsupportedError') { const msg = error.message.replace(/\d+/g, match => { let msg = match; - const chainName = capitalize(toChainName(Number(match))); + const chainName = utils.string.capitalize(toChainName(Number(match))); if (chainName) { - msg += ` (${capitalize(toChainName(Number(match)))})`; + msg += ` (${utils.string.capitalize(toChainName(Number(match)))})`; } return msg; }); @@ -126,7 +126,7 @@ export const Login = () => { return ( -
+
{TITLE_TXT}

diff --git a/src/components/Features/Login/Login.strings.js b/src/components/Features/Login/Login.strings.js index 83248e2d..b7c197b7 100644 --- a/src/components/Features/Login/Login.strings.js +++ b/src/components/Features/Login/Login.strings.js @@ -1,8 +1,8 @@ -import {evaluate, getTranslation} from '../../../utils'; +import utils from '../../../utils'; -const {title_txt, subtitle_txt, download_txt, modal_txt} = getTranslation('menus.login'); +const {title_txt, subtitle_txt, download_txt, modal_txt} = utils.getTranslation('menus.login'); export const TITLE_TXT = title_txt; export const DOWNLOAD_TEXT = download_txt; -export const SUBTITLE_TXT = networkName => evaluate(subtitle_txt, {networkName}); -export const MODAL_TXT = walletName => evaluate(modal_txt, {walletName}); +export const SUBTITLE_TXT = networkName => utils.object.evaluate(subtitle_txt, {networkName}); +export const MODAL_TXT = walletName => utils.object.evaluate(modal_txt, {walletName}); diff --git a/src/components/Features/ModalProvider/ModalProvider.strings.js b/src/components/Features/ModalProvider/ModalProvider.strings.js index bd02a0ff..e3bffdf1 100644 --- a/src/components/Features/ModalProvider/ModalProvider.strings.js +++ b/src/components/Features/ModalProvider/ModalProvider.strings.js @@ -1,5 +1,5 @@ -import {getTranslation} from '../../../utils'; +import utils from '../../../utils'; -export const TRANSACTION_SUBMITTED_TITLE_TXT = getTranslation( +export const TRANSACTION_SUBMITTED_TITLE_TXT = utils.getTranslation( 'modals.transactionSubmitted.title_txt' ); diff --git a/src/components/Features/SelectToken/SelectToken.strings.js b/src/components/Features/SelectToken/SelectToken.strings.js index c3ac8bcd..7a47146e 100644 --- a/src/components/Features/SelectToken/SelectToken.strings.js +++ b/src/components/Features/SelectToken/SelectToken.strings.js @@ -1,3 +1,3 @@ -import {getTranslation} from '../../../utils'; +import utils from '../../../utils'; -export const TITLE_TXT = getTranslation('menus.selectToken.title_txt'); +export const TITLE_TXT = utils.getTranslation('menus.selectToken.title_txt'); diff --git a/src/components/Features/ToastProvider/ToastProvider.js b/src/components/Features/ToastProvider/ToastProvider.js index 29c21a11..039325ef 100644 --- a/src/components/Features/ToastProvider/ToastProvider.js +++ b/src/components/Features/ToastProvider/ToastProvider.js @@ -13,10 +13,10 @@ import { } from '../../../enums'; import {useCompleteTransferToL1, usePrevious} from '../../../hooks'; import {useTransfers} from '../../../providers/TransfersProvider'; -import {getFullTime} from '../../../utils'; -import {useBridgeActions} from '../../Features/Bridge/Bridge.hooks'; -import {useIsL1, useIsL2} from '../../Features/Transfer/Transfer.hooks'; +import utils from '../../../utils'; import {ToastBody, TransferToast, CompleteTransferToL1Toast} from '../../UI'; +import {useBridgeActions} from '../Bridge/Bridge.hooks'; +import {useIsL1, useIsL2} from '../Transfer/Transfer.hooks'; import styles from './ToastProvider.module.scss'; import {ALPHA_DISCLAIMER_MSG} from './ToastProvider.strings'; @@ -162,7 +162,7 @@ export const TransferData = ({transfer, style}) => { style={style} /> - + ); }; diff --git a/src/components/Features/ToastProvider/ToastProvider.strings.js b/src/components/Features/ToastProvider/ToastProvider.strings.js index d4c23aa8..02f64783 100644 --- a/src/components/Features/ToastProvider/ToastProvider.strings.js +++ b/src/components/Features/ToastProvider/ToastProvider.strings.js @@ -1,3 +1,3 @@ -import {getTranslation} from '../../../utils'; +import utils from '../../../utils'; -export const ALPHA_DISCLAIMER_MSG = getTranslation('toasts.alpha_disclaimer_msg'); +export const ALPHA_DISCLAIMER_MSG = utils.getTranslation('toasts.alpha_disclaimer_msg'); diff --git a/src/components/Features/Transfer/Transfer.strings.js b/src/components/Features/Transfer/Transfer.strings.js index 2f73c068..144245b1 100644 --- a/src/components/Features/Transfer/Transfer.strings.js +++ b/src/components/Features/Transfer/Transfer.strings.js @@ -1,8 +1,11 @@ -import {evaluate, getTranslation} from '../../../utils'; +import utils from '../../../utils'; -export const INSUFFICIENT_BALANCE_ERROR_MSG = getTranslation( +export const INSUFFICIENT_BALANCE_ERROR_MSG = utils.getTranslation( 'menus.transfer.insufficient_balance_error_msg' ); export const MAX_AMOUNT_ERROR_MSG = (maxAmount, symbol) => - evaluate(getTranslation('menus.transfer.max_amount_error_msg'), {maxAmount, symbol}); + utils.object.evaluate(utils.getTranslation('menus.transfer.max_amount_error_msg'), { + maxAmount, + symbol + }); diff --git a/src/components/Features/TransferLog/TransferLog.js b/src/components/Features/TransferLog/TransferLog.js index 628d3e29..db9d2ec6 100644 --- a/src/components/Features/TransferLog/TransferLog.js +++ b/src/components/Features/TransferLog/TransferLog.js @@ -11,7 +11,7 @@ import { } from '../../../enums'; import {useColors} from '../../../hooks'; import {useWallets} from '../../../providers/WalletsProvider'; -import {getFullTime, toClasses} from '../../../utils'; +import utils from '../../../utils'; import {Button, CryptoLogo} from '../../UI'; import {CryptoLogoSize} from '../../UI/CryptoLogo/CryptoLogo.enums'; import {LinkButton} from '../../UI/LinkButton/LinkButton'; @@ -33,7 +33,7 @@ export const TransferLog = ({transfer, onCompleteTransferClick}) => { const renderTransferStatus = () => { return !isOnChain(status) ? ( -

+
{TransactionStatusFriendlyMessage[status]}
) : null; @@ -70,7 +70,7 @@ export const TransferLog = ({transfer, onCompleteTransferClick}) => {
{name} -
{`${getFullTime(timestamp)}`}
+
{`${utils.date.getFullTime(timestamp)}`}
diff --git a/src/components/Features/TransferLog/TransferLog.strings.js b/src/components/Features/TransferLog/TransferLog.strings.js index 251234d1..bde1cb8e 100644 --- a/src/components/Features/TransferLog/TransferLog.strings.js +++ b/src/components/Features/TransferLog/TransferLog.strings.js @@ -1,5 +1,5 @@ -import {getTranslation} from '../../../utils'; +import utils from '../../../utils'; -export const COMPLETE_TRANSFER_BTN_TXT = getTranslation( +export const COMPLETE_TRANSFER_BTN_TXT = utils.getTranslation( 'menus.account.transferLogContainer.transferLog.complete_transfer_btn_txt' ); diff --git a/src/components/UI/AccountAddress/AccountAddress.js b/src/components/UI/AccountAddress/AccountAddress.js index 35a3fa66..fd7a31de 100644 --- a/src/components/UI/AccountAddress/AccountAddress.js +++ b/src/components/UI/AccountAddress/AccountAddress.js @@ -3,7 +3,7 @@ import React, {useRef} from 'react'; import {ReactComponent as CopyIcon} from '../../../assets/svg/icons/copy.svg'; import {useAnimation} from '../../../hooks'; -import {toClasses} from '../../../utils'; +import utils from '../../../utils'; import {COPIED_ANIMATION_TIMEOUT_INTERVAL} from './AccountAddress.constants'; import styles from './AccountAddress.module.scss'; import {COPIED_MSG_TXT} from './AccountAddress.strings'; @@ -24,7 +24,7 @@ export const AccountAddress = ({address}) => { {address.length <= 42 ? address : `${address.substring(0, 42)}...`}
-
+
{COPIED_MSG_TXT}
diff --git a/src/components/UI/AccountAddress/AccountAddress.strings.js b/src/components/UI/AccountAddress/AccountAddress.strings.js index 7798d6b4..18044439 100644 --- a/src/components/UI/AccountAddress/AccountAddress.strings.js +++ b/src/components/UI/AccountAddress/AccountAddress.strings.js @@ -1,3 +1,3 @@ -import {getTranslation} from '../../../utils'; +import utils from '../../../utils'; -export const COPIED_MSG_TXT = getTranslation('menus.account.copied_msg_txt'); +export const COPIED_MSG_TXT = utils.getTranslation('menus.account.copied_msg_txt'); diff --git a/src/components/UI/BackButton/BackButton.strings.js b/src/components/UI/BackButton/BackButton.strings.js index 5893b227..35101268 100644 --- a/src/components/UI/BackButton/BackButton.strings.js +++ b/src/components/UI/BackButton/BackButton.strings.js @@ -1,3 +1,3 @@ -import {getTranslation} from '../../../utils'; +import utils from '../../../utils'; -export const BTN_TXT = getTranslation('menus.back_btn_txt'); +export const BTN_TXT = utils.getTranslation('menus.back_btn_txt'); diff --git a/src/components/UI/Button/Button.js b/src/components/UI/Button/Button.js index ef0bf706..5ad3479a 100644 --- a/src/components/UI/Button/Button.js +++ b/src/components/UI/Button/Button.js @@ -1,7 +1,7 @@ import PropTypes from 'prop-types'; import React, {useState} from 'react'; -import {toClasses} from '../../../utils'; +import utils from '../../../utils'; import {Loading} from '../Loading/Loading'; import {LoadingSize} from '../Loading/Loading.enums'; import styles from './Button.module.scss'; @@ -35,7 +35,7 @@ export const Button = ({ return (