|
| 1 | +import { formatEther, Hex } from 'viem'; |
| 2 | +import { actionPresets } from './common'; |
| 3 | +import { printTransactionHash, showError, showText } from '../display'; |
| 4 | +import { collapseAddress } from '../common'; |
| 5 | +import { getSymbolFromChainId, promptForConfirmation } from '../getters'; |
| 6 | + |
| 7 | +export const transferSignerBalanceAction = async ( |
| 8 | + symbol: string, |
| 9 | + params: { |
| 10 | + receiver: Hex; |
| 11 | + gasLimit: number; |
| 12 | + }, |
| 13 | +) => { |
| 14 | + try { |
| 15 | + const { cm, config } = await actionPresets(symbol, false); |
| 16 | + const currencySymbol = getSymbolFromChainId(cm.chainId); |
| 17 | + |
| 18 | + // Get current balance |
| 19 | + const balance = await cm.client.getBalance({ |
| 20 | + address: cm.signer, |
| 21 | + }); |
| 22 | + |
| 23 | + // Estimate gas for the transfer |
| 24 | + const gasPrice = await cm.client.getGasPrice(); |
| 25 | + const gasLimit = BigInt(params.gasLimit); |
| 26 | + const gasCost = gasPrice * BigInt(gasLimit); |
| 27 | + |
| 28 | + if (balance <= gasCost) { |
| 29 | + throw new Error( |
| 30 | + `Insufficient balance to cover gas fees. Balance: ${formatEther(balance)} ${currencySymbol}, Gas cost: ${formatEther(gasCost)} ${currencySymbol}`, |
| 31 | + ); |
| 32 | + } |
| 33 | + |
| 34 | + // Transfer amount = balance - gas cost |
| 35 | + const transferAmount = balance - gasCost; |
| 36 | + |
| 37 | + const confirm = await promptForConfirmation( |
| 38 | + `You are about to transfer all available balance: ${formatEther(balance)} ${currencySymbol} to ${collapseAddress(params.receiver)}. Do you want to proceed?`, |
| 39 | + ); |
| 40 | + if (!confirm) { |
| 41 | + showText('Transfer cancelled. Aborting...'); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + showText( |
| 46 | + `Transferring all available balance: ${formatEther(transferAmount)} ${currencySymbol} to ${collapseAddress(params.receiver)}`, |
| 47 | + `(Reserving ${formatEther(gasCost)} ${currencySymbol} for gas fees)`, |
| 48 | + false, |
| 49 | + false, |
| 50 | + ); |
| 51 | + |
| 52 | + const txHash = await cm.transferNative({ |
| 53 | + to: params.receiver, |
| 54 | + amount: transferAmount, |
| 55 | + gasLimit, |
| 56 | + }); |
| 57 | + |
| 58 | + const receipt = await cm.waitForTransactionReceipt(txHash); |
| 59 | + |
| 60 | + if (receipt.status !== 'success') { |
| 61 | + throw new Error('Transaction failed'); |
| 62 | + } |
| 63 | + |
| 64 | + printTransactionHash(receipt.transactionHash, config.chainId); |
| 65 | + showText( |
| 66 | + `Successfully transferred ${formatEther(transferAmount)} ${currencySymbol} to ${collapseAddress(params.receiver)}`, |
| 67 | + ); |
| 68 | + } catch (error: any) { |
| 69 | + showError({ |
| 70 | + text: `Failed to transfer all native currency: ${error.message}`, |
| 71 | + }); |
| 72 | + } |
| 73 | +}; |
0 commit comments