-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
b256.ts
36 lines (30 loc) · 903 Bytes
/
b256.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
import { hexlify, arrayify } from '@ethersproject/bytes';
import { toBigInt } from '@fuel-ts/math';
import Coder from './abstract-coder';
export default class B256Coder extends Coder<string, string> {
constructor() {
super('b256', 'b256', 32);
}
encode(value: string): Uint8Array {
let encodedValue;
try {
encodedValue = arrayify(value);
} catch (error) {
this.throwError(`Invalid ${this.type}`, value);
}
if (encodedValue.length !== 32) {
this.throwError(`Invalid ${this.type}`, value);
}
return encodedValue;
}
decode(data: Uint8Array, offset: number): [string, number] {
let bytes = data.slice(offset, offset + 32);
if (toBigInt(bytes) === 0n) {
bytes = new Uint8Array(32);
}
if (bytes.length !== 32) {
this.throwError('Invalid size for b256', bytes);
}
return [hexlify(bytes), offset + 32];
}
}