-
Notifications
You must be signed in to change notification settings - Fork 110
/
contract.ts
112 lines (100 loc) · 2.77 KB
/
contract.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
import { TokenSchema } from './../schema/types';
import { encodeAddress, validateAddress, ValidationResult } from '@taquito/utils';
import { ContractTokenSchema } from '../schema/types';
import { SemanticEncoding, Token, TokenFactory, TokenValidationError } from './token';
/**
* @category Error
* @description Error that indicates a failure happening when parsing encoding/executing a Contract
*/
export class ContractValidationError extends TokenValidationError {
name = 'ContractValidationError';
constructor(
public value: any,
public token: ContractToken,
message: string
) {
super(value, token, message);
}
}
export class ContractToken extends Token {
static prim: 'contract' = 'contract' as const;
constructor(
protected val: { prim: string; args: any[]; annots: any[] },
protected idx: number,
protected fac: TokenFactory
) {
super(val, idx, fac);
}
/**
* @throws {@link ContractValidationError}
*/
private validate(value: any) {
// tz1,tz2 and tz3 seems to be valid contract values (for Unit contract)
if (validateAddress(value) !== ValidationResult.VALID) {
throw new ContractValidationError(
value,
this,
`Value ${JSON.stringify(value)} is not a valid contract address.`
);
}
return null;
}
/**
* @throws {@link ContractValidationError}
*/
public Execute(val: { bytes: string; string: string }) {
if (val.string) {
return val.string;
}
if (!val.bytes) {
throw new ContractValidationError(
val,
this,
`Value ${JSON.stringify(
val
)} is not a valid contract address. must contain bytes or string.`
);
}
return encodeAddress(val.bytes);
}
/**
* @throws {@link ContractValidationError}
*/
public Encode(args: any[]): any {
const val = args.pop();
this.validate(val);
return { string: val };
}
/**
* @throws {@link ContractValidationError}
*/
public EncodeObject(val: any, semantic?: SemanticEncoding): any {
this.validate(val);
if (semantic && semantic[ContractToken.prim]) {
return semantic[ContractToken.prim](val);
}
return { string: val };
}
/**
* @deprecated ExtractSchema has been deprecated in favor of generateSchema
*
*/
public ExtractSchema() {
return ContractToken.prim;
}
generateSchema(): ContractTokenSchema {
const valueSchema = this.createToken(this.val.args[0], 0);
return {
__michelsonType: ContractToken.prim,
schema: {
parameter: this.val.args[0] ? valueSchema.generateSchema() : ({} as TokenSchema),
},
};
}
findAndReturnTokens(tokenToFind: string, tokens: Token[]) {
if (ContractToken.prim === tokenToFind) {
tokens.push(this);
}
return tokens;
}
}