OSDN Git Service

update error code
[bytom/Bytom-JS-SDK.git] / src / utils / convertArguement.js
1 import { hexEncode } from './hex.js';
2 import bech32 from 'bech32';
3 import Error from './error';
4
5 export function convertArgument(obj){
6     const type = obj.type;
7     const value = obj.raw_data.value;
8     let convertValue;
9     switch (type) {
10     case 'data' :
11         convertValue =convertData(value);
12         break;
13     case 'integer':
14         convertValue = convertInteger(value);
15         break;
16     case 'string':
17         convertValue = hexEncode(value);
18         break;
19     case 'boolean':
20         convertValue = convertBoolean(value);
21         break;
22     case 'address':
23         convertValue = convertAddress(value);
24         break;
25     default:
26         throw new Error('Invalid data type.', 'BTM3101');
27     }
28     return { data: convertValue };
29 }
30
31 function convertBoolean(bool) {
32     if(bool === true){
33         return '01';
34     }else if(bool === false){
35         return '';
36     }else {
37         throw new Error('Invalid Boolean argument','BTM3102');
38     }
39 }
40
41 function convertInteger(int){
42     const hexInt =  Number(int).toString(16);
43     if(hexInt.length % 2){
44         return convertToLittleEnd('0'+hexInt);
45     }else{
46         return convertToLittleEnd(hexInt);
47     }
48 }
49
50 function convertToLittleEnd(hex){
51     return hex.match(/../g).reverse().join('');
52 }
53
54 function convertData(data){
55     if(/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/i.test(data)){
56         return data;
57     }else{
58         throw new Error('Invalid hex data','BTM3103');
59     }
60 }
61
62 function convertAddress(address) {
63     const addressPrefix = address.substring(0,2);
64     const validAddressArray = ['tm', 'bm', 'sm'];
65     if( !validAddressArray.includes(addressPrefix) ){
66         throw 'bad address format';
67     }
68
69     const decodedWord = bech32.decode(address);
70     let array = decodedWord.words;
71     array.shift();
72
73     const words = bech32.fromWords(array);
74
75     if(words.length!==20 && words.length!==32){
76         throw `invalid data length for witness , ${words.length}`;
77     }
78
79     const hex  = '00'+Number(words.length).toString(16)+(Buffer.from(words)).toString('hex');
80
81     return hex;
82 }