UNPKG

@foreverrbum/ethsign

Version:

This package will allow you to electronically sign documents within your application

1,385 lines (1,113 loc) 59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDocumentFormattedStatus = exports.getDocumentDetails = exports.getDocumentComment = exports.getDocument = exports.getData = exports.getCurrentBlockNumber = exports.findTrustedParties = exports.findSignersForDocument = exports.findCreator = exports.exportHistory = exports.default = exports.archiveDocuments = void 0; exports.getIpfsHashFromBytes32 = getIpfsHashFromBytes32; exports.validateExpiration = exports.truncate = exports.timer = exports.storeNotif = exports.safeToAscii = exports.manipulateFileName = exports.loadHistory = exports.isEmptyFile = exports.handleShowLabel = exports.getWeb3Credentials = exports.getSignInWalletLogo = exports.getNewDocumentKey = exports.getLoggedOutWeb3Credentials = void 0; var _bs = _interopRequireDefault(require("bs58")); var _reactNotificationsComponent = require("react-notifications-component"); var _download = require("./download"); var _fortmatic = _interopRequireDefault(require("fortmatic")); var _torusEmbed = _interopRequireDefault(require("@toruslabs/torus-embed")); var _EthSign = _interopRequireDefault(require("../artifacts/EthSign.json")); var _jspdf = _interopRequireDefault(require("jspdf")); require("jspdf-autotable"); var _logo = _interopRequireDefault(require("../assets/logo.png")); var _moment = _interopRequireDefault(require("moment")); var _request = _interopRequireDefault(require("request")); var _ethers = require("ethers"); var _uuid = require("uuid"); var _lodash = _interopRequireDefault(require("lodash")); var _block = require("./block"); var _chains = require("./chains"); var _mexa = require("@biconomy/mexa"); var _metamask = _interopRequireDefault(require("../assets/metamask.svg")); var _fortmatic2 = _interopRequireDefault(require("../assets/fortmatic.svg")); var _torus = _interopRequireDefault(require("../assets/torus.svg")); var _imtoken = _interopRequireDefault(require("../assets/imtoken.svg")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } // const fromAscii = ethers.utils.formatBytes32String; var toAscii = _ethers.ethers.utils.parseBytes32String; var fortmatic_key = 'pk_live_6D2FFF6E41301BF0'; var fortmatic_test_key = 'pk_test_F4BDDED1F885923E'; var getLoggedOutWeb3Credentials = /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(networkId) { var provider, deployedNetwork, contract; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: provider = new _ethers.ethers.providers.JsonRpcProvider((0, _chains.getChain)(networkId).rpc[0]); deployedNetwork = _EthSign.default.networks[networkId]; contract = new _ethers.ethers.Contract(deployedNetwork.address, _EthSign.default.abi, provider); return _context.abrupt("return", { networkId: networkId, provider: provider, contract: contract }); case 4: case "end": return _context.stop(); } } }, _callee); })); return function getLoggedOutWeb3Credentials(_x) { return _ref.apply(this, arguments); }; }(); exports.getLoggedOutWeb3Credentials = getLoggedOutWeb3Credentials; var getWeb3Credentials = /*#__PURE__*/function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(web3Case, preferredNetwork, location, history, _provider) { var fm, biconomy, torus, innerNetwork, _location$state, _location$state2, _location$state3, originalProvider, _originalProvider, _originalProvider2, signer, account, networkId, deployedNetwork, contract; return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: fm = null; biconomy = null; torus = null; innerNetwork = preferredNetwork; // Detect case if none provided if (!(web3Case == null)) { _context3.next = 21; break; } innerNetwork = (_location$state = location.state) === null || _location$state === void 0 ? void 0 : _location$state.networkId; if (!(location.state !== undefined && location.state.fortmatic && (_location$state2 = location.state) !== null && _location$state2 !== void 0 && _location$state2.networkId)) { _context3.next = 10; break; } web3Case = 1; _context3.next = 21; break; case 10: if (!(location.state !== undefined && location.state.torus && (_location$state3 = location.state) !== null && _location$state3 !== void 0 && _location$state3.networkId)) { _context3.next = 14; break; } web3Case = 4; _context3.next = 21; break; case 14: if (!window.ethereum) { _context3.next = 18; break; } web3Case = 2; _context3.next = 21; break; case 18: window.alert('No wallet detected!'); history.goBack(); return _context3.abrupt("return"); case 21: if (!(web3Case == 1)) { _context3.next = 26; break; } if (innerNetwork == 1) { fm = new _fortmatic.default(fortmatic_key); } else { fm = new _fortmatic.default((0, _chains.isTestnet)(innerNetwork) ? fortmatic_test_key : fortmatic_key, (0, _chains.getFortmaticChainOptions)(innerNetwork)); } if ((0, _chains.getChain)(innerNetwork).biconomySupport) { originalProvider = new _ethers.ethers.providers.Web3Provider(fm.getProvider()); biconomy = new _mexa.Biconomy(originalProvider, { apiKey: (0, _chains.getChain)(innerNetwork).biconomyKey, strictMode: false }); _provider = new _ethers.ethers.providers.Web3Provider(biconomy); } else { _provider = new _ethers.ethers.providers.Web3Provider(fm.getProvider()); } _context3.next = 56; break; case 26: if (!(web3Case == 4)) { _context3.next = 36; break; } torus = new _torusEmbed.default(); _context3.next = 30; return torus.init((0, _chains.getTorusChainOptions)(innerNetwork)); case 30: _context3.next = 32; return torus.ethereum.enable(); case 32: torus.ethereum.isStatus = true; if ((0, _chains.getChain)(innerNetwork).biconomySupport) { _originalProvider = new _ethers.ethers.providers.Web3Provider(torus.ethereum); biconomy = new _mexa.Biconomy(_originalProvider, { apiKey: (0, _chains.getChain)(innerNetwork).biconomyKey, strictMode: false }); _provider = new _ethers.ethers.providers.Web3Provider(biconomy); } else { _provider = new _ethers.ethers.providers.Web3Provider(torus.ethereum); } _context3.next = 56; break; case 36: if (!(web3Case == 2)) { _context3.next = 56; break; } _context3.t0 = _chains.getChain; _context3.next = 40; return window.ethereum.request({ method: 'eth_chainId' }); case 40: _context3.t1 = _context3.sent; if (!(0, _context3.t0)(_context3.t1).biconomySupport) { _context3.next = 55; break; } _originalProvider2 = new _ethers.ethers.providers.Web3Provider(window.ethereum); _context3.t2 = _mexa.Biconomy; _context3.t3 = _originalProvider2; _context3.t4 = _chains.getChain; _context3.next = 48; return window.ethereum.request({ method: 'eth_chainId' }); case 48: _context3.t5 = _context3.sent; _context3.t6 = (0, _context3.t4)(_context3.t5).biconomyKey; _context3.t7 = { apiKey: _context3.t6, strictMode: false }; biconomy = new _context3.t2(_context3.t3, _context3.t7); _provider = new _ethers.ethers.providers.Web3Provider(biconomy); _context3.next = 56; break; case 55: _provider = new _ethers.ethers.providers.Web3Provider(window.ethereum); case 56: _context3.next = 58; return _provider.getSigner(); case 58: signer = _context3.sent; _context3.next = 61; return signer.getAddress(); case 61: account = _context3.sent; _context3.next = 64; return _provider.getNetwork(); case 64: networkId = _context3.sent.chainId; deployedNetwork = _EthSign.default.networks[networkId]; contract = null; if (!(biconomy == null)) { _context3.next = 72; break; } contract = new _ethers.ethers.Contract(deployedNetwork.address, _EthSign.default.abi, _provider); console.log("EthSign: Initialized normally."); _context3.next = 74; break; case 72: _context3.next = 74; return new Promise(function (resolve, reject) { biconomy.onEvent(biconomy.READY, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: contract = new _ethers.ethers.Contract(deployedNetwork.address, _EthSign.default.abi, biconomy.getSignerByAddress(account)); console.log("EthSign: Initialized with Mexa."); resolve(); case 3: case "end": return _context2.stop(); } } }, _callee2); }))).onEvent(biconomy.ERROR, function (error, message) { console.log("EthSign: Failed to initialize with Mexa."); console.log(message); console.log(error); reject(); }); }); case 74: return _context3.abrupt("return", { web3: _provider, fm: fm, torus: torus, ethAccount: account === null || account === void 0 ? void 0 : account.toLowerCase(), networkId: networkId, contract: contract, web3Case: web3Case }); case 75: case "end": return _context3.stop(); } } }, _callee3); })); return function getWeb3Credentials(_x2, _x3, _x4, _x5, _x6) { return _ref2.apply(this, arguments); }; }(); exports.getWeb3Credentials = getWeb3Credentials; var timer = function timer(ms) { return new Promise(function (res) { return setTimeout(res, ms); }); }; exports.timer = timer; var getSignInWalletLogo = function getSignInWalletLogo(walletName) { switch (walletName) { case 'Metamask': return _metamask.default; case 'Fortmatic': return _fortmatic2.default; case 'Torus': return _torus.default; case 'imToken': return _imtoken.default; default: return null; } }; exports.getSignInWalletLogo = getSignInWalletLogo; var getPastEvents = /*#__PURE__*/function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(provider, contract, filter, fromBlock) { var latest, networkId, contractBirth, contractBirthTxHash, events, i_increment, i, toBlock, slicedEvents; return regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return provider.getBlockNumber(); case 2: latest = _context4.sent; _context4.next = 5; return provider.getNetwork(); case 5: networkId = _context4.sent.chainId; if (!(fromBlock != null)) { _context4.next = 10; break; } contractBirth = fromBlock; _context4.next = 14; break; case 10: contractBirthTxHash = _EthSign.default.networks[networkId].transactionHash; _context4.next = 13; return provider.getTransaction(contractBirthTxHash); case 13: contractBirth = _context4.sent.blockNumber; case 14: events = []; if (!(networkId == 56 || networkId == 1)) { _context4.next = 30; break; } if (networkId == "56") i_increment = 4999;else if (networkId == "1") i_increment = 511; i = contractBirth; case 18: if (!(i < latest)) { _context4.next = 28; break; } toBlock = void 0; if (i + i_increment > latest) { toBlock = latest; } else { toBlock = i + i_increment; } _context4.next = 23; return contract.queryFilter(filter, i, toBlock); case 23: slicedEvents = _context4.sent; events.push.apply(events, slicedEvents); case 25: i += i_increment; _context4.next = 18; break; case 28: _context4.next = 33; break; case 30: _context4.next = 32; return contract.queryFilter(filter, contractBirth, latest); case 32: events = _context4.sent; case 33: console.log(events); return _context4.abrupt("return", events); case 35: case "end": return _context4.stop(); } } }, _callee4); })); return function getPastEvents(_x7, _x8, _x9, _x10) { return _ref4.apply(this, arguments); }; }(); function getIpfsHashFromBytes32(bytes32Hex) { if (bytes32Hex == null || bytes32Hex === '' || bytes32Hex === '0x0000000000000000000000000000000000000000000000000000000000000000') return ""; // Add our default ipfs values for first 2 bytes: // function:0x12=sha2, size:0x20=256 bits // and cut off leading "0x" var hashHex = '1220' + bytes32Hex.slice(2); var hashBytes = Buffer.from(hashHex, 'hex'); var hashStr = _bs.default.encode(hashBytes); return hashStr; } var getDocumentDetails = /*#__PURE__*/function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(documentKey, documentBasicInfo, contract, provider) { var _yield$signer$getAddr; var signer, signerAddress, instance, name, birth, expiration, numOfSigners, initiator, created_at, currentBlock, expire_at, expiration_block, estimateDate, _yield$instance$getDo, docStorageProvider, docStorage_id0, docStorage_id1, _yield$instance$getDo2, metaStorageProvider, metaStorage_id0, metaStorage_id1, docHash, metaHash, commentDataRaw, commentData, voteStatus, signatureDataRaw, signatureData, numAllSignersTotalSigned, numAllSignersTotalFields, signers, withPassword, enrolledNumOfSigners, storageProvider; return regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: signer = provider.getSigner(); _context5.next = 3; return signer.getAddress(); case 3: _context5.t1 = _yield$signer$getAddr = _context5.sent; _context5.t0 = _context5.t1 === null; if (_context5.t0) { _context5.next = 7; break; } _context5.t0 = _yield$signer$getAddr === void 0; case 7: if (!_context5.t0) { _context5.next = 11; break; } _context5.t2 = void 0; _context5.next = 12; break; case 11: _context5.t2 = _yield$signer$getAddr.toLowerCase(); case 12: signerAddress = _context5.t2; _context5.next = 15; return contract.connect(signer); case 15: instance = _context5.sent; name = documentBasicInfo.name, birth = documentBasicInfo.birth, expiration = documentBasicInfo.expiration, numOfSigners = documentBasicInfo.numOfSigners, initiator = documentBasicInfo.initiator; _context5.next = 19; return provider.getBlock(birth); case 19: created_at = _context5.sent; _context5.next = 22; return getCurrentBlockNumber(provider); case 22: currentBlock = _context5.sent; expire_at = null, expiration_block = expiration; if (!(expiration !== 0)) { _context5.next = 31; break; } _context5.next = 27; return (0, _block.getTimestampOfFutureBlock)(expiration, currentBlock, provider); case 27: estimateDate = _context5.sent; expire_at = estimateDate ? (0, _moment.default)(estimateDate).unix() : null; _context5.next = 32; break; case 31: expiration_block = 'Never'; case 32: _context5.next = 34; return instance.getDocumentDocStorageInfo(documentKey); case 34: _yield$instance$getDo = _context5.sent; docStorageProvider = _yield$instance$getDo.docStorageProvider; docStorage_id0 = _yield$instance$getDo.docStorage_id0; docStorage_id1 = _yield$instance$getDo.docStorage_id1; _context5.next = 40; return instance.getDocumentMetaStorageInfo(documentKey); case 40: _yield$instance$getDo2 = _context5.sent; metaStorageProvider = _yield$instance$getDo2.metaStorageProvider; metaStorage_id0 = _yield$instance$getDo2.metaStorage_id0; metaStorage_id1 = _yield$instance$getDo2.metaStorage_id1; docHash = getIpfsHashFromBytes32(docStorage_id0) + getIpfsHashFromBytes32(docStorage_id1); metaHash = getIpfsHashFromBytes32(metaStorage_id0) + getIpfsHashFromBytes32(metaStorage_id1); _context5.next = 48; return instance.aggregateGetAllCommentsOfAllSigners(documentKey); case 48: commentDataRaw = _context5.sent; commentData = []; commentDataRaw.map(function (data) { var signer = data.signer, commentStorageInfo = data.commentStorageInfo; var storage_id0 = commentStorageInfo.storage_id0, storage_id1 = commentStorageInfo.storage_id1, provider = commentStorageInfo.provider; var commentHash = getIpfsHashFromBytes32(storage_id0) + getIpfsHashFromBytes32(storage_id1); if (commentHash != "") { commentData.push({ address: signer.toLowerCase(), provider: safeToAscii(provider), commentHash: commentHash }); } }); /* * Statuses: * 0: 'PDF Not Uploaded' * 1: 'More Signers Needed' * 2: 'Pending Signatures' * 3: 'All Signed' * 4: 'Waiting For Others' * 5: 'Need More Signers' */ voteStatus = 2; if (docStorageProvider == 0) { // console.log("Document suspended: PDF needs to be uploaded"); voteStatus = 0; } _context5.next = 55; return instance.aggregateGetIsSignedForAllSignatureFields(documentKey); case 55: signatureDataRaw = _context5.sent; signatureData = []; numAllSignersTotalSigned = 0; numAllSignersTotalFields = 0; signers = []; signatureDataRaw.map(function (data) { var signer = data.signer, fieldSigned = data.fieldSigned; var signed = fieldSigned.filter(function (field) { return field == true; }); var numSignedFields = signed.length; var numTotalFields = fieldSigned.length; if (signer == signerAddress && numSignedFields == numTotalFields) { voteStatus = 4; // user signed all his fields } numAllSignersTotalSigned = numAllSignersTotalSigned + numSignedFields; numAllSignersTotalFields = numAllSignersTotalFields + numTotalFields; signatureData.push({ signer: signer.toLowerCase(), signed: signed.length, notSigned: fieldSigned.length - signed.length, fieldSigned: fieldSigned }); signers.push({ address: signer.toLowerCase(), avatar: null, alias: null, fullySigned: numSignedFields == numTotalFields }); }); if (numAllSignersTotalSigned == numAllSignersTotalFields) { voteStatus = 3; } _context5.next = 64; return (0, _download.isFileWithPassword)(docHash); case 64: withPassword = _context5.sent; _context5.next = 67; return instance.getNumberOfSignersForDocument(documentKey); case 67: enrolledNumOfSigners = _context5.sent; // Total number of signers enrolled (needs to match totalNumOfSigners to proceed at all) if (enrolledNumOfSigners != numOfSigners) { voteStatus = 5; } // TODO: voteStatus for need more signers state // with the assumption that all files (doc, meta, comments) are stored at the same storageprovider storageProvider = safeToAscii(docStorageProvider); return _context5.abrupt("return", { documentKey: documentKey, initiator: initiator, name: name, creation: { block: birth, date: created_at.timestamp }, expiration: { block: expiration_block, date: expire_at ? expire_at : null }, status: voteStatus, ipfsHash: docHash, metaHash: metaHash, storageProvider: storageProvider, commentData: commentData, withPassword: withPassword, signers: signers, signatureData: signatureData }); case 71: case "end": return _context5.stop(); } } }, _callee5); })); return function getDocumentDetails(_x11, _x12, _x13, _x14) { return _ref5.apply(this, arguments); }; }(); exports.getDocumentDetails = getDocumentDetails; var getDocument = /*#__PURE__*/function () { var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(documentKey, contract, provider, formatMessage) { var instance, document, _documentBasicInfo$in, documentBasicInfo; return regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return contract.connect(provider.getSigner()); case 2: instance = _context6.sent; document = {}; _context6.prev = 4; _context6.next = 7; return instance.getDocumentBasicInfo(documentKey); case 7: documentBasicInfo = _context6.sent; document.birth = documentBasicInfo.birth.toNumber(); document.expiration = documentBasicInfo.expiration.toNumber(); document.name = safeToAscii(documentBasicInfo.name).replace(/\0.*$/g, ''); document.numOfSigners = documentBasicInfo.numOfSigners.toNumber(); document.initiator = (_documentBasicInfo$in = documentBasicInfo.initiator) === null || _documentBasicInfo$in === void 0 ? void 0 : _documentBasicInfo$in.toLowerCase(); _context6.next = 19; break; case 15: _context6.prev = 15; _context6.t0 = _context6["catch"](4); console.log(_context6.t0); storeNotif(formatMessage({ id: "ERROR_FETCHING_DATA" }), formatMessage({ id: "DATA_NOT_FETCHED_PLEASE_RELOAD" }), 'danger'); case 19: return _context6.abrupt("return", document); case 20: case "end": return _context6.stop(); } } }, _callee6, null, [[4, 15]]); })); return function getDocument(_x15, _x16, _x17, _x18) { return _ref6.apply(this, arguments); }; }(); exports.getDocument = getDocument; var getData = /*#__PURE__*/function () { var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(filter, contract, provider) { var instance, documents, numOfDocumentsCreatedByMe, i, _document, documentKey, documentBasicInfo, numOfDocumentsSharedWithMe, _i, _document2, _documentKey, _documentBasicInfo, numOfDocumentsArchived, _i2, _document3, _documentKey2, _documentBasicInfo2; return regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return contract.connect(provider.getSigner()); case 2: instance = _context7.sent; // This gives a JsonRpcSigner, aka read & write // Commented code below is for testing // const docName = fromAscii('Name_PLACEHOLDER2.pdf'); // const docPW = fromAscii('Password PLACEHOLDER'); // const expiration = 0; // PLACEHOLDER // const numOfSigners = 1; // PLACEHOLDER // const docKey = await instance.hashDocumentKey(docName, docPW); // await handleNewBasicDocument(instance, docKey, docName, expiration, numOfSigners); // await handleAddSigners(instance, docKey, ['0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266']); documents = []; if (!(filter == 'original')) { _context7.next = 32; break; } _context7.next = 7; return instance.getNumOfDocumentsCreatedByMe(); case 7: numOfDocumentsCreatedByMe = _context7.sent.toNumber(); i = 0; case 9: if (!(i < numOfDocumentsCreatedByMe)) { _context7.next = 30; break; } _document = {}; _context7.next = 13; return instance.getDocumentCreatedByMeAtIndex(i); case 13: documentKey = _context7.sent; _context7.next = 16; return instance.getDocumentBasicInfo(documentKey); case 16: documentBasicInfo = _context7.sent; // console.log(documentBasicInfo); _document.birth = documentBasicInfo.birth.toNumber(); _document.expiration = documentBasicInfo.expiration.toNumber(); _document.name = safeToAscii(documentBasicInfo.name).replace(/\0.*$/g, ''); _document.numOfSigners = documentBasicInfo.numOfSigners.toNumber(); _document.initiator = documentBasicInfo.initiator.toLowerCase(); // console.log(i); _context7.next = 24; return getDocumentDetails(documentKey, _document, contract, provider); case 24: _document = _context7.sent; _document.type = 'CreatedByMe'; if (_document.status != 5) { documents.push(_document); } // console.log("findSignersForDocument():", await findSignersForDocument(contract, documentKey)); // await loadHistory(contract, provider, documentBasicInfo, documentKey); case 27: ++i; _context7.next = 9; break; case 30: _context7.next = 86; break; case 32: if (!(filter == 'shared')) { _context7.next = 60; break; } _context7.next = 35; return instance.getNumOfDocumentsSharedWithMe(); case 35: numOfDocumentsSharedWithMe = _context7.sent.toNumber(); _i = 0; case 37: if (!(_i < numOfDocumentsSharedWithMe)) { _context7.next = 58; break; } _document2 = {}; _context7.next = 41; return instance.getDocumentSharedWithMeAtIndex(_i); case 41: _documentKey = _context7.sent; _context7.next = 44; return instance.getDocumentBasicInfo(_documentKey); case 44: _documentBasicInfo = _context7.sent; _document2.birth = _documentBasicInfo.birth.toNumber(); _document2.expiration = _documentBasicInfo.expiration.toNumber(); _document2.name = safeToAscii(_documentBasicInfo.name).replace(/\0.*$/g, ''); _document2.numOfSigners = _documentBasicInfo.numOfSigners.toNumber(); _document2.initiator = _documentBasicInfo.initiator.toLowerCase(); _context7.next = 52; return getDocumentDetails(_documentKey, _document2, contract, provider); case 52: _document2 = _context7.sent; _document2.type = 'SharedWithMe'; if (_document2.status != 5) { documents.push(_document2); } // console.log("getDocumentDetails():", await getDocumentDetails(documentKey, documentBasicInfo, contract, provider)); // console.log("findSignersForDocument():", await findSignersForDocument(contract, documentKey)); case 55: ++_i; _context7.next = 37; break; case 58: _context7.next = 86; break; case 60: if (!(filter == 'archived')) { _context7.next = 86; break; } _context7.next = 63; return instance.getNumOfDocumentsArchived(); case 63: numOfDocumentsArchived = _context7.sent.toNumber(); _i2 = 0; case 65: if (!(_i2 < numOfDocumentsArchived)) { _context7.next = 86; break; } _document3 = {}; _context7.next = 69; return instance.getDocumentArchivedAtIndex(_i2); case 69: _documentKey2 = _context7.sent; _context7.next = 72; return instance.getDocumentBasicInfo(_documentKey2); case 72: _documentBasicInfo2 = _context7.sent; // console.log(documentBasicInfo); _document3.birth = _documentBasicInfo2.birth.toNumber(); _document3.expiration = _documentBasicInfo2.expiration.toNumber(); _document3.name = safeToAscii(_documentBasicInfo2.name).replace(/\0.*$/g, ''); _document3.numOfSigners = _documentBasicInfo2.numOfSigners.toNumber(); _document3.initiator = _documentBasicInfo2.initiator.toLowerCase(); // console.log(i); _context7.next = 80; return getDocumentDetails(_documentKey2, _document3, contract, provider); case 80: _document3 = _context7.sent; _document3.type = 'Archived'; if (_document3.status != 5) { documents.push(_document3); } // console.log("findSignersForDocument():", await findSignersForDocument(contract, documentKey)); // await loadHistory(contract, provider, documentBasicInfo, documentKey); case 83: ++_i2; _context7.next = 65; break; case 86: return _context7.abrupt("return", documents); case 87: case "end": return _context7.stop(); } } }, _callee7); })); return function getData(_x19, _x20, _x21) { return _ref7.apply(this, arguments); }; }(); exports.getData = getData; var archiveDocuments = /*#__PURE__*/function () { var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(provider, contract, documentKeys, handleArchivedWaiting, formatMessage) { var signer, instance, tx, networkId; return regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.prev = 0; _context8.next = 3; return provider.getSigner(); case 3: signer = _context8.sent; _context8.next = 6; return contract.connect(signer); case 6: instance = _context8.sent; _context8.next = 9; return instance.archiveDocuments(documentKeys, { gasLimit: 250000 }); case 9: tx = _context8.sent; handleArchivedWaiting(true); _context8.next = 13; return provider.getNetwork(); case 13: networkId = _context8.sent.chainId; _context8.next = 16; return tx.wait(networkId == 1287 ? 2 : 1).then(function (receipt) {// console.log(receipt) }); case 16: return _context8.abrupt("return", true); case 19: _context8.prev = 19; _context8.t0 = _context8["catch"](0); storeNotif(formatMessage({ id: "TRANSACTION_ERROR" }), formatMessage({ id: "ERROR_ARCHIVING_DOCUMENT" }), 'danger'); console.log(_context8.t0); return _context8.abrupt("return", false); case 24: case "end": return _context8.stop(); } } }, _callee8, null, [[0, 19]]); })); return function archiveDocuments(_x22, _x23, _x24, _x25, _x26) { return _ref8.apply(this, arguments); }; }(); exports.archiveDocuments = archiveDocuments; var getCurrentBlockNumber = /*#__PURE__*/function () { var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(provider) { var currentBlock; return regeneratorRuntime.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return provider.getBlockNumber(); case 2: currentBlock = _context9.sent; return _context9.abrupt("return", currentBlock); case 4: case "end": return _context9.stop(); } } }, _callee9); })); return function getCurrentBlockNumber(_x27) { return _ref9.apply(this, arguments); }; }(); exports.getCurrentBlockNumber = getCurrentBlockNumber; var findCreator = /*#__PURE__*/function () { var _ref10 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10(provider, contract, datasource) { var LogNewDocumentFilter, newDocEvent; return regeneratorRuntime.wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: LogNewDocumentFilter = contract.filters.LogNewDocument(null, datasource.documentKey); _context10.next = 3; return getPastEvents(provider, contract, LogNewDocumentFilter); case 3: newDocEvent = _context10.sent; return _context10.abrupt("return", newDocEvent[0].args.sender); case 5: case "end": return _context10.stop(); } } }, _callee10); })); return function findCreator(_x28, _x29, _x30) { return _ref10.apply(this, arguments); }; }(); // This replaces findTrustedParties exports.findCreator = findCreator; var findSignersForDocument = /*#__PURE__*/function () { var _ref11 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11(contract, documentKey) { var signers, numOfSigners, i, signer; return regeneratorRuntime.wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: signers = []; _context11.next = 3; return contract.getNumberOfSignersForDocument(documentKey); case 3: numOfSigners = _context11.sent.toNumber(); i = 0; case 5: if (!(i < numOfSigners)) { _context11.next = 13; break; } _context11.next = 8; return contract.getDocumentSignerAtIndex(documentKey, i); case 8: signer = _context11.sent; signers.push(signer.toLowerCase()); case 10: ++i; _context11.next = 5; break; case 13: return _context11.abrupt("return", signers); case 14: case "end": return _context11.stop(); } } }, _callee11); })); return function findSignersForDocument(_x31, _x32) { return _ref11.apply(this, arguments); }; }(); exports.findSignersForDocument = findSignersForDocument; var findTrustedParties = /*#__PURE__*/function () { var _ref12 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12(contract, datasource, creator) { var trustedParties, LogClearedProposalFilter, addedTrustedPartyEvents, _iterator, _step, _loop; return regeneratorRuntime.wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: trustedParties = []; LogClearedProposalFilter = contract.filters.LogClearedProposal(null, datasource.documentKey, null, null, 1); _context12.next = 4; return getPastEvents(provider, contract, LogClearedProposalFilter); case 4: addedTrustedPartyEvents = _context12.sent; _iterator = _createForOfIteratorHelper(addedTrustedPartyEvents); try { _loop = function _loop() { var event = _step.value; var returnValues = event.args; if (returnValues.proposedAuthorizedParty !== '0x0000000000000000000000000000000000000000') { if (returnValues.passed) { // this is an add party event trustedParties.push(returnValues.proposedAuthorizedParty); } else { // this is a remove party event // Don't think this is possible trustedParties = trustedParties.filter(function (item) { return item !== returnValues.proposedAuthorizedParty; }); } } }; for (_iterator.s(); !(_step = _iterator.n()).done;) { _loop(); } // adds creator to trustedParties if there are other trustedparties } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (trustedParties.length > 0 && creator) { trustedParties.push(creator); } return _context12.abrupt("return", trustedParties); case 9: case "end": return _context12.stop(); } } }, _callee12); })); return function findTrustedParties(_x33, _x34, _x35) { return _ref12.apply(this, arguments); }; }(); exports.findTrustedParties = findTrustedParties; var validateExpiration = function validateExpiration(documentExpiration, currentBlock) { if (documentExpiration <= currentBlock && documentExpiration != 0) { _reactNotificationsComponent.store.addNotification({ title: 'Error', message: "The expiration block (".concat(documentExpiration, ") must be larger than the current block (").concat(currentBlock, ")."), type: 'danger', insert: 'top', container: 'bottom-right', animationIn: ['animated', 'fadeIn'], animationOut: ['animated', 'fadeOut'], dismiss: { duration: 10000, onScreen: true } }); return false; } else { return true; } }; exports.validateExpiration = validateExpiration; var getNewDocumentKey = /*#__PURE__*/function () { var _ref13 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13(contract) { var documentKey, boolDocumentExists; return regeneratorRuntime.wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: boolDocumentExists = true; case 1: if (!(boolDocumentExists == true)) { _context13.next = 16; break; } _context13.prev = 2; _context13.next = 5; return contract.hashDocumentKey((0, _uuid.v4)()); case 5: documentKey = _context13.sent; _context13.next = 8; return contract.getDocumentBasicInfo(documentKey); case 8: document = _context13.sent; _context13.next = 14; break; case 11: _context13.prev = 11; _context13.t0 = _context13["catch"](2); boolDocumentExists = false; case 14: _context13.next = 1; break; case 16: return _context13.abrupt("return", documentKey); case 17: case "end": return _context13.stop(); } } }, _callee13, null, [[2, 11]]); })); return function getNewDocumentKey(_x36) { return _ref13.apply(this, arguments); }; }(); exports.getNewDocumentKey = getNewDocumentKey; var safeToAscii = function safeToAscii(value) { var parsed; try { parsed = toAscii(value); } catch (err) { parsed = ""; } return parsed; }; exports.safeToAscii = safeToAscii; var loadHistory = /*#__PURE__*/function () { var _ref14 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14(contract, provider, doc, documentKey) { var selfAddress, birth, LogNewDocumentFilter, newDocumentEvent, LogChangedStorageFilter, changedStorageEvents, LogChangedMetadataFilter, changedMetadataEvents, LogAddedNewSignerForDocumentFilter, newSignerEvents, LogSetNumberOfSignatureFieldsFilter, setNumberOfSignatureFieldsEvents, LogLeftNewCommentOnDocumentFilter, leftNewCommentOnDocumentEvents, LogEditedCommentOnDocumentFilter, editedCommentOnDocumentEvents, combined, toAscii, combinedViewModel, _iterator2, _step2, event, eventType, comment, storage_provider, id0, id1, block; return regeneratorRuntime.wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return provider.getSigner().getAddress(); case 2: selfAddress = _context14.sent; birth = doc.creation.block; LogNewDocumentFilter = contract.filters.LogNewDocument(null, documentKey); _context14.next = 7; return getPastEvents(provider, contract, LogNewDocumentFilter, birth); case 7: newDocumentEvent = _context14.sent; LogChangedStorageFilter = contract.filters.LogChangedDocumentStorage(documentKey); _context14.next = 11; return getPastEvents(provider, contract, LogChangedStorageFilter, birth); case 11: changedStorageEvents = _context14.sent; LogChangedMetadataFilter = contract.filters.LogChangedMetadataStorage(documentKey); _context14.next = 15; return getPastEvents(provider, contract, LogChangedMetadataFilter, birth); case 15: changedMetadataEvents = _context14.sent; LogAddedNewSignerForDocumentFilter = contract.filters.LogAddedNewSignerForDocument(null, documentKey); _context14.next = 19; return getPastEvents(provider, contract, LogAddedNewSignerForDocumentFilter, birth); case 19: newSignerEvents = _context14.sent; LogSetNumberOfSignatureFieldsFilter = contract.filters.LogSetNumberOfSignatureFields(documentKey); _context14.next = 23; return getPastEvents(provider, contract, LogSetNumberOfSignatureFieldsFilter, birth); case 23: setNumberOfSignatureFieldsEvents = _context14.sent; LogLeftNewCommentOnDocumentFilter = contract.filters.LogLeftNewCommentOnDocument(null, documentKey); _context14.next = 27; return getPastEvents(provider, contract, LogLeftNewCommentOnDocumentFilter, birth); case 27: leftNewCommentOnDocumentEvents = _context14.sent; LogEditedCommentOnDocumentFilter = contract.filters.LogEditedCommentOnDocument(null, documentKey); _context14.next = 31; return getPastEvents(provider, contract, LogEditedCommentOnDocumentFilter, birth); case 31: editedCommentOnDocumentEvents = _context14.sent; combined = [].concat.apply([], [newDocumentEvent, changedStorageEvents, changedMetadataEvents, newSignerEvents, setNumberOfSignatureFieldsEvents, leftNewCommentOnDocumentEvents, editedCommentOnDocumentEvents]); combined.sort(function (a, b) { return a.blockNumber > b.blockNumber ? 1 : a.blockNumber === b.blockNumber ? a.event === 'LogNewDocument' ? 1 : a.event !== 'LogNewDocument' ? a.event === 'LogAddedNewSignerForDocument' ? 1 : -1 : -1 : -1; }); toAscii = _ethers.ethers.utils.parseBytes32String; combinedViewModel = []; // TODO: Change history table columns to: // Event type, comment (not the comment in 2.0, but any extra information), raw event name (e.g. LogChangedDocumentStorage) _iterator2 = _createForOfIteratorHelper(combined); _context14.prev = 37; _iterator2.s(); case 39: if ((_step2 = _iterator2.n()).done) { _context14.next = 76; bre