From 3ab605c065d8b47c1baab0b4859f596e7422810c Mon Sep 17 00:00:00 2001 From: julian Date: Fri, 24 Mar 2023 15:30:29 -0600 Subject: [PATCH] amount serialization --- lib/utilities/amount.dart | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/utilities/amount.dart b/lib/utilities/amount.dart index 6955e2489..74d37b6b5 100644 --- a/lib/utilities/amount.dart +++ b/lib/utilities/amount.dart @@ -1,8 +1,11 @@ +import 'dart:convert'; + import 'package:decimal/decimal.dart'; +import 'package:equatable/equatable.dart'; final _ten = BigInt.from(10); -class Amount { +class Amount implements Equatable { Amount({ required BigInt rawValue, required this.fractionDigits, @@ -40,4 +43,38 @@ class Amount { /// convenience getter @Deprecated("provided for convenience only. Use fractionDigits instead.") int get decimals => fractionDigits; + + Map toMap() { + // =========================================================================== + // ======= Serialization ===================================================== + + return {"raw": raw.toString(), "fractionDigits": fractionDigits}; + } + + String toJsonString() { + return jsonEncode(toMap()); + } + + // =========================================================================== + // ======= Deserialization =================================================== + + static Amount fromSerializedJsonString(String json) { + final map = jsonDecode(json) as Map; + return Amount( + rawValue: BigInt.parse(map["raw"] as String), + fractionDigits: map["fractionDigits"] as int, + ); + } + + // =========================================================================== + // ======= Overrides ========================================================= + + @override + String toString() => "Amount($raw, $fractionDigits)"; + + @override + List get props => [fractionDigits, _value]; + + @override + bool? get stringify => false; }