-
Notifications
You must be signed in to change notification settings - Fork 110
/
bytes.ts
118 lines (98 loc) · 2.63 KB
/
bytes.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { BaseTokenSchema } from '../../schema/types';
import {
TokenFactory,
ComparableToken,
TokenValidationError,
Token,
SemanticEncoding,
} from '../token';
import { stripHexPrefix } from '@taquito/utils';
/**
* @category Error
* @description Error that indicates a failure happening when parsing encoding/executing Bytes
*/
export class BytesValidationError extends TokenValidationError {
name = 'BytesValidationError';
constructor(public value: any, public token: BytesToken, message: string) {
super(value, token, message);
}
}
export class BytesToken extends ComparableToken {
static prim: 'bytes' = 'bytes' as const;
constructor(
protected val: { prim: string; args: any[]; annots: any[] },
protected idx: number,
protected fac: TokenFactory
) {
super(val, idx, fac);
}
public ToBigMapKey(val: string) {
return {
key: { bytes: val },
type: { prim: BytesToken.prim },
};
}
/**
* @throws {@link BytesValidationError}
*/
private validate(val: any) {
if (typeof val === 'string' && /^[0-9a-fA-F]*$/.test(val) && val.length % 2 === 0) {
return;
}
throw new BytesValidationError(val, this, `Invalid bytes: ${val}`);
}
private convertUint8ArrayToHexString(val: any) {
return val.constructor === Uint8Array ? Buffer.from(val).toString('hex') : val;
}
/**
* @throws {@link BytesValidationError}
*/
public Encode(args: any[]): any {
let val = args.pop();
val = stripHexPrefix(this.convertUint8ArrayToHexString(val));
this.validate(val);
return { bytes: String(val).toString() };
}
/**
* @throws {@link BytesValidationError}
*/
public EncodeObject(val: string | Uint8Array, semantic?: SemanticEncoding) {
val = this.convertUint8ArrayToHexString(val);
if (typeof val === 'string') {
val = stripHexPrefix(val);
}
this.validate(val);
if (semantic && semantic[BytesToken.prim]) {
return semantic[BytesToken.prim](val);
}
return { bytes: String(val).toString() };
}
public Execute(val: any): string {
return val.bytes;
}
/**
* @deprecated ExtractSchema has been deprecated in favor of generateSchema
*
*/
public ExtractSchema() {
return BytesToken.prim;
}
generateSchema(): BaseTokenSchema {
return {
__michelsonType: BytesToken.prim,
schema: BytesToken.prim,
};
}
public ToKey({ bytes, string }: any) {
if (string) {
return string;
}
return bytes;
}
findAndReturnTokens(tokenToFind: string, tokens: Token[]) {
if (BytesToken.prim === tokenToFind) {
tokens.push(this);
}
return tokens;
}
}