import { isSuiStructEqual, SUI_COIN } from '@msafe/sui3-utils'; import { SuiClient } from '@mysten/sui.js/client'; import { TransactionBlock } from '@mysten/sui.js/transactions'; export interface CoinTransferIntention { recipient: string; coinType: string; amount: string; } export async function buildCoinTransferTxb(client: SuiClient, intention: CoinTransferIntention, sender: string) { if (isSuiStructEqual(intention.coinType, SUI_COIN)) { return buildSuiCoinTransferTxb(intention, sender); } return buildOtherCoinTransferTxb(client, intention, sender); } export function buildSuiCoinTransferTxb(intention: CoinTransferIntention, sender: string) { const block = new TransactionBlock(); const [coin] = block.splitCoins(block.gas, [block.pure(intention.amount)]); block.transferObjects([coin], block.pure(intention.recipient)); block.setSender(sender); return block; } export async function buildOtherCoinTransferTxb(client: SuiClient, intention: CoinTransferIntention, sender: string) { const { data: objs } = await client.getCoins({ owner: sender, coinType: intention.coinType, }); if (objs.length === 0) { throw new Error('No valid coin found to send'); } const totalBal = objs.reduce((sum, coin) => sum + BigInt(coin.balance), 0n); if (totalBal < BigInt(intention.amount)) { throw new Error('Not enough balance'); } const txb = new TransactionBlock(); const primary = txb.object(objs[0].coinObjectId); if (objs.length > 1) { txb.mergeCoins( primary, objs.slice(1).map((obj) => txb.object(obj.coinObjectId)), ); } const [coin] = txb.splitCoins(primary, [txb.pure(intention.amount)]); txb.transferObjects([coin], txb.pure(intention.recipient)); txb.setSender(sender); return txb; }