From d307bcc7a9495986cd46c0c17f1d649b1b8a5ca3 Mon Sep 17 00:00:00 2001 From: vnaysngh Date: Sun, 28 Jul 2024 23:22:44 +0530 Subject: [PATCH] web wallet fixes --- src/context/StarknetProvider.tsx | 13 ++++---- src/pages/AddLiquidity/index.tsx | 55 +++++++++++++------------------- src/pages/Pool/PositionPage.tsx | 34 ++++++++------------ src/pages/RemoveLiquidity/V3.tsx | 43 +++++++++++-------------- src/pages/Rewards/index.tsx | 38 ++++++++++------------ src/pages/Swap/index.tsx | 36 ++++++++------------- src/pages/Vault/index.tsx | 40 +++++++++-------------- 7 files changed, 108 insertions(+), 151 deletions(-) diff --git a/src/context/StarknetProvider.tsx b/src/context/StarknetProvider.tsx index ae5ccb58..730d0600 100644 --- a/src/context/StarknetProvider.tsx +++ b/src/context/StarknetProvider.tsx @@ -19,12 +19,12 @@ export const connectors = [ new InjectedConnector({ options: { id: 'braavos', name: 'Braavos' } }), new InjectedConnector({ options: { id: 'argentX', name: 'Argent X' } }), new InjectedConnector({ options: { id: 'okxwallet', name: 'OKX' } }), - // new WebWalletConnector({ - // url: isTestnet ? 'https://web.hydrogen.argent47.net' : 'https://web.argent.xyz/', - // provider: new RpcProvider({ - // nodeUrl: 'https://api-starknet-mainnet.dwellir.com/dd28e566-3260-4d8d-8180-6ef1a161e41c', - // }), - // }), + new WebWalletConnector({ + url: isTestnet ? 'https://web.hydrogen.argent47.net' : 'https://web.argent.xyz/', + provider: new RpcProvider({ + nodeUrl: 'https://api-starknet-mainnet.dwellir.com/dd28e566-3260-4d8d-8180-6ef1a161e41c', + }), + }), new ArgentMobileConnector({ projectId: '4b1e5f71ad6f3397afaf5cf19d816ca2', dappName: 'Jediswap Interface', @@ -57,7 +57,6 @@ export const getConnectorDiscovery = (id: string) => { if (walletData.downloads && typeof navigator !== 'undefined') { const browser = getBrowser(navigator.userAgent) - console.log('browser') return walletData.downloads[browser as keyof typeof walletData.downloads] ?? walletData.website } diff --git a/src/pages/AddLiquidity/index.tsx b/src/pages/AddLiquidity/index.tsx index d65989b3..993288a3 100644 --- a/src/pages/AddLiquidity/index.tsx +++ b/src/pages/AddLiquidity/index.tsx @@ -66,8 +66,7 @@ import { Dots } from '../Pool/styled' import { Review } from './Review' import { DynamicSection, MediumOnly, ResponsiveTwoColumns, ScrollablePage, StyledInput, Wrapper } from './styled' import { useAccountDetails, useWalletConnect } from 'hooks/starknet-react' -import { useContractWrite, useProvider } from '@starknet-react/core' -import { BigNumberish, cairo, Call, CallData, hash, num } from 'starknet' +import { BigNumberish, cairo, Call, CallData, hash, InvokeFunctionResponse, num } from 'starknet' import JSBI from 'jsbi' import { toI32 } from 'utils/toI32' import { useApprovalCall } from 'hooks/useApproveCall' @@ -105,7 +104,7 @@ function AddLiquidity() { feeAmount?: string tokenId?: string }>() - const { address: account, chainId } = useAccountDetails() + const { address, account, chainId } = useAccountDetails() const theme = useTheme() const { openModal } = useWalletModal() const toggleWalletDrawer = useWalletConnect() // toggle wallet when disconnected @@ -165,9 +164,21 @@ function AddLiquidity() { const { onFieldAInput, onFieldBInput, onLeftRangeInput, onRightRangeInput, onStartPriceInput } = useV3MintActionHandlers(noLiquidity) - const { writeAsync, data: txData } = useContractWrite({ - calls: mintCallData, - }) + useEffect(() => { + const executeTransaction = async () => { + try { + const response: any = await account?.execute(mintCallData) + setAttemptingTxn(false) + if (response?.transaction_hash) { + setTxHash(response.transaction_hash) + } + } catch (error) { + console.error('Error executing transaction:', error) + setAttemptingTxn(false) + } + } + if (mintCallData && mintCallData.length && account) executeTransaction() + }, [mintCallData, account]) const isValid = !errorMessage && !invalidRange @@ -276,34 +287,14 @@ function AddLiquidity() { } }, [separatedFiatValueofLiquidity]) - useEffect(() => { - if (txData) console.log(txData, 'txData') - }, [txData]) - useEffect(() => { if (chainId) { if (chainId === ChainId.GOERLI) setShowWarning(false) } }, [chainId]) - useEffect(() => { - if (mintCallData) { - writeAsync() - .then((response) => { - setAttemptingTxn(false) - if (response?.transaction_hash) { - setTxHash(response.transaction_hash) - } - }) - .catch((err) => { - console.log(err?.message) - setAttemptingTxn(false) - }) - } - }, [mintCallData]) - async function onAdd() { - if (!chainId || !account) { + if (!chainId || !address) { return } @@ -319,7 +310,7 @@ function AddLiquidity() { if (parsedAmounts[Field.CURRENCY_B] && Number(parsedAmounts?.[Field.CURRENCY_B]?.raw.toString()) > 0) approvalB = approvalBCallback() - if (position && account && deadline) { + if (position && address && deadline) { // get amounts const { amount0: amount0Desired, amount1: amount1Desired } = position.mintAmounts @@ -389,7 +380,7 @@ function AddLiquidity() { amount1_desired: cairo.uint256(amount1Desired.toString()), amount0_min: cairo.uint256(amount0Min.toString()), amount1_min: cairo.uint256(amount1Min.toString()), - recipient: account, + recipient: address, deadline: cairo.felt(deadline.toString()), } const mintCallData = CallData.compile(mintData) @@ -566,7 +557,7 @@ function AddLiquidity() { // END: sync values with query string const Buttons = () => - !account ? ( + !address ? ( Connect wallet @@ -588,8 +579,8 @@ function AddLiquidity() { // const owner = useSingleCallResult(tokenId ? positionManager : null, 'ownerOf', [tokenId]).result?.[0] // const ownsNFT = - // addressesAreEquivalent(owner, account) || addressesAreEquivalent(existingPositionDetails?.operator, account) - // const showOwnershipWarning = Boolean(hasExistingPosition && account && !ownsNFT) + // addressesAreEquivalent(owner, address) || addressesAreEquivalent(existingPositionDetails?.operator, address) + // const showOwnershipWarning = Boolean(hasExistingPosition && address && !ownsNFT) return ( <> diff --git a/src/pages/Pool/PositionPage.tsx b/src/pages/Pool/PositionPage.tsx index c0d27572..91c4b44d 100644 --- a/src/pages/Pool/PositionPage.tsx +++ b/src/pages/Pool/PositionPage.tsx @@ -48,7 +48,6 @@ import { SwitchLocaleLink } from '../../components/SwitchLocaleLink' import { useV3PositionTokenURI } from '../../hooks/usePositionTokenURI' import { ExplorerDataType, getExplorerLink } from '../../utils/getExplorerLink' import { LoadingRows } from './styled' -import { useContractWrite } from '@starknet-react/core' import { cairo, Call, CallData, validateAndParseAddress } from 'starknet' import { DEFAULT_CHAIN_ID, MAX_UINT128, NONFUNGIBLE_POOL_MANAGER_ADDRESS } from 'constants/tokens' import TokensList from 'data/tokens-list.json' @@ -703,9 +702,20 @@ function PositionPageContent() { const isCollectPending = useIsTransactionPending(collectMigrationHash ?? undefined) const [showConfirm, setShowConfirm] = useState(false) const [callData, setCallData] = useState([]) - const { writeAsync, data: txData } = useContractWrite({ - calls: callData, - }) + + useEffect(() => { + const executeTransaction = async () => { + try { + const response: any = await account?.execute(callData) + setCollecting(false) + if (response?.transaction_hash) setTxHash(response.transaction_hash) + } catch (error) { + console.error('Error executing transaction:', error) + setCollecting(false) + } + } + if (callData && callData.length && account) executeTransaction() + }, [callData, account]) const fiatPrices = useQuery({ queryKey: [`fiat_prices_position/${tokenId}/${position?.amount0.toSignificant()}`], @@ -731,22 +741,6 @@ function PositionPageContent() { return undefined }, [token0usdValue, token1usdValue]) - useEffect(() => { - if (callData) { - writeAsync() - .then((response) => { - setCollecting(false) - if (response?.transaction_hash) { - setTxHash(response.transaction_hash) - } - }) - .catch((err) => { - console.log(err?.message) - setCollecting(false) - }) - } - }, [callData]) - const addTransaction = useTransactionAdder() const positionManager = useV3NFTPositionManagerContract() const collect = useCallback(async () => { diff --git a/src/pages/RemoveLiquidity/V3.tsx b/src/pages/RemoveLiquidity/V3.tsx index bbb6388b..95849c5c 100644 --- a/src/pages/RemoveLiquidity/V3.tsx +++ b/src/pages/RemoveLiquidity/V3.tsx @@ -38,7 +38,7 @@ import { ThemedText } from 'theme/components' import TransactionConfirmationModal, { ConfirmationModalContent } from '../../components/TransactionConfirmationModal' import AppBody from '../AppBody' import { ResponsiveHeaderText, SmallMaxButton, Wrapper } from './styled' -import { useContractWrite, useProvider } from '@starknet-react/core' +import { useProvider } from '@starknet-react/core' import { Call, CallData, cairo } from 'starknet' import { DEFAULT_CHAIN_ID, NONFUNGIBLE_POOL_MANAGER_ADDRESS } from '../../constants/tokens' import JSBI from 'jsbi' @@ -71,7 +71,7 @@ export default function RemoveLiquidityV3() { function Remove({ tokenId }: { tokenId: number }) { const { position } = useV3PosFromTokenId(tokenId) const theme = useTheme() - const { address: account, chainId } = useAccountDetails() + const { address, account, chainId } = useAccountDetails() const { provider } = useProvider() const trace = useTrace() @@ -107,31 +107,26 @@ function Remove({ tokenId }: { tokenId: number }) { const [attemptingTxn, setAttemptingTxn] = useState(false) const [txnHash, setTxnHash] = useState() const [mintCallData, setMintCallData] = useState([]) - const { writeAsync, data: txData } = useContractWrite({ - calls: mintCallData, - }) useEffect(() => { - if (chainId) { - if (chainId === ChainId.GOERLI) setShowWarning(false) + const executeTransaction = async () => { + try { + const response: any = await account?.execute(mintCallData) + if (response?.transaction_hash) setTxnHash(response.transaction_hash) + setAttemptingTxn(false) + } catch (error) { + console.error('Error executing transaction:', error) + setAttemptingTxn(false) + } } - }, [chainId]) + if (mintCallData && mintCallData.length && account) executeTransaction() + }, [mintCallData, account]) useEffect(() => { - if (mintCallData) { - writeAsync() - .then((response) => { - setAttemptingTxn(false) - if (response?.transaction_hash) { - setTxnHash(response.transaction_hash) - } - }) - .catch((err) => { - console.log(err?.message) - setAttemptingTxn(false) - }) + if (chainId) { + if (chainId === ChainId.GOERLI) setShowWarning(false) } - }, [mintCallData]) + }, [chainId]) const addTransaction = useTransactionAdder() const positionManager = useV3NFTPositionManagerContract() @@ -140,7 +135,7 @@ function Remove({ tokenId }: { tokenId: number }) { !liquidityValue0 || !liquidityValue1 || !deadline || - !account || + !address || !chainId || !positionSDK || !liquidityPercentage @@ -171,7 +166,7 @@ function Remove({ tokenId }: { tokenId: number }) { // } const collectFeeParams = { tokenId: cairo.uint256(tokenId), - recipient: account, + recipient: address, amount0_max: MAX_UINT128, amount1_max: MAX_UINT128, } @@ -197,7 +192,7 @@ function Remove({ tokenId }: { tokenId: number }) { liquidityValue0, liquidityValue1, deadline, - account, + address, chainId, positionSDK, liquidityPercentage, diff --git a/src/pages/Rewards/index.tsx b/src/pages/Rewards/index.tsx index 47cca369..7ec69e5d 100644 --- a/src/pages/Rewards/index.tsx +++ b/src/pages/Rewards/index.tsx @@ -14,7 +14,7 @@ import { CurrencyAmount, Token } from '@jediswap/sdk' import { ButtonPrimary, ButtonSecondary } from 'components/Button' import { RowBetween, RowFixed } from 'components/Row' import { Button as RebassButton, ButtonProps } from 'rebass/styled-components' -import { useContractRead, useContractWrite } from '@starknet-react/core' +import { useContractRead } from '@starknet-react/core' import { Call, CallData, validateAndParseAddress } from 'starknet' import { DEFAULT_CHAIN_ID, STARKNET_REWARDS_API_URL, STRK_PRICE_API_URL, getStarkRewardAddress } from 'constants/tokens' import REWARDS_ABI from 'abis/strk-rewards.json' @@ -491,7 +491,7 @@ function getRewardsData(jediRewards: any, pool: any) { export default function Rewards() { const [allPools, setAllPools] = useState([]) - const { address, chainId } = useAccountDetails() + const { address, account, chainId } = useAccountDetails() const [poolsLoading, setPoolsLoading] = useState(true) const STRK_REWARDS_ADDRESS = getStarkRewardAddress(chainId ?? DEFAULT_CHAIN_ID) const allTokens = useDefaultActiveTokens(DEFAULT_CHAIN_ID) @@ -599,9 +599,7 @@ export default function Rewards() { const [claimData, setClaimData] = useState({}) const [allocated, setAllocated] = useState(false) const [callData, setCallData] = useState([]) - const { writeAsync, data: txData } = useContractWrite({ - calls: callData, - }) + const [txHash, setTxHash] = useState('') const [claimError, setClaimError] = useState('') const [txPending, setTxPending] = useState(false) @@ -645,23 +643,21 @@ export default function Rewards() { }, [address, chainId]) useEffect(() => { - if (callData.length && address) { - writeAsync() - .then((res) => { - if (res && res.transaction_hash) { - setTxHash(res.transaction_hash) - } - }) - .catch((error) => { - const errorMessage = new Error(error) - setClaimError(errorMessage.message) - }) - .finally(() => { - setAttemptingTxn(false) - setCallData([]) - }) + const executeTransaction = async () => { + try { + const response: any = await account?.execute(callData) + if (response?.transaction_hash) setTxHash(response.transaction_hash) + } catch (error) { + console.error('Error executing transaction:', error) + const errorMessage = new Error(error) + setClaimError(errorMessage.message) + } finally { + setAttemptingTxn(false) + setCallData([]) + } } - }, [callData, address]) + if (callData && callData.length && account) executeTransaction() + }, [callData, account]) const onClaim = () => { setAttemptingTxn(true) diff --git a/src/pages/Swap/index.tsx b/src/pages/Swap/index.tsx index 37fa8236..1e688a8a 100644 --- a/src/pages/Swap/index.tsx +++ b/src/pages/Swap/index.tsx @@ -65,9 +65,8 @@ import { useScreenSize } from '../../hooks/useScreenSize' import { OutputTaxTooltipBody } from './TaxTooltipBody' import { SWAP_ROUTER_ADDRESS_V2, getSwapCurrencyId, DEFAULT_CHAIN_ID, SWAP_ROUTER_ADDRESS_V1 } from 'constants/tokens' import fetchAllPools from 'api/fetchAllPools' -import { Call, CallData, cairo, num, validateAndParseAddress } from 'starknet' +import { Call, CallData, InvokeFunctionResponse, cairo, num, validateAndParseAddress } from 'starknet' import { LoadingRows } from 'components/Loader/styled' -import { useConnect, useContractWrite } from '@starknet-react/core' import useTransactionDeadline from 'hooks/useTransactionDeadline' import { useApprovalCall } from 'hooks/useApproveCall' import { Pool, TradeType, toHex } from '@vnaysn/jediswap-sdk-v3' @@ -301,8 +300,6 @@ export function Swap({ const theme = useTheme() - const toggleWalletModal = useWalletConnect() - // swap state const prefilledState = useMemo( () => ({ @@ -520,29 +517,24 @@ export function Swap({ })) }, []) const [swapCallData, setSwapCallData] = useState([]) - - const { - writeAsync, - data: txData, - error, - } = useContractWrite({ - calls: swapCallData, - }) + const [txData, setTxData] = useState(undefined) + const [error, setError] = useState(null) const deadline = useTransactionDeadline() // custom from users settings useEffect(() => { - if (swapCallData) { - writeAsync() - .then((response) => { - if (response?.transaction_hash) { - } - }) - .catch((err) => { - console.log(err?.message) - }) + const executeTransaction = async () => { + try { + const response: any = await account?.execute(swapCallData) + setTxData(response) + } catch (error) { + console.error('Error executing transaction:', error) + setError(error) + // Handle the error, e.g., show an error message to the user + } } - }, [swapCallData]) + if (swapCallData && swapCallData.length && account) executeTransaction() + }, [swapCallData, account]) const separatedFiatValueofLiquidity = useQuery({ queryKey: ['fiat_value', trade?.inputAmount, trade?.outputAmount], diff --git a/src/pages/Vault/index.tsx b/src/pages/Vault/index.tsx index 8e3c02fb..ead23cd7 100644 --- a/src/pages/Vault/index.tsx +++ b/src/pages/Vault/index.tsx @@ -9,7 +9,6 @@ import { ChainId, Currency, CurrencyAmount, ONE, Percent, Token } from '@vnaysn/ import { DEFAULT_CHAIN_ID } from 'constants/tokens' import { isEmpty } from 'lodash' import { Link, useNavigate, useParams } from 'react-router-dom' -import { useBalance, useContractWrite } from '@starknet-react/core' import { useSelector } from 'react-redux' import JSBI from 'jsbi' import { useAccountDetails, useWalletConnect } from 'hooks/starknet-react' @@ -634,7 +633,7 @@ export function VaultElement({ const [callData, setCallData] = useState([]) const [activeButton, setActiveButton] = useState('Deposit') const connectionReady = useConnectionReady() - const { address: account } = useAccountDetails() + const { address, account } = useAccountDetails() const { openModal } = useWalletModal() const { vaultId: vaultAddressFromUrl } = useParams() const vaultState = useVaultState() @@ -664,30 +663,21 @@ export function VaultElement({ const fee_configAll = useFeeConfig(vaultAddressFromUrl) const fee_config = fee_configAll ? Number(num.getDecimalString(fee_configAll[fee_configAll.length - 3])) : 0 const { [Field.CURRENCY_A]: parsedAmountA, [Field.CURRENCY_B]: parsedAmountB } = parsedAmounts - const { - writeAsync, - data: txData, - error, - } = useContractWrite({ - calls: callData, - }) useEffect(() => { - if (callData) { - writeAsync() - .then((response) => { - setAttemptingTxn(false) - if (response?.transaction_hash) { - setTxHash(response.transaction_hash) - } - }) - .catch((err) => { - console.log(err?.message) - setAttemptingTxn(false) - setShowConfirm(false) - }) + const executeTransaction = async () => { + try { + const response: any = await account?.execute(callData) + if (response?.transaction_hash) setTxHash(response.transaction_hash) + setAttemptingTxn(false) + } catch (error) { + console.error('Error executing transaction:', error) + setAttemptingTxn(false) + setShowConfirm(false) + } } - }, [callData]) + if (callData && callData.length && account) executeTransaction() + }, [callData, account]) const vaultAddress = vaultAddressFromUrl // check - replace vault address const defaultDepositSlippage = new Percent(1, 100) @@ -705,7 +695,7 @@ export function VaultElement({ const approvalBCallback = useApprovalCall(amountBToApprove, vaultAddress) const onDeposit = () => { - if (!chainId || !account || !parsedAmountA || !parsedAmountB || !vaultAddress) { + if (!chainId || !address || !parsedAmountA || !parsedAmountB || !vaultAddress) { return } const callData = [] @@ -787,7 +777,7 @@ export function VaultElement({ } const getActionContent = () => { switch (true) { - case connectionReady && !account: + case connectionReady && !address: return ( Connect wallet