@@ -44,6 +44,15 @@ export class ChainportMemoMetadata {
44
44
return String . fromCharCode ( num - 10 + "a" . charCodeAt ( 0 ) ) ;
45
45
}
46
46
47
+ public static convertHexToBinary ( encodedHex : string ) : string {
48
+ const buffer = Buffer . from ( encodedHex , "hex" ) ;
49
+ let binaryString = "" ;
50
+ for ( let i = 0 ; i < buffer . length ; i ++ ) {
51
+ binaryString += buffer [ i ] . toString ( 2 ) . padStart ( 8 , "0" ) ;
52
+ }
53
+ return binaryString ;
54
+ }
55
+
47
56
/**
48
57
* Decode the encoded hex string into a network id, address, and toIronfish flag
49
58
* @param encodedHex - The encoded hex string
@@ -70,12 +79,30 @@ export class ChainportMemoMetadata {
70
79
}
71
80
72
81
public static decodeV2 ( encodedHex : string ) : [ number , string , boolean ] {
73
- const bytes = Buffer . from ( encodedHex , "hex" ) ;
74
- const networkId = bytes . readUInt8 ( 0 ) ;
75
- const addressBytes = bytes . subarray ( 1 , 21 ) ;
76
- const address = "0x" + addressBytes . toString ( "hex" ) ;
77
- const toIronfish = ( bytes [ 21 ] & 0x80 ) !== 0 ;
82
+ const bits = this . convertHexToBinary ( encodedHex ) ;
83
+ const toIronfish = bits [ 6 ] === "1" ;
84
+ const memoHexVersion = bits . slice ( 8 , 10 ) ;
85
+ if ( memoHexVersion !== "01" ) {
86
+ throw new Error ( `Unexpected memoHex version: ${ memoHexVersion } ` ) ;
87
+ }
88
+
89
+ const networkIdBits = bits . slice ( 10 , 16 ) ;
90
+ const networkId = parseInt ( networkIdBits , 2 ) ;
91
+ const addressBits = bits . slice ( 16 , 176 ) ;
92
+ let address = "0x" ;
93
+ for ( let i = 0 ; i < addressBits . length ; i += 4 ) {
94
+ address += parseInt ( addressBits . slice ( i , i + 4 ) , 2 ) . toString ( 16 ) ;
95
+ }
78
96
79
97
return [ networkId , address . toLowerCase ( ) , toIronfish ] ;
80
98
}
99
+
100
+ public static decode ( encodedHex : string ) : [ number , string , boolean ] {
101
+ const bits = this . convertHexToBinary ( encodedHex ) ;
102
+ const memoHexVersion = bits . slice ( 8 , 10 ) ;
103
+ if ( memoHexVersion === "01" ) {
104
+ return this . decodeV2 ( encodedHex ) ;
105
+ }
106
+ return this . decodeV1 ( encodedHex ) ;
107
+ }
81
108
}
0 commit comments