aboutsummaryrefslogtreecommitdiff
path: root/src/amounts.ts
diff options
context:
space:
mode:
authorFlorian Dold <florian.dold@gmail.com>2018-01-29 22:58:47 +0100
committerFlorian Dold <florian.dold@gmail.com>2018-01-29 22:58:47 +0100
commit97f6e68ce3a515938228b9a4d3e41b5f4b25a015 (patch)
tree371331acc56b7c56abec502126c2a40cdb23a95f /src/amounts.ts
parent9fe6dc596573f38b13f0b15c946b8bc16013fdd9 (diff)
change protocol to string amount network format
Diffstat (limited to 'src/amounts.ts')
-rw-r--r--src/amounts.ts36
1 files changed, 32 insertions, 4 deletions
diff --git a/src/amounts.ts b/src/amounts.ts
index a31bec3da..fafbcb3ef 100644
--- a/src/amounts.ts
+++ b/src/amounts.ts
@@ -38,19 +38,19 @@ export class AmountJson {
/**
* Value, must be an integer.
*/
- @Checkable.Number
+ @Checkable.Number()
readonly value: number;
/**
* Fraction, must be an integer. Represent 1/1e8 of a unit.
*/
- @Checkable.Number
+ @Checkable.Number()
readonly fraction: number;
/**
* Currency of the amount.
*/
- @Checkable.String
+ @Checkable.String()
readonly currency: string;
/**
@@ -226,7 +226,7 @@ export function isNonZero(a: AmountJson): boolean {
* Parse an amount like 'EUR:20.5' for 20 Euros and 50 ct.
*/
export function parse(s: string): AmountJson|undefined {
- const res = s.match(/([a-zA-Z0-9_*-]+):([0-9])+([.][0-9]+)?/);
+ const res = s.match(/([a-zA-Z0-9_*-]+):([0-9]+)([.][0-9]+)?/);
if (!res) {
return undefined;
}
@@ -237,6 +237,14 @@ export function parse(s: string): AmountJson|undefined {
};
}
+export function parseOrThrow(s: string): AmountJson {
+ const res = parse(s);
+ if (!res) {
+ throw Error(`Can't parse amount: "${s}"`);
+ }
+ return res;
+}
+
/**
* Convert the amount to a float.
*/
@@ -255,3 +263,23 @@ export function fromFloat(floatVal: number, currency: string) {
value: Math.floor(floatVal),
};
}
+
+/**
+ * Convert to standard human-readable string representation that's
+ * also used in JSON formats.
+ */
+export function toString(a: AmountJson) {
+ return `${a.currency}:${a.value + (a.fraction / fractionalBase)}`;
+}
+
+export function check(a: any) {
+ if (typeof a !== "string") {
+ return false;
+ }
+ try {
+ const parsedAmount = parse(a);
+ return !!parsedAmount;
+ } catch {
+ return false;
+ }
+}