-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
number.ts
68 lines (58 loc) · 1.86 KB
/
number.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { zeroPad } from '@ethersproject/bytes';
import { toArray, toBigInt, toNumber } from '@fuel-ts/math';
import Coder from './abstract-coder';
type NumberCoderType = 'u8' | 'u16' | 'u32' | 'u64';
type ToDecodedType<TBaseType extends NumberCoderType> = TBaseType extends 'u64' ? bigint : number;
export default class NumberCoder<TBaseType extends NumberCoderType = NumberCoderType> extends Coder<
number | bigint,
ToDecodedType<TBaseType>
> {
// This is to align the bits to the total bytes
// See https://github.com/FuelLabs/fuel-specs/blob/master/specs/protocol/abi.md#unsigned-integers
length: number;
baseType: TBaseType;
constructor(baseType: TBaseType) {
super('number', baseType, 8);
this.baseType = baseType;
switch (baseType) {
case 'u8':
this.length = 1;
break;
case 'u16':
this.length = 2;
break;
case 'u32':
this.length = 4;
break;
case 'u64':
default:
this.length = 8;
break;
}
}
encode(value: number | bigint): Uint8Array {
let bytes;
try {
bytes = toArray(value);
} catch (error) {
this.throwError(`Invalid ${this.baseType}`, value);
}
if (bytes.length > this.length) {
this.throwError(`Invalid ${this.baseType}`, value);
}
return zeroPad(bytes, 8);
}
#decodeBigInt(data: Uint8Array, offset: number): [bigint, number] {
let bytes = data.slice(offset, offset + 8);
bytes = bytes.slice(8 - this.length, 8);
const num = toBigInt(bytes);
return [num, offset + 8];
}
decode(data: Uint8Array, offset: number): [ToDecodedType<TBaseType>, number] {
const [num, nextOffset] = this.#decodeBigInt(data, offset);
if (this.baseType === 'u64') {
return [num as ToDecodedType<TBaseType>, nextOffset];
}
return [toNumber(num) as ToDecodedType<TBaseType>, nextOffset];
}
}