Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix autoconnect wallet #787

Merged
merged 2 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/components/Header/HeaderButton/ChangeWalletButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ export const ChangeWalletButton: React.FC<IProps> = ({
const [isChangeWallet, setIsChangeWallet] = React.useState<boolean>(false)

const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
console.log('connected', connected)
if (!connected) {
setIsOpenSelectWallet(true)
setAnchorEl(event.currentTarget)
Expand Down
69 changes: 35 additions & 34 deletions src/containers/HeaderWrapper/HeaderWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import React, { useEffect, useMemo } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useLocation, useNavigate } from 'react-router-dom'
import { actions as snackbarsActions } from '@store/reducers/snackbars'
import { changeToNightlyAdapter, connectStaticWallet } from '@utils/web3/wallet'
import { changeToNightlyAdapter, connectStaticWallet, getSolanaWallet } from '@utils/web3/wallet'
import { sleep } from '@invariant-labs/sdk'

export const HeaderWrapper: React.FC = () => {
const dispatch = useDispatch()
Expand All @@ -25,44 +26,46 @@ export const HeaderWrapper: React.FC = () => {
useEffect(() => {
const reconnectStaticWallet = async (wallet: WalletType) => {
await connectStaticWallet(wallet)
dispatch(walletActions.connect())
dispatch(walletActions.connect(true))
}

if (currentNetwork === NetworkType.Testnet) {
dispatch(actions.setNetwork(NetworkType.Devnet))
dispatch(actions.setRPCAddress(RPC.DEV))
}

const walletType = localStorage.getItem('WALLET_TYPE') as WalletType | null

if (walletType !== null && walletType === WalletType.NIGHTLY) {
nightlyConnectAdapter.addListener('connect', () => {
const eagerConnectToNightly = async () => {
try {
changeToNightlyAdapter()
dispatch(walletActions.connect())
})
const nightlyAdapter = getSolanaWallet()

if (nightlyConnectAdapter.connected) {
changeToNightlyAdapter()
dispatch(walletActions.connect())
await nightlyAdapter.connect()
await sleep(500)
if (!nightlyAdapter.connected) {
await nightlyAdapter.connect()
await sleep(500)
}
dispatch(walletActions.connect(true))
} catch (error) {
console.error('Error during Nightly eager connection:', error)
}
}

;(async () => {
if (currentNetwork === NetworkType.Testnet) {
dispatch(actions.setNetwork(NetworkType.Devnet))
dispatch(actions.setRPCAddress(RPC.DEV))
}

nightlyConnectAdapter.canEagerConnect().then(
async canEagerConnect => {
if (canEagerConnect) {
changeToNightlyAdapter()
await nightlyConnectAdapter.connect()
}
},
error => {
console.log(error)
const walletType = localStorage.getItem('WALLET_TYPE') as WalletType | null

if (walletType === WalletType.NIGHTLY) {
const canEagerConnect = await nightlyConnectAdapter.canEagerConnect().catch(error => {
console.error('Error checking eager connect:', error)
return false
})
if (canEagerConnect) {
await eagerConnectToNightly()
}
)
} else {
if (!walletType || walletType === null) {
return
} else if (walletType) {
await reconnectStaticWallet(walletType)
}
reconnectStaticWallet(walletType)
}
})()
}, [])

const defaultTestnetRPC = useMemo(() => {
Expand Down Expand Up @@ -150,8 +153,6 @@ export const HeaderWrapper: React.FC = () => {
<Header
address={walletAddress}
onNetworkSelect={(network, rpcAddress) => {
console.log('network', network)
console.log('rpcAddress', rpcAddress)
if (rpcAddress !== currentRpc) {
localStorage.setItem(`INVARIANT_RPC_SOLANA_${network}`, rpcAddress)
dispatch(actions.setRPCAddress(rpcAddress))
Expand All @@ -173,7 +174,7 @@ export const HeaderWrapper: React.FC = () => {
}
}}
onConnectWallet={() => {
dispatch(walletActions.connect())
dispatch(walletActions.connect(false))
}}
landing={location.pathname.substring(1)}
walletConnected={walletStatus === Status.Initialized}
Expand Down
4 changes: 2 additions & 2 deletions src/containers/NewPositionWrapper/NewPositionWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,7 @@ export const NewPositionWrapper: React.FC<IProps> = ({
solBalance={solBalance}
walletStatus={walletStatus}
onConnectWallet={() => {
dispatch(walletActions.connect())
dispatch(walletActions.connect(false))
}}
onDisconnectWallet={() => {
dispatch(walletActions.disconnect())
Expand All @@ -789,7 +789,7 @@ export const NewPositionWrapper: React.FC<IProps> = ({
loadingTicksAndTickMaps={loadingTicksAndTickMaps}
noConnectedBlockerProps={{
onConnect: () => {
dispatch(walletActions.connect())
dispatch(walletActions.connect(false))
},
descCustomText: 'Cannot add any liquidity.'
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ export const SinglePositionWrapper: React.FC<IProps> = ({ id }) => {
className={classes.fullHeightContainer}>
<NoConnected
onConnect={() => {
dispatch(walletActions.connect())
dispatch(walletActions.connect(false))
}}
title='Connect a wallet to view your position,'
descCustomText='or start exploring liquidity pools now!'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export const WrappedPositionsList: React.FC = () => {
itemsPerPage={POSITIONS_PER_PAGE}
noConnectedBlockerProps={{
onConnect: () => {
dispatch(walletActions.connect())
dispatch(walletActions.connect(false))
},
title: 'Start exploring liquidity pools right now!',
descCustomText: 'Or, connect your wallet to see existing positions, and create a new one!'
Expand Down
2 changes: 1 addition & 1 deletion src/containers/WrappedSwap/WrappedSwap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ export const WrappedSwap = ({ initialTokenFrom, initialTokenTo }: Props) => {
}
}}
onConnectWallet={() => {
dispatch(walletActions.connect())
dispatch(walletActions.connect(false))
}}
onDisconnectWallet={() => {
dispatch(walletActions.disconnect())
Expand Down
4 changes: 3 additions & 1 deletion src/store/reducers/solanaWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ const solanaWalletSlice = createSlice({
// Triggers rescan for tokens that we control
rescanTokens() {},
airdrop() {},
connect() {},
connect(state, _action: PayloadAction<boolean>) {
return state
},
disconnect() {}
}
})
Expand Down
56 changes: 44 additions & 12 deletions src/store/sagas/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
spawn,
all,
select,
takeLatest
takeLatest,
delay
} from 'typed-redux-saga'
import { actions, ITokenAccount, Status } from '@store/reducers/solanaWallet'
import { getConnection, handleRpcError } from './connection'
Expand Down Expand Up @@ -35,6 +36,7 @@ import { actions as farmsActions } from '@store/reducers/farms'
import { actions as bondsActions } from '@store/reducers/bonds'
import { closeSnackbar } from 'notistack'
import { createLoaderKey } from '@utils/utils'
import { PayloadAction } from '@reduxjs/toolkit'

export function* getWallet(): SagaGenerator<WalletAdapter> {
const wallet = yield* call(getSolanaWallet)
Expand Down Expand Up @@ -375,9 +377,43 @@ export function* createMultipleAccounts(tokenAddress: PublicKey[]): SagaGenerato
return associatedAccs
}

export function* init(): Generator {
export function* init(isEagerConnect: boolean): Generator {
try {
if (isEagerConnect) {
yield* delay(500)
}

const wallet = yield* call(getWallet)
if (!wallet.connected) {
yield* delay(500)
}

const wallet2 = yield* call(getWallet)

if (!wallet2.connected) {
yield* put(actions.setStatus(Status.Uninitialized))
return
}
yield* put(actions.setStatus(Status.Init))

if (isEagerConnect) {
yield* put(
snackbarsActions.add({
message: 'Wallet reconnected.',
variant: 'success',
persist: false
})
)
} else {
yield* put(
snackbarsActions.add({
message: 'Wallet connected.',
variant: 'success',
persist: false
})
)
}

yield* call(handleBalance)
yield* put(actions.setStatus(Status.Initialized))
} catch (error) {}
Expand All @@ -400,10 +436,12 @@ export function* sendSol(amount: BN, recipient: PublicKey): SagaGenerator<string
return txid
}

export function* handleConnect(): Generator {
export function* handleConnect(action: PayloadAction<boolean>): Generator {
try {
const walletStatus = yield* select(status)
if (walletStatus === Status.Initialized) {
const wallet = yield* call(getWallet)

if (walletStatus === Status.Initialized && wallet.connected) {
yield* put(
snackbarsActions.add({
message: 'Wallet already connected.',
Expand All @@ -413,7 +451,7 @@ export function* handleConnect(): Generator {
)
return
}
yield* call(init)
yield* call(init, action.payload)
} catch (error) {
yield* call(handleRpcError, (error as Error).message)
}
Expand Down Expand Up @@ -451,16 +489,10 @@ export function* airdropSaga(): Generator {
yield takeLeading(actions.airdrop, handleAirdrop)
}

export function* initSaga(): Generator {
yield takeLeading(actions.initWallet, init)
}

export function* handleBalanceSaga(): Generator {
yield takeLatest(actions.getBalance, handleBalance)
}

export function* walletSaga(): Generator {
yield all(
[initSaga, airdropSaga, connectHandler, disconnectHandler, handleBalanceSaga].map(spawn)
)
yield all([airdropSaga, connectHandler, disconnectHandler, handleBalanceSaga].map(spawn))
}
17 changes: 10 additions & 7 deletions src/utils/web3/selector.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { NightlyConnectAdapter } from '@nightlylabs/wallet-selector-solana'

export const nightlyConnectAdapter: NightlyConnectAdapter = NightlyConnectAdapter.buildLazy({
appMetadata: {
name: 'Invariant',
description: 'Invariant - AMM DEX provided concentrated liquidity',
icon: 'https://invariant.app/favicon-192x192.png'
export const nightlyConnectAdapter: NightlyConnectAdapter = await NightlyConnectAdapter.build(
{
appMetadata: {
name: 'Invariant',
description: 'Invariant - AMM DEX provided concentrated liquidity',
icon: 'https://invariant.app/favicon-192x192.png'
},
url: 'https://nc2.nightly.app'
},
url: 'https://nc2.nightly.app'
})
{ initOnConnect: true }
)

export const openWalletSelectorModal = async () => {
try {
Expand Down
4 changes: 3 additions & 1 deletion src/utils/web3/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { PhantomWalletAdapter } from './adapters/phantom'
import { BackpackWalletAdapter } from './adapters/backpack'
import { SolflareWalletAdapter } from './adapters/solflare'
import { WalletType } from '@store/consts/types'
import { sleep } from '@invariant-labs/sdk'

let _wallet: WalletAdapter

Expand All @@ -30,7 +31,8 @@ const connectStaticWallet = async (wallet: WalletType) => {
_wallet = new PhantomWalletAdapter()
break
}
console.log('Connecting wallet')

await sleep(300)
await _wallet.connect()
}

Expand Down