@taquito/tzip16 11.1.0 → 12.0.0-beta-RC.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +31 -18
  2. package/dist/lib/composer.js +5 -4
  3. package/dist/lib/composer.js.map +1 -1
  4. package/dist/lib/handlers/http-handler.js +14 -43
  5. package/dist/lib/handlers/http-handler.js.map +1 -1
  6. package/dist/lib/handlers/ipfs-handler.js +14 -44
  7. package/dist/lib/handlers/ipfs-handler.js.map +1 -1
  8. package/dist/lib/handlers/tezos-storage-handler.js +31 -70
  9. package/dist/lib/handlers/tezos-storage-handler.js.map +1 -1
  10. package/dist/lib/metadata-provider.js +36 -71
  11. package/dist/lib/metadata-provider.js.map +1 -1
  12. package/dist/lib/tzip16-contract-abstraction.js +72 -155
  13. package/dist/lib/tzip16-contract-abstraction.js.map +1 -1
  14. package/dist/lib/tzip16-errors.js +44 -55
  15. package/dist/lib/tzip16-errors.js.map +1 -1
  16. package/dist/lib/tzip16-extension.js +9 -10
  17. package/dist/lib/tzip16-extension.js.map +1 -1
  18. package/dist/lib/tzip16-utils.js +1 -1
  19. package/dist/lib/tzip16-utils.js.map +1 -1
  20. package/dist/lib/version.js +2 -4
  21. package/dist/lib/version.js.map +1 -1
  22. package/dist/lib/viewKind/michelson-storage-view.js +98 -196
  23. package/dist/lib/viewKind/michelson-storage-view.js.map +1 -1
  24. package/dist/lib/viewKind/viewFactory.js +16 -19
  25. package/dist/lib/viewKind/viewFactory.js.map +1 -1
  26. package/dist/taquito-tzip16.es6.js +569 -0
  27. package/dist/taquito-tzip16.es6.js.map +1 -0
  28. package/dist/taquito-tzip16.umd.js +326 -522
  29. package/dist/taquito-tzip16.umd.js.map +1 -1
  30. package/dist/types/composer.d.ts +1 -1
  31. package/dist/types/tzip16-errors.d.ts +15 -22
  32. package/dist/types/viewKind/michelson-storage-view.d.ts +3 -1
  33. package/dist/types/viewKind/viewFactory.d.ts +2 -2
  34. package/package.json +27 -27
  35. package/dist/taquito-tzip16.es5.js +0 -761
  36. package/dist/taquito-tzip16.es5.js.map +0 -1
@@ -1,761 +0,0 @@
1
- import { HttpBackend } from '@taquito/http-utils';
2
- import { Schema, ParameterSchema } from '@taquito/michelson-encoder';
3
- import { bytes2Char } from '@taquito/utils';
4
- export { bytes2Char, char2Bytes } from '@taquito/utils';
5
- import { BigMapAbstraction } from '@taquito/taquito';
6
- import BigNumber from 'bignumber.js';
7
- import CryptoJS from 'crypto-js';
8
-
9
- /*! *****************************************************************************
10
- Copyright (c) Microsoft Corporation.
11
-
12
- Permission to use, copy, modify, and/or distribute this software for any
13
- purpose with or without fee is hereby granted.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
- PERFORMANCE OF THIS SOFTWARE.
22
- ***************************************************************************** */
23
-
24
- function __awaiter(thisArg, _arguments, P, generator) {
25
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
26
- return new (P || (P = Promise))(function (resolve, reject) {
27
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
28
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
29
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
30
- step((generator = generator.apply(thisArg, _arguments || [])).next());
31
- });
32
- }
33
-
34
- function __generator(thisArg, body) {
35
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
- function verb(n) { return function (v) { return step([n, v]); }; }
38
- function step(op) {
39
- if (f) throw new TypeError("Generator is already executing.");
40
- while (_) try {
41
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
- if (y = 0, t) op = [op[0] & 2, t.value];
43
- switch (op[0]) {
44
- case 0: case 1: t = op; break;
45
- case 4: _.label++; return { value: op[1], done: false };
46
- case 5: _.label++; y = op[1]; op = [0]; continue;
47
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
- default:
49
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
- if (t[2]) _.ops.pop();
54
- _.trys.pop(); continue;
55
- }
56
- op = body.call(thisArg, _);
57
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
- }
60
- }
61
-
62
- function __values(o) {
63
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
64
- if (m) return m.call(o);
65
- if (o && typeof o.length === "number") return {
66
- next: function () {
67
- if (o && i >= o.length) o = void 0;
68
- return { value: o && o[i++], done: !o };
69
- }
70
- };
71
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
72
- }
73
-
74
- function __read(o, n) {
75
- var m = typeof Symbol === "function" && o[Symbol.iterator];
76
- if (!m) return o;
77
- var i = m.call(o), r, ar = [], e;
78
- try {
79
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
80
- }
81
- catch (error) { e = { error: error }; }
82
- finally {
83
- try {
84
- if (r && !r.done && (m = i["return"])) m.call(i);
85
- }
86
- finally { if (e) throw e.error; }
87
- }
88
- return ar;
89
- }
90
-
91
- /** @deprecated */
92
- function __spread() {
93
- for (var ar = [], i = 0; i < arguments.length; i++)
94
- ar = ar.concat(__read(arguments[i]));
95
- return ar;
96
- }
97
-
98
- var HttpHandler = /** @class */ (function () {
99
- function HttpHandler() {
100
- this.httpBackend = new HttpBackend();
101
- }
102
- HttpHandler.prototype.getMetadata = function (_contractAbstraction, _a, _context) {
103
- var protocol = _a.protocol, location = _a.location;
104
- return __awaiter(this, void 0, void 0, function () {
105
- return __generator(this, function (_b) {
106
- return [2 /*return*/, this.httpBackend.createRequest({
107
- url: protocol + ":" + decodeURIComponent(location),
108
- method: 'GET',
109
- mimeType: "text; charset=utf-8",
110
- json: false
111
- })];
112
- });
113
- });
114
- };
115
- return HttpHandler;
116
- }());
117
-
118
- var BigMapMetadataNotFound = /** @class */ (function () {
119
- function BigMapMetadataNotFound() {
120
- this.name = 'BigMapMetadataNotFound';
121
- this.message = 'Non-compliance with the TZIP-016 standard. No big map named metadata was found in the contract storage.';
122
- }
123
- return BigMapMetadataNotFound;
124
- }());
125
- var MetadataNotFound = /** @class */ (function () {
126
- function MetadataNotFound(info) {
127
- this.info = info;
128
- this.name = 'MetadataNotFound';
129
- this.message = "No metadata was found in the contract storage. " + info;
130
- }
131
- return MetadataNotFound;
132
- }());
133
- var UriNotFound = /** @class */ (function () {
134
- function UriNotFound() {
135
- this.name = 'UriNotFound';
136
- this.message = 'Non-compliance with the TZIP-016 standard. No URI found in the contract storage.';
137
- }
138
- return UriNotFound;
139
- }());
140
- var InvalidUri = /** @class */ (function () {
141
- function InvalidUri(uri) {
142
- this.uri = uri;
143
- this.name = 'InvalidUri';
144
- this.message = "Non-compliance with the TZIP-016 standard. The URI is invalid: " + uri + ".";
145
- }
146
- return InvalidUri;
147
- }());
148
- var InvalidMetadata = /** @class */ (function () {
149
- function InvalidMetadata(invalidMetadata) {
150
- this.invalidMetadata = invalidMetadata;
151
- this.name = 'InvalidMetadata';
152
- this.message = "The metadata found at the pointed ressource are not compliant with tzip16 standard: " + invalidMetadata + ".";
153
- }
154
- return InvalidMetadata;
155
- }());
156
- var ProtocolNotSupported = /** @class */ (function () {
157
- function ProtocolNotSupported(protocol) {
158
- this.protocol = protocol;
159
- this.name = 'ProtocolNotSupported';
160
- this.message = "The protocol found in the URI is not supported: " + protocol + ".";
161
- }
162
- return ProtocolNotSupported;
163
- }());
164
- var InvalidMetadataType = /** @class */ (function () {
165
- function InvalidMetadataType() {
166
- this.name = 'InvalidMetadataType';
167
- this.message = 'The contract does not comply with the tzip16 standard. The type of metadata should be bytes.';
168
- }
169
- return InvalidMetadataType;
170
- }());
171
- var UnconfiguredMetadataProviderError = /** @class */ (function () {
172
- function UnconfiguredMetadataProviderError() {
173
- this.name = 'UnconfiguredMetadataProviderError';
174
- this.message = 'No metadata provider has been configured. The default one can be configured by calling addExtension(new Tzip16Module()) on your TezosToolkit instance.';
175
- }
176
- return UnconfiguredMetadataProviderError;
177
- }());
178
- var ForbiddenInstructionInViewCode = /** @class */ (function () {
179
- function ForbiddenInstructionInViewCode(instruction) {
180
- this.instruction = instruction;
181
- this.name = 'ForbiddenInstructionInViewCode';
182
- this.message = "Error found in the code of the view. It contains a forbidden instruction: " + instruction + ".";
183
- }
184
- return ForbiddenInstructionInViewCode;
185
- }());
186
- var NoParameterExpectedError = /** @class */ (function () {
187
- function NoParameterExpectedError(viewName, args) {
188
- this.viewName = viewName;
189
- this.args = args;
190
- this.name = 'NoParameterExpectedError';
191
- this.message = viewName + " Received " + args.length + " arguments while expecting no parameter or 'Unit'";
192
- }
193
- return NoParameterExpectedError;
194
- }());
195
- var InvalidViewParameterError = /** @class */ (function () {
196
- function InvalidViewParameterError(viewName, sigs, args) {
197
- this.viewName = viewName;
198
- this.sigs = sigs;
199
- this.args = args;
200
- this.name = 'InvalidViewParameterError';
201
- this.message = viewName + " Received " + args.length + " arguments while expecting one of the following signatures (" + JSON.stringify(sigs) + ")";
202
- }
203
- return InvalidViewParameterError;
204
- }());
205
-
206
- var typeOfValueToFind = {
207
- prim: 'big_map',
208
- args: [{ prim: 'string' }, { prim: 'bytes' }],
209
- annots: ['%metadata'],
210
- };
211
- var TezosStorageHandler = /** @class */ (function () {
212
- function TezosStorageHandler() {
213
- this.TEZOS_STORAGE_REGEX = /^(?:\/\/(KT1\w{33})(?:\.(.+))?\/)?([\w|\%]+)$/;
214
- }
215
- TezosStorageHandler.prototype.getMetadata = function (contractAbstraction, _a, context) {
216
- var location = _a.location;
217
- return __awaiter(this, void 0, void 0, function () {
218
- var parsedTezosStorageUri, storage, bigMapId, bytes;
219
- return __generator(this, function (_b) {
220
- switch (_b.label) {
221
- case 0:
222
- parsedTezosStorageUri = this.parseTezosStorageUri(location);
223
- if (!parsedTezosStorageUri) {
224
- throw new InvalidUri("tezos-storage:" + location);
225
- }
226
- return [4 /*yield*/, context.rpc.getNormalizedScript(parsedTezosStorageUri.contractAddress || contractAbstraction.address)];
227
- case 1:
228
- storage = _b.sent();
229
- bigMapId = Schema.fromRPCResponse({ script: storage }).FindFirstInTopLevelPair(storage.storage, typeOfValueToFind);
230
- if (!bigMapId) {
231
- throw new BigMapMetadataNotFound();
232
- }
233
- return [4 /*yield*/, context.contract.getBigMapKeyByID(bigMapId['int'].toString(), parsedTezosStorageUri.path, new Schema(typeOfValueToFind))];
234
- case 2:
235
- bytes = _b.sent();
236
- if (!bytes) {
237
- throw new MetadataNotFound("No '" + parsedTezosStorageUri.path + "' key found in the big map %metadata of the contract " + (parsedTezosStorageUri.contractAddress || contractAbstraction.address));
238
- }
239
- if (!/^[0-9a-fA-F]*$/.test(bytes)) {
240
- throw new InvalidMetadataType();
241
- }
242
- return [2 /*return*/, bytes2Char(bytes)];
243
- }
244
- });
245
- });
246
- };
247
- /**
248
- * @description Extract the smart contract address, the network and the path pointing to the metadata from the uri
249
- * @returns an object which contains the properties allowing to find where the metadata are located or it returns undefined if the uri is not valid
250
- * @param tezosStorageURI URI (without the tezos-storage prefix)
251
- */
252
- TezosStorageHandler.prototype.parseTezosStorageUri = function (tezosStorageURI) {
253
- var extractor = this.TEZOS_STORAGE_REGEX.exec(tezosStorageURI);
254
- if (!extractor)
255
- return;
256
- return {
257
- contractAddress: extractor[1],
258
- network: extractor[2],
259
- path: decodeURIComponent(extractor[3]),
260
- };
261
- };
262
- return TezosStorageHandler;
263
- }());
264
-
265
- var IpfsHttpHandler = /** @class */ (function () {
266
- function IpfsHttpHandler(ipfsGatheway) {
267
- this.httpBackend = new HttpBackend();
268
- this._ipfsGateway = ipfsGatheway ? ipfsGatheway : 'ipfs.io';
269
- }
270
- IpfsHttpHandler.prototype.getMetadata = function (_contractAbstraction, _a, _context) {
271
- var location = _a.location;
272
- return __awaiter(this, void 0, void 0, function () {
273
- return __generator(this, function (_b) {
274
- return [2 /*return*/, this.httpBackend.createRequest({
275
- url: "https://" + this._ipfsGateway + "/ipfs/" + location.substring(2) + "/",
276
- method: 'GET',
277
- headers: { 'Content-Type': 'text/plain' },
278
- mimeType: "text; charset=utf-8",
279
- json: false
280
- })];
281
- });
282
- });
283
- };
284
- return IpfsHttpHandler;
285
- }());
286
-
287
- var ViewImplementationType;
288
- (function (ViewImplementationType) {
289
- ViewImplementationType["MICHELSON_STORAGE"] = "michelsonStorageView";
290
- ViewImplementationType["REST_API_QUERY"] = "restApiQuery";
291
- })(ViewImplementationType || (ViewImplementationType = {}));
292
-
293
- var MichelsonStorageView = /** @class */ (function () {
294
- function MichelsonStorageView(viewName, contract, rpc, returnType, code, viewParameterType) {
295
- this.viewName = viewName;
296
- this.contract = contract;
297
- this.rpc = rpc;
298
- this.returnType = returnType;
299
- this.code = code;
300
- this.viewParameterType = viewParameterType;
301
- this.validateArgs = function (args, schema, viewName) {
302
- var sigs = schema.ExtractSignatures();
303
- if (!sigs.find(function (x) { return x.length === args.length; })) {
304
- throw new InvalidViewParameterError(viewName, sigs, args);
305
- }
306
- };
307
- }
308
- /**
309
- * @description According to the tzip-16 standard, the following instructions must not be used in the code of the view:
310
- * 'AMOUNT', 'CREATE_CONTRACT', 'SENDER', 'SET_DELEGATE', 'SOURCE', and 'TRANSFER_TOKENS'
311
- * The method throw an error if an illegal instruction is found
312
- */
313
- MichelsonStorageView.prototype.findForbiddenInstructionInViewCode = function (code) {
314
- var e_1, _a, e_2, _b;
315
- var illegalInstructions = [
316
- 'AMOUNT',
317
- 'CREATE_CONTRACT',
318
- 'SENDER',
319
- 'SET_DELEGATE',
320
- 'SOURCE',
321
- 'TRANSFER_TOKENS'
322
- ];
323
- try {
324
- for (var illegalInstructions_1 = __values(illegalInstructions), illegalInstructions_1_1 = illegalInstructions_1.next(); !illegalInstructions_1_1.done; illegalInstructions_1_1 = illegalInstructions_1.next()) {
325
- var forbiddenInstruction = illegalInstructions_1_1.value;
326
- try {
327
- for (var code_1 = (e_2 = void 0, __values(code)), code_1_1 = code_1.next(); !code_1_1.done; code_1_1 = code_1.next()) {
328
- var instruction = code_1_1.value;
329
- if (instruction.prim === forbiddenInstruction) {
330
- throw new ForbiddenInstructionInViewCode(forbiddenInstruction);
331
- }
332
- if (instruction.args && instruction.args.length !== 0) {
333
- this.findForbiddenInstructionInViewCode(instruction.args);
334
- }
335
- }
336
- }
337
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
338
- finally {
339
- try {
340
- if (code_1_1 && !code_1_1.done && (_b = code_1.return)) _b.call(code_1);
341
- }
342
- finally { if (e_2) throw e_2.error; }
343
- }
344
- }
345
- }
346
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
347
- finally {
348
- try {
349
- if (illegalInstructions_1_1 && !illegalInstructions_1_1.done && (_a = illegalInstructions_1.return)) _a.call(illegalInstructions_1);
350
- }
351
- finally { if (e_1) throw e_1.error; }
352
- }
353
- };
354
- /**
355
- * @description According to the tzip-16 standard, in the first version of the specification, the instruction SELF should only be used before ADDRESS
356
- * The method throws an error is the instruction SELF is present, but not followed by ADDRESS
357
- */
358
- MichelsonStorageView.prototype.illegalUseOfSelfInstruction = function (code) {
359
- var e_3, _a;
360
- try {
361
- for (var code_2 = __values(code), code_2_1 = code_2.next(); !code_2_1.done; code_2_1 = code_2.next()) {
362
- var instruction = code_2_1.value;
363
- if (instruction.prim === 'SELF') {
364
- var index = code.indexOf(instruction);
365
- var nextInstruction = code[index + 1] ? code[index + 1].prim : undefined;
366
- if (nextInstruction !== 'ADDRESS') {
367
- throw new ForbiddenInstructionInViewCode('the instruction SELF should only be used before ADDRESS');
368
- }
369
- }
370
- if (instruction.args && instruction.args.length !== 0) {
371
- this.illegalUseOfSelfInstruction(instruction.args);
372
- }
373
- }
374
- }
375
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
376
- finally {
377
- try {
378
- if (code_2_1 && !code_2_1.done && (_a = code_2.return)) _a.call(code_2);
379
- }
380
- finally { if (e_3) throw e_3.error; }
381
- }
382
- };
383
- /**
384
- * @description Loops through the view's code and replace SELF, BALANCE, NOW, and CHAIN_ID with Michelson expressions that match the current context, if applicable.
385
- */
386
- MichelsonStorageView.prototype.adaptViewCodeToContext = function (code, contractBalance, blockTimeStamp, chainId) {
387
- var _this = this;
388
- var instructionsToReplace = {
389
- SELF: [
390
- { prim: 'PUSH', args: [{ prim: 'address' }, { string: this.contract.address }] },
391
- { prim: 'CONTRACT', args: [{ prim: 'unit' }] },
392
- { prim: 'IF_NONE', args: [[{ prim: 'UNIT' }, { prim: 'FAILWITH' }], []] }
393
- ],
394
- BALANCE: [{ prim: 'PUSH', args: [{ prim: 'mutez' }, { int: contractBalance }] }],
395
- NOW: [{ prim: 'PUSH', args: [{ prim: 'timestamp' }, { string: blockTimeStamp }] }],
396
- CHAIN_ID: [{ prim: 'PUSH', args: [{ prim: 'string' }, { string: chainId }] }]
397
- };
398
- code.forEach(function (x, i) {
399
- for (var instruction in instructionsToReplace) {
400
- if (x.prim === instruction) {
401
- code[i] = Object(instructionsToReplace)[instruction];
402
- }
403
- if (x.args && x.args.length !== 0) {
404
- _this.adaptViewCodeToContext(x.args, contractBalance, blockTimeStamp, chainId);
405
- }
406
- }
407
- });
408
- return code;
409
- };
410
- MichelsonStorageView.prototype.formatArgsAndParameter = function (argView) {
411
- var args = argView;
412
- var viewParameterType = this.viewParameterType;
413
- if (!viewParameterType) {
414
- viewParameterType = { args: [], prim: 'unit', annots: [] };
415
- }
416
- if (viewParameterType.prim === 'unit') {
417
- if (args.length === 0) {
418
- args = ['Unit'];
419
- }
420
- if (args.length !== 0 && args[0] !== 'Unit') {
421
- throw new NoParameterExpectedError(this.viewName, argView);
422
- }
423
- }
424
- var parameterViewSchema = new ParameterSchema(viewParameterType);
425
- this.validateArgs(args, parameterViewSchema, this.viewName);
426
- var arg = parameterViewSchema.Encode.apply(parameterViewSchema, __spread(args));
427
- return { arg: arg, viewParameterType: viewParameterType };
428
- };
429
- MichelsonStorageView.prototype.executeView = function () {
430
- var args = [];
431
- for (var _i = 0; _i < arguments.length; _i++) {
432
- args[_i] = arguments[_i];
433
- }
434
- return __awaiter(this, void 0, void 0, function () {
435
- var _a, arg, viewParameterType, storageType, storageArgs, storageValue, chainId, contractBalance, block, blockTimestamp, code, viewScript, result, viewResultSchema;
436
- return __generator(this, function (_b) {
437
- switch (_b.label) {
438
- case 0:
439
- // validate view code against tzip-16 specifications
440
- this.findForbiddenInstructionInViewCode(this.code);
441
- this.illegalUseOfSelfInstruction(this.code);
442
- _a = this.formatArgsAndParameter(args), arg = _a.arg, viewParameterType = _a.viewParameterType;
443
- storageType = this.contract.script.code.find(function (x) { return x.prim === 'storage'; });
444
- storageArgs = storageType.args[0];
445
- storageValue = this.contract.script.storage;
446
- return [4 /*yield*/, this.rpc.getChainId()];
447
- case 1:
448
- chainId = _b.sent();
449
- return [4 /*yield*/, this.rpc.getBalance(this.contract.address)];
450
- case 2:
451
- contractBalance = (_b.sent()).toString();
452
- return [4 /*yield*/, this.rpc.getBlock()];
453
- case 3:
454
- block = _b.sent();
455
- blockTimestamp = block.header.timestamp.toString();
456
- code = this.adaptViewCodeToContext(this.code, contractBalance, blockTimestamp, chainId);
457
- if (!this.viewParameterType) {
458
- code.unshift({ prim: 'CDR' });
459
- }
460
- viewScript = {
461
- script: [
462
- { prim: 'parameter', args: [{ prim: 'pair', args: [viewParameterType, storageArgs] }] },
463
- { prim: 'storage', args: [{ prim: 'option', args: [this.returnType] }] },
464
- {
465
- prim: 'code',
466
- args: [
467
- [
468
- { prim: 'CAR' },
469
- code,
470
- { prim: 'SOME' },
471
- { prim: 'NIL', args: [{ prim: 'operation' }] },
472
- { prim: 'PAIR' }
473
- ]
474
- ]
475
- }
476
- ],
477
- storage: { prim: 'None' },
478
- input: { prim: 'Pair', args: [arg, storageValue] },
479
- amount: '0',
480
- chain_id: chainId,
481
- balance: '0'
482
- };
483
- return [4 /*yield*/, this.rpc.runCode(viewScript)];
484
- case 4:
485
- result = _b.sent();
486
- viewResultSchema = new ParameterSchema(this.returnType);
487
- return [2 /*return*/, viewResultSchema.Execute(result.storage.args[0])];
488
- }
489
- });
490
- });
491
- };
492
- return MichelsonStorageView;
493
- }());
494
-
495
- var ViewFactory = /** @class */ (function () {
496
- function ViewFactory() {
497
- }
498
- ViewFactory.prototype.getView = function (viewName, rpc, contract, viewImplementation) {
499
- if (this.isMichelsonStorageView(viewImplementation)) {
500
- var viewValues_1 = viewImplementation[ViewImplementationType.MICHELSON_STORAGE];
501
- if (!viewValues_1.returnType || !viewValues_1.code) {
502
- console.warn(viewName + " is missing mandatory code or returnType property therefore it will be skipped.");
503
- return;
504
- }
505
- return function () {
506
- var view = new MichelsonStorageView(viewName, contract, rpc, viewValues_1.returnType, viewValues_1.code, viewValues_1.parameter);
507
- return view;
508
- };
509
- }
510
- };
511
- ViewFactory.prototype.getImplementationType = function (viewImplementation) {
512
- return Object.keys(viewImplementation)[0];
513
- };
514
- ViewFactory.prototype.isMichelsonStorageView = function (viewImplementation) {
515
- return this.getImplementationType(viewImplementation) === ViewImplementationType.MICHELSON_STORAGE;
516
- };
517
- return ViewFactory;
518
- }());
519
-
520
- var metadataBigMapType = {
521
- prim: 'big_map',
522
- args: [{ prim: 'string' }, { prim: 'bytes' }],
523
- annots: ['%metadata']
524
- };
525
- var Tzip16ContractAbstraction = /** @class */ (function () {
526
- function Tzip16ContractAbstraction(constractAbstraction, context) {
527
- this.constractAbstraction = constractAbstraction;
528
- this.context = context;
529
- this._viewFactory = new ViewFactory();
530
- this._metadataViewsObject = {};
531
- this._metadataProvider = context.metadataProvider;
532
- }
533
- Tzip16ContractAbstraction.prototype.findMetadataBigMap = function () {
534
- var metadataBigMapId = this.constractAbstraction.schema.FindFirstInTopLevelPair(this.constractAbstraction.script.storage, metadataBigMapType);
535
- if (!metadataBigMapId) {
536
- throw new BigMapMetadataNotFound();
537
- }
538
- return new BigMapAbstraction(new BigNumber(metadataBigMapId['int']), new Schema(metadataBigMapType), this.context.contract);
539
- };
540
- Tzip16ContractAbstraction.prototype.getUriOrFail = function () {
541
- return __awaiter(this, void 0, void 0, function () {
542
- var metadataBigMap, uri;
543
- return __generator(this, function (_a) {
544
- switch (_a.label) {
545
- case 0:
546
- metadataBigMap = this.findMetadataBigMap();
547
- return [4 /*yield*/, metadataBigMap.get('')];
548
- case 1:
549
- uri = _a.sent();
550
- if (!uri) {
551
- throw new UriNotFound();
552
- }
553
- return [2 /*return*/, uri];
554
- }
555
- });
556
- });
557
- };
558
- /**
559
- * @description Return an object containing the metadata, the uri, an optional integrity check result and an optional sha256 hash
560
- */
561
- Tzip16ContractAbstraction.prototype.getMetadata = function () {
562
- return __awaiter(this, void 0, void 0, function () {
563
- var uri, _a;
564
- return __generator(this, function (_b) {
565
- switch (_b.label) {
566
- case 0:
567
- if (!this._metadataProvider) {
568
- throw new UnconfiguredMetadataProviderError();
569
- }
570
- if (!!this._metadataEnvelope) return [3 /*break*/, 3];
571
- return [4 /*yield*/, this.getUriOrFail()];
572
- case 1:
573
- uri = _b.sent();
574
- _a = this;
575
- return [4 /*yield*/, this._metadataProvider.provideMetadata(this.constractAbstraction, bytes2Char(uri), this.context)];
576
- case 2:
577
- _a._metadataEnvelope = _b.sent();
578
- _b.label = 3;
579
- case 3: return [2 /*return*/, this._metadataEnvelope];
580
- }
581
- });
582
- });
583
- };
584
- Tzip16ContractAbstraction.prototype.metadataViews = function () {
585
- return __awaiter(this, void 0, void 0, function () {
586
- return __generator(this, function (_a) {
587
- switch (_a.label) {
588
- case 0:
589
- if (!(Object.keys(this._metadataViewsObject).length === 0)) return [3 /*break*/, 2];
590
- return [4 /*yield*/, this.initializeMetadataViewsList()];
591
- case 1:
592
- _a.sent();
593
- _a.label = 2;
594
- case 2: return [2 /*return*/, this._metadataViewsObject];
595
- }
596
- });
597
- });
598
- };
599
- Tzip16ContractAbstraction.prototype.initializeMetadataViewsList = function () {
600
- var _a;
601
- return __awaiter(this, void 0, void 0, function () {
602
- var metadata, metadataViews;
603
- var _this = this;
604
- return __generator(this, function (_b) {
605
- switch (_b.label) {
606
- case 0: return [4 /*yield*/, this.getMetadata()];
607
- case 1:
608
- metadata = (_b.sent()).metadata;
609
- metadataViews = {};
610
- (_a = metadata.views) === null || _a === void 0 ? void 0 : _a.forEach(function (view) { return _this.createViewImplementations(view, metadataViews); });
611
- this._metadataViewsObject = metadataViews;
612
- return [2 /*return*/];
613
- }
614
- });
615
- });
616
- };
617
- Tzip16ContractAbstraction.prototype.generateIndexedViewName = function (viewName, metadataViews) {
618
- var i = 1;
619
- if (viewName in metadataViews) {
620
- while ("" + viewName + i in metadataViews) {
621
- i++;
622
- }
623
- viewName = "" + viewName + i;
624
- }
625
- return viewName;
626
- };
627
- Tzip16ContractAbstraction.prototype.createViewImplementations = function (view, metadataViews) {
628
- var e_1, _a;
629
- var _b;
630
- try {
631
- for (var _c = __values((_b = view === null || view === void 0 ? void 0 : view.implementations) !== null && _b !== void 0 ? _b : []), _d = _c.next(); !_d.done; _d = _c.next()) {
632
- var viewImplementation = _d.value;
633
- if (view.name) {
634
- // when views have the same name, add an index at the end of the name
635
- var viewName = this.generateIndexedViewName(view.name, metadataViews);
636
- var metadataView = this._viewFactory.getView(viewName, this.context.rpc, this.constractAbstraction, viewImplementation);
637
- if (metadataView) {
638
- metadataViews[viewName] = metadataView;
639
- }
640
- else {
641
- console.warn("Skipped generating " + viewName + " because the view has an unsupported type: " + this._viewFactory.getImplementationType(viewImplementation));
642
- }
643
- }
644
- }
645
- }
646
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
647
- finally {
648
- try {
649
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
650
- }
651
- finally { if (e_1) throw e_1.error; }
652
- }
653
- };
654
- return Tzip16ContractAbstraction;
655
- }());
656
-
657
- var ABSTRACTION_KEY = Symbol("Tzip16ContractAbstractionObjectKey");
658
- function tzip16(abs, context) {
659
- return Object.assign(abs, {
660
- // namespace tzip16
661
- tzip16: function () {
662
- if (!this[ABSTRACTION_KEY]) {
663
- this[ABSTRACTION_KEY] = new Tzip16ContractAbstraction(this, context);
664
- }
665
- return this[ABSTRACTION_KEY];
666
- }
667
- });
668
- }
669
-
670
- function calculateSHA256Hash(preimage) {
671
- return CryptoJS.SHA256(preimage).toString(CryptoJS.enc.Hex);
672
- }
673
-
674
- /**
675
- * @description: Metadata Provider
676
- */
677
- var MetadataProvider = /** @class */ (function () {
678
- function MetadataProvider(handlers) {
679
- this.handlers = handlers;
680
- this.PROTOCOL_REGEX = /(?:sha256\:\/\/0x(.*)\/)?(https?|ipfs|tezos-storage)\:(.*)/;
681
- }
682
- /**
683
- * @description Fetch the metadata by using the appropriate handler based on the protcol found in the URI
684
- * @returns an object which contains the uri, the metadata, an optional integrity check result and an optional SHA256 hash
685
- * @param _contractAbstraction the contract abstraction which contains the URI in its storage
686
- * @param _uri the decoded uri found in the storage
687
- * @param context the TezosToolkit Context
688
- */
689
- MetadataProvider.prototype.provideMetadata = function (contractAbstraction, uri, context) {
690
- return __awaiter(this, void 0, void 0, function () {
691
- var uriInfo, handler, metadata, sha256Hash, metadataJSON;
692
- return __generator(this, function (_a) {
693
- switch (_a.label) {
694
- case 0:
695
- uriInfo = this.extractProtocolInfo(uri);
696
- if (!uriInfo || !uriInfo.location) {
697
- throw new InvalidUri(uri);
698
- }
699
- handler = this.handlers.get(uriInfo.protocol);
700
- if (!handler) {
701
- throw new ProtocolNotSupported(uriInfo.protocol);
702
- }
703
- return [4 /*yield*/, handler.getMetadata(contractAbstraction, uriInfo, context)];
704
- case 1:
705
- metadata = _a.sent();
706
- sha256Hash = calculateSHA256Hash(metadata);
707
- try {
708
- metadataJSON = JSON.parse(metadata);
709
- }
710
- catch (ex) {
711
- throw new InvalidMetadata(metadata);
712
- }
713
- return [2 /*return*/, {
714
- uri: uri,
715
- metadata: metadataJSON,
716
- integrityCheckResult: uriInfo.sha256hash ? uriInfo.sha256hash === sha256Hash : undefined,
717
- sha256Hash: uriInfo.sha256hash ? sha256Hash : undefined
718
- }];
719
- }
720
- });
721
- });
722
- };
723
- MetadataProvider.prototype.extractProtocolInfo = function (_uri) {
724
- var extractor = this.PROTOCOL_REGEX.exec(_uri);
725
- if (!extractor)
726
- return;
727
- return {
728
- sha256hash: extractor[1],
729
- protocol: extractor[2],
730
- location: extractor[3]
731
- };
732
- };
733
- return MetadataProvider;
734
- }());
735
-
736
- var DEFAULT_HANDLERS = new Map([
737
- ['http', new HttpHandler()],
738
- ['https', new HttpHandler()],
739
- ['tezos-storage', new TezosStorageHandler()],
740
- ['ipfs', new IpfsHttpHandler()]
741
- ]);
742
- var Tzip16Module = /** @class */ (function () {
743
- function Tzip16Module(metadataProvider) {
744
- this._metadataProvider = metadataProvider ? metadataProvider : new MetadataProvider(DEFAULT_HANDLERS);
745
- }
746
- Tzip16Module.prototype.configureContext = function (context) {
747
- Object.assign(context, { metadataProvider: this._metadataProvider });
748
- };
749
- return Tzip16Module;
750
- }());
751
-
752
- // IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT OR CHECKIN!
753
- /* tslint:disable */
754
- var VERSION = {
755
- "commitHash": "e1723ab725df70755b4cd73b75aa981f913d0d5c",
756
- "version": "11.1.0"
757
- };
758
- /* tslint:enable */
759
-
760
- export { BigMapMetadataNotFound, DEFAULT_HANDLERS, ForbiddenInstructionInViewCode, HttpHandler, InvalidMetadata, InvalidMetadataType, InvalidUri, InvalidViewParameterError, IpfsHttpHandler, MetadataNotFound, MetadataProvider, MichelsonStorageView, NoParameterExpectedError, ProtocolNotSupported, TezosStorageHandler, Tzip16ContractAbstraction, Tzip16Module, UnconfiguredMetadataProviderError, UriNotFound, VERSION, ViewFactory, ViewImplementationType, calculateSHA256Hash, tzip16 };
761
- //# sourceMappingURL=taquito-tzip16.es5.js.map