feat: add `truncateDecimals` method to EVMChainFormatter and update transaction logic to improve decimal handling (#2540)

Konstantin Ullrich committed Sep 25, 2025 at 14:52 UTC 28184e223a6cdbb5709bcf52d7d8379af9c575a3
3 files changed +26 -9
cw_evm/lib/evm_chain_formatter.dart
+10
@@ -21,6 +21,16 @@ class EVMChainFormatter {
21 }
22 }
23
24 + static String truncateDecimals(String amount, int decimals) {
25 + final parts = amount.split(".");
26 +
27 + if (parts.length == 2) {
28 + parts[1] = parts[1].substring(0, parts[1].length > decimals ? decimals : parts[1].length);
29 + }
30 +
31 + return parts.join(".");
32 + }
33 +
34 static int _getDividerForInput(String amount) {
35 final result = amount.split('.');
36 if (result.length > 1) {
cw_evm/lib/evm_chain_wallet.dart
+5 -2
@@ -490,7 +490,9 @@ abstract class EVMChainWalletBase
490
491 final totalOriginalAmount = EVMChainFormatter.parseEVMChainAmountToDouble(
492 outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0)));
493 - totalAmount = parseFixed(totalOriginalAmount.toString(), exponent);
493 +
494 + totalAmount = parseFixed(
495 + EVMChainFormatter.truncateDecimals(totalOriginalAmount.toString(), exponent), exponent);
496
497 final gasFeesModel = await calculateActualEstimatedFeeForCreateTransaction(
498 amount: totalAmount,
@@ -512,7 +514,8 @@ abstract class EVMChainWalletBase
514 final totalOriginalAmount =
515 EVMChainFormatter.parseEVMChainAmountToDouble(output.formattedCryptoAmount ?? 0);
516
515 - totalAmount = parseFixed(totalOriginalAmount.toString(), exponent);
517 + totalAmount = parseFixed(
518 + EVMChainFormatter.truncateDecimals(totalOriginalAmount.toString(), exponent), exponent);
519 }
520
521 if (output.sendAll && transactionCurrency is Erc20Token) {
cw_evm/test/cw_evm_test.dart
+11 -7
@@ -1,12 +1,16 @@
1 +import 'package:cw_evm/evm_chain_formatter.dart';
2 import 'package:flutter_test/flutter_test.dart';
3
3 -import 'package:cw_evm/cw_evm.dart';
4 -
4 void main() {
6 - test('adds one to input values', () {
7 - final calculator = Calculator();
8 - expect(calculator.addOne(2), 3);
9 - expect(calculator.addOne(-7), -6);
10 - expect(calculator.addOne(0), 1);
5 + group('EVMChainFormatter', () {
6 + group('truncateDecimals', () {
7 + test('no decimals', () => expect(EVMChainFormatter.truncateDecimals("5", 6), "5"));
8 + test('less than max decimals',
9 + () => expect(EVMChainFormatter.truncateDecimals("5.00001", 6), "5.00001"));
10 + test('max decimals',
11 + () => expect(EVMChainFormatter.truncateDecimals("5.000001", 6), "5.000001"));
12 + test('more than max decimals',
13 + () => expect(EVMChainFormatter.truncateDecimals("5.0000001", 6), "5.000000"));
14 + });
15 });
16 }