findWalCoin method

Future<String?> findWalCoin(
  1. String ownerAddress,
  2. BigInt requiredAmount, {
  3. bool merge = false,
})

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 and the combined balance is sufficient, returns the largest coin as a merge candidate. This method does not sign or merge; call mergeWalCoins before using a candidate with insufficient balance.

Implementation

Future<String?> findWalCoin(
  String ownerAddress,
  BigInt requiredAmount, {
  bool merge = false,
}) async {
  final walType = await getWalType();
  var totalBalance = BigInt.zero;
  CoinStruct? largestCoin;
  var largestBalance = BigInt.zero;

  // Stop as soon as one coin suffices; otherwise search the full balance.
  await for (final coin in walCoins(suiClient, ownerAddress, walType)) {
    final balance = BigInt.tryParse(coin.balance) ?? BigInt.zero;
    if (balance >= requiredAmount) {
      return coin.coinObjectId;
    }
    totalBalance += balance;
    if (largestCoin == null || balance > largestBalance) {
      largestCoin = coin;
      largestBalance = balance;
    }
  }

  if (merge && totalBalance >= requiredAmount) {
    return largestCoin?.coinObjectId;
  }

  return null;
}