-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
B256Coder.ts
45 lines (36 loc) · 1.25 KB
/
B256Coder.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
import { ErrorCode, FuelError } from '@fuel-ts/errors';
import { bn, toHex } from '@fuel-ts/math';
import { arrayify } from '@fuel-ts/utils';
import { WORD_SIZE } from '../../utils/constants';
import { Coder } from './AbstractCoder';
export class B256Coder extends Coder<string, string> {
constructor() {
super('b256', 'b256', WORD_SIZE * 4);
}
encode(value: string): Uint8Array {
let encodedValue;
try {
encodedValue = arrayify(value);
} catch (error) {
throw new FuelError(ErrorCode.ENCODE_ERROR, `Invalid ${this.type}.`);
}
if (encodedValue.length !== this.encodedLength) {
throw new FuelError(ErrorCode.ENCODE_ERROR, `Invalid ${this.type}.`);
}
return encodedValue;
}
decode(data: Uint8Array, offset: number): [string, number] {
if (data.length < this.encodedLength) {
throw new FuelError(ErrorCode.DECODE_ERROR, `Invalid b256 data size.`);
}
let bytes = data.slice(offset, offset + this.encodedLength);
const decoded = bn(bytes);
if (decoded.isZero()) {
bytes = new Uint8Array(32);
}
if (bytes.length !== this.encodedLength) {
throw new FuelError(ErrorCode.DECODE_ERROR, `Invalid b256 byte data size.`);
}
return [toHex(bytes, 32), offset + 32];
}
}