findWalCoin method
Find a WAL coin with sufficient balance for the given amount.
Returns the coin object ID, or null if no coin has enough balance.
If merge is true, will merge coins to create one with enough.
Implementation
Future<String?> findWalCoin(
String ownerAddress,
BigInt requiredAmount, {
bool merge = false,
}) async {
final walType = await getWalType();
final coins = await suiClient.getCoins(ownerAddress, coinType: walType);
if (coins.data.isEmpty) return null;
// Try to find a single coin with enough balance.
for (final coin in coins.data) {
final balance = BigInt.tryParse(coin.balance) ?? BigInt.zero;
if (balance >= requiredAmount) {
return coin.coinObjectId;
}
}
// If merge requested and we have multiple coins, check combined balance.
if (merge && coins.data.isNotEmpty) {
// Sum all coin balances to check if combined amount is sufficient.
var totalBalance = BigInt.zero;
for (final coin in coins.data) {
totalBalance += BigInt.tryParse(coin.balance) ?? BigInt.zero;
}
if (totalBalance < requiredAmount) {
// Combined balance insufficient even after merging.
return null;
}
// Return the largest coin — caller should merge before using.
coins.data.sort((a, b) {
final balA = BigInt.tryParse(a.balance) ?? BigInt.zero;
final balB = BigInt.tryParse(b.balance) ?? BigInt.zero;
return balB.compareTo(balA);
});
return coins.data.first.coinObjectId;
}
return null;
}