-
Notifications
You must be signed in to change notification settings - Fork 110
/
storage.ts
344 lines (312 loc) · 9.9 KB
/
storage.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import {
MichelsonV1Expression,
MichelsonV1ExpressionBase,
MichelsonV1ExpressionExtended,
ScriptResponse,
} from '@taquito/rpc';
import { BigMapToken } from '../tokens/bigmap';
import { createToken } from '../tokens/createToken';
import { MapToken } from '../tokens/map';
import { OrToken } from '../tokens/or';
import { PairToken } from '../tokens/pair';
import { TicketToken } from '../tokens/ticket';
import { TicketDeprecatedToken } from '../tokens/ticket-deprecated';
import {
BigMapKeyType,
Semantic,
SemanticEncoding,
Token,
TokenValidationError,
} from '../tokens/token';
import {
InvalidRpcResponseError,
InvalidBigMapSchemaError,
InvalidBigMapDiffError,
BigMapEncodingError,
StorageEncodingError,
MissingArgumentError,
} from './errors';
import { RpcTransaction } from './model';
import { TokenSchema } from './types';
const schemaTypeSymbol = Symbol.for('taquito-schema-type-symbol');
// collapse comb pair
function collapse(
val: Token['val'] | MichelsonV1Expression,
prim: string = PairToken.prim
): Token['val'] {
if (Array.isArray(val)) {
return collapse(
{
prim: prim,
args: val,
},
prim
);
}
const extended = val as MichelsonV1ExpressionExtended;
if (extended.prim === prim && extended.args && extended.args.length > 2) {
return {
...extended,
args: [
extended.args?.[0],
{
prim: prim,
args: extended.args?.slice(1),
},
],
};
}
return extended;
}
export function deepEqual(
a: MichelsonV1Expression | undefined,
b: MichelsonV1Expression | undefined
): boolean {
if (a === undefined || b === undefined) {
return a === b;
}
const ac = collapse(a);
const bc = collapse(b);
return (
ac.prim === bc.prim &&
((ac.args === undefined && bc.args === undefined) ||
(ac.args !== undefined &&
bc.args !== undefined &&
ac.args.length === bc.args.length &&
ac.args.every((v, i) => deepEqual(v, bc.args?.[i] ?? {})))) &&
((ac.annots === undefined && bc.annots === undefined) ||
(ac.annots !== undefined &&
bc.annots !== undefined &&
ac.annots.length === bc.annots.length &&
ac.annots.every((v, i) => v === bc.annots?.[i])))
);
}
/**
* @warn Our current smart contract abstraction feature is currently in preview. Its API is not final, and it may not cover every use case (yet). We will greatly appreciate any feedback on this feature.
*/
export class Schema {
private root: Token;
public [schemaTypeSymbol] = true;
public static isSchema(obj: Schema): boolean {
return obj && obj[schemaTypeSymbol] === true;
}
// TODO: Should we deprecate this?
private bigMap?: BigMapToken;
/**
* @throws {@link InvalidRpcResponseError}
*/
static fromRPCResponse(val: { script: ScriptResponse }) {
if (!val) {
throw new InvalidRpcResponseError(val, 'the RPC response is empty');
}
if (!val.script) {
throw new InvalidRpcResponseError(val, 'the RPC response has no script');
}
if (!Array.isArray(val.script.code)) {
throw new InvalidRpcResponseError(val, 'The response.script.code should be an array');
}
let code = val.script.code;
while (code.length === 1 && Array.isArray(code[0])) {
code = code[0];
}
const storage = code.find(
(x) => 'prim' in x && x.prim === 'storage'
) as MichelsonV1ExpressionExtended;
if (!storage || !Array.isArray(storage.args)) {
throw new InvalidRpcResponseError(
val,
'The response.script.code has an element of type {prim: "storage"}, but its args is not an array'
);
}
return new Schema(storage.args[0]);
}
private isExpressionExtended(
val: any
): val is Required<Pick<MichelsonV1ExpressionExtended, 'prim' | 'args'>> {
return 'prim' in val && Array.isArray(val.args);
}
constructor(readonly val: MichelsonV1Expression) {
this.root = createToken(val, 0);
if (this.root instanceof BigMapToken) {
this.bigMap = this.root;
} else if (this.isExpressionExtended(val) && val.prim === 'pair') {
const exp = val.args[0];
if (this.isExpressionExtended(exp) && exp.prim === 'big_map') {
this.bigMap = new BigMapToken(exp, 0, createToken);
}
}
}
private removeTopLevelAnnotation(obj: any) {
// PairToken and OrToken can have redundant top level annotation in their storage
if (this.root instanceof PairToken || this.root instanceof OrToken) {
if (this.root.hasAnnotations() && typeof obj === 'object' && Object.keys(obj).length === 1) {
return obj[Object.keys(obj)[0]];
}
}
return obj;
}
Execute(val: any, semantics?: Semantic) {
const storage = this.root.Execute(val, semantics);
return this.removeTopLevelAnnotation(storage);
}
Typecheck(val: any) {
if (this.root instanceof BigMapToken && Number.isInteger(Number(val))) {
return;
}
if (this.root instanceof TicketToken && val.ticketer && val.value && val.amount) {
return;
}
if (this.root instanceof TicketDeprecatedToken && val.ticketer && val.value && val.amount) {
return;
}
if (this.root instanceof MapToken && this.root.ValueSchema instanceof BigMapToken) {
return;
}
this.root.EncodeObject(val);
}
/**
* @throws {@link InvalidBigMapSchemaError}
* @throws {@link InvalidBigMapDiffError}
*/
ExecuteOnBigMapDiff(diff: any[], semantics?: Semantic) {
if (!this.bigMap) {
throw new InvalidBigMapSchemaError('Big map schema is undefined');
}
if (!Array.isArray(diff)) {
throw new InvalidBigMapDiffError(
`Big map diff must be an array, got: ${JSON.stringify(diff)}`,
diff
);
}
const eltFormat = diff.map(({ key, value }) => ({ args: [key, value] }));
return this.bigMap.Execute(eltFormat, semantics);
}
/**
* @throws {@link InvalidBigMapSchemaError}
*/
ExecuteOnBigMapValue(key: any, semantics?: Semantic) {
if (!this.bigMap) {
throw new InvalidBigMapSchemaError('Big map schema is undefined');
}
return this.bigMap.ValueSchema.Execute(key, semantics);
}
/**
* @throws {@link InvalidBigMapSchemaError}
* @throws {@link BigMapEncodingError}
*/
EncodeBigMapKey(key: BigMapKeyType) {
if (!this.bigMap) {
throw new InvalidBigMapSchemaError('Big map schema is undefined');
}
try {
return this.bigMap.KeySchema.ToBigMapKey(key);
} catch (ex) {
throw new BigMapEncodingError('key', ex, this.bigMap.KeySchema, key);
}
}
/**
* @throws {@link TokenValidationError}
* @throws {@link StorageEncodingError}
*/
Encode(value?: any, semantics?: SemanticEncoding) {
try {
return this.root.EncodeObject(value, semantics);
} catch (ex) {
if (ex instanceof TokenValidationError) {
throw ex;
}
throw new StorageEncodingError('storage object', ex, this.root, value, semantics);
}
}
/**
* @deprecated ExtractSchema has been deprecated in favor of generateSchema
*
*/
ExtractSchema() {
return this.removeTopLevelAnnotation(this.root.ExtractSchema());
}
/**
* @description Produce a representation of the storage schema.
* Note: Provide guidance on how to write the storage object for the origination operation with Taquito.
*/
generateSchema(): TokenSchema {
return this.removeTopLevelAnnotation(this.root.generateSchema());
}
/**
* @deprecated
* @throws {@link InvalidBigMapSchemaError}
*/
ComputeState(tx: RpcTransaction[], state: any) {
if (!this.bigMap) {
throw new InvalidBigMapSchemaError('Big map schema is undefined');
}
const bigMap = tx.reduce((prev, current) => {
return {
...prev,
...this.ExecuteOnBigMapDiff(current.contents[0].metadata.operation_result.big_map_diff),
};
}, {});
return {
...this.Execute(state),
[this.bigMap.annot()]: bigMap,
};
}
/**
* @description Look up in top-level pairs of the storage to find a value matching the specified type
*
* @returns The first value found that match the type or `undefined` if no value is found
*
* @param storage storage to parse to find the value
* @param valueType type of value to look for
*
*/
FindFirstInTopLevelPair<T extends MichelsonV1Expression>(storage: any, valueType: any) {
return this.findValue(this.root['val'], storage, valueType) as T | undefined;
}
// TODO check these type casts
/**
* @throws {@link MissingArgumentError}
*/
private findValue(
schema: MichelsonV1Expression,
storage: any,
valueToFind: any
): MichelsonV1ExpressionBase | undefined {
if (deepEqual(valueToFind, schema)) {
return storage;
}
if (Array.isArray(schema) || (schema as MichelsonV1ExpressionExtended).prim === 'pair') {
const sch = collapse(schema);
const strg = collapse(storage, 'Pair');
if (sch.args === undefined || strg.args === undefined) {
throw new MissingArgumentError('Tokens have no arguments'); // unlikely
}
if (sch.args[0])
return (
// unsafe
this.findValue(sch.args[0] as MichelsonV1ExpressionExtended, strg.args[0], valueToFind) ||
this.findValue(sch.args[1] as MichelsonV1ExpressionExtended, strg.args[1], valueToFind)
);
}
}
/**
* @description Look up the schema to find any occurrence of a particular token.
*
* @returns an array of tokens of the specified kind or an empty array if no token was found
*
* @param tokenToFind string representing the prim property of the token to find
*
* @example
* ```
* Useful to find all global constants in a script, an array of GlobalConstantToken is returned:
*
* const schema = new Schema(script);
* const allGlobalConstantTokens = schema.findToken('constant');
* ```
*
*/
findToken(tokenToFind: string): Array<Token> {
const tokens: Array<Token> = [];
return this.root.findAndReturnTokens(tokenToFind, tokens);
}
}