Skip to content

Commit

Permalink
chore: load bridging request
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaisailovic committed Sep 6, 2024
1 parent afb38d4 commit 44b5b0b
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,57 +5,92 @@ import RequestMethodCard from '@/components/RequestMethodCard'
import { Divider, Text } from '@nextui-org/react'
import RequestModal from './RequestModal'
import ModalStore from '@/store/ModalStore'
import { useCallback, useEffect } from 'react'
import { bridgeFunds } from '@/utils/MultibridgeUtil'
import { useCallback, useEffect, useState } from 'react'
import {
bridgeFunds,
BridgingRequest,
getAssetByContractAddress,
supportedAssets
} from '@/utils/MultibridgeUtil'
import { getWallet } from '@/utils/EIP155WalletUtil'
import { providers } from 'ethers'
import { EIP155_CHAINS, TEIP155Chain } from '@/data/EIP155Data'
import { styledToast } from '@/utils/HelperUtil'

interface IProps {
onApprove: () => void
onReject: () => void
approveLoader?: LoaderProps
bridgingRequest?: BridgingRequest
rejectLoader?: LoaderProps
}

export default function MultibridgeRequestModal({
onApprove,
bridgingRequest,
onReject,
approveLoader,
rejectLoader
}: IProps) {
const [isLoadingApprove, setIsLoadingApprove] = useState(false)

// Get request and wallet data from store
const requestEvent = ModalStore.state.data?.requestEvent
const requestSession = ModalStore.state.data?.requestSession

const topic = requestEvent?.topic
const params = requestEvent?.params

const chainId = params?.chainId
const request = params?.request
const transaction = request?.params[0]

const brdige = useCallback(async () => {
const bridge = useCallback(async () => {
if (!bridgingRequest) {
throw new Error('Bridging request is unavailable')
}

const wallet = await getWallet(params)
const provider = new providers.JsonRpcProvider(EIP155_CHAINS[chainId as TEIP155Chain].rpc)

const asset = getAssetByContractAddress(bridgingRequest.transfer.contract)
if (!asset) {
throw new Error('Source chain asset unavailable')
}
const sourceChainAssetAddress = supportedAssets[asset][bridgingRequest.sourceChain]
if (!sourceChainAssetAddress) {
throw new Error('Source chain asset address unavailable')
}

await bridgeFunds(
{
fromChainId: 8453,
toChainId: 42161,
fromAssetAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
toAssetAddress: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',
amount: 500000, // 0.5
userAddress: '0x81D8C68Be5EcDC5f927eF020Da834AA57cc3Bd24',
fromChainId: bridgingRequest.sourceChain,
toChainId: bridgingRequest.targetChain,
fromAssetAddress: sourceChainAssetAddress,
toAssetAddress: bridgingRequest.transfer.contract,
amount: bridgingRequest.transfer.amount,
userAddress: wallet.getAddress(),
uniqueRoutesPerBridge: true,
sort: 'time',
singleTxOnly: true
},
wallet,
provider
)
}, [params, chainId])
}, [params, chainId, bridgingRequest])

const onApprove = useCallback(async () => {
if (requestEvent && topic) {
setIsLoadingApprove(true)
try {
await bridge()
} catch (e) {
setIsLoadingApprove(false)
styledToast((e as Error).message, 'error')
return
}
setIsLoadingApprove(false)
ModalStore.close()
}
}, [requestEvent, topic])

if (!request || !requestSession) {
if (!request || !requestSession || !bridgingRequest) {
return <Text>Request not found</Text>
}

Expand All @@ -65,7 +100,7 @@ export default function MultibridgeRequestModal({
metadata={requestSession?.peer.metadata}
onApprove={onApprove}
onReject={onReject}
approveLoader={approveLoader}
approveLoader={{ active: isLoadingApprove }}
rejectLoader={rejectLoader}
>
<RequestDataCard data={transaction} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ export async function getErc20TokenBalance(
return Number(balance)
}

export type BridgingRequest = {
transfer: Erc20Transfer,
sourceChain: number,
targetChain: number,
}

type Erc20Transfer = {
from: Hex
to: Hex
Expand Down Expand Up @@ -221,7 +227,7 @@ async function getBridgeStatus(params: BridgeStatusParams): Promise<any> {


export async function bridgeFunds(bridgingParams: BridgingParams, wallet: EIP155Lib | SmartAccountLib, provider: providers.JsonRpcProvider): Promise<any> {
console.log('Bridging funds');
console.log('Bridging funds', bridgingParams);
const quote = await getQuote(bridgingParams)
console.log('Fetched quote', quote);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { styledToast } from '@/utils/HelperUtil'
import { web3wallet } from '@/utils/WalletConnectUtil'
import RequestModal from '@/components/RequestModal'
import {
BridgingRequest,
decodeErc20Transaction,
getCrossChainTokens,
getErc20TokenBalance
Expand All @@ -21,6 +22,7 @@ export default function SessionSendTransactionModal() {
const [isLoadingReject, setIsLoadingReject] = useState(false)
const [isTypeResolved, setIsTypeResolved] = useState(false)
const [shouldUseMultibridge, setShouldUseMultibridge] = useState(false)
const [bridgingRequest, setBridingRequest] = useState<BridgingRequest>()

// Get request and wallet data from store
const requestEvent = ModalStore.state.data?.requestEvent
Expand Down Expand Up @@ -58,6 +60,7 @@ export default function SessionSendTransactionModal() {
}
const otherTokens = getCrossChainTokens(transfer.contract)
let otherBalance = 0
let otherChain = 0

for (const chain in otherTokens) {
const balance = await getErc20TokenBalance(
Expand All @@ -66,15 +69,24 @@ export default function SessionSendTransactionModal() {
transfer.from,
false
)
otherBalance += balance
if (balance >= transfer.amount) {
otherBalance = balance
otherChain = Number(chain)
setShouldUseMultibridge(true)
setIsTypeResolved(true)
console.log('Found chain to bridge from', {
otherBalance,
requiredBalance: transfer.amount,
otherChain
})
setBridingRequest({
transfer,
sourceChain: otherChain,
targetChain: Number(parsedChainId)
})
return
}
}
if (transfer.amount > otherBalance) {
setIsTypeResolved(true)
return
}
console.log('Balance on other chains', { otherBalance, requiredBalance: transfer.amount })

setShouldUseMultibridge(true)
} catch (error) {
console.log('Unable to check multibridge availability', error)
} finally {
Expand Down Expand Up @@ -155,9 +167,8 @@ export default function SessionSendTransactionModal() {
</RequestModal>
) : (
<MultibridgeRequestModal
onApprove={onApprove}
bridgingRequest={bridgingRequest}
onReject={onReject}
approveLoader={{ active: isLoadingApprove }}
rejectLoader={{ active: isLoadingReject }}
/>
)
Expand Down

0 comments on commit 44b5b0b

Please sign in to comment.