1 import { hexEncode } from './hex.js';
2 import bech32 from 'bech32';
3 import Error from './error';
5 export function convertArgument(obj){
7 const value = obj.raw_data.value;
11 convertValue =convertData(value);
14 convertValue = convertInteger(value);
17 convertValue = hexEncode(value);
20 convertValue = convertBoolean(value);
23 convertValue = convertAddress(value);
26 throw new Error('Invalid data type.', 'BTM3101');
28 return { data: convertValue };
31 function convertBoolean(bool) {
34 }else if(bool === false){
37 throw new Error('Invalid Boolean argument','BTM3102');
41 function convertInteger(int){
42 const hexInt = Number(int).toString(16);
43 if(hexInt.length % 2){
44 return convertToLittleEnd('0'+hexInt);
46 return convertToLittleEnd(hexInt);
50 function convertToLittleEnd(hex){
51 return hex.match(/../g).reverse().join('');
54 function convertData(data){
55 if(/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/i.test(data)){
58 throw new Error('Invalid hex data','BTM3103');
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';
69 const decodedWord = bech32.decode(address);
70 let array = decodedWord.words;
73 const words = bech32.fromWords(array);
75 if(words.length!==20 && words.length!==32){
76 throw `invalid data length for witness , ${words.length}`;
79 const hex = '00'+Number(words.length).toString(16)+(Buffer.from(words)).toString('hex');