11import BigNumber from "bignumber.js" ;
22import { BigIntType , BigIntValue , ManagedDecimalSignedType , ManagedDecimalSignedValue , U32Value } from "../typesystem" ;
33import { BinaryCodec } from "./binary" ;
4- import { bufferToBigInt } from "./utils" ;
54import { SizeOfU32 } from "./constants" ;
5+ import { bufferToBigInt } from "./utils" ;
66
77export class ManagedDecimalSignedCodec {
88 private readonly binaryCodec : BinaryCodec ;
@@ -12,8 +12,20 @@ export class ManagedDecimalSignedCodec {
1212 }
1313
1414 decodeNested ( buffer : Buffer , type : ManagedDecimalSignedType ) : [ ManagedDecimalSignedValue , number ] {
15- const length = buffer . readUInt32BE ( 0 ) ;
16- const payload = buffer . slice ( 0 , length ) ;
15+ let payload : Buffer ;
16+ let length : number ;
17+
18+ if ( type . isVariable ( ) ) {
19+ // read BigInt value length
20+ const bigIntSizeBytes = buffer . slice ( 0 , SizeOfU32 ) ;
21+ const bigIntLength = bigIntSizeBytes . readUInt32BE ( 0 ) ;
22+
23+ length = SizeOfU32 + bigIntLength + SizeOfU32 ;
24+ payload = buffer . slice ( 0 , length ) ;
25+ } else {
26+ length = buffer . readUInt32BE ( 0 ) ;
27+ payload = buffer . slice ( 0 , length ) ;
28+ }
1729
1830 const result = this . decodeTopLevel ( payload , type ) ;
1931 return [ result , length ] ;
@@ -30,13 +42,15 @@ export class ManagedDecimalSignedCodec {
3042 const [ value ] = this . binaryCodec . decodeNested ( buffer . slice ( 0 , bigintSize ) , new BigIntType ( ) ) ;
3143 const scale = buffer . readUInt32BE ( bigintSize ) ;
3244
33- return new ManagedDecimalSignedValue ( value . valueOf ( ) . shiftedBy ( - scale ) , scale ) ;
45+ return new ManagedDecimalSignedValue ( value . valueOf ( ) . shiftedBy ( - scale ) , scale , true ) ;
3446 }
3547
3648 const value = bufferToBigInt ( buffer ) ;
3749 const metadata = type . getMetadata ( ) ;
50+
51+ // if this code executes, metadata is guaranteed to be a number
3852 const scale = metadata !== "usize" ? parseInt ( metadata . toString ( ) ) : 0 ;
39- return new ManagedDecimalSignedValue ( value . shiftedBy ( - scale ) , scale ) ;
53+ return new ManagedDecimalSignedValue ( value . shiftedBy ( - scale ) , scale , false ) ;
4054 }
4155
4256 encodeNested ( value : ManagedDecimalSignedValue ) : Buffer {
0 commit comments