cake_wallet/cw_ethereum/lib/ethereum_balance.dart

42 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-01-04 14:51:23 +00:00
import 'package:web3dart/web3dart.dart';
2022-12-28 15:02:04 +00:00
class EthereumBalance extends Balance {
2023-04-05 16:01:20 +00:00
EthereumBalance(this.balance)
: super(balance.getValueInUnit(EtherUnit.wei).toInt(),
balance.getValueInUnit(EtherUnit.wei).toInt());
final EtherAmount balance;
2022-12-28 15:02:04 +00:00
@override
String get formattedAdditionalBalance {
final String formattedBalance = balance.getValueInUnit(EtherUnit.ether).toString();
return formattedBalance.substring(0, min(12, formattedBalance.length));
}
2022-12-28 15:02:04 +00:00
@override
String get formattedAvailableBalance {
final String formattedBalance = balance.getValueInUnit(EtherUnit.ether).toString();
return formattedBalance.substring(0, min(12, formattedBalance.length));
}
2023-01-04 14:51:23 +00:00
2023-04-05 16:01:20 +00:00
String toJSON() => json.encode({'balanceInWei': balance.getInWei.toString()});
2023-01-05 19:05:44 +00:00
static EthereumBalance? fromJSON(String? jsonSource) {
if (jsonSource == null) {
return null;
}
final decoded = json.decode(jsonSource) as Map;
2023-04-05 16:01:20 +00:00
try {
return EthereumBalance(EtherAmount.inWei(BigInt.parse(decoded['balanceInWei'])));
} catch (e) {
return EthereumBalance(EtherAmount.zero());
}
2023-01-05 19:05:44 +00:00
}
2023-01-04 14:51:23 +00:00
}