Skip to content

Commit

Permalink
Clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
nop33 committed Sep 1, 2023
1 parent 7da3390 commit 3bcbb5c
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 150 deletions.
8 changes: 2 additions & 6 deletions src/api/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ export const buildSweepTransactions = async (fromAddress: Address, toAddressHash
export const buildUnsignedTransactions = async (
fromAddress: Address,
toAddressHash: string,
assetAmounts: AssetAmount[],
gasAmount?: number,
gasPrice?: string
assetAmounts: AssetAmount[]
) => {
const assetsWithAvailableBalance = getAddressAssetsAvailableBalance(fromAddress).filter(
(asset) => asset.availableBalance > 0
Expand All @@ -60,9 +58,7 @@ export const buildUnsignedTransactions = async (
const data = await buildTransferTransaction({
fromAddress,
toAddress: toAddressHash,
assetAmounts,
gasAmount,
gasPrice
assetAmounts
})

return {
Expand Down
27 changes: 14 additions & 13 deletions src/components/DashboardHeaderActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ const DashboardHeaderActions = ({ style }: DashboardHeaderActionsProps) => {
const isCameraOpen = useAppSelector((s) => s.app.isCameraOpen)
const dispatch = useAppDispatch()
const posthog = usePostHog()
const { pair, walletConnectClient, activeSessions } = useWalletConnectContext()
const { pairWithDapp, walletConnectClient, activeSessions } = useWalletConnectContext()
const {
ref: currentConnectionsModalRef,
open: openCurrentConnectionsModal,
close: closeCurrentConnectionsModal
ref: currentWalletConnectConnectionsModalRef,
open: openCurrentWalletConnectConnectionsModal,
close: closeCurrentWalletConnectConnectionsModal
} = useModalize()

const openQRCodeScannerModal = () => dispatch(cameraToggled(true))
Expand All @@ -62,14 +62,10 @@ const DashboardHeaderActions = ({ style }: DashboardHeaderActionsProps) => {

const handleQRCodeScan = async (text: string) => {
if (isAddressValid(text)) {
navigation.navigate('SendNavigation', {
screen: 'OriginScreen',
params: { toAddressHash: text }
})

navigation.navigate('SendNavigation', { screen: 'OriginScreen', params: { toAddressHash: text } })
posthog?.capture('Send: Captured destination address by scanning QR code from Dashboard')
} else if (text.startsWith('wc:')) {
pair(text)
pairWithDapp(text)
}
}

Expand All @@ -86,7 +82,12 @@ const DashboardHeaderActions = ({ style }: DashboardHeaderActionsProps) => {
variant={isMnemonicBackedUp ? 'default' : 'alert'}
/>
{walletConnectClient && activeSessions.length > 0 && (
<Button onPress={() => openCurrentConnectionsModal()} Icon={Radio} type="transparent" variant="accent" />
<Button
onPress={() => openCurrentWalletConnectConnectionsModal()}
Icon={Radio}
type="transparent"
variant="accent"
/>
)}
<Button onPress={openQRCodeScannerModal} Icon={ScanLine} type="transparent" />
<Button onPress={() => navigation.navigate('SettingsScreen')} Icon={Settings} type="transparent" />
Expand All @@ -100,8 +101,8 @@ const DashboardHeaderActions = ({ style }: DashboardHeaderActionsProps) => {
)}

<Portal>
<Modalize ref={currentConnectionsModalRef}>
<WalletConnectPairingsModal onClose={closeCurrentConnectionsModal} />
<Modalize ref={currentWalletConnectConnectionsModalRef}>
<WalletConnectPairingsModal onClose={closeCurrentWalletConnectConnectionsModal} />
</Modalize>
</Portal>
</>
Expand Down
27 changes: 10 additions & 17 deletions src/contexts/SendContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,20 +48,20 @@ interface SendContextValue {
setToAddress: (toAddress: AddressHash) => void
fromAddress?: AddressHash
setFromAddress: (toAddress: AddressHash) => void
setAssetAmount: (assetId: string, amount?: bigint) => void
assetAmounts: AssetAmount[]
setAssetAmount: (assetId: string, amount?: bigint) => void
fees: bigint
buildTransaction: (callbacks: BuildTransactionCallbacks) => Promise<void>
sendTransaction: (onSendSuccess: (signature?: string) => void) => Promise<void>
sendTransaction: (onSendSuccess: () => void) => Promise<void>
}

const initialValues: SendContextValue = {
toAddress: undefined,
setToAddress: () => null,
fromAddress: undefined,
setFromAddress: () => null,
setAssetAmount: () => null,
assetAmounts: [],
setAssetAmount: () => null,
fees: BigInt(0),
buildTransaction: () => Promise.resolve(undefined),
sendTransaction: () => Promise.resolve(undefined)
Expand Down Expand Up @@ -116,13 +116,10 @@ export const SendContextProvider = ({ children }: { children: ReactNode }) => {

const buildTransaction = useCallback(
async (callbacks: BuildTransactionCallbacks) => {
if (!address) return
if (!address || !toAddress) return

try {
if (!toAddress) throw new Error('Destination address not set')

const data = await buildUnsignedTransactions(address, toAddress, assetAmounts)

setUnsignedTxData(data)
callbacks.onBuildSuccess()
} catch (e) {
Expand All @@ -144,22 +141,20 @@ export const SendContextProvider = ({ children }: { children: ReactNode }) => {
)

const sendTransaction = useCallback(
async (onSendSuccess: (signature?: string) => void) => {
if (!address) return
async (onSendSuccess: () => void) => {
if (!address || !toAddress) return

const { attoAlphAmount, tokens } = getTransactionAssetAmounts(assetAmounts)
let signature

try {
for (const { txId, unsignedTx } of unsignedTxData.unsignedTxs) {
const data = await signAndSendTransaction(address, txId, unsignedTx)
signature = data.signature

dispatch(
transactionSent({
hash: data.txId,
fromAddress: address.hash,
toAddress: consolidationRequired ? address.hash : toAddress ?? '',
toAddress: consolidationRequired ? address.hash : toAddress,
amount: attoAlphAmount,
tokens,
timestamp: new Date().getTime(),
Expand All @@ -169,9 +164,7 @@ export const SendContextProvider = ({ children }: { children: ReactNode }) => {
)
}

console.log('SUCCESS SENDING')

onSendSuccess(signature)
onSendSuccess()

posthog?.capture('Send: Sent transaction', { tokens: tokens.length })
} catch (e) {
Expand All @@ -180,7 +173,7 @@ export const SendContextProvider = ({ children }: { children: ReactNode }) => {
posthog?.capture('Error', { message: 'Could not send transaction' })
}
},
[address, assetAmounts, consolidationRequired, dispatch, posthog, toAddress, unsignedTxData]
[address, assetAmounts, consolidationRequired, dispatch, posthog, toAddress, unsignedTxData.unsignedTxs]
)

const authenticateAndSend = useCallback(
Expand All @@ -202,8 +195,8 @@ export const SendContextProvider = ({ children }: { children: ReactNode }) => {
setToAddress,
fromAddress,
setFromAddress,
setAssetAmount,
assetAmounts,
setAssetAmount,
fees: unsignedTxData.fees,
buildTransaction,
sendTransaction: authenticateAndSend
Expand Down
69 changes: 34 additions & 35 deletions src/contexts/walletConnect/WalletConnectContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,32 +51,37 @@ import {
import Modalize from '~/components/layout/Modalize'
import SpinnerModal from '~/components/SpinnerModal'
import WalletConnectSessionProposalModal from '~/contexts/walletConnect/WalletConnectSessionProposalModal'
import WalletConnectTxModal from '~/contexts/walletConnect/WalletConnectTxModal'
import WalletConnectSessionRequestModal from '~/contexts/walletConnect/WalletConnectSessionRequestModal'
import { useAppSelector } from '~/hooks/redux'
import { selectAllAddresses } from '~/store/addressesSlice'
import { Address } from '~/types/addresses'
import { CallContractTxData, DeployContractTxData, TransferTxData } from '~/types/transactions'
import { SessionProposalEvent, SessionRequestEvent, TxData } from '~/types/walletConnect'
import { SessionProposalEvent, SessionRequestData, SessionRequestEvent } from '~/types/walletConnect'
import { WALLETCONNECT_ERRORS } from '~/utils/constants'
import { getActiveWalletConnectSessions, isNetworkValid, parseSessionProposalEvent } from '~/utils/walletConnect'

interface WalletConnectContextValue {
walletConnectClient?: SignClient
pair: (uri: string) => Promise<void>
unpair: (pairingTopic: string) => Promise<void>
pairWithDapp: (uri: string) => Promise<void>
unpairFromDapp: (pairingTopic: string) => Promise<void>
activeSessions: SessionTypes.Struct[]
}

const initialValues: WalletConnectContextValue = {
walletConnectClient: undefined,
pair: () => Promise.resolve(),
unpair: () => Promise.resolve(),
pairWithDapp: () => Promise.resolve(),
unpairFromDapp: () => Promise.resolve(),
activeSessions: []
}

const WalletConnectContext = createContext(initialValues)

export const WalletConnectContextProvider = ({ children }: { children: ReactNode }) => {
const currentNetworkId = useAppSelector((s) => s.network.settings.networkId)
const currentNetworkName = useAppSelector((s) => s.network.name)
const addresses = useAppSelector(selectAllAddresses)
const posthog = usePostHog()

const {
ref: sessionProposalModalRef,
open: openSessionProposalModal,
Expand All @@ -87,18 +92,14 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
open: openSessionRequestModal,
close: closeSessionRequestModal
} = useModalize()
const currentNetworkId = useAppSelector((s) => s.network.settings.networkId)
const currentNetworkName = useAppSelector((s) => s.network.name)
const addresses = useAppSelector(selectAllAddresses)
const posthog = usePostHog()

const [walletConnectClient, setWalletConnectClient] = useState<WalletConnectContextValue['walletConnectClient']>()
const [activeSessions, setActiveSessions] = useState<SessionTypes.Struct[]>([])
const [sessionProposalEvent, setSessionProposalEvent] = useState<SessionProposalEvent>()
const [sessionRequestEvent, setSessionRequestEvent] = useState<SessionRequestEvent>()
const [loading, setLoading] = useState('')
const [txData, setTxData] = useState<TxData>()
const [sessionRequestData, setSessionRequestData] = useState<SessionRequestData>()
const [isSessionRequestModalOpen, setIsSessionRequestModalOpen] = useState(false)
const [loading, setLoading] = useState('')

const activeSessionMetadata = activeSessions.find((s) => s.topic === sessionRequestEvent?.topic)?.peer.metadata

Expand Down Expand Up @@ -161,6 +162,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
]

const fromAddress = addresses.find((address) => address.hash === signerAddress)

if (!fromAddress) {
return respondToWalletConnectWithError(requestEvent, {
message: 'Signer address doesn\t exist',
Expand All @@ -183,7 +185,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
console.log('✅ BUILDING TX: DONE!')
setLoading('')

setTxData({
setSessionRequestData({
type: 'transfer',
wcData: wcTxData,
unsignedTxData: buildTransactionTxResult
Expand Down Expand Up @@ -229,7 +231,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
console.log('✅ BUILDING TX: DONE!')
setLoading('')

setTxData({
setSessionRequestData({
type: 'deploy-contract',
wcData: wcTxData,
unsignedTxData: buildDeployContractTxResult
Expand Down Expand Up @@ -287,7 +289,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
console.log('✅ BUILDING TX: DONE!')
setLoading('')

setTxData({
setSessionRequestData({
type: 'call-contract',
wcData: wcTxData,
unsignedTxData: buildCallContractTxResult
Expand Down Expand Up @@ -318,7 +320,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
break
}
default:
// TODO: support all of the other SignerProvider methods
// TODO: Support all of the other SignerProvider methods
respondToWalletConnectWithError(requestEvent, getSdkError('WC_METHOD_UNSUPPORTED'))
}
} catch (e) {
Expand All @@ -329,7 +331,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
posthog?.capture('Error', { message: 'Could not build transaction' })
}
},
// The `addresses` depedency causes re-rendering when any property of an Address changes, even though we only need
// The `addresses` dependency causes re-rendering when any property of an Address changes, even though we only need
// the `hash`, the `publicKey`, and the `privateKey`. Creating a selector that extracts those 3 doesn't help.
// TODO: Figure out a way to avoid re-renders
[
Expand Down Expand Up @@ -438,7 +440,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
walletConnectClient
])

const pair = useCallback(
const pairWithDapp = useCallback(
async (uri: string) => {
if (!walletConnectClient) return

Expand Down Expand Up @@ -487,7 +489,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
[onSessionProposal, walletConnectClient]
)

const unpair = useCallback(
const unpairFromDapp = useCallback(
async (topic: string) => {
if (!walletConnectClient) return

Expand Down Expand Up @@ -569,16 +571,14 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
try {
setLoading('Approving...')
console.log('⏳ APPROVING PROPOSAL...')

const { topic, acknowledged } = await walletConnectClient.approve({ id, relayProtocol, namespaces })
console.log('👉 APPROVAL TOPIC RECEIVED:', topic)
console.log('✅ APPROVING: DONE!')

console.log('⏳ APPROVAL TOPIC RECEIVED:', topic)
console.log('⏳ WAITING FOR DAPP ACKNOWLEDGEMENT...')
const res = await acknowledged()
console.log('👉 DID DAPP ACTUALLY ACKNOWLEDGE?', res.acknowledged)

console.log('✅ APPROVING: DONE!')

setSessionProposalEvent(undefined)
setActiveSessions(getActiveWalletConnectSessions(walletConnectClient))

Expand All @@ -592,8 +592,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
}

const rejectProposal = async () => {
if (!walletConnectClient) return
if (sessionProposalEvent === undefined) return
if (!walletConnectClient || sessionProposalEvent === undefined) return

try {
setLoading('Rejecting...')
Expand Down Expand Up @@ -639,7 +638,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
} finally {
console.log('👉 RESETTING SESSION REQUEST EVENT.')
setSessionRequestEvent(undefined)
setTxData(undefined)
setSessionRequestData(undefined)
setLoading('')
}
}
Expand All @@ -656,16 +655,16 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
} finally {
console.log('👉 RESETTING SESSION REQUEST EVENT.')
setSessionRequestEvent(undefined)
setTxData(undefined)
setSessionRequestData(undefined)
}
}

const handleTxModalClose = async () => {
const handleSessionRequestModalClose = async () => {
setIsSessionRequestModalOpen(false)
onTxModalClose()
onSessionRequestModalClose()
}

const onTxModalClose = async () => {
const onSessionRequestModalClose = async () => {
console.log('👉 CLOSING MODAL.')

if (sessionRequestEvent && walletConnectClient && walletConnectClient?.getPendingSessionRequests().length > 0) {
Expand All @@ -679,7 +678,7 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
}, [closeSessionRequestModal, isSessionRequestModalOpen, sessionRequestEvent])

return (
<WalletConnectContext.Provider value={{ pair, unpair, walletConnectClient, activeSessions }}>
<WalletConnectContext.Provider value={{ pairWithDapp, unpairFromDapp, walletConnectClient, activeSessions }}>
{children}
<Portal>
<Modalize ref={sessionProposalModalRef}>
Expand All @@ -695,11 +694,11 @@ export const WalletConnectContextProvider = ({ children }: { children: ReactNode
<Modalize
ref={walletConnectSessionRequestModalRef}
onOpen={() => setIsSessionRequestModalOpen(true)}
onClose={handleTxModalClose}
onClose={handleSessionRequestModalClose}
>
{txData && (
<WalletConnectTxModal
txData={txData}
{sessionRequestData && (
<WalletConnectSessionRequestModal
requestData={sessionRequestData}
onApprove={handleApprovePress}
onReject={handleRejectPress}
metadata={activeSessionMetadata}
Expand Down
Loading

0 comments on commit 3bcbb5c

Please sign in to comment.