UNPKG

@minespider/core-bundles

Version:

A high-level SDK for Minespider Core. It abstract the low-level features from the core SDK for a more high-level usage such as DAPPs. Some of the features are 1:1 with the SDK some others abstract some low-level interactions or multiple actions

361 lines 18 kB
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; define(["require", "exports", "ethers", "@minespider/core-sdk", "../../Communication/Adapter/CertificateCacheServiceAdapter"], function (require, exports, ethers, core_sdk_1, CertificateCacheServiceAdapter_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MinespiderModel = void 0; ethers = __importStar(ethers); const ERROR_NO_PRIVATE_METADATA = "No private metadata found for certificate"; const ERROR_NO_PUBLIC_METADATA = "No public metadata found for certificate"; const ERROR_PATH_NOT_EXIST = "Path doesn't exist"; const certificateEnvelopesMap = new Map(); const certificates = new Map(); const entities = new Map(); class MinespiderModel { constructor(minespider, mnemonic, certificateCacheServiceEndpoint) { this.minespider = minespider; this.cacheAdapter = new CertificateCacheServiceAdapter_1.CertificateCacheServiceAdapter(certificateCacheServiceEndpoint); this.wallet = ethers.Wallet.fromMnemonic(mnemonic); } async getCertificateById(id) { if (!certificates.has(id.toLowerCase())) { try { const certificate = await this.cacheAdapter.getCertificate(id.toLowerCase(), this.wallet.privateKey); certificates.set(id.toLowerCase(), certificate); } catch (error) { throw error; } } return Object.assign({}, certificates.get(id.toLowerCase())); } async getCertificateHistoryByCertificate(certificateUuid, parentsDepth = 10, childrenDepth = 10) { return this.cacheAdapter.getCertificateHistoryByCertificate(certificateUuid, parentsDepth, childrenDepth); } async getCertificateHistoryByOwner(entityId) { return this.cacheAdapter.getCertificateHistoryByOwner(entityId); } async getCertificates() { try { const ownerUuid = await this.minespider.getCurrentAccountAddress(); const entries = await this.cacheAdapter.getCertificates(ownerUuid, this.wallet.privateKey); await this.refreshEntitiesCache(); const certificateEnvelopes = await this.minespider.getMyCertificateEnvelopes(); certificateEnvelopes.map((certificateEnvelope) => { certificateEnvelopesMap.set(certificateEnvelope.manifest.uuid.toLowerCase(), certificateEnvelope); }); return Promise.all(entries.map(async (certificateDTO) => { const certificateEnvelope = certificateEnvelopesMap.get(certificateDTO.uuid.toLowerCase()); certificates.set(certificateDTO.uuid.toLowerCase(), Object.assign(Object.assign({}, certificateDTO), { metadataFiles: { public: certificateEnvelope.publicMetadataFiles, private: certificateEnvelope.privateMetadataFiles, } })); const certificate = certificates.get(certificateDTO.uuid.toLowerCase()); return Object.assign({}, certificate); })); } catch (error) { throw error; } } async getCertificatesFromCertificateEnvelopes() { try { const entries = []; const certificateEnvelopes = await this.minespider.getMyCertificateEnvelopes(); await Promise.all(certificateEnvelopes.map(async (certificateEnvelope) => { certificateEnvelopesMap.set(certificateEnvelope.manifest.uuid.toLowerCase(), certificateEnvelope); const certificate = await this.cacheAdapter.getCertificate(certificateEnvelope.manifest.uuid, this.wallet.privateKey); entries.push(certificate); })); return entries; } catch (error) { throw error; } } async refreshEntitiesCache() { (await this.minespider.getEntities()).map((entityDTO) => { entities.set(entityDTO.id.toLowerCase(), entityDTO); }); } async createEntity(name, latitude, longitude, location, meta, entityType, materialMassBalanceCertifications) { try { const account = await this.minespider.registerEntity(entityType, name, latitude, longitude, location, materialMassBalanceCertifications); await this.cacheAdapter.registerClient({ uuid: account.address.toString(), type: entityType, mnemonic: account.mnemonic.toString(), publicKey: account.keyPair.publicKey.toString(), }); await this.refreshEntitiesCache(); return account; } catch (error) { throw error; } } async createCertifier(name, latitude, longitude, location, meta = {}) { return this.createEntity(name, latitude, longitude, location, meta, core_sdk_1.EntityType.Certifier); } async createProducer(name, latitude, longitude, location, meta = {}) { return this.createEntity(name, latitude, longitude, location, meta, core_sdk_1.EntityType.Producer); } async modifyMassBalanceCertification(producerId, materialTaxonomyUuid, measurementUnitUuid, amount) { let result = await this.minespider.modifyMassBalanceCertification(producerId, materialTaxonomyUuid, measurementUnitUuid, amount); return result; } async modifyMassBalanceCertificationForMultipleMaterials(producerId, materialMassBalanceCertifications) { let result = await this.minespider.modifyMassBalanceCertificationForMultipleMaterials(producerId, materialMassBalanceCertifications); return result; } async getEntityDetails(entityId) { try { return await this.minespider.getEntityDetails(entityId); } catch (error) { throw error; } } async getEntitiesByName(entityName) { try { const entities = await this.getEntities(); return entities.filter(entity => entity.name.toLowerCase().indexOf(entityName.toLowerCase()) > -1); } catch (error) { throw error; } } async getEntities() { if (entities.size == 0) { await this.refreshEntitiesCache(); } return Array.from(entities.values()); } async getProducerMBCertification(producerId, materialTaxonomyUuid, measurementUnitUuid) { try { return await this.minespider.getProducerMBCertification(producerId, materialTaxonomyUuid, measurementUnitUuid); } catch (error) { throw error; } } async downloadCertificateEnvelope(address) { return this.minespider.downloadCertificateEnvelope(address); } async createCertificate(certificate) { try { const response = await this.minespider.createCertificate(certificate.certificateAmount, certificate.certificateRawAmount, certificate.certificateGrade, certificate.certificateUnit, certificate.certificateProducer, certificate.materialTaxonomyUuid, certificate.materialTypeUuid, certificate.publicFiles, certificate.privateFiles, certificate.meta); await this.getCertificates(); return response; } catch (error) { throw error; } } async sellCertificate(certificateUuid, amount, newOwnerAddress, publicFilesList, privateFilesList, newCertificateType, meta) { try { if (certificates.size <= 0 || !certificates.has(certificateUuid.toLowerCase())) { await this.getCertificates(); } const certificateEnvelope = certificateEnvelopesMap.get(certificateUuid.toLowerCase()); const sellCertificateResponse = await this.minespider.sellCertificate(certificateEnvelopesMap.get(certificateUuid.toLowerCase()), amount, newOwnerAddress, publicFilesList, privateFilesList, newCertificateType, meta); const certificateDTO = await this.cacheAdapter.getCertificate(certificateEnvelope.manifest.uuid.toLowerCase(), this.wallet.privateKey); certificates.set(certificateEnvelope.manifest.uuid.toLowerCase(), Object.assign(Object.assign({}, certificateDTO), { metadataFiles: { public: certificateEnvelope.publicMetadataFiles, private: certificateEnvelope.privateMetadataFiles, } })); return sellCertificateResponse; } catch (error) { throw error; } } async getCertificatePublicFiles(certificateUuid) { if (certificates.size <= 0 || !certificates.has(certificateUuid.toLowerCase())) { await this.getCertificates(); } const dataPacketEnvelope = certificateEnvelopesMap.get(certificateUuid.toLowerCase()); return dataPacketEnvelope.publicMetadataFiles; } async getCertificatePrivateFiles(certificateUuid) { if (certificates.size <= 0 || !certificates.has(certificateUuid.toLowerCase())) { await this.getCertificates(); } const dataPacketEnvelope = certificateEnvelopesMap.get(certificateUuid.toLowerCase()); return dataPacketEnvelope.privateMetadataFiles; } async downloadCertificatePublicFile(certificateUuid, fileAddress) { const dataPacketEnvelope = certificateEnvelopesMap.get(certificateUuid.toLowerCase()); const fileMetadata = dataPacketEnvelope.publicMetadataFiles.find((file) => { return file.target === fileAddress; }); if (!fileMetadata) { throw new Error(`No file metadata found for the address ${fileAddress}`); } return this.minespider.downloadFile(dataPacketEnvelope.publicFilesKey, fileMetadata); } async downloadCertificatePrivateFile(certificateUuid, fileAddress) { const dataPacketEnvelope = certificateEnvelopesMap.get(certificateUuid.toLowerCase()); const fileMetadata = dataPacketEnvelope.privateMetadataFiles.find((file) => { return file.target === fileAddress; }); if (!fileMetadata) { throw new Error(`No file metadata found for the address ${fileAddress}`); } return this.minespider.downloadFile(dataPacketEnvelope.privateFilesKey, fileMetadata); } async getCurrentAccountAddress() { return await this.minespider.getCurrentAccountAddress(); } async getCertificateManifest(certificateUuid) { const dataPacketEnvelope = certificateEnvelopesMap.get(certificateUuid.toLowerCase()); return dataPacketEnvelope.manifest; } async readCertificateFileList(fileList) { var certificateFiles = []; for (let i = 0; i < fileList.length; i++) { var fileContent = await new Promise((resolve, reject) => { var reader = new FileReader(); reader.onload = function (event) { resolve(Buffer.from(event.target.result)); }; reader.readAsArrayBuffer(fileList[i]); }); certificateFiles.push(new core_sdk_1.CertificateFile(fileContent, fileList[i].name, { type: fileList[i].type, })); } return certificateFiles; } async getMaterialAllowances(balanceHolderUuid, materialTypeUuid, measurementUnitUuid) { return this.minespider.getMaterialAllowances(balanceHolderUuid, materialTypeUuid, measurementUnitUuid); } async getMaterialTaxonomies() { return this.minespider.getMaterialTaxonomies(); } async getMaterialTypes() { return this.minespider.getMaterialTypes(); } async getMeasurementUnits() { return this.minespider.getMeasurementUnits(); } async getMeasurementUnitTypes() { return this.minespider.getMeasurementUnitTypes(); } async getPrivateMetadata(certificateUuid, path) { const dataPacketEnvelope = certificateEnvelopesMap.get(certificateUuid.toLowerCase()); const fileMetadata = dataPacketEnvelope.privateMetadataFiles .filter((file) => { return file.filename === "minespider.json"; }) .pop(); if (!fileMetadata) { throw new Error(`${ERROR_NO_PRIVATE_METADATA} ${certificateUuid}`); } const file = await this.minespider.downloadFile(dataPacketEnvelope.privateFilesKey, fileMetadata); try { const metadata = JSON.parse(file.buffer.toString()); return this.getObjectPath(metadata, path); } catch (e) { throw e; } } async getPublicMetadata(certificateUuid, path) { const dataPacketEnvelope = certificateEnvelopesMap.get(certificateUuid.toLowerCase()); const fileMetadata = dataPacketEnvelope.publicMetadataFiles .filter((file) => { return file.filename === "minespider.json"; }) .pop(); if (!fileMetadata) { throw new Error(`${ERROR_NO_PUBLIC_METADATA} ${certificateUuid}`); } const file = await this.minespider.downloadFile(dataPacketEnvelope.publicFilesKey, fileMetadata); try { const metadata = JSON.parse(file.buffer.toString()); return this.getObjectPath(metadata, path); } catch (e) { throw e; } } getObjectPath(obj, path) { if (!path) { return obj; } return path.split(".").reduce((acc, key) => { if (!acc[key]) { throw new Error(ERROR_PATH_NOT_EXIST); } acc = acc[key]; return acc; }, obj); } async getCertificateOwner(certificateId) { if (certificates.size <= 0 || !certificates.has(certificateId.toLowerCase())) { await this.getCertificates(); } const certificate = await this.cacheAdapter.getCertificate(certificateId.toLowerCase(), this.wallet.privateKey); if (!certificate) { return; } if (entities.has(certificate.owner.uuid.toLowerCase())) { const entity = entities.get(certificate.owner.uuid.toLowerCase()); return entity; } const entity = Object.assign(Object.assign({}, (await this.minespider.getEntityDetails(certificate.owner.uuid.toLowerCase()))), { entityType: certificate.owner.type }); if (!entity.id) { return; } entities.set(entity.id.toLowerCase(), entity); return entity; } async getCertificateParentOwner(certificateId) { if (certificates.size <= 0 || !certificates.has(certificateId.toLowerCase())) { await this.getCertificates(); } const certificate = certificates.get(certificateId.toLowerCase()); const parentCertificate = await this.cacheAdapter.getCertificate(certificate.details.parent.toLowerCase(), this.wallet.privateKey); if (!parentCertificate) { return; } if (entities.has(parentCertificate.owner.uuid.toLowerCase())) { return entities.get(parentCertificate.owner.uuid.toLowerCase()); } const entity = Object.assign(Object.assign({}, (await this.minespider.getEntityDetails(parentCertificate.owner.uuid.toLowerCase()))), { entityType: parentCertificate.owner.type }); entities.set(entity.id.toLowerCase(), entity); return entity; } async getBalanceHolderUuid() { return this.minespider.getBalanceHolderUuid(); } async acceptCertificate(certificateUuid) { return this.minespider.acceptCertificate(certificateUuid); } } exports.MinespiderModel = MinespiderModel; }); //# sourceMappingURL=MinespiderModel.js.map