cake_wallet/cw_ethereum/lib/erc20_balance.dart

48 lines
1.2 KiB
Dart
Raw Normal View History

2023-01-04 14:51:23 +00:00
import 'dart:convert';
import 'dart:math';
2023-01-04 14:51:23 +00:00
2022-12-28 15:02:04 +00:00
import 'package:cw_core/balance.dart';
2023-05-23 18:31:54 +00:00
class ERC20Balance extends Balance {
ERC20Balance(this.balance, {this.exponent = 18})
: super(balance.toInt(),
balance.toInt());
2023-04-05 16:01:20 +00:00
2023-05-23 18:31:54 +00:00
final BigInt balance;
final int exponent;
2022-12-28 15:02:04 +00:00
@override
String get formattedAdditionalBalance {
2023-05-23 18:31:54 +00:00
final String formattedBalance = (balance / BigInt.from(10).pow(exponent)).toString();
return formattedBalance.substring(0, min(12, formattedBalance.length));
}
2022-12-28 15:02:04 +00:00
@override
String get formattedAvailableBalance {
2023-05-23 18:31:54 +00:00
final String formattedBalance = (balance / BigInt.from(10).pow(exponent)).toString();
return formattedBalance.substring(0, min(12, formattedBalance.length));
}
2023-01-04 14:51:23 +00:00
2023-05-23 18:31:54 +00:00
String toJSON() => json.encode({
'balanceInWei': balance.toString(),
'exponent': exponent,
});
2023-01-05 19:05:44 +00:00
2023-05-23 18:31:54 +00:00
static ERC20Balance? fromJSON(String? jsonSource) {
2023-01-05 19:05:44 +00:00
if (jsonSource == null) {
return null;
}
final decoded = json.decode(jsonSource) as Map;
2023-04-05 16:01:20 +00:00
try {
2023-05-23 18:31:54 +00:00
return ERC20Balance(
BigInt.parse(decoded['balanceInWei']),
exponent: decoded['exponent'],
);
2023-04-05 16:01:20 +00:00
} catch (e) {
2023-05-23 18:31:54 +00:00
return ERC20Balance(BigInt.zero);
2023-04-05 16:01:20 +00:00
}
2023-01-05 19:05:44 +00:00
}
2023-01-04 14:51:23 +00:00
}