2023-01-04 14:51:23 +00:00
|
|
|
import 'dart:convert';
|
2023-04-14 12:05:24 +00:00
|
|
|
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
|
2023-04-14 12:05:24 +00:00
|
|
|
String get formattedAdditionalBalance {
|
2023-05-23 18:31:54 +00:00
|
|
|
final String formattedBalance = (balance / BigInt.from(10).pow(exponent)).toString();
|
2023-04-14 12:05:24 +00:00
|
|
|
return formattedBalance.substring(0, min(12, formattedBalance.length));
|
|
|
|
}
|
2022-12-28 15:02:04 +00:00
|
|
|
|
|
|
|
@override
|
2023-04-14 12:05:24 +00:00
|
|
|
String get formattedAvailableBalance {
|
2023-05-23 18:31:54 +00:00
|
|
|
final String formattedBalance = (balance / BigInt.from(10).pow(exponent)).toString();
|
2023-04-14 12:05:24 +00:00
|
|
|
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
|
|
|
}
|