Skip to content

Commit

Permalink
web wallet fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
vnaysngh committed Jul 28, 2024
1 parent 13e4dd6 commit d307bcc
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 151 deletions.
13 changes: 6 additions & 7 deletions src/context/StarknetProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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
}

Expand Down
55 changes: 23 additions & 32 deletions src/pages/AddLiquidity/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
}

Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -566,7 +557,7 @@ function AddLiquidity() {
// END: sync values with query string

const Buttons = () =>
!account ? (
!address ? (
<ButtonPrimary onClick={openModal} $borderRadius="12px" style={{ padding: '12px', fontSize: '18px' }}>
<Trans>Connect wallet</Trans>
</ButtonPrimary>
Expand All @@ -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 (
<>
Expand Down
34 changes: 14 additions & 20 deletions src/pages/Pool/PositionPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -703,9 +702,20 @@ function PositionPageContent() {
const isCollectPending = useIsTransactionPending(collectMigrationHash ?? undefined)
const [showConfirm, setShowConfirm] = useState(false)
const [callData, setCallData] = useState<Call[]>([])
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()}`],
Expand All @@ -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 () => {
Expand Down
43 changes: 19 additions & 24 deletions src/pages/RemoveLiquidity/V3.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -107,31 +107,26 @@ function Remove({ tokenId }: { tokenId: number }) {
const [attemptingTxn, setAttemptingTxn] = useState(false)
const [txnHash, setTxnHash] = useState<string | undefined>()
const [mintCallData, setMintCallData] = useState<Call[]>([])
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()
Expand All @@ -140,7 +135,7 @@ function Remove({ tokenId }: { tokenId: number }) {
!liquidityValue0 ||
!liquidityValue1 ||
!deadline ||
!account ||
!address ||
!chainId ||
!positionSDK ||
!liquidityPercentage
Expand Down Expand Up @@ -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,
}
Expand All @@ -197,7 +192,7 @@ function Remove({ tokenId }: { tokenId: number }) {
liquidityValue0,
liquidityValue1,
deadline,
account,
address,
chainId,
positionSDK,
liquidityPercentage,
Expand Down
38 changes: 17 additions & 21 deletions src/pages/Rewards/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -491,7 +491,7 @@ function getRewardsData(jediRewards: any, pool: any) {

export default function Rewards() {
const [allPools, setAllPools] = useState<any[]>([])
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)
Expand Down Expand Up @@ -599,9 +599,7 @@ export default function Rewards() {
const [claimData, setClaimData] = useState({})
const [allocated, setAllocated] = useState(false)
const [callData, setCallData] = useState<Call[]>([])
const { writeAsync, data: txData } = useContractWrite({
calls: callData,
})

const [txHash, setTxHash] = useState('')
const [claimError, setClaimError] = useState('')
const [txPending, setTxPending] = useState(false)
Expand Down Expand Up @@ -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)
Expand Down
Loading

0 comments on commit d307bcc

Please sign in to comment.