UNPKG

pcs-js-eos

Version:

Client Api for PCS protocol

1,681 lines (1,420 loc) 50.3 kB
'use strict'; exports.__esModule = true; exports.default = void 0; var _eosjsEcc = _interopRequireDefault(require("eosjs-ecc")); var _bs = _interopRequireDefault(require("bs58")); var _bigi = _interopRequireDefault(require("bigi")); var _jsFileDownload = _interopRequireDefault(require("js-file-download")); var _scatterx = require("scatterx"); var _checkSig = _interopRequireDefault(require("./checkSig")); var _server = _interopRequireDefault(require("./util/server")); var _config = require("./util/config"); var _util = require("./util/util"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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); }); }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var PcsClient = /*#__PURE__*/ function (_ScatterEOSX) { _inheritsLoose(PcsClient, _ScatterEOSX); function PcsClient(_ref, appName, contractName) { var _this; var protocol = _ref.protocol, host = _ref.host, port = _ref.port, chainId = _ref.chainId; if (contractName === void 0) { contractName = _config.CONTRACT_ACCOUNT; } _this = _ScatterEOSX.call(this, { protocol: protocol, host: host, port: port, chainId: chainId }, appName) || this; _this.contractName = contractName; return _this; } /** * Create PCS Token. Only contract-deployer or 'issuer' execute this. * @param {string} issuer - token issuer except this contract * @param {string} symbol - the symbol name of token */ var _proto = PcsClient.prototype; _proto.create = /*#__PURE__*/ function () { var _create = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(issuer, symbol) { var actObj, res; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this.login(); case 2: actObj = { "contractName": this.contractName, "actionName": "create", "params": [this.account.name, issuer, symbol] }; _context.next = 5; return this.action(actObj); case 5: res = _context.sent; return _context.abrupt("return", res); case 7: case "end": return _context.stop(); } } }, _callee, this); })); function create(_x, _x2) { return _create.apply(this, arguments); } return create; }() /** * Issue a PCS token. This method fails if the token has not been created. * @param {string} to - Account to receive issued token * @param {string} quantity - How much and what kind of token symbol. * e.g. if you want to issue two PCS tokens, quantity is "2 PCS" * @param {string} memo - Data that can be written as the user likes. */ ; _proto.issue = /*#__PURE__*/ function () { var _issue = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee2(to, quantity, memo) { var actObj, res; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.login(); case 2: actObj = { "contractName": this.contractName, "actionName": "issue", "params": [to, quantity, memo] }; _context2.next = 5; return this.action(actObj); case 5: res = _context2.sent; return _context2.abrupt("return", res); case 7: case "end": return _context2.stop(); } } }, _callee2, this); })); function issue(_x3, _x4, _x5) { return _issue.apply(this, arguments); } return issue; }() /** * Issue a PCS token with agent as owner. This method fails if the token has not been created. * @param {string} symbol - token symbol * @param {string} password - password given to the issued token */ ; _proto.issueToAgent = /*#__PURE__*/ function () { var _issueToAgent = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee3(symbol, password) { var id, pcsSig, _ref2, privateKey, publicKey, actObj, res; return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.fetchAvailableTokenId(symbol); case 2: id = _context3.sent; pcsSig = new _checkSig.default(this.network, symbol, this.contractName); _context3.next = 6; return pcsSig.genKeyPair(id, password); case 6: _ref2 = _context3.sent; privateKey = _ref2.privateKey; publicKey = _ref2.publicKey; _context3.next = 11; return this.login(); case 11: actObj = { "contractName": this.contractName, "actionName": "issuetoagent", "params": [symbol, id, publicKey, ""] }; _context3.next = 14; return this.action(actObj); case 14: res = _context3.sent; return _context3.abrupt("return", res); case 16: case "end": return _context3.stop(); } } }, _callee3, this); })); function issueToAgent(_x6, _x7) { return _issueToAgent.apply(this, arguments); } return issueToAgent; }() /** * transfer PCS Token to recipient. * @param {string} recipient token recipient * @param {string} symbol token symbol * @param {number} nftId nft id */ ; _proto.transferById = /*#__PURE__*/ function () { var _transferById = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee4(recipient, symbol, nftId) { var actObj, res; return regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this.login(); case 2: actObj = { "contractName": this.contractName, "actionName": "transferbyid", "params": [this.account.name, recipient, symbol, nftId, "return token"] }; _context4.next = 5; return this.action(actObj); case 5: res = _context4.sent; return _context4.abrupt("return", res); case 7: case "end": return _context4.stop(); } } }, _callee4, this); })); function transferById(_x8, _x9, _x10) { return _transferById.apply(this, arguments); } return transferById; }() /** * Execute transfer action by using agent signature * @param {string} oldPrivateKey subsig private key * @param {string} recipient recipient * @param {string} symbol token symbol * @param {number} nftId nft id */ ; _proto.transferByIdByAgent = /*#__PURE__*/ function () { var _transferByIdByAgent = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee5(oldPrivateKey, recipient, symbol, nftId) { var act_bin, to_bin, sym_bin, id_bin, ts_bin, message_bin, message, sig, query, signedTx, response; return regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: if (_eosjsEcc.default.isValidPrivate(oldPrivateKey)) { _context5.next = 2; break; } throw new RangeError("invalid private_key format"); case 2: // generate message for signature act_bin = bin(this.encodeName("transferid2")); to_bin = bin(this.encodeName(recipient)); sym_bin = bin(getSymbolCodeRaw(symbol)); id_bin = bin(new _bigi.default(String(nftId))); ts_bin = bin(getTimestamp()); message_bin = [].concat(act_bin, to_bin, sym_bin, id_bin, ts_bin); message = Buffer(message_bin); // generate signature for action data sig = _eosjsEcc.default.sign(message, oldPrivateKey); // generate query for PCS server query = { AgentEvent: "TRANSFER", newAddress: recipient, symbolCode: symbol, tokenId: String(nftId), signature: sig }; // request that the agent signs Transaction. _context5.next = 13; return _server.default.requestSignTx(query, this.network.chainId); case 13: signedTx = _context5.sent; _context5.next = 16; return this.eosJS.pushTransaction(signedTx); case 16: response = _context5.sent; return _context5.abrupt("return", response); case 18: case "end": return _context5.stop(); } } }, _callee5, this); })); function transferByIdByAgent(_x11, _x12, _x13, _x14) { return _transferByIdByAgent.apply(this, arguments); } return transferByIdByAgent; }() /** * Restore authority, if password is valid. * @param {string} currentPassword password for current subsig key pair * @param {string} symbol community symbol * @param {number} nftId nft id * @returns {boolean} Whether password is valid */ ; _proto.restoreKey = /*#__PURE__*/ function () { var _restoreKey = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee6(currentPassword, symbol, nftId) { var subsig, _ref3, subkey, _ref4, privateKey, publicKey, signature; return regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: subsig = new _checkSig.default(this.network, symbol, this.contractName); _context6.next = 3; return subsig.getEOSAuth(nftId); case 3: _ref3 = _context6.sent; subkey = _ref3.subkey; _context6.next = 7; return subsig.genKeyPair(nftId, currentPassword); case 7: _ref4 = _context6.sent; privateKey = _ref4.privateKey; publicKey = _ref4.publicKey; if (!(publicKey === subkey)) { _context6.next = 17; break; } subsig.setSessionAuth(nftId, privateKey); signature = _checkSig.default.genSig(privateKey); subsig.setLocalAuth(nftId, signature); return _context6.abrupt("return", true); case 17: return _context6.abrupt("return", false); case 18: case "end": return _context6.stop(); } } }, _callee6, this); })); function restoreKey(_x15, _x16, _x17) { return _restoreKey.apply(this, arguments); } return restoreKey; }() /** * Refresh authority in EOS table and set new authority in web storage. * @param {string} password new password to generate subsig key pair * @param {string} symbol community symbol * @param {number} nftId nft id */ ; _proto.refreshKey = /*#__PURE__*/ function () { var _refreshKey = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee7(password, symbol, nftId) { var subsig, _ref5, subkey, _ref6, privateKey, publicKey, _signature, tokenOwner, scatterAccount, actObj, response, signature; return regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: subsig = new _checkSig.default(this.network, symbol, this.contractName); _context7.next = 3; return subsig.getEOSAuth(nftId); case 3: _ref5 = _context7.sent; subkey = _ref5.subkey; _context7.next = 7; return subsig.genKeyPair(nftId, password); case 7: _ref6 = _context7.sent; privateKey = _ref6.privateKey; publicKey = _ref6.publicKey; if (!(publicKey === subkey)) { _context7.next = 15; break; } // if password is valid, restore authority. subsig.setSessionAuth(nftId, privateKey); _signature = _checkSig.default.genSig(privateKey); subsig.setLocalAuth(nftId, _signature); return _context7.abrupt("return", true); case 15: _context7.next = 17; return this.login(); case 17: _context7.next = 19; return this.fetchTokenInfo(symbol, nftId); case 19: tokenOwner = _context7.sent.owner; scatterAccount = this.account.name; case 21: if (!(tokenOwner !== scatterAccount)) { _context7.next = 29; break; } _context7.next = 24; return this.logout(); case 24: _context7.next = 26; return this.login(); case 26: scatterAccount = this.account.name; _context7.next = 21; break; case 29: actObj = { "contractName": this.contractName, "actionName": "refreshkey", "params": [symbol, nftId, publicKey] }; _context7.next = 32; return this.action(actObj); case 32: response = _context7.sent; // if action succeeds, store authority. subsig.setSessionAuth(nftId, privateKey); signature = _checkSig.default.genSig(privateKey); subsig.setLocalAuth(nftId, signature); return _context7.abrupt("return", response); case 37: case "end": return _context7.stop(); } } }, _callee7, this); })); function refreshKey(_x18, _x19, _x20) { return _refreshKey.apply(this, arguments); } return refreshKey; }() /** * Refresh password in batch process * @param {object} passList * [{symbol: "TST", nftId: 0, "password": "hello0"}, ...] */ ; _proto.batchRefreshKey = /*#__PURE__*/ function () { var _batchRefreshKey = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee9() { var _this2 = this; var _len, passList, _key, actionList, response, _args9 = arguments; return regeneratorRuntime.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: for (_len = _args9.length, passList = new Array(_len), _key = 0; _key < _len; _key++) { passList[_key] = _args9[_key]; } _context9.next = 3; return (0, _util.asyncMap)(passList, /*#__PURE__*/ function () { var _ref7 = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee8(auth) { var subsig, _ref8, privateKey, publicKey, actObj; return regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: subsig = new _checkSig.default(_this2.network, auth.symbol, _this2.contractName); _context8.next = 3; return subsig.genKeyPair(auth.nftId, auth.password); case 3: _ref8 = _context8.sent; privateKey = _ref8.privateKey; publicKey = _ref8.publicKey; actObj = { "contractName": _this2.contractName, "actionName": "refreshkey", "params": [auth.symbol, auth.nftId, publicKey] }; return _context8.abrupt("return", actObj); case 8: case "end": return _context8.stop(); } } }, _callee8); })); return function (_x21) { return _ref7.apply(this, arguments); }; }()); case 3: actionList = _context9.sent; _context9.next = 6; return this.login(); case 6: _context9.next = 8; return this.transaction.apply(this, actionList); case 8: response = _context9.sent; return _context9.abrupt("return", response); case 10: case "end": return _context9.stop(); } } }, _callee9, this); })); function batchRefreshKey() { return _batchRefreshKey.apply(this, arguments); } return batchRefreshKey; }() /** * Execute refreshKey action by using agent signature * @param {string} oldPrivateKey subsig privatekey * @param {string} newPassword subsig new password * @param {string} symbol token symbol * @param {number} nftId nft id */ ; _proto.refreshKeyByAgent = /*#__PURE__*/ function () { var _refreshKeyByAgent = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee10(oldPrivateKey, newPassword, symbol, nftId) { var subsig, newKeyPair, _ref9, subkey, _signature2, tokenOwner, act_bin, sym_bin, id_bin, sk_bin, ts_bin, message_bin, message, sig, query, signedTx, res, signature; return regeneratorRuntime.wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: // generate new key pair subsig = new _checkSig.default(this.network, symbol, this.contractName); _context10.next = 3; return subsig.genKeyPair(nftId, newPassword); case 3: newKeyPair = _context10.sent; _context10.next = 6; return subsig.getEOSAuth(nftId); case 6: _ref9 = _context10.sent; subkey = _ref9.subkey; if (!(newKeyPair.publicKey === subkey)) { _context10.next = 13; break; } // if password is valid, restore authority. subsig.setSessionAuth(nftId, newKeyPair.privateKey); _signature2 = _checkSig.default.genSig(newKeyPair.privateKey); subsig.setLocalAuth(nftId, _signature2); return _context10.abrupt("return", true); case 13: if (_eosjsEcc.default.isValidPrivate(oldPrivateKey)) { _context10.next = 15; break; } throw new RangeError("invalid private_key format"); case 15: _context10.next = 17; return this.fetchTokenInfo(symbol, nftId); case 17: tokenOwner = _context10.sent.owner; if (tokenOwner === _config.AGENT_ACCOUNT) { _context10.next = 20; break; } throw new RangeError("this token is not owned by agent"); case 20: // generate message for signature act_bin = bin(this.encodeName("refreshkey2")); sym_bin = bin(getSymbolCodeRaw(symbol)); id_bin = bin(new _bigi.default(String(nftId))); sk_bin = Array.from(publicKeyToBuffer(newKeyPair.publicKey)); ts_bin = bin(getTimestamp()); message_bin = [].concat(act_bin, sym_bin, id_bin, sk_bin, ts_bin); message = Buffer(message_bin); // generate signature for query sig = _eosjsEcc.default.sign(message, oldPrivateKey); // generate query for PCS server query = { AgentEvent: "REFRESH", symbolCode: symbol, tokenId: nftId, signature: sig, newSubKey: newKeyPair.publicKey }; // request that the agent signs Transaction. _context10.next = 31; return _server.default.requestSignTx(query, this.network.chainId); case 31: signedTx = _context10.sent; _context10.next = 34; return this.eosJS.pushTransaction(signedTx); case 34: res = _context10.sent; // if action succeeds, store authority. subsig.setSessionAuth(nftId, newKeyPair.privateKey); signature = _checkSig.default.genSig(newKeyPair.privateKey); subsig.setLocalAuth(nftId, signature); return _context10.abrupt("return", res); case 39: case "end": return _context10.stop(); } } }, _callee10, this); })); function refreshKeyByAgent(_x22, _x23, _x24, _x25) { return _refreshKeyByAgent.apply(this, arguments); } return refreshKeyByAgent; }() /** * export password to local pc * @param {string} symbol * @param {number} nftId * @param {string} password */ ; _proto.exportPassword = function exportPassword(symbol, nftId, password) { (0, _jsFileDownload.default)(symbol + "@" + nftId + "'s password: " + password, symbol + "@" + nftId + ".txt"); } /** * Check the token authority of the specified Symbol using the PCS server. * Return true, if the possession of the token is confirmed. * @param {string} symbol community symbol * @returns {boolean} If authority is verified */ ; _proto.checkSecurity = /*#__PURE__*/ function () { var _checkSecurity = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee11(symbol) { var subsig, _subsig$getLocalAuth, id, signature, verified; return regeneratorRuntime.wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: subsig = new _checkSig.default(this.network, symbol, this.contractName); _subsig$getLocalAuth = subsig.getLocalAuth(), id = _subsig$getLocalAuth.id, signature = _subsig$getLocalAuth.signature; _context11.prev = 2; _context11.next = 5; return subsig.verifyAuth(id, signature); case 5: verified = _context11.sent; return _context11.abrupt("return", verified); case 9: _context11.prev = 9; _context11.t0 = _context11["catch"](2); console.error(_context11.t0); return _context11.abrupt("return", false); case 13: case "end": return _context11.stop(); } } }, _callee11, this, [[2, 9]]); })); function checkSecurity(_x26) { return _checkSecurity.apply(this, arguments); } return checkSecurity; }() /** * set token meta data * @param {string} symbol * @param {number} nftId * @param {string} metaStr * @return {*} transaction data */ ; _proto.setMetaData = /*#__PURE__*/ function () { var _setMetaData = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee12(symbol, nftId, metaStr, privateKey) { var act_bin, sym_bin, id_bin, meta_bin, ts_bin, message_bin, message, sig, query, signedTx; return regeneratorRuntime.wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: // generate message for signature act_bin = bin(this.encodeName("setmeta")); sym_bin = bin(getSymbolCodeRaw(symbol)); id_bin = bin(new _bigi.default(String(nftId))); meta_bin = stringToBuffer(metaStr); ts_bin = bin(getTimestamp()); message_bin = [].concat(act_bin, sym_bin, id_bin, meta_bin, ts_bin); message = Buffer(message_bin); // generate signature for query sig = _eosjsEcc.default.sign(message, privateKey); // generate query for PCS server query = { AgentEvent: "SETMETA", symbolCode: symbol, tokenId: nftId, metaStr: metaStr, signature: sig }; // request that the agent signs Transaction. _context12.next = 11; return _server.default.requestSignTx(query, this.network.chainId); case 11: signedTx = _context12.sent; _context12.next = 14; return this.eosJS.pushTransaction(signedTx); case 14: return _context12.abrupt("return", _context12.sent); case 15: case "end": return _context12.stop(); } } }, _callee12, this); })); function setMetaData(_x27, _x28, _x29, _x30) { return _setMetaData.apply(this, arguments); } return setMetaData; }() /** * create sell order * @param {string} symbol - Token symbol * @param {number} tokenId - Token ID * @param {number} price - Token Price by EOS */ ; _proto.addSellOrderByid = /*#__PURE__*/ function () { var _addSellOrderByid = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee13(symbol, tokenId, price) { var quantity, actObj, res; return regeneratorRuntime.wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: quantity = PcsClient.numToAsset(Number(price)); // e.g. "1.1000 EOS" _context13.next = 3; return this.login(); case 3: actObj = { "contractName": this.contractName, "actionName": "addsellobyid", "params": [symbol, tokenId, quantity, "add sell order"] }; _context13.next = 6; return this.action(actObj); case 6: res = _context13.sent; return _context13.abrupt("return", res); case 8: case "end": return _context13.stop(); } } }, _callee13, this); })); function addSellOrderByid(_x31, _x32, _x33) { return _addSellOrderByid.apply(this, arguments); } return addSellOrderByid; }() /** * Buy Token from sell order * @param {string} symbol - Token symbol * @param {number} tokenId - Token ID in sell order table */ ; _proto.buyFromOrder = /*#__PURE__*/ function () { var _buyFromOrder = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee14(symbol, tokenId) { var row, seller, price, actObj1, actObj2, res; return regeneratorRuntime.wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return this.fetchSellInfo(symbol, tokenId); case 2: row = _context14.sent; seller = row.user, price = row.price; _context14.next = 6; return this.login(); case 6: actObj1 = { "contractName": "eosio.token", "actionName": "transfer", "params": [this.account.name, this.contractName, price, "deposit EOS to buy token from order"] }; actObj2 = { "contractName": this.contractName, "actionName": "buyfromorder", "params": [this.account.name, symbol, tokenId, "buy token from " + seller] }; _context14.next = 10; return this.transaction(actObj1, actObj2); case 10: res = _context14.sent; return _context14.abrupt("return", res); case 12: case "end": return _context14.stop(); } } }, _callee14, this); })); function buyFromOrder(_x34, _x35) { return _buyFromOrder.apply(this, arguments); } return buyFromOrder; }() /** * Cancel your sell order * @param {string} symbol - Token Symbol * @param {number} tokenId - Token ID in sell order table */ ; _proto.cancelSellOrderById = /*#__PURE__*/ function () { var _cancelSellOrderById = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee15(symbol, tokenId) { var actObj, res; return regeneratorRuntime.wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: _context15.next = 2; return this.login(); case 2: actObj = { "contractName": this.contractName, "actionName": "cancelsobyid", "params": [symbol, tokenId] }; _context15.next = 5; return this.action(actObj); case 5: res = _context15.sent; return _context15.abrupt("return", res); case 7: case "end": return _context15.stop(); } } }, _callee15, this); })); function cancelSellOrderById(_x36, _x37) { return _cancelSellOrderById.apply(this, arguments); } return cancelSellOrderById; }() /** * create buy order * @param {string} symbol - Token Symbol * @param {number} price - Token Order Price by EOS */ ; _proto.addBuyOrder = /*#__PURE__*/ function () { var _addBuyOrder = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee16(symbol, price) { var quantity, actObj1, actObj2, res; return regeneratorRuntime.wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: quantity = PcsClient.numToAsset(Number(price)); _context16.next = 3; return this.login(); case 3: actObj1 = { "contractName": "eosio.token", "actionName": "transfer", "params": [this.account.name, this.contractName, quantity, "deposit EOS to order token"] }; actObj2 = { "contractName": this.contractName, "actionName": "addbuyorder", "params": [this.account.name, symbol, quantity, ""] }; _context16.next = 7; return this.transaction(actObj1, actObj2); case 7: res = _context16.sent; return _context16.abrupt("return", res); case 9: case "end": return _context16.stop(); } } }, _callee16, this); })); function addBuyOrder(_x38, _x39) { return _addBuyOrder.apply(this, arguments); } return addBuyOrder; }() /** * Sell token to other's buy order * @param {string} symbol - Token symbol * @param {number} tokenId - your Token ID to sell * @param {number} orderId - Order ID in buy table */ ; _proto.sellToBuyOrder = /*#__PURE__*/ function () { var _sellToBuyOrder = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee17(symbol, tokenId, orderId, memo) { var actObj, res; return regeneratorRuntime.wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: if (memo === void 0) { memo = ""; } _context17.next = 3; return this.login(); case 3: actObj = { "contractName": this.contractName, "actionName": "selltoorder", "params": [symbol, tokenId, orderId, memo] }; _context17.next = 6; return this.action(actObj); case 6: res = _context17.sent; return _context17.abrupt("return", res); case 8: case "end": return _context17.stop(); } } }, _callee17, this); })); function sellToBuyOrder(_x40, _x41, _x42, _x43) { return _sellToBuyOrder.apply(this, arguments); } return sellToBuyOrder; }() /** * cancel your buy order * @param {string} symbol - Token symbol * @param {number} orderId - Order ID in buy table */ ; _proto.cancelBuyOrderById = /*#__PURE__*/ function () { var _cancelBuyOrderById = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee18(symbol, orderId) { var row, quantity, actObj1, actObj2, res; return regeneratorRuntime.wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: _context18.next = 2; return this.login(); case 2: _context18.next = 4; return this.fetchBuyInfo(symbol, orderId); case 4: row = _context18.sent; quantity = row.price; // e.g. "2.3000 EOS" actObj1 = { "contractName": this.contractName, "actionName": "cancelbobyid", "params": [symbol, orderId] }; actObj2 = { "contractName": this.contractName, "actionName": "withdraw", "params": [this.account.name, quantity, "cancel buy order"] }; _context18.next = 10; return this.transaction(actObj1, actObj2); case 10: res = _context18.sent; return _context18.abrupt("return", res); case 12: case "end": return _context18.stop(); } } }, _callee18, this); })); function cancelBuyOrderById(_x44, _x45) { return _cancelBuyOrderById.apply(this, arguments); } return cancelBuyOrderById; }() /** * withdraw deposit EOS from PCS contract. * @param {string} quantity EOS quantity. e.g. "1.4200 EOS" * @param {string} memo optional string */ ; _proto.withdraw = /*#__PURE__*/ function () { var _withdraw = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee19(quantity, memo) { var actObj, res; return regeneratorRuntime.wrap(function _callee19$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: if (memo === void 0) { memo = ""; } _context19.next = 3; return this.login(); case 3: actObj = { "contractName": this.contractName, "actionName": "withdraw", "params": [this.account.name, quantity, memo] }; _context19.next = 6; return this.action(actObj); case 6: res = _context19.sent; return _context19.abrupt("return", res); case 8: case "end": return _context19.stop(); } } }, _callee19, this); })); function withdraw(_x46, _x47) { return _withdraw.apply(this, arguments); } return withdraw; }() /** * fetch buy order list from pcs contract table * @param {string} symbol - Token symbol */ ; _proto.fetchBuyTable = /*#__PURE__*/ function () { var _fetchBuyTable = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee20(symbol) { var query, rows; return regeneratorRuntime.wrap(function _callee20$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: query = { "code": this.contractName, "scope": symbol, "table": "buyorder", "limit": 100 }; _context20.next = 3; return this.fetchTableMore(query); case 3: rows = _context20.sent; return _context20.abrupt("return", rows); case 5: case "end": return _context20.stop(); } } }, _callee20, this); })); function fetchBuyTable(_x48) { return _fetchBuyTable.apply(this, arguments); } return fetchBuyTable; }() /** * fetch sell order list from pcs contract table * @param {string} symbol - Token symbol */ ; _proto.fetchSellTable = /*#__PURE__*/ function () { var _fetchSellTable = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee21(symbol) { var query, rows; return regeneratorRuntime.wrap(function _callee21$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: query = { "code": this.contractName, "scope": symbol, "table": "sellorder", "limit": 100 }; _context21.next = 3; return this.fetchTableMore(query); case 3: rows = _context21.sent; return _context21.abrupt("return", rows); case 5: case "end": return _context21.stop(); } } }, _callee21, this); })); function fetchSellTable(_x49) { return _fetchSellTable.apply(this, arguments); } return fetchSellTable; }() // fetch information of a buy order from EOS table. ; _proto.fetchBuyInfo = /*#__PURE__*/ function () { var _fetchBuyInfo = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee22(symbol, orderId) { var query, response, rows, row; return regeneratorRuntime.wrap(function _callee22$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: query = { "code": this.contractName, "scope": symbol, "table": "buyorder", "lower_bound": orderId, "upper_bound": orderId, "limit": 1 }; _context22.next = 3; return this.fetchTable(query); case 3: response = _context22.sent; rows = response.rows; if (rows.length) { _context22.next = 7; break; } throw new ReferenceError("buy order is not found."); case 7: row = rows[0]; return _context22.abrupt("return", row); case 9: case "end": return _context22.stop(); } } }, _callee22, this); })); function fetchBuyInfo(_x50, _x51) { return _fetchBuyInfo.apply(this, arguments); } return fetchBuyInfo; }() // fetch information of a sell order from EOS table. ; _proto.fetchSellInfo = /*#__PURE__*/ function () { var _fetchSellInfo = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee23(symbol, nftId) { var query, response, rows, row; return regeneratorRuntime.wrap(function _callee23$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: query = { "code": this.contractName, "scope": symbol, "table": "sellorder", "lower_bound": nftId, "upper_bound": nftId, "limit": 1 }; _context23.next = 3; return this.fetchTable(query); case 3: response = _context23.sent; rows = response.rows; if (rows.length) { _context23.next = 7; break; } throw new ReferenceError("sell order is not found."); case 7: row = rows[0]; return _context23.abrupt("return", row); case 9: case "end": return _context23.stop(); } } }, _callee23, this); })); function fetchSellInfo(_x52, _x53) { return _fetchSellInfo.apply(this, arguments); } return fetchSellInfo; }() /** * fetch token information from EOS table. * @param {string} symbol * @param {number} nftId */ ; _proto.fetchTokenInfo = /*#__PURE__*/ function () { var _fetchTokenInfo = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee24(symbol, nftId) { var query, response, rows, row; return regeneratorRuntime.wrap(function _callee24$(_context24) { while (1) { switch (_context24.prev = _context24.next) { case 0: query = { "code": this.contractName, "scope": symbol, "table": "token", "lower_bound": nftId, "upper_bound": nftId, "limit": 1 }; _context24.next = 3; return this.fetchTable(query); case 3: response = _context24.sent; rows = response.rows; if (rows.length) { _context24.next = 7; break; } throw new ReferenceError("token info is not found."); case 7: row = rows[0]; return _context24.abrupt("return", row); case 9: case "end": return _context24.stop(); } } }, _callee24, this); })); function fetchTokenInfo(_x54, _x55) { return _fetchTokenInfo.apply(this, arguments); } return fetchTokenInfo; }() // encode name type into raw by big endian ; _proto.encodeName = function encodeName(name) { return this.eosJS.modules.format.encodeName(name, false); } /** * fetch the token's maximum ID plus one * @param {string} symbol * @returns {number} available token id */ ; _proto.fetchAvailableTokenId = /*#__PURE__*/ function () { var _fetchAvailableTokenId = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee25(symbol) { var query, response, last_token_id; return regeneratorRuntime.wrap(function _callee25$(_context25) { while (1) { switch (_context25.prev = _context25.next) { case 0: query = { "code": this.contractName, "scope": symbol, "table": "token", "limit": 1, "reverse": true }; _context25.next = 3; return this.fetchTable(query); case 3: response = _context25.sent; console.log("response: ", response); if (!(response.rows.length > 0)) { _context25.next = 10; break; } last_token_id = new _bigi.default(String(response.rows[0].id)); return _context25.abrupt("return", last_token_id.add(new _bigi.default("1")).toString()); case 10: return _context25.abrupt("return", "0"); case 11: case "end": return _context25.stop(); } } }, _callee25, this); })); function fetchAvailableTokenId(_x56) { return _fetchAvailableTokenId.apply(this, arguments); } return fetchAvailableTokenId; }(); return PcsClient; }(_scatterx.ScatterEOSX); exports.default = PcsClient; ; // get timestamp for action data function getTimestamp() { var duration = 15 * 1000; var now = Number(new Date()); var timestamp = Math.floor(now / duration) * duration; var timestamp_bn = new _bigi.default(timestamp.toString()); var timstamp_micro = timestamp_bn.multiply(new _bigi.default("1000")); console.log("timestamp:", timstamp_micro.toString()); return timstamp_micro; } // convert publicKey to a format suitable for use as an action argument function publicKeyToBuffer(public_key) { var pk_prefix = "EOS"; var pk_body = public_key.slice(pk_prefix.length); var raw_pk = _bs.default.decode(pk_body); return Buffer([0].concat(Array.from(raw_pk).slice(0, -4).map(function (v) { return +v; }))); } // convert uint64 value to a format suitable for use as an action argument function uint64ToBuffer(num) { var bn = _bigi.default.isBigInteger(num) ? num : new _bigi.default(num); var two = new _bigi.default("2"); var a_byte = two.pow(8); var bytearray = Array.from({ length: 8 }, function (v, i) { return Number(bn.divide(two.pow(8 * i)).remainder(a_byte)); }); console.log("bytearray:", bytearray); return Buffer(bytearray); } // convert symbol_code value to a format suitable for use as an action argument function getSymbolCodeRaw(symbol_code) { if (typeof symbol_code !== "string") { throw new Error("the first argument should be string type"); } if (symbol_code.length > 7) { throw new Error("string is too long to be a valid symbol_code"); } var raw = new _bigi.default("0"); var a_byte = new _bigi.default("256"); for (var i = symbol_code.length - 1; i >= 0; i--) { var c = symbol_code[i]; if (c < 'A' || 'Z' < c) { throw new Error("only uppercase letters allowed in symbol_code string"); } raw = raw.multiply(a_byte); raw = raw.add(new _bigi.default(c.charCodeAt().toString())); } return raw; } /// convert into big integer function toBI(num) { if (num instanceof Buffer) { return new _bigi.default(Array.from(num).reverse()); } else if (num instanceof Array) { return new _bigi.default(num); } else if (typeof num === "string") { num.split("").forEach(function (c) { if ((c < "0" || "9" < c) && c !== "-") { throw new Error("only '0123456789-' must be included in BigInteger," + " but given argument is", num); } }); num = new _bigi.default(num); } else if (Number.isSafeInteger(num)) { num = new _bigi.default(String(num)); } else if (num == null) { num = new _bigi.default("0"); } else if (!_bigi.default.isBigInteger(num)) { throw new Error("'num' cannot convert into BigInteger"); } return num; } /// convert into safe integer for js function toSI(num) { if (num == null) { num = 0; } if (num instanceof Buffer) { num = Array.from(num).reverse(); } if (num instanceof Array) { num = new _bigi.default(num); } if (_bigi.default.isBigInteger(num)) { num = num.toString(); } if (typeof num === "string") { num = parseInt(num); } if (!Number.isSafeInteger(num)) { throw new Error("'num' cannot convert into safe integer"); } return num; } function unsignedIntToBuffer(num) { var bytearray = []; var mask = new _bigi.default("1111111", 2); var carry = new _bigi.default("10000000", 2); var value = toBI(num); var v = value.and(mask); value = value.shiftRight(7); while (value.signum() !== 0) { bytearray.push(toSI(carry.add(v))); v = value.and(mask); value = value.shiftRight(7); } bytearray.push