Skip to content

Commit

Permalink
chore: extract chain abstraction transaction fetch logic
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaisailovic committed Sep 18, 2024
1 parent 32f9df4 commit ba0157f
Showing 1 changed file with 27 additions and 131 deletions.
158 changes: 27 additions & 131 deletions advanced/wallets/react-wallet-v2/src/utils/MultibridgeUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,62 +245,39 @@ async function getBridgeStatus(params: BridgeStatusParams): Promise<any> {
return json
}

export async function bridgeFunds(
bridgingParams: BridgingParams,
wallet: EIP155Lib | SmartAccountLib
): Promise<void> {
performance.mark('startGetQuote')
console.log('Bridging funds', bridgingParams)

async function getBridgingTransactions(bridgingParams: BridgingParams, walletAddress: string): Promise<any>{
const transactions = []
const originalAmount = bridgingParams.amount
bridgingParams.amount = Math.round(originalAmount * AMOUNT_MULTIPLIER)
const quote = await getQuote(bridgingParams)
performance.mark('endGetQuote')
console.log('Fetched quote', quote)

const route = quote.result.routes[0]
if (!route) {
throw new Error('No routes found')
}
performance.mark('startGetRouteTransactionData')
const apiReturnData = await getRouteTransactionData(route)
performance.mark('endGetRouteTransactionData')
const approvalData = apiReturnData.result.approvalData
const { allowanceTarget, minimumApprovalAmount } = approvalData
performance.mark('startGetWalletAddress')
const sourceChainProvider = new providers.JsonRpcProvider(
EIP155_CHAINS[`eip155:${bridgingParams.fromChainId}` as TEIP155Chain].rpc
)
const sourceChainConnectedWallet = await wallet.connect(sourceChainProvider)
const walletAddress = wallet.getAddress()
performance.mark('endGetWalletAddress')
console.log({ approvalData })
let currentNonce = await sourceChainProvider.getTransactionCount(walletAddress)
// approvalData from apiReturnData is null for native tokens
// Values are returned for ERC20 tokens but token allowance needs to be checked
if (approvalData !== null) {
// Fetches token allowance given to Bungee contracts
performance.mark('startCheckAllowance')
const allowanceCheckStatus = await checkAllowance({
chainId: bridgingParams.fromChainId,
owner: bridgingParams.userAddress,
allowanceTarget,
tokenAddress: bridgingParams.fromAssetAddress
})
performance.mark('endCheckAllowance')
const allowanceValue = allowanceCheckStatus.result?.value
console.log('Allowance value', allowanceValue)
if (minimumApprovalAmount > allowanceValue) {
console.log("Bungee contracts don't have sufficient allowance")
performance.mark('startGetApprovalTransactionData')
const approvalTransactionData = await getApprovalTransactionData({
chainId: bridgingParams.fromChainId,
owner: bridgingParams.userAddress,
allowanceTarget,
tokenAddress: bridgingParams.fromAssetAddress,
amount: bridgingParams.amount
})
performance.mark('endGetApprovalTransactionData')
performance.mark('startApprovalTransactionGasEstimate')
const gasPrice = sourceChainProvider.getGasPrice()
const gasEstimate = await sourceChainProvider.estimateGas({
from: walletAddress,
Expand All @@ -309,10 +286,7 @@ export async function bridgeFunds(
data: approvalTransactionData.result?.data,
gasPrice: gasPrice
})
performance.mark('endApprovalTransactionGasEstimate')

performance.mark('startApprovalTransactionSend')
const hash = await sourceChainConnectedWallet.sendTransaction({
transactions.push({
from: approvalTransactionData.result?.from,
to: approvalTransactionData.result?.to,
value: '0x00',
Expand All @@ -321,14 +295,9 @@ export async function bridgeFunds(
gasLimit: gasEstimate,
nonce: currentNonce
})
const receipt = typeof hash === 'string' ? hash : hash?.hash
performance.mark('endApprovalTransactionSend')
console.log('Approval Transaction', { receipt })
currentNonce++
}
}

performance.mark('startBridgingTransactionGasEstimate')
const gasPrice = await sourceChainProvider.getGasPrice()
let gasEstimate = BigInt('0x029a6b') * BigInt(4)
try {
Expand All @@ -344,10 +313,7 @@ export async function bridgeFunds(
} catch {
console.log('Failed gas estimate. Using default with 4x increase')
}
performance.mark('endBridgingTransactionGasEstimate')

performance.mark('startBridgingTransactionSend')
const hash = await sourceChainConnectedWallet.sendTransaction({
transactions.push({
from: walletAddress,
to: apiReturnData.result.txTarget,
data: apiReturnData.result.txData,
Expand All @@ -356,11 +322,29 @@ export async function bridgeFunds(
gasLimit: gasEstimate,
nonce: currentNonce
})
const receipt = typeof hash === 'string' ? hash : hash?.hash
console.log('Bridging Transaction : ', { receipt })
performance.mark('endBridgingTransactionSend')
return transactions
}


performance.mark('startBridgingTransactionCheck')
export async function bridgeFunds(
bridgingParams: BridgingParams,
wallet: EIP155Lib | SmartAccountLib
): Promise<void> {
const originalAmount = bridgingParams.amount
const sourceChainProvider = new providers.JsonRpcProvider(
EIP155_CHAINS[`eip155:${bridgingParams.fromChainId}` as TEIP155Chain].rpc
)
const sourceChainConnectedWallet = await wallet.connect(sourceChainProvider)
const walletAddress = wallet.getAddress()
console.log('Getting bridging transactions')
const transactions = await getBridgingTransactions(bridgingParams, walletAddress)
console.log('Bridging transactions', transactions);
for (const transaction of transactions) {
const hash = await sourceChainConnectedWallet.sendTransaction(transaction)
const receipt = typeof hash === 'string' ? hash : hash?.hash
console.log('Transaction broadcasted', {receipt});

}
let interations = 0
while (interations < 20) {
const balance = await getErc20TokenBalance(
Expand All @@ -369,100 +353,12 @@ export async function bridgeFunds(
walletAddress as Hex,
false
)
console.log('Checking destination address', { balance, originalAmount })

if (balance >= originalAmount) {
console.log('Bridging completed')
performance.mark('endBridgingTransactionCheck')
printMeasurements()
return
}
await new Promise(resolve => setTimeout(resolve, 1500))
interations++
}
}

function printMeasurements() {
console.log(
`Total duration: ${
performance.measure('total-duration', 'startGetQuote', 'endBridgingTransactionCheck').duration
} ms`
)
console.log(
`Get quote: ${performance.measure('get-quote', 'startGetQuote', 'endGetQuote').duration} ms`
)
console.log(
`Get Route Transaction Data: ${
performance.measure(
'get-route-transaction',
'startGetRouteTransactionData',
'endGetRouteTransactionData'
).duration
} ms`
)
console.log(
`Get Wallet Address: ${
performance.measure('get-wallet-address', 'startGetWalletAddress', 'endGetWalletAddress')
.duration
} ms`
)
console.log(
`Check Allowance: ${
performance.measure('check-allowance', 'startCheckAllowance', 'endCheckAllowance').duration
} ms`
)
console.log(
`Get Approval Transaction Data: ${
performance.measure(
'get-approval-tx-data',
'startGetApprovalTransactionData',
'endGetApprovalTransactionData'
).duration
} ms`
)
console.log(
`Get Approval Transaction Gas Estimate: ${
performance.measure(
'get-approval-tx-gas-estimate',
'startApprovalTransactionGasEstimate',
'endApprovalTransactionGasEstimate'
).duration
} ms`
)
console.log(
`Approval transaction send: ${
performance.measure(
'approval-transaction-send',
'startApprovalTransactionSend',
'endApprovalTransactionSend'
).duration
} ms`
)
console.log(
`Bridging transaction gas estimate: ${
performance.measure(
'bridging-tx-gas-estimate',
'startBridgingTransactionGasEstimate',
'endBridgingTransactionGasEstimate'
).duration
} ms`
)
console.log(
`Bridging transaction send: ${
performance.measure(
'bridging-tx-send',
'startBridgingTransactionSend',
'endBridgingTransactionSend'
).duration
} ms`
)
console.log(
`Bridging transaction check: ${
performance.measure(
'bridging-tx-check',
'startBridgingTransactionCheck',
'endBridgingTransactionCheck'
).duration
} ms`
)
}

0 comments on commit ba0157f

Please sign in to comment.