@biconomy/sdk
Version:
SDK for Biconomy integration with support for account abstraction, smart accounts, ERC-4337.
138 lines • 5.67 kB
JavaScript
import { toAcrossPlugin } from "../utils/toAcrossPlugin.js";
import { queryBridge } from "./queryBridge.js";
/**
* Makes sure that the user has enough funds on the selected chain before filling the
* supertransaction. Bridges funds from other chains if needed.
*
* @param params - {@link MultichainBridgingParams} Configuration for the bridge operation
* @param params.account - The smart account to execute the bridging
* @param params.amount - The amount to bridge
* @param params.toChain - The destination chain
* @param params.unifiedBalance - Current token balances across chains
* @param params.bridgingPlugins - Optional array of bridging plugins (defaults to Across)
* @param params.feeData - Optional fee configuration
*
* @returns Promise resolving to {@link BridgingInstructions} containing all necessary operations
*
* @throws Error if insufficient balance is available for bridging
* @throws Error if chain configuration is missing for any deployment
*
* @example
* const bridgeInstructions = await buildBridgeInstructions({
* account: myMultichainAccount,
* amount: BigInt("1000000"), // 1 USDC
* toChain: optimism,
* unifiedBalance: myTokenBalance,
* bridgingPlugins: [acrossPlugin],
* feeData: {
* txFeeChainId: 1,
* txFeeAmount: BigInt("100000")
* }
* });
*/
export const buildBridgeInstructions = async (params) => {
const { account, amount: targetAmount, toChain, unifiedBalance, bridgingPlugins = [toAcrossPlugin()], feeData } = params;
// Create token address mapping
const tokenMapping = {
on: (chainId) => unifiedBalance.mcToken.deployments.get(chainId) || "0x",
deployments: Array.from(unifiedBalance.mcToken.deployments.entries(), ([chainId, address]) => ({
chainId,
address
}))
};
// Get current balance on destination chain
const destinationBalance = unifiedBalance.breakdown.find((b) => b.chainId === toChain.id)?.balance ||
0n;
// If we have enough on destination, no bridging needed
if (destinationBalance >= targetAmount) {
return {
instructions: [],
meta: {
bridgingInstructions: [],
totalAvailableOnDestination: destinationBalance
}
};
}
// Calculate how much we need to bridge
const amountToBridge = targetAmount - destinationBalance;
// Get available balances from source chains
const sourceBalances = unifiedBalance.breakdown
.filter((balance) => balance.chainId !== toChain.id)
.map((balance) => {
// If this is the fee payment chain, adjust available balance
const isFeeChain = feeData && feeData.txFeeChainId === balance.chainId;
const availableBalance = isFeeChain && "txFeeAmount" in feeData
? balance.balance > feeData.txFeeAmount
? balance.balance - feeData.txFeeAmount
: 0n
: balance.balance;
return {
chainId: balance.chainId,
balance: availableBalance
};
})
.filter((balance) => balance.balance > 0n);
// Get chain configurations
const chains = Object.fromEntries(account.deployments.map((deployment) => {
const chain = deployment.client.chain;
if (!chain) {
throw new Error(`Client not configured with chain for deployment at ${deployment.address}`);
}
return [chain.id, chain];
}));
// Query all possible routes
const bridgeQueries = sourceBalances.flatMap((source) => {
const fromChain = chains[source.chainId];
if (!fromChain)
return [];
return bridgingPlugins.map((plugin) => queryBridge({
fromChain,
toChain,
plugin,
amount: source.balance,
account,
tokenMapping
}));
});
const bridgeResults = (await Promise.all(bridgeQueries))
.filter((result) => result !== null)
// Sort by received amount relative to sent amount
.sort((a, b) => Number((b.receivedAtDestination * 10000n) / b.amount) -
Number((a.receivedAtDestination * 10000n) / a.amount));
// Build instructions by taking from best routes until we have enough
const bridgingInstructions = [];
const instructions = [];
let totalBridged = 0n;
let remainingNeeded = amountToBridge;
for (const result of bridgeResults) {
if (remainingNeeded <= 0n)
break;
const amountToTake = result.amount >= remainingNeeded ? remainingNeeded : result.amount;
// Recalculate received amount based on portion taken
const receivedFromRoute = (result.receivedAtDestination * amountToTake) / result.amount;
instructions.push(result.userOp);
bridgingInstructions.push({
userOp: result.userOp,
receivedAtDestination: receivedFromRoute,
bridgingDurationExpectedMs: result.bridgingDurationExpectedMs
});
totalBridged += receivedFromRoute;
remainingNeeded -= amountToTake;
}
// Check if we got enough
if (remainingNeeded > 0n) {
throw new Error(`Insufficient balance for bridging:
Required: ${targetAmount.toString()}
Available to bridge: ${totalBridged.toString()}
Shortfall: ${remainingNeeded.toString()}`);
}
return {
instructions,
meta: {
bridgingInstructions,
totalAvailableOnDestination: destinationBalance + totalBridged
}
};
};
export default buildBridgeInstructions;
//# sourceMappingURL=buildBridgeInstructions.js.map