-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
abstract-coder.ts
52 lines (42 loc) · 1.47 KB
/
abstract-coder.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
import type { BytesLike } from '@ethersproject/bytes';
import { Logger } from '@ethersproject/logger';
const logger = new Logger(process.env.BUILD_VERSION || '~');
type Primitive = string | number | boolean | bigint;
/**
* The type of value you can provide to `Coder.encode`
*/
export type InputValue =
| Primitive
| BytesLike
| InputValue[]
| { [key: string]: InputValue }
| Record<string, Primitive | BytesLike>;
/**
* The type of value you can get from `Coder.decode`
*/
export type DecodedValue =
| Primitive
| DecodedValue[]
| { [key: string]: DecodedValue }
| Record<string, Primitive>;
export type TypesOfCoder<TCoder> = TCoder extends Coder<infer TInput, infer TDecoded>
? { Input: TInput; Decoded: TDecoded }
: never;
export default abstract class Coder<TInput = unknown, TDecoded = unknown> {
readonly name: string;
readonly type: string;
readonly encodedLength: number;
constructor(name: string, type: string, encodedLength: number) {
this.name = name;
this.type = type;
this.encodedLength = encodedLength;
}
throwError(message: string, value: unknown): never {
logger.throwArgumentError(message, this.name, value);
// `logger.throwArgumentError` throws, but TS doesn't know it
// so we throw here to make sure our `never` works
throw new Error('unreachable');
}
abstract encode(value: TInput, length?: number): Uint8Array;
abstract decode(data: Uint8Array, offset: number, length?: number): [TDecoded, number];
}