From 7e18f6a606c9ec57605bac1ee60e8297b155109e Mon Sep 17 00:00:00 2001 From: Senji888 <44082144+Ben-Rey@users.noreply.github.com> Date: Tue, 21 Nov 2023 15:59:21 +0100 Subject: [PATCH] Remove massa-proto-cli --- .../massa-proto-cli/dist/MassaProtoFile.js | 3 - .../dist/MassaProtoFile.js.map | 1 - packages/massa-proto-cli/dist/as-gen.js | 118 ---- packages/massa-proto-cli/dist/as-gen.js.map | 1 - packages/massa-proto-cli/dist/index.js | 85 --- packages/massa-proto-cli/dist/index.js.map | 1 - packages/massa-proto-cli/dist/protobuf.js | 122 ---- packages/massa-proto-cli/dist/protobuf.js.map | 1 - packages/massa-proto-cli/dist/ts-gen.js | 594 ------------------ packages/massa-proto-cli/dist/ts-gen.js.map | 1 - .../massa-proto-cli/dist/tsProtoTypes.json | 16 - .../dist/utils/bytesArrayToString.js | 20 - .../dist/utils/bytesArrayToString.js.map | 1 - 13 files changed, 964 deletions(-) delete mode 100644 packages/massa-proto-cli/dist/MassaProtoFile.js delete mode 100644 packages/massa-proto-cli/dist/MassaProtoFile.js.map delete mode 100644 packages/massa-proto-cli/dist/as-gen.js delete mode 100644 packages/massa-proto-cli/dist/as-gen.js.map delete mode 100755 packages/massa-proto-cli/dist/index.js delete mode 100644 packages/massa-proto-cli/dist/index.js.map delete mode 100644 packages/massa-proto-cli/dist/protobuf.js delete mode 100644 packages/massa-proto-cli/dist/protobuf.js.map delete mode 100644 packages/massa-proto-cli/dist/ts-gen.js delete mode 100644 packages/massa-proto-cli/dist/ts-gen.js.map delete mode 100644 packages/massa-proto-cli/dist/tsProtoTypes.json delete mode 100644 packages/massa-proto-cli/dist/utils/bytesArrayToString.js delete mode 100644 packages/massa-proto-cli/dist/utils/bytesArrayToString.js.map diff --git a/packages/massa-proto-cli/dist/MassaProtoFile.js b/packages/massa-proto-cli/dist/MassaProtoFile.js deleted file mode 100644 index 9696cb50..00000000 --- a/packages/massa-proto-cli/dist/MassaProtoFile.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=MassaProtoFile.js.map \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/MassaProtoFile.js.map b/packages/massa-proto-cli/dist/MassaProtoFile.js.map deleted file mode 100644 index 9bb22ef4..00000000 --- a/packages/massa-proto-cli/dist/MassaProtoFile.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"MassaProtoFile.js","sourceRoot":"","sources":["../src/MassaProtoFile.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/as-gen.js b/packages/massa-proto-cli/dist/as-gen.js deleted file mode 100644 index f94dc8d4..00000000 --- a/packages/massa-proto-cli/dist/as-gen.js +++ /dev/null @@ -1,118 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generateAsCallers = exports.generateAsCall = void 0; -const fs_1 = require("fs"); -const child_process_1 = require("child_process"); -const path_1 = __importDefault(require("path")); -const asProtoTypes = __importStar(require("./asProtoTypes.json")); -/** - * Creates a contract function caller with the given proto file and address. - * - * @param protoData - the proto file containing the information to call the contract's function - * @param address - the address of the contract containing the function to call - * @param outputDirectory - the output directory to create the file for the caller - */ -function generateAsCall(protoData, address, outputDirectory) { - // check if all the arguments are supported (to avoid 'undefined' objects in the generated code) - protoData.argFields.forEach(({ type }) => { - if (!asProtoTypes[type]) { - throw new Error(`Unsupported type: ${type}`); - } - }); - // generating AS arguments - let args = []; - protoData.argFields.forEach(({ name, type }) => args.push(`${name}: ${asProtoTypes[type]}`)); - let responseDecoding = ''; - let responseTypeImports = ''; - if (protoData.resType !== null) { - responseTypeImports += ` -import { decode${protoData.funcName}RHelper } from './${protoData.funcName}RHelper';`; - responseDecoding = ` - - // Convert the result to the expected response type - const response = decode${protoData.funcName}RHelper(Uint8Array.wrap(changetype(result))); - - return response.value;`; - } - ; - // generating the content of the file - // eslint-disable-next-line max-len - const content = `import { encode${protoData.funcName}Helper, ${protoData.funcName}Helper } from './${protoData.funcName}Helper';${responseTypeImports} -import { call, Address } from "@massalabs/massa-as-sdk"; -import { Args } from '@massalabs/as-types'; - -export function ${protoData.funcName}(${args.length > 0 ? args.join(', ') + ', ' : ''} coins: u64): ${protoData.resType !== null ? asProtoTypes[protoData.resType] : 'void'} { - - const result = call( - new Address("${address}"), - "${protoData.funcName}", - new Args(changetype>(encode${protoData.funcName}Helper(new ${protoData.funcName}Helper( - ${protoData.argFields.map(({ name, type }) => name).join(',\n')} - )))), - coins - );${responseDecoding} -} -`; - // Save the content to a ts file - (0, fs_1.writeFileSync)(path_1.default.join(outputDirectory, `${protoData.funcName}Caller.ts`), content); -} -exports.generateAsCall = generateAsCall; -/** - * Creates the assembly script helper for serializing and deserializing with the given protobuf file. - * - * @param protoData - the proto file data. - * @param outputDirectory - the directory where to generate such helpers. - */ -function generateProtocAsHelper(protoData, outputDirectory) { - let protocProcess = (0, child_process_1.spawnSync)('protoc', [ - `--plugin=protoc-gen-as=./node_modules/.bin/as-proto-gen`, - `--as_out=${outputDirectory}`, - `--as_opt=gen-helper-methods`, - `--proto_path=${outputDirectory}`, - `${outputDirectory}${protoData.funcName}.proto` - ]); - if (protocProcess.status !== 0) { - throw new Error(`Failed to generate AS helpers code for ${protoData} with error: ${protocProcess.stderr}`); - } -} -/** - * Creates assembly script sc callers with the given protobuf files. - * - * @param protoFiles - the array of proto files data - * @param address - the address of the contract where the proto files are coming from - * @param outputDirectory - the output directory where to generates the callers - */ -function generateAsCallers(protoFiles, address, outputDirectory) { - for (const file of protoFiles) { - generateProtocAsHelper(file, outputDirectory); - generateAsCall(file, address, outputDirectory); - } -} -exports.generateAsCallers = generateAsCallers; -//# sourceMappingURL=as-gen.js.map \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/as-gen.js.map b/packages/massa-proto-cli/dist/as-gen.js.map deleted file mode 100644 index 7a226e6d..00000000 --- a/packages/massa-proto-cli/dist/as-gen.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"as-gen.js","sourceRoot":"","sources":["../src/as-gen.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2BAAmC;AACnC,iDAA0C;AAC1C,gDAAwB;AAExB,kEAAoD;AAGpD;;;;;;GAMG;AACH,SAAgB,cAAc,CAC5B,SAAoB,EACpB,OAAe,EACf,eAAuB;IAEvB,gGAAgG;IAChG,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE;QACvC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE;YACvB,MAAM,IAAI,KAAK,CAAC,qBAAqB,IAAI,EAAE,CAAC,CAAC;SAC9C;IACH,CAAC,CAAC,CAAC;IAEH,0BAA0B;IAC1B,IAAI,IAAI,GAAa,EAAE,CAAC;IACxB,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,CAC7C,IAAI,CAAC,IAA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;;GAKG;AACH,SAAS,sBAAsB,CAAC,SAAoB,EAAE,eAAuB;IAC3E,IAAI,aAAa,GAAG,IAAA,yBAAS,EAAC,QAAQ,EAAE;QACtC,yDAAyD;QACzD,YAAY,eAAe,EAAE;QAC7B,6BAA6B;QAC7B,gBAAgB,eAAe,EAAE;QACjC,GAAG,eAAe,GAAG,SAAS,CAAC,QAAQ,QAAQ;KAChD,CAAC,CAAC;IAEH,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,EAAE;QAC9B,MAAM,IAAI,KAAK,CACb,0CAA0C,SAAS,gBAAgB,aAAa,CAAC,MAAM,EAAE,CAC1F,CAAC;KACH;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAC/B,UAAuB,EACvB,OAAe,EACf,eAAuB;IAEvB,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE;QAC7B,sBAAsB,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QAC9C,cAAc,CAAC,IAAI,EAAE,OAAO,EAAE,eAAe,CAAC,CAAC;KAChD;AACH,CAAC;AATD,8CASC"} \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/index.js b/packages/massa-proto-cli/dist/index.js deleted file mode 100755 index 6f482d49..00000000 --- a/packages/massa-proto-cli/dist/index.js +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env node -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const as_gen_1 = require("./as-gen"); -const ts_gen_1 = require("./ts-gen"); -const protobuf_1 = require("./protobuf"); -const commander_1 = require("commander"); -const dotenv = __importStar(require("dotenv")); -const fs_1 = require("fs"); -// Load .env file content into process.env -dotenv.config(); -const program = new commander_1.Command(); -program - .option('-g, --gen ', 'the generation mode for contracts callers (sc) or web3 app (web3)', 'sc') - .option('-a, --addr ', 'the public address of the contract to interact with', '') - .option('-o, --out ', 'optional output directory for the callers to generate', './helpers/') - .parse(); -// Get the URL for a public JSON RPC API endpoint from the environment variables -const publicApi = process.env.JSON_RPC_URL_PUBLIC; -if (!publicApi) { - throw new Error('Missing JSON_RPC_URL_PUBLIC in .env file'); -} -// Create an account using the private key -/** - * Massa-Proto-Cli program entry point. - * - * @param arguments - arguments. - */ -async function run() { - const args = program.opts(); - let files = []; - let mode = args['gen']; - let address = args['addr']; - let out = args['out']; - if (mode === '' || address === '') { - program.help(); - return 1; - } - // execute 'mkdir helpers' if the folder doesn't exist yet - if (!(0, fs_1.existsSync)(out)) { - (0, fs_1.mkdirSync)(out); - } - // call sc client to fetch protos - const mpFiles = await (0, protobuf_1.getProtoFiles)([address], out, publicApi); - // call proto parser with fetched files - for (const mpfile of mpFiles) { - let protoFile = await (0, protobuf_1.getProtoFunction)(mpfile.filePath); - files.push(protoFile); - } - // call the generator - if (mode === 'sc') { - (0, as_gen_1.generateAsCallers)(files, address, out); - } - else if (mode === 'web3' || mode === 'wallet') { - (0, ts_gen_1.generateTsCallers)(files, out, publicApi, address, mode); - } - else { - throw new Error(`Unsupported mode: ${mode}`); - } -} -run(); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/index.js.map b/packages/massa-proto-cli/dist/index.js.map deleted file mode 100644 index 56c8e812..00000000 --- a/packages/massa-proto-cli/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,qCAA6C;AAC7C,qCAA6C;AAC7C,yCAAwE;AACxE,yCAAoC;AAEpC,+CAAiC;AACjC,2BAA2C;AAC3C,0CAA0C;AAC1C,MAAM,CAAC,MAAM,EAAE,CAAC;AAChB,MAAM,OAAO,GAAG,IAAI,mBAAO,EAAE,CAAC;AAE9B,OAAO;KACJ,MAAM,CACL,kBAAkB,EAClB,mEAAmE,EACnE,IAAI,CACL;KACA,MAAM,CACL,oBAAoB,EACpB,qDAAqD,EACrD,EAAE,CACH;KACA,MAAM,CACL,kBAAkB,EAClB,uDAAuD,EACvD,YAAY,CACb;KACA,KAAK,EAAE,CAAC;AAEX,gFAAgF;AAChF,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;AAClD,IAAI,CAAC,SAAS,EAAE;IACd,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;CAC7D;AAED,0CAA0C;AAE1C;;;;GAIG;AACH,KAAK,UAAU,GAAG;IAChB,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAC5B,IAAI,KAAK,GAAgB,EAAE,CAAC;IAC5B,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;IACvB,IAAI,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3B,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;IAEtB,IAAI,IAAI,KAAK,EAAE,IAAI,OAAO,KAAK,EAAE,EAAE;QACjC,OAAO,CAAC,IAAI,EAAE,CAAC;QACf,OAAO,CAAC,CAAC;KACV;IAED,0DAA0D;IAC1D,IAAI,CAAC,IAAA,eAAU,EAAC,GAAG,CAAC,EAAE;QACpB,IAAA,cAAS,EAAC,GAAG,CAAC,CAAC;KAChB;IAED,iCAAiC;IACjC,MAAM,OAAO,GAAqB,MAAM,IAAA,wBAAa,EACnD,CAAC,OAAO,CAAC,EACT,GAAG,EACH,SAAS,CACV,CAAC;IAEF,uCAAuC;IACvC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;QAC5B,IAAI,SAAS,GAAG,MAAM,IAAA,2BAAgB,EAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACxD,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;KACvB;IAED,qBAAqB;IACrB,IAAI,IAAI,KAAK,IAAI,EAAE;QACjB,IAAA,0BAAiB,EAAC,KAAK,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;KACxC;SAAM,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI,KAAK,QAAQ,EAAE;QAC/C,IAAA,0BAAiB,EAAC,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;KACzD;SAAM;QACL,MAAM,IAAI,KAAK,CAAC,qBAAqB,IAAI,EAAE,CAAC,CAAC;KAC9C;AACH,CAAC;AAED,GAAG,EAAE,CAAC"} \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/protobuf.js b/packages/massa-proto-cli/dist/protobuf.js deleted file mode 100644 index 210f1ddc..00000000 --- a/packages/massa-proto-cli/dist/protobuf.js +++ /dev/null @@ -1,122 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getProtoFiles = exports.getProtoFunction = void 0; -const massa_web3_1 = require("@massalabs/massa-web3"); -const bytesArrayToString_1 = require("./utils/bytesArrayToString"); -const fs_1 = require("fs"); -const protobufjs_1 = require("protobufjs"); -const path_1 = __importDefault(require("path")); -/** - * Retrieve all the function's data and return them as an ProtoFile - * - * @param protoPath - the path to the proto file - * - * @returns The ProtoFile containing the function, its arguments name, arguments type and its return type - */ -async function getProtoFunction(protoPath) { - const protoContent = await (0, protobufjs_1.load)(protoPath); - const protoJSON = protoContent.toJSON(); - // protoJSON.nested shouldn't be undefined - if (!protoJSON.nested) - throw new Error('Error: nested is undefined. Please check your proto file.'); - const messageNames = Object.keys(protoJSON.nested); - // check if the proto file contains 2 messages - if (messageNames.length !== 2) { - throw new Error('Error: the protoFile should contain 2 messages.'); - } - // get the Helper message - const helper = protoJSON.nested[messageNames[0]]; - // get the arguments of the Helper - const argFields = Object.entries(helper.fields) - .filter(([, value]) => value) - .map(([name, field]) => ({ - name, - type: field.type, - })); - const rHelper = protoJSON.nested[messageNames[1]]; - const rHelperKeys = Object.keys(rHelper.fields); - const resType = rHelperKeys.length === 1 ? rHelper.fields[rHelperKeys[0]].type : 'void'; - const funcName = messageNames[0].replace(/Helper$/, ''); - const protoData = await fs_1.promises.readFile(protoPath, 'utf8').catch((error) => { - throw new Error('Error while reading the proto file: ' + error); - }); - return { argFields, funcName, resType, protoData, protoPath }; -} -exports.getProtoFunction = getProtoFunction; -/** - * Get the proto file of the contracts from the Massa Blockchain. - * - * @param contractAddresses - An array of contract addresses (as strings) - * - * @returns A promise that resolves to the array of IProtoFiles corresponding - * to the proto file associated with each contract or the values are null if the file is unavailable. - */ -async function getProtoFiles(contractAddresses, outputDirectory, providerUrl) { - // prepare request body - const requestProtoFiles = []; - for (let address of contractAddresses) { - requestProtoFiles.push({ - address: address, - key: Array.from((0, massa_web3_1.strToBytes)(massa_web3_1.MASSA_PROTOFILE_KEY)), - }); - } - const body = { - jsonrpc: '2.0', - method: 'get_datastore_entries', - params: [requestProtoFiles], - id: 1, - }; - // send request - let response = null; - try { - response = await fetch(providerUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(body), - }); - // parse response - const json = await response.json(); - let protoFiles = []; - // for each contract, get the proto files - for (let contract of json.result) { - if (!contract.final_value) { - throw new Error('No proto file found'); - } - const retrievedProtoFiles = (0, bytesArrayToString_1.bytesArrayToString)(contract.final_value); // converting the Uint8Array to string - // splitting all the proto functions to make separate proto file for each functions - const protos = retrievedProtoFiles.split(massa_web3_1.PROTO_FILE_SEPARATOR); - // for proto file, save it and get the function name - for (let protoContent of protos) { - // remove all the text before the first appearance of the 'syntax' keyword - const proto = protoContent.substring(protoContent.indexOf('syntax')); - // get the function name from the proto file - const functionName = proto - .substring(proto.indexOf('message '), proto.indexOf('Helper')) - .replace('message ', '') - .trim(); - // save the proto file - const filepath = path_1.default.join(outputDirectory, functionName + '.proto'); - (0, fs_1.writeFileSync)(filepath, proto); - const extractedProto = { - data: proto, - filePath: filepath, - protoFuncName: functionName, - }; - protoFiles.push(extractedProto); - } - } - return protoFiles; - } - catch (ex) { - const msg = `Failed to retrieve the proto files.`; - console.error(msg, ex); - throw ex; - } -} -exports.getProtoFiles = getProtoFiles; -//# sourceMappingURL=protobuf.js.map \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/protobuf.js.map b/packages/massa-proto-cli/dist/protobuf.js.map deleted file mode 100644 index 0fc0472f..00000000 --- a/packages/massa-proto-cli/dist/protobuf.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"protobuf.js","sourceRoot":"","sources":["../src/protobuf.ts"],"names":[],"mappings":";;;;;;AAAA,sDAI+B;AAC/B,mEAAgE;AAChE,2BAAmD;AAEnD,2CAAyC;AACzC,gDAAwB;AA8BxB;;;;;;GAMG;AACI,KAAK,UAAU,gBAAgB,CAAC,SAAiB;IACtD,MAAM,YAAY,GAAG,MAAM,IAAA,iBAAI,EAAC,SAAS,CAAC,CAAC;IAC3C,MAAM,SAAS,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC;IAExC,0CAA0C;IAC1C,IAAI,CAAC,SAAS,CAAC,MAAM;QACnB,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;IAEJ,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI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nF,MAAM,MAAM,GAAG,mBAAmB,CAAC,KAAK,CAAC,iCAAoB,CAAC,CAAC;YAE/D,oDAAoD;YACpD,KAAK,IAAI,YAAY,IAAI,MAAM,EAAE;gBAC/B,0EAA0E;gBAC1E,MAAM,KAAK,GAAG,YAAY,CAAC,SAAS,CAAC,YAAY,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAErE,4CAA4C;gBAC5C,MAAM,YAAY,GAAG,KAAK;qBACvB,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;qBAC7D,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;qBACvB,IAAI,EAAE,CAAC;gBACV,sBAAsB;gBACtB,MAAM,QAAQ,GAAG,cAAI,CAAC,IAAI,CAAC,eAAe,EAAE,YAAY,GAAG,QAAQ,CAAC,CAAC;gBACrE,IAAA,kBAAa,EAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;gBAC/B,MAAM,cAAc,GAAmB;oBACrC,IAAI,EAAE,KAAK;oBACX,QAAQ,EAAE,QAAQ;oBAClB,aAAa,EAAE,YAAY;iBAC5B,CAAC;gBACF,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;aACjC;SACF;QACD,OAAO,UAAU,CAAC;KACnB;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,qCAAqC,CAAC;QAClD,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QACvB,MAAM,EAAE,CAAC;KACV;AACH,CAAC;AAvED,sCAuEC"} \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/ts-gen.js b/packages/massa-proto-cli/dist/ts-gen.js deleted file mode 100644 index e6de876e..00000000 --- a/packages/massa-proto-cli/dist/ts-gen.js +++ /dev/null @@ -1,594 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generateTsCallers = exports.generateTSCaller = exports.compileProtoToTSHelper = void 0; -const fs_1 = require("fs"); -const child_process_1 = require("child_process"); -const returnType = __importStar(require("./tsProtoTypes.json")); -const path_1 = require("path"); -/** - * Compile proto file to TypeScript helper class. - * - * @remarks - * - The ts helper file is generated in the folder 'helpers' at the same location as your current terminal. - * - If the @see protoFilePath is the relative path, it should be based on the location of your terminal - * - * @param protoFilePath - The path to the proto file. - */ -function compileProtoToTSHelper(protoFilePath) { - // Compile the proto file to a ts file - // If 'protoFilePath' is absolute, then 'npx protoc' will not work. We need to convert it to relative path - try { - (0, child_process_1.execSync)(`npx protoc --ts_out="./helpers" --proto_path helpers "${convertToRelativePath(protoFilePath)}"`); - } - catch (e) { - throw new Error('Error while compiling the proto file: ' + e + - '\nIs the proto file in a sub folder of the current terminal location?'); - } -} -exports.compileProtoToTSHelper = compileProtoToTSHelper; -/** - * Setup the arguments for the caller function definition. - * - * @param protoFile - The proto file object. - * - * @returns The formatted arguments for the caller function definition. - * - * @throws Error if the type of an argument is not supported. - */ -function setupArguments(protoFile) { - return protoFile.argFields - .reduce((content, arg) => { - if (!returnType[arg.type]) - throw new Error(`Unsupported type: ${arg.type}`); - return `${content}${arg.name}: ${returnType[arg.type]}, `; - }, '').slice(0, -2); -} -/** - * Generates code to check if unsigned arguments of a protobuf message are negative. - * - * @param protoFile - The proto file object. - * - * @returns The string containing code for unsigned argument checks. - */ -function generateUnsignedArgCheckCode(protoFile) { - const unsignedPBTypes = new Set(['uint32', 'uint64', 'fixed32', 'fixed64']); - const checks = protoFile.argFields - .filter((arg) => unsignedPBTypes.has(arg.type)) - /* eslint-disable max-len */ - .map((arg) => `\t\tif (${arg.name} < 0) throw new Error("Invalid argument: ${arg.name} cannot be negative according to protobuf file.");`); - if (checks.length > 0) { - return '// Verify that the given arguments are valid\n' + checks.join('\n'); - } - return ''; -} -/** - * Generate the TypeScript code for the ts caller function - * to serialize the arguments using protobuf. - * - * @param protoFile - The protoFile object - * - * @returns - The generated serialization arguments - */ -function argumentSerialization(protoFile) { - const args = protoFile.argFields - .map((arg) => `${arg.name}: ${arg.name}`) - .join(',\n '); - if (protoFile.argFields.length > 0) { - return `// Serialize the arguments - const serializedArgs = ${protoFile.funcName}Helper.toBinary({ - ${args} - });`; - } - return ''; -} -/** - * Generate argument documentation for ts Caller function - * - * @param protoFile - The protoFile object used to generate the documentation - * - * @returns - The generated documentation arguments - */ -function generateDocArgs(protoFile) { - return protoFile.argFields - .map((arg) => ` * @param {${returnType[arg.type]}} ${arg.name} - `) - .join('\n'); -} -/** - * Generate the TypeScript code for the ts caller function, depending of the chosen mode - */ -function callSCConstructor(mode) { - if (mode == 'web3') { - return `{ operationId: - await account.callSmartContract( - { - fee: 1n, - maxGas: 10000000n, - coins: coins, - targetAddress: contractAddress, - functionName: functionName, - parameter: Array.from(args), - } as ICallData, - ) - }`; - } - if (mode == 'wallet') { - return `await account.callSC( - contractAddress, - functionName, - args, - coins, - )`; - } -} -/** - * Generate a TypeScript file to allow the user to easily call a function of a Smart Contract - * - * @remarks - * - If the @see helperFilePath is the relative path based on the .proto file path - * - If the @see outputPath is the relative path based on the location of your terminal - * - Don't forget to run 'npm install protobuf-ts/plugin' in your project folder for the caller to work - * - * @param outputPath - The path where the file will be generated - * @param protoFile - The protoFile object used to generate the caller - * @param contractAddress - The address of the Smart Contract to interact with (optional) - */ -function generateTSCaller(outputPath, protoFile, contractAddress, mode) { - // check the mode - if (mode != 'web3' && mode != 'wallet') - throw new Error('Error: mode must be either "web3" or "wallet".'); - // generate the helper file using protoc. Throws an error if the command fails. - // protoPath is mandatory to generate the helper file - if (!protoFile.protoPath) - throw new Error('Error: protoPath is undefined.'); - try { - compileProtoToTSHelper(protoFile.protoPath); - } - catch (e) { - throw new Error('Error while generating the helper file: ' + e); - } - // Get the new location for the helper file (it should be in the same folder as the caller file) - let newLocation = convertToAbsolutePath(outputPath); - // New location and renaming = absolute_outputPath + protoFile.funcName + 'Helper.ts' - if (!newLocation.endsWith('/') && !newLocation.endsWith('\\')) { - newLocation += '/' + protoFile.funcName + 'Helper.ts'; - } - else { - newLocation += protoFile.funcName + 'Helper.ts'; - } - const helperPath = protoFile.protoPath.replace('.proto', '.ts'); - // join "./helpers/" and helperPath - const startPath = (0, path_1.join)(helperPath); - // check the os to use the correct command to rename the helper file - if (process.platform === 'win32') { - (0, child_process_1.execSync)(`move "${startPath}" "${newLocation}"`); - } - else { - (0, child_process_1.execSync)(`mv "${startPath}" "${newLocation}"`); - } - // generate the arguments - const args = setupArguments(protoFile); - // generate the documentation - const documentationArgs = generateDocArgs(protoFile); - // verify that the given arguments are valid - const checkUnsignedArgs = generateUnsignedArgCheckCode(protoFile); - // generate the caller function body - const argsSerialization = argumentSerialization(protoFile); - // generate the caller function - const content = `import { ${protoFile.funcName}Helper } from "./${protoFile.funcName}Helper"; -import { - Client, - IClientConfig, - IEventFilter, - IProvider, - ProviderType, - EventPoller, - ON_MASSA_EVENT_DATA, - ON_MASSA_EVENT_ERROR, - IEvent, - INodeStatus, - time,${mode == 'web3' ? `\n SmartContractsClient, - ICallData, - PublicApiClient, - IAccount, - WalletClient,` : ''} -} from "@massalabs/massa-web3"; -${mode == 'wallet' ? 'import { IAccount, providers } from "@massalabs/wallet-provider";\n' : ''} -/** - * This interface represents the details of the transaction. - * - * @see operationId - The operationId of the Smart Contract call - */ -export interface TransactionDetails { - operationId: string; -} - -/** - * This interface represents the result of the event poller. - * - * @see isError - A boolean indicating wether the Smart Contract call has failed or not - * @see eventPoller - The eventPoller object - * @see events - The events emitted by the Smart Contract call - */ -export interface EventPollerResult { - isError: boolean; - eventPoller: EventPoller; - events: IEvent[]; -} - -/** - * This interface is used to represents the outputs of the SC call. - * - * @see outputs - The outputs of the SC call (optional) - * @see events - The events emitted by the SC call (optional) - */ -export interface OperationOutputs { - outputs?: any; - events: IEvent[]; -} - -const MASSA_EXEC_ERROR = 'massa_execution_error'; -const OUTPUTS_PREFIX = 'Result${protoFile.funcName}: '; - -export class ${protoFile.funcName[0].toUpperCase() + protoFile.funcName.slice(1)}BlockchainCaller { - private nodeRPC: string; - - public account: ${mode == 'web3' ? 'SmartContractsClient' : 'IAccount'}; - public coins: bigint; - - - constructor(account: ${mode == 'web3' ? 'SmartContractsClient' : 'IAccount'}, coins: bigint, nodeRPC: string) { - this.nodeRPC = nodeRPC; - this.account = account; - this.coins = coins; - } - - /** - * This method have been generated by the Massa Proto CLI. - * It allows you to instantiate a new ${protoFile.funcName[0].toUpperCase() + protoFile.funcName.slice(1)}BlockchainCaller object with the default values. - * - * @param envPath - The path to the .env file (default: './'), relative to the terminal location - * @returns {Promise<${protoFile.funcName[0].toUpperCase() + protoFile.funcName.slice(1)}BlockchainCaller>} A promise that resolves to a new ${protoFile.funcName[0].toUpperCase() + protoFile.funcName.slice(1)}BlockchainCaller object - */ - static async newDefault(${mode == 'web3' ? "envPath = './'" : 'providerName: string, accountIndex: string'}): Promise<${protoFile.funcName[0].toUpperCase() + protoFile.funcName.slice(1)}BlockchainCaller> { - ${mode == 'web3' ? `// check if the environment variables are set - if (!process.env.NODE_RPC) { - throw new Error('NODE_RPC environment variable is not set'); - } - if (!process.env.ACCOUNT_SECRET_KEY) { - throw new Error('ACCOUNT_SECRET_KEY environment variable is not set'); - } - const providerPub = { - url: process.env.NODE_RPC, - type: ProviderType.PUBLIC, - }; - const providerPriv = { - url: process.env.NODE_RPC, - type: ProviderType.PRIVATE, - }; - const clientConfig = { - providers: [providerPub, providerPriv], - periodOffset: null, - }; - const publicApiClient = new PublicApiClient(clientConfig); - const walletClient = new WalletClient(clientConfig, publicApiClient); - const account: IAccount = await WalletClient.getAccountFromSecretKey(process.env.ACCOUNT_SECRET_KEY); - walletClient.setBaseAccount(account); - const SC_Client = new SmartContractsClient( - clientConfig, - publicApiClient, - walletClient, - );` : `// get the available providers - const provider = await providers(); - // chose the provider - const providerToUse = provider.find((p) => String(p.name) === providerName); - if (!providerToUse) { - throw new Error("Provider '" + providerName + "'not found"); - }`} - return new ${protoFile.funcName[0].toUpperCase() + protoFile.funcName.slice(1)}BlockchainCaller(${mode == 'web3' ? 'SC_Client' : 'await providerToUse.accounts()[accountIndex]'}, 0n, ${mode == 'web3' ? 'process.env.NODE_RPC' : 'providerToUse.getNodesUrls[0]'}); - } - - /** - * This method have been generated by the Massa Proto CLI. - * It allows you to call the "${protoFile.funcName}" function of the - * "${contractAddress}" Smart Contract. - * - * @remarks - * To work properly, you need to run 'npm install @protobuf-ts/plugin' in your project folder. - * Otherwise, this caller will not work. - * - ${documentationArgs.slice(3)} - * - * @param {bigint} coins - The amount of Massa coins to send to the block creator - * - * @returns {Promise} A promise that resolves to an object which contains the outputs and events from the call to ${protoFile.funcName}. - */ - async ${protoFile.funcName}(${args}): Promise { - ${checkUnsignedArgs} - - ${argsSerialization} - - // Send the operation to the blockchain and retrieve its outputs - return ( - await extractOutputsAndEvents( - '${contractAddress}', - '${protoFile.funcName}', - serializedArgs, - this.coins, - '${returnType[protoFile.resType]}', - this.account, - this.nodeRPC, - ) - ); - } - - /** - * This method have been generated by the Massa Proto CLI. - * It allows you to update the amount of Massa coins to send to the block creator when calling the Smart Contract. - */ - editCoins(coins: bigint) { - this.coins = coins; - } -} - -async function extractOutputsAndEvents( - contractAddress: string, - functionName: string, - args: Uint8Array, - coins: bigint, - returnType: string, - account: ${mode == 'web3' ? 'SmartContractsClient' : 'IAccount'}, - nodeUrl: string, - ): Promise { - - let events: IEvent[] = []; - - // try to call the Smart Contract - try{ - events = await getEvents( - ${callSCConstructor(mode)}, - nodeUrl, - ) - } - catch (err) { - return { - events: events, - } as OperationOutputs; - } - - // if the call is successful, retrieve the outputs from the events - let rawOutput: string | null = null; - for (let event of events) { - if (event.data.slice(0, OUTPUTS_PREFIX.length) == OUTPUTS_PREFIX) { - rawOutput = event.data.slice(OUTPUTS_PREFIX.length); - // remove the event from the list - events.splice(events.indexOf(event), 1); - break; - } - } - - // check the output and return the result - if (rawOutput === null && returnType !== 'void') { - return { - events: events, - } as OperationOutputs; - } - if(rawOutput === null && returnType === 'void') { - return { - events: events, - } as OperationOutputs; - } - if(rawOutput !== null && returnType !== 'void') { - // try to deserialize the outputs - let output: Uint8Array = new Uint8Array(0); - let deserializedOutput = null; - try{ - output = rawOutput.slice(1,-1).split(',').map( - (s) => parseInt(s) - ) as unknown as Uint8Array; - deserializedOutput = ${protoFile.funcName}Helper.fromBinary(output); - } - catch (err) { - return { - events: events, - } as OperationOutputs; - } - return { - outputs: output, - events: events, - } as OperationOutputs; - } - return { - events: events, - } as OperationOutputs; -} - -/** - * This method have been generated by the Massa Proto CLI. - * It sets up all the objects needed to poll the events generated by the "${protoFile.funcName}" function. - * - * @param {TransactionDetails} txDetails - An object containing the operationId of SC call. - * @param {string} nodeUrl - The url of the node to connect to. - * - * @returns {Promise} An object containing the eventPoller and the events. - */ -async function getEvents(txDetails: TransactionDetails, nodeUrl: string): Promise{ - const opId = txDetails.operationId; - - // setup the providers - const providerPub: IProvider = { - url: nodeUrl, - type: ProviderType.PUBLIC, - }; - const providerPriv: IProvider = { - url: nodeUrl, - type: ProviderType.PRIVATE, - }; // we don't need it here but a private provider is required by the BaseClient object - - // setup the client config - const clientConfig: IClientConfig = { - providers: [providerPub, providerPriv], - periodOffset: null, - }; - // setup the client - const client = new Client(clientConfig); - - // async poll events in the background for the given opId - const { isError, eventPoller, events }: EventPollerResult = - await time.withTimeoutRejection( - pollAsyncEvents(client, opId), - 20000, - ); - - // stop polling - eventPoller.stopPolling(); - - // if errors, don't await finalization - if (isError) { - throw new Error( - 'Massa Operation Error: ' + JSON.stringify(events, null, 4), - ); - } - - return events; -} - -/** - * Asynchronously polls events from the chain for a given operationId - * - * @param web3Client - an initialized web3 client - * @param opId - the operation id whose events are to be polled - * - * @throws in case of a timeout or massa execution error - * - * @returns A promise that resolves to an 'EventPollerResult' - * - */ -const pollAsyncEvents = async ( - web3Client: Client, - opId: string, -): Promise => { - console.log('Operation Id: ', opId); - console.log('Polling for events...'); - // determine the last slot - let nodeStatusInfo: INodeStatus | null | undefined = await web3Client - .publicApi() - .getNodeStatus(); - - // set the events filter - const eventsFilter = { - start: { period: nodeStatusInfo.last_slot.period - 2, thread: nodeStatusInfo.last_slot.thread }, // last slot - 2 to avoid missing events - end: null, - original_caller_address: null, - original_operation_id: opId, - emitter_address: null, - is_final: false, - } as IEventFilter; - - const eventPoller = EventPoller.startEventsPolling( - eventsFilter, - 1000, - web3Client, - ); - - return new Promise((resolve, reject) => { - eventPoller.on(ON_MASSA_EVENT_DATA, (events: Array) => { - let errorEvents: IEvent[] = events.filter((e) => - e.data.includes(MASSA_EXEC_ERROR), - ); - if (errorEvents.length > 0) { - return resolve({ - isError: true, - eventPoller, - events: errorEvents, - } as EventPollerResult); - } - - if (events.length > 0) { - return resolve({ - isError: false, - eventPoller, - events, - } as EventPollerResult); - } else { - console.log('No events have been emitted'); - } - }); - eventPoller.on(ON_MASSA_EVENT_ERROR, (error: Error) => { - console.log('Event Data Error:', error); - return reject(error); - }); - }); -}; -`; - // save content to file - const fileName = `${protoFile.funcName}Caller.ts`; - if (outputPath.slice(-1) != '/') { - outputPath += '/'; - } - (0, fs_1.writeFileSync)(`${outputPath}${fileName}`, content, 'utf8'); - console.log(`Caller file: ${fileName} generated at: ${outputPath}`); -} -exports.generateTSCaller = generateTSCaller; -/** - * Convert the given path to a relative path based on the current terminal path. - * - * @param absolutePath - The absolute path to convert. - * - * @returns The relative path based on the current terminal path. - */ -function convertToRelativePath(absolutePath) { - return (0, path_1.relative)(process.cwd(), absolutePath); -} -/** - * Convert the given path to an absolute path. - * - * @param givenPath - The path to convert. - * - * @returns The absolute path. - */ -function convertToAbsolutePath(givenPath) { - if (givenPath.startsWith('.')) { - return (0, path_1.resolve)(givenPath); - } - return givenPath; -} -/** - * Creates types script smart contract callers with the given protobuf files. - * - * @param protoFiles - the array of proto files objects - * @param address - the address of the contract where the proto files are coming from (optional) - * @param outputDirectory - the output directory where to generates the callers - */ -function generateTsCallers(protoFiles, outputDirectory, providerUrl, address, mode) { - for (const file of protoFiles) { - if (!file.protoPath) - throw new Error('Error: protoPath is undefined.'); - // generate the helper and the caller inside the same folder - generateTSCaller(outputDirectory, file, address, mode); - } -} -exports.generateTsCallers = generateTsCallers; -//# sourceMappingURL=ts-gen.js.map \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/ts-gen.js.map b/packages/massa-proto-cli/dist/ts-gen.js.map deleted file mode 100644 index 0b921d02..00000000 --- a/packages/massa-proto-cli/dist/ts-gen.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ts-gen.js","sourceRoot":"","sources":["../src/ts-gen.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,2BAAmC;AACnC,iDAAyC;AACzC,gEAAkD;AAClD,+BAA+C;AAI/C;;;;;;;;GAQG;AACH,SAAgB,sBAAsB,CACpC,aAAqB;IAGrB,sCAAsC;IACtC,0GAA0G;IAC1G,IAAG;QACD,IAAA,wBAAQ,EAAC,yDAAyD,qBAAqB,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;KAC5G;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,IAAI,KAAK,CACb,wCAAwC,GAAG,C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GAMG;AACH,SAAS,qBAAqB,CAAC,YAAoB;IACjD,OAAO,IAAA,eAAQ,EAAC,OAAO,CAAC,GAAG,EAAE,EAAE,YAAY,CAAC,CAAC;AAC/C,CAAC;AAED;;;;;;GAMG;AACH,SAAS,qBAAqB,CAAC,SAAiB;IAC9C,IAAI,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;QAC7B,OAAO,IAAA,cAAO,EAAC,SAAS,CAAC,CAAC;KAC3B;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAC/B,UAAuB,EACvB,eAAuB,EACvB,WAAmB,EACnB,OAAe,EACf,IAAY;IAEZ,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE;QAC7B,IAAG,CAAC,IAAI,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;QACtE,4DAA4D;QAC5D,gBAAgB,CAAC,eAAe,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;KACxD;AACH,CAAC;AAZD,8CAYC"} \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/tsProtoTypes.json b/packages/massa-proto-cli/dist/tsProtoTypes.json deleted file mode 100644 index 02873064..00000000 --- a/packages/massa-proto-cli/dist/tsProtoTypes.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "double": "number", - "int32": "number", - "int64": "bigint", - "uint32": "number", - "uint64": "bigint", - "sint32": "number", - "sint64": "bigint", - "fixed32": "number", - "fixed64": "bigint", - "sfixed32": "number", - "sfixed64": "bigint", - "bool": "boolean", - "string": "string", - "bytes": "Uint8Array" -} diff --git a/packages/massa-proto-cli/dist/utils/bytesArrayToString.js b/packages/massa-proto-cli/dist/utils/bytesArrayToString.js deleted file mode 100644 index 16d1708b..00000000 --- a/packages/massa-proto-cli/dist/utils/bytesArrayToString.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bytesArrayToString = void 0; -/** - * Converts any Uint8Array to string - * - * @param bytesArray - Uint8Array to convert - * - * @returns The string representation of the Uint8Array - */ -function bytesArrayToString(bytesArray) { - let str = ''; - // use a for-of loop - for (const byte of bytesArray) { - str += String.fromCharCode(byte); - } - return str; -} -exports.bytesArrayToString = bytesArrayToString; -//# sourceMappingURL=bytesArrayToString.js.map \ No newline at end of file diff --git a/packages/massa-proto-cli/dist/utils/bytesArrayToString.js.map b/packages/massa-proto-cli/dist/utils/bytesArrayToString.js.map deleted file mode 100644 index a3389ba5..00000000 --- a/packages/massa-proto-cli/dist/utils/bytesArrayToString.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bytesArrayToString.js","sourceRoot":"","sources":["../../src/utils/bytesArrayToString.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,SAAgB,kBAAkB,CAAC,UAAsB;IACvD,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,oBAAoB;IACpB,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE;QAC7B,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;KAClC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAPD,gDAOC"} \ No newline at end of file