This repository has been archived by the owner on Jun 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
mosaic.service.ts
87 lines (80 loc) · 2.76 KB
/
mosaic.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
*
* Copyright 2018-present NEM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {ExpectedError} from 'clime';
import {Mosaic, MosaicId, NamespaceId, UInt64} from 'nem2-sdk';
/**
* Mosaic service
*/
export class MosaicService {
public static ALIAS_TAG = '@';
/**
* Constructor
*/
constructor() {}
/**
* Validates a mosaic object from a string.
* @param {string} value - Mosaic in the form mosaicId::amount.
* @throws {ExpectedError}
*/
static validate(value: string) {
const mosaicParts = value.split('::');
let valid = true;
try {
if (isNaN(+mosaicParts[1])) {
valid = false;
}
const ignored = new Mosaic(this.getMosaicId(mosaicParts[0]),
UInt64.fromUint(+mosaicParts[1]));
} catch (err) {
valid = false;
}
if (!valid) {
throw new ExpectedError('Mosaic should be in the format (mosaicId(hex)|@aliasName)::absoluteAmount,' +
' (Ex: sending 1 cat.currency, @cat.currency::1000000)');
}
}
/**
* Creates a MosaicId object from a string.
* @param {string} rawMosaicId - Mosaic identifier. If starts with "@", it is a namespace name.
* @returns {MosaicId | NamespaceId}
*/
static getMosaicId(rawMosaicId: string): MosaicId | NamespaceId {
let mosaicId: MosaicId | NamespaceId;
if (rawMosaicId.charAt(0) === MosaicService.ALIAS_TAG) {
mosaicId = new NamespaceId(rawMosaicId.substring(1));
} else {
mosaicId = new MosaicId(rawMosaicId);
}
return mosaicId;
}
/**
* Creates an array of mosaics from a string.
* @param {string} rawMosaics - Mosaics in the form mosaicId::amount, separated by commas.
* @returns {Mosaic[]}
*/
static getMosaics(rawMosaics: string): Mosaic[] {
const mosaics: Mosaic[] = [];
const mosaicsData = rawMosaics.split(',');
mosaicsData.forEach((mosaicData) => {
const mosaicParts = mosaicData.split('::');
mosaics.push(new Mosaic(this.getMosaicId(mosaicParts[0]),
UInt64.fromNumericString(mosaicParts[1])));
});
return mosaics;
}
}