import * as types from "../config/types" ; import * as checkUtil from './checkUtil' ; import BN from 'bn.js' ; const UNPREFIX_HEX_REGEX = /^[a-fA-F0-9]+$/ ; const evenHexDigit = ( hex ) => ( hex . length % 2 !== 0 ? `0${ hex }` : hex ) ; export const removeHex0x = ( hex ) => ( hex . slice ( 0 , 2 ) === '0x' ? hex . slice ( 2 ) : hex ) ; export const handleHex = ( hex ) => evenHexDigit ( removeHex0x ( hex ) ) ; export function bnToBn < ExtToBn extends types . ToBn > ( value ? ) { if ( ! value ) { return new BN ( 0 ) ; } else if ( checkUtil . isHex ( value ) ) { return hexToBn ( value . toString ( ) ) ; } else if ( checkUtil . isBigInt ( value ) ) { return new BN ( value . toString ( ) ) ; } return numberToBn ( value ) ; } export function hexToBn ( value ? , options = { isLe : false , isNegative : false } ) { if ( ! value ) { return new BN ( 0 ) ; } const _options = { isLe : false , isNegative : false , ... ( checkUtil . isBoolean ( options ) ? { isLe : options } : options ) } ; const _value = hexStripPrefix ( value as string ) ; const bn = new BN ( ( _options . isLe ? reverse ( _value ) : _value ) || '00' , 16 ) ; return _options . isNegative ? bn . fromTwos ( _value . length * 4 ) : bn ; } export function hexStripPrefix ( value ? ) { if ( ! value ) { return '' ; } if ( hexHasPrefix ( value ) ) { return value . substr ( 2 ) ; } if ( UNPREFIX_HEX_REGEX . test ( value ) ) { return value ; } throw new Error ( `Invalid hex ${ value } passed to hexStripPrefix` ) ; } export function hexHasPrefix ( value ? ) { return ! ! ( value && checkUtil . isHex ( value , - 1 , true ) && value . substr ( 0 , 2 ) === '0x' ) ; } export function reverse ( value ) { return ( value . match ( /.{1,2}/g ) || [ ] ) . reverse ( ) . join ( '' ) ; } export function numberToBn < ExtToBn extends types . ToBn > ( value ) { return BN . isBN ( value ) ? value : checkUtil . isToBn ( value ) ? value . toBn ( ) : new BN ( value ) ; } export function paddingString ( binaryString ) { if ( binaryString . length % 2 != 0 ) { return '0' + binaryString ; } return binaryString ; }