@stellar-broker/client 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"stellarbroker.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,EAAQG,QAAQ,yBACR,mBAAXC,QAAyBA,OAAOC,IAC9CD,OAAO,CAAC,wBAAyBJ,GACP,iBAAZC,QACdA,QAAuB,cAAID,EAAQG,QAAQ,yBAE3CJ,EAAoB,cAAIC,EAAQD,EAAK,wBACtC,CATD,CASGO,MAAOC,G,kCCTVL,EAAOD,QAAUM,C,GCCbC,EAA2B,CAAC,E,YAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAaV,QAGrB,IAAIC,EAASM,EAAyBE,GAAY,CAGjDT,QAAS,CAAC,GAOX,OAHAY,EAAoBH,GAAUR,EAAQA,EAAOD,QAASQ,GAG/CP,EAAOD,OACf,C,MCtBwCa,MCyUZ,IAAIC,IAAI,CAAC,QAAS,SAAU,WAAY,WAAY,U","sources":["webpack://stellarbroker/webpack/universalModuleDefinition","webpack://stellarbroker/external umd \"@stellar/stellar-sdk\"","webpack://stellarbroker/webpack/bootstrap","webpack://stellarbroker/./src/errors.js","webpack://stellarbroker/./src/client.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"@stellar/stellar-sdk\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"@stellar/stellar-sdk\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"stellarbroker\"] = factory(require(\"@stellar/stellar-sdk\"));\n\telse\n\t\troot[\"stellarbroker\"] = factory(root[\"@stellar/stellar-sdk\"]);\n})(this, (__WEBPACK_EXTERNAL_MODULE__346__) => {\nreturn ","module.exports = __WEBPACK_EXTERNAL_MODULE__346__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","export class StellarBrokerError extends Error {\n constructor(code, message) {\n super(message)\n this.code = code\n }\n\n /**\n * Numeric error code\n * @type {number}\n * @readonly\n */\n code = 0\n}\n\nconst errors = {\n invalidInitParam(param) {\n return new StellarBrokerError(1, `Invalid parameter value: \"${param}\"`)\n },\n invalidAuthorizationParam() {\n return new StellarBrokerError(2, 'Invalid authorization secret key or callback provided')\n },\n notConnected() {\n return new StellarBrokerError(3, 'Client not connected to the server')\n },\n quoteNotSet() {\n return new StellarBrokerError(11, 'Price quote not available')\n },\n quoteExpired() {\n return new StellarBrokerError(12, 'Price quote expired')\n },\n quoteError(message) {\n return new StellarBrokerError(13, 'Price quotation error: ' + message)\n },\n invalidQuoteParam(invalidParamName = 'asset', details) {\n return new StellarBrokerError(14, `Invalid quote request parameter: \"${invalidParamName}\". ${details}`)\n },\n tradeInProgress() {\n return new StellarBrokerError(20, 'Cannot change quote while trade is in progress')\n },\n invalidSwapTx() {\n return new StellarBrokerError(21, 'Invalid swap transaction received from the server')\n },\n failedToSignTx() {\n return new StellarBrokerError(22, 'Failed to sign received transaction')\n },\n unsupportedEventType(type) {\n return new StellarBrokerError(31, 'Unknown event type: ' + type)\n },\n\n\n serverError(message) {\n return new StellarBrokerError(101, message)\n }\n}\n\nexport default errors","import {Networks, StrKey} from '@stellar/stellar-sdk'\nimport errors from './errors.js'\nimport {buildEvent} from './events.js'\nimport {processTxRequest} from './tx-processor.js'\nimport {validateQuoteRequest} from './quote-request.js'\nimport {QuoteResult} from './quote-result.js'\nimport {AuthorizationWrapper} from './authorization.js'\n\n/**\n * Client for StellarBroker service\n */\nexport class StellarBrokerClient {\n /**\n * @param {ClientInitializationParams} params\n */\n constructor(params) {\n this.partnerKey = params.partnerKey\n this.emitter = new EventTarget()\n this.network = Networks.PUBLIC\n this.trader = params.account\n this.authorization = new AuthorizationWrapper(params.authorization)\n }\n\n /**\n * @type {string}\n * @private\n */\n uid\n /**\n * @type {ClientSessionStatus}\n * @readonly\n */\n status = 'disconnected'\n /**\n * @type {WebSocket}\n * @private\n */\n socket\n /**\n * @type {EventTarget}\n * @private\n */\n emitter\n /**\n * @type {string}\n * @private\n */\n origin = 'https://api.stellar.broker'\n /**\n * Stellar network passphrase\n * @type {string}\n * @readonly\n */\n network = ''\n /**\n * Last quote request submitted by the client\n * @type {QuoteParams}\n * @readonly\n */\n quoteRequest\n /**\n * Last quote received from the sever\n * @type {QuoteResult}\n * @readonly\n */\n lastQuote\n /**\n * Current quote accepted for the trading\n * @private\n */\n tradeQuote\n /**\n * API key of the partner\n * @type {string}\n * @readonly\n */\n partnerKey\n /**\n * Account secret key or authorization callback\n * @type {AuthorizationWrapper}\n * @private\n */\n authorization\n /**\n * Trader account public key\n * @type {string}\n * @readonly\n */\n trader\n\n /**\n * Connect to the StellarBroker server\n * @return {Promise<StellarBrokerClient>}\n */\n connect() {\n if (this.socket?.readyState === WebSocket.OPEN)\n return Promise.resolve(this) //already opened\n this.socket = new WebSocket(this.origin + '/ws?partner=' + encodeURIComponent(this.partnerKey))\n this.socket.onmessage = this.processMessage.bind(this)\n this.socket.onclose = () => {\n if (this.status !== 'disconnected') {\n this.status = 'disconnected'\n this.notifyError(errors.notConnected())\n }\n console.log('Connection closed')\n }\n\n this.socket.onerror = e => console.error(e)\n\n return new Promise((confirm, reject) => { //TODO: use 'once'\n const expirationTimeout = setTimeout(() => reject(this), 2000) // 2s timeout\n this.onSocketOpen = () => {\n this.status = 'ready'\n this.heartbeat()\n this.onSocketOpen = undefined\n clearTimeout(expirationTimeout)\n confirm(this)\n }\n })\n }\n\n /**\n * Process incoming message\n * @param message\n * @private\n */\n processMessage(message) {\n const raw = JSON.parse(message.data)\n switch (raw.type) {\n case 'connected':\n this.uid = raw.uid\n if (this.onSocketOpen) {\n this.onSocketOpen()\n }\n if (this.status === 'disconnected') {\n this.status = 'ready'\n }\n break\n case 'quote':\n this.lastQuote = new QuoteResult(raw.quote)\n //send event to the client app\n this.emitter.dispatchEvent(buildEvent('quote', this.lastQuote))\n break\n case 'paused':\n //quotation paused due to inactivity\n this.emitter.dispatchEvent(buildEvent('paused', {}))\n break\n case 'tx':\n if (this.status !== 'trade') {\n console.log('Received tx in a non-trading state', this.status, raw)\n return //skip unless trading is in progress\n }\n processTxRequest(this, raw)\n .then(xdr => {\n this.send({\n type: 'tx',\n hash: raw.hash,\n xdr\n })\n })\n .catch(e => this.notifyError(e))\n break\n case 'stop':\n this.emitter.dispatchEvent(buildEvent('finished', {\n status: raw.status,\n sold: raw.sold,\n bought: raw.bought\n }, 'result'))\n this.status = 'ready'\n this.tradeQuote = undefined\n break\n case 'progress':\n this.emitter.dispatchEvent(buildEvent('progress', {\n sold: raw.sold,\n bought: raw.bought\n }, 'status'))\n break\n case 'ping':\n if (raw.uid === this.uid) {\n this.heartbeat()\n this.send({type: 'pong', uid: this.uid})\n }\n break\n case 'error':\n this.stop()\n this.notifyError(raw.error)\n break\n default:\n console.log('Unknown message type: ' + raw.type)\n break\n }\n }\n\n /**\n * Request swap quote\n * @param {QuoteParams} params - Quote parameters\n */\n quote(params) {\n if (this.status === 'trade')\n throw errors.tradeInProgress()\n this.quoteRequest = validateQuoteRequest(params)\n\n this.status = 'quote'\n this.connect()\n .then(() => {\n this.status = 'quote'\n this.send({\n type: 'quote',\n ...this.quoteRequest\n })\n })\n }\n\n /**\n * Confirm current quote and start trading\n * @param {string} [account] - Trader account address (overrides value provided in the constructor)\n */\n confirmQuote(account) {\n if (this.status === 'disconnected')\n throw errors.notConnected()\n if (this.status === 'trade')\n throw errors.tradeInProgress()\n if (this.status !== 'quote' || !this.lastQuote)\n throw errors.quoteNotSet()\n if ((new Date() - this.lastQuote.ts) > 10_000) //do not allow stale quotes quoted more than 10s ago\n throw errors.quoteExpired()\n if (this.lastQuote.status !== 'success')\n throw errors.quoteError(this.lastQuote.error || 'quote not available')\n if (account) {\n this.trader = account\n }\n //ensure that a trader account address provided\n const {trader} = this\n if (!trader || !StrKey.isValidEd25519PublicKey(trader))\n throw errors.invalidQuoteParam('account', 'Invalid trader account address: ' + (!trader ? 'missing' : trader))\n this.tradeQuote = this.lastQuote\n this.send({\n type: 'trade',\n account: trader\n })\n this.status = 'trade'\n }\n\n /**\n * Stop quotation/trading\n */\n stop() {\n if (this.status !== 'trade' && this.status !== 'quote')\n return\n this.send({type: 'stop'})\n this.tradeQuote = undefined\n this.status = 'ready'\n }\n\n /**\n * @param {{}} data\n * @private\n */\n send(data) {\n this.socket.send(JSON.stringify(data))\n }\n\n /**\n * @private\n */\n heartbeat() {\n clearTimeout(this.pingHandler)\n this.pingHandler = setTimeout(() => {\n console.warn('Lost connection with the server')\n this.socket.close()\n }, 7_000) // 7 seconds heartbeat timeout\n }\n\n /**\n * Add event listener\n * @param {StellarBrokerClientEvent} type\n * @param {function} callback\n */\n on(type, callback) {\n validateEventType(type)\n this.emitter.addEventListener(type, callback)\n }\n\n /**\n * Add event listener that will be executed once\n * @param {StellarBrokerClientEvent} type\n * @param {function} callback\n */\n once(type, callback) {\n validateEventType(type)\n this.emitter.addEventListener(type, callback, {once: true})\n }\n\n /**\n * Remove event listener\n * @param {StellarBrokerClientEvent} type\n * @param {function} callback\n */\n off(type, callback) {\n validateEventType(type)\n this.emitter.removeEventListener(type, callback)\n }\n\n /**\n * Close underlying connection and finalize the client\n */\n close() {\n try {\n //TODO: remove all attached event listeners\n this.status = 'disconnected'\n this.socket.close()\n } catch (e) {\n }\n }\n\n /**\n * @param {Error} e\n * @private\n */\n notifyError(e) {\n console.error(e)\n try {\n this.emitter.dispatchEvent(buildEvent('error', e instanceof Error ? e.message : e))\n } catch (e) {\n console.error(e)\n }\n }\n}\n\nconst stellarBrokerEvents = new Set(['quote', 'paused', 'progress', 'finished', 'error'])\n\nfunction validateEventType(type) {\n if (!stellarBrokerEvents.has(type))\n throw errors.unsupportedEventType(type)\n}\n\n/**\n * @typedef {object} ClientInitializationParams\n * @property {ClientAuthorizationParams} authorization - Authorization method, either account secret key or an authorization callback\n * @property {string} [account] - Trader account address\n * @property {string} [partnerKey] - Partner key\n */\n\n/**\n * @typedef {'disconnected'|'ready'|'quote'|'trade'} ClientSessionStatus - Current client session status\n */\n\n/**\n * @typedef {'quote'|'paused'|'progress'|'finished'|'error'} StellarBrokerClientEvent - Event type generated by the client\n */\n"],"names":["root","factory","exports","module","require","define","amd","this","__WEBPACK_EXTERNAL_MODULE__346__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","Error","Set"],"sourceRoot":""}
1
+ {"version":3,"file":"stellarbroker.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,EAAQG,QAAQ,yBACR,mBAAXC,QAAyBA,OAAOC,IAC9CD,OAAO,CAAC,wBAAyBJ,GACP,iBAAZC,QACdA,QAAuB,cAAID,EAAQG,QAAQ,yBAE3CJ,EAAoB,cAAIC,EAAQD,EAAK,wBACtC,CATD,CASGO,MAAOC,G,kCCTVL,EAAOD,QAAUM,C,GCCbC,EAA2B,CAAC,E,YAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAaV,QAGrB,IAAIC,EAASM,EAAyBE,GAAY,CAGjDT,QAAS,CAAC,GAOX,OAHAY,EAAoBH,GAAUR,EAAQA,EAAOD,QAASQ,GAG/CP,EAAOD,OACf,C,MCtBwCa,MCgVZ,IAAIC,IAAI,CAAC,QAAS,SAAU,WAAY,WAAY,U","sources":["webpack://stellarbroker/webpack/universalModuleDefinition","webpack://stellarbroker/external umd \"@stellar/stellar-sdk\"","webpack://stellarbroker/webpack/bootstrap","webpack://stellarbroker/./src/errors.js","webpack://stellarbroker/./src/client.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"@stellar/stellar-sdk\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"@stellar/stellar-sdk\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"stellarbroker\"] = factory(require(\"@stellar/stellar-sdk\"));\n\telse\n\t\troot[\"stellarbroker\"] = factory(root[\"@stellar/stellar-sdk\"]);\n})(this, (__WEBPACK_EXTERNAL_MODULE__346__) => {\nreturn ","module.exports = __WEBPACK_EXTERNAL_MODULE__346__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","export class StellarBrokerError extends Error {\n constructor(code, message) {\n super(message)\n this.code = code\n }\n\n /**\n * Numeric error code\n * @type {number}\n * @readonly\n */\n code = 0\n}\n\nconst errors = {\n invalidInitParam(param) {\n return new StellarBrokerError(1, `Invalid parameter value: \"${param}\"`)\n },\n invalidAuthorizationParam() {\n return new StellarBrokerError(2, 'Invalid authorization secret key or callback provided')\n },\n notConnected() {\n return new StellarBrokerError(3, 'Client not connected to the server')\n },\n quoteNotSet() {\n return new StellarBrokerError(11, 'Price quote not available')\n },\n quoteExpired() {\n return new StellarBrokerError(12, 'Price quote expired')\n },\n quoteError(message) {\n return new StellarBrokerError(13, 'Price quotation error: ' + message)\n },\n invalidQuoteParam(invalidParamName = 'asset', details) {\n return new StellarBrokerError(14, `Invalid quote request parameter: \"${invalidParamName}\". ${details}`)\n },\n tradeInProgress() {\n return new StellarBrokerError(20, 'Cannot change quote while trade is in progress')\n },\n invalidSwapTx() {\n return new StellarBrokerError(21, 'Invalid swap transaction received from the server')\n },\n failedToSignTx() {\n return new StellarBrokerError(22, 'Failed to sign received transaction')\n },\n unsupportedEventType(type) {\n return new StellarBrokerError(31, 'Unknown event type: ' + type)\n },\n\n\n serverError(message) {\n return new StellarBrokerError(101, message)\n }\n}\n\nexport default errors","import {Networks, StrKey} from '@stellar/stellar-sdk'\nimport errors from './errors.js'\nimport {buildEvent} from './events.js'\nimport {processTxRequest} from './tx-processor.js'\nimport {validateQuoteRequest} from './quote-request.js'\nimport {QuoteResult} from './quote-result.js'\nimport {AuthorizationWrapper} from './authorization.js'\n\n/**\n * Client for StellarBroker service\n */\nexport class StellarBrokerClient {\n /**\n * @param {ClientInitializationParams} params\n */\n constructor(params) {\n this.partnerKey = params.partnerKey\n this.emitter = new EventTarget()\n this.network = Networks.PUBLIC\n this.trader = params.account\n if (params.authorization) {\n this.authorization = new AuthorizationWrapper(params.authorization)\n }\n }\n\n /**\n * @type {string}\n * @private\n */\n uid\n /**\n * @type {ClientSessionStatus}\n * @readonly\n */\n status = 'disconnected'\n /**\n * @type {WebSocket}\n * @private\n */\n socket\n /**\n * @type {EventTarget}\n * @private\n */\n emitter\n /**\n * @type {string}\n * @private\n */\n origin = 'https://api.stellar.broker'\n /**\n * Stellar network passphrase\n * @type {string}\n * @readonly\n */\n network = ''\n /**\n * Last quote request submitted by the client\n * @type {QuoteParams}\n * @readonly\n */\n quoteRequest\n /**\n * Last quote received from the sever\n * @type {QuoteResult}\n * @readonly\n */\n lastQuote\n /**\n * Current quote accepted for the trading\n * @private\n */\n tradeQuote\n /**\n * API key of the partner\n * @type {string}\n * @readonly\n */\n partnerKey\n /**\n * Account secret key or authorization callback\n * @type {AuthorizationWrapper}\n * @private\n */\n authorization\n /**\n * Trader account public key\n * @type {string}\n * @readonly\n */\n trader\n\n /**\n * Connect to the StellarBroker server\n * @return {Promise<StellarBrokerClient>}\n */\n connect() {\n if (this.socket?.readyState === WebSocket.OPEN)\n return Promise.resolve(this) //already opened\n this.socket = new WebSocket(this.origin + '/ws?partner=' + encodeURIComponent(this.partnerKey))\n this.socket.onmessage = this.processMessage.bind(this)\n this.socket.onclose = () => {\n if (this.status !== 'disconnected') {\n this.status = 'disconnected'\n this.notifyError(errors.notConnected())\n }\n console.log('Connection closed')\n }\n\n this.socket.onerror = e => console.error(e)\n\n return new Promise((confirm, reject) => { //TODO: use 'once'\n const expirationTimeout = setTimeout(() => reject(this), 2000) // 2s timeout\n this.onSocketOpen = () => {\n this.status = 'ready'\n this.heartbeat()\n this.onSocketOpen = undefined\n clearTimeout(expirationTimeout)\n confirm(this)\n }\n })\n }\n\n /**\n * Process incoming message\n * @param message\n * @private\n */\n processMessage(message) {\n const raw = JSON.parse(message.data)\n switch (raw.type) {\n case 'connected':\n this.uid = raw.uid\n if (this.onSocketOpen) {\n this.onSocketOpen()\n }\n if (this.status === 'disconnected') {\n this.status = 'ready'\n }\n break\n case 'quote':\n this.lastQuote = new QuoteResult(raw.quote)\n //send event to the client app\n this.emitter.dispatchEvent(buildEvent('quote', this.lastQuote))\n break\n case 'paused':\n //quotation paused due to inactivity\n this.emitter.dispatchEvent(buildEvent('paused', {}))\n break\n case 'tx':\n if (this.status !== 'trade') {\n console.log('Received tx in a non-trading state', this.status, raw)\n return //skip unless trading is in progress\n }\n processTxRequest(this, raw)\n .then(xdr => {\n this.send({\n type: 'tx',\n hash: raw.hash,\n xdr\n })\n })\n .catch(e => this.notifyError(e))\n break\n case 'stop':\n this.emitter.dispatchEvent(buildEvent('finished', {\n status: raw.status,\n sold: raw.sold,\n bought: raw.bought\n }, 'result'))\n this.status = 'ready'\n this.tradeQuote = undefined\n break\n case 'progress':\n this.emitter.dispatchEvent(buildEvent('progress', {\n sold: raw.sold,\n bought: raw.bought\n }, 'status'))\n break\n case 'ping':\n if (raw.uid === this.uid) {\n this.heartbeat()\n this.send({type: 'pong', uid: this.uid})\n }\n break\n case 'error':\n this.stop()\n this.notifyError(raw.error)\n break\n default:\n console.log('Unknown message type: ' + raw.type)\n break\n }\n }\n\n /**\n * Request swap quote\n * @param {QuoteParams} params - Quote parameters\n */\n quote(params) {\n if (this.status === 'trade')\n throw errors.tradeInProgress()\n this.quoteRequest = validateQuoteRequest(params)\n\n this.status = 'quote'\n this.connect()\n .then(() => {\n this.status = 'quote'\n this.send({\n type: 'quote',\n ...this.quoteRequest\n })\n })\n }\n\n /**\n * Confirm current quote and start trading\n * @param {string} [account] - Trader account address (overrides value provided in the constructor)\n * @param {ClientAuthorizationParams} [authorization] - Authorization params (overrides value provided in the constructor)\n */\n confirmQuote(account, authorization) {\n if (this.status === 'disconnected')\n throw errors.notConnected()\n if (this.status === 'trade')\n throw errors.tradeInProgress()\n if (this.status !== 'quote' || !this.lastQuote)\n throw errors.quoteNotSet()\n if ((new Date() - this.lastQuote.ts) > 10_000) //do not allow stale quotes quoted more than 10s ago\n throw errors.quoteExpired()\n if (this.lastQuote.status !== 'success')\n throw errors.quoteError(this.lastQuote.error || 'quote not available')\n if (account) {\n this.trader = account\n }\n if (authorization) {\n this.authorization = new AuthorizationWrapper(authorization)\n }\n const {trader} = this\n if (!trader || !StrKey.isValidEd25519PublicKey(trader)) //ensure that a trader account address provided\n throw errors.invalidQuoteParam('account', 'Invalid trader account address: ' + (!trader ? 'missing' : trader))\n if (!this.authorization)\n throw errors.invalidQuoteParam('authorization', 'Client authorization not provided')\n this.tradeQuote = this.lastQuote\n this.send({\n type: 'trade',\n account: trader\n })\n this.status = 'trade'\n }\n\n /**\n * Stop quotation/trading\n */\n stop() {\n if (this.status !== 'trade' && this.status !== 'quote')\n return\n this.send({type: 'stop'})\n this.tradeQuote = undefined\n this.status = 'ready'\n }\n\n /**\n * @param {{}} data\n * @private\n */\n send(data) {\n this.socket.send(JSON.stringify(data))\n }\n\n /**\n * @private\n */\n heartbeat() {\n clearTimeout(this.pingHandler)\n this.pingHandler = setTimeout(() => {\n console.warn('Lost connection with the server')\n this.socket.close()\n }, 7_000) // 7 seconds heartbeat timeout\n }\n\n /**\n * Add event listener\n * @param {StellarBrokerClientEvent} type\n * @param {function} callback\n */\n on(type, callback) {\n validateEventType(type)\n this.emitter.addEventListener(type, callback)\n }\n\n /**\n * Add event listener that will be executed once\n * @param {StellarBrokerClientEvent} type\n * @param {function} callback\n */\n once(type, callback) {\n validateEventType(type)\n this.emitter.addEventListener(type, callback, {once: true})\n }\n\n /**\n * Remove event listener\n * @param {StellarBrokerClientEvent} type\n * @param {function} callback\n */\n off(type, callback) {\n validateEventType(type)\n this.emitter.removeEventListener(type, callback)\n }\n\n /**\n * Close underlying connection and finalize the client\n */\n close() {\n try {\n //TODO: remove all attached event listeners\n this.status = 'disconnected'\n this.socket.close()\n } catch (e) {\n }\n }\n\n /**\n * @param {Error} e\n * @private\n */\n notifyError(e) {\n console.error(e)\n try {\n this.emitter.dispatchEvent(buildEvent('error', e instanceof Error ? e.message : e))\n } catch (e) {\n console.error(e)\n }\n }\n}\n\nconst stellarBrokerEvents = new Set(['quote', 'paused', 'progress', 'finished', 'error'])\n\nfunction validateEventType(type) {\n if (!stellarBrokerEvents.has(type))\n throw errors.unsupportedEventType(type)\n}\n\n/**\n * @typedef {object} ClientInitializationParams\n * @property {string} [partnerKey] - Partner key\n * @property {string} [account] - Trader account address\n * @property {ClientAuthorizationParams} [authorization] - Authorization method, either account secret key or an authorization callback\n */\n\n/**\n * @typedef {'disconnected'|'ready'|'quote'|'trade'} ClientSessionStatus - Current client session status\n */\n\n/**\n * @typedef {'quote'|'paused'|'progress'|'finished'|'error'} StellarBrokerClientEvent - Event type generated by the client\n */\n"],"names":["root","factory","exports","module","require","define","amd","this","__WEBPACK_EXTERNAL_MODULE__346__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","Error","Set"],"sourceRoot":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stellar-broker/client",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "description": "Client library for StellarBroker service",
5
5
  "author": "team@stellar.broker",
6
6
  "homepage": "https://stellar.broker",
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "repository": {
17
17
  "type": "git",
18
- "url": "https://github.com/stellar-broker/client"
18
+ "url": "git+https://github.com/stellar-broker/client.git"
19
19
  },
20
20
  "peerDependencies": {
21
21
  "@stellar/stellar-sdk": ">=13"
package/src/client.js CHANGED
@@ -18,7 +18,9 @@ export class StellarBrokerClient {
18
18
  this.emitter = new EventTarget()
19
19
  this.network = Networks.PUBLIC
20
20
  this.trader = params.account
21
- this.authorization = new AuthorizationWrapper(params.authorization)
21
+ if (params.authorization) {
22
+ this.authorization = new AuthorizationWrapper(params.authorization)
23
+ }
22
24
  }
23
25
 
24
26
  /**
@@ -214,8 +216,9 @@ export class StellarBrokerClient {
214
216
  /**
215
217
  * Confirm current quote and start trading
216
218
  * @param {string} [account] - Trader account address (overrides value provided in the constructor)
219
+ * @param {ClientAuthorizationParams} [authorization] - Authorization params (overrides value provided in the constructor)
217
220
  */
218
- confirmQuote(account) {
221
+ confirmQuote(account, authorization) {
219
222
  if (this.status === 'disconnected')
220
223
  throw errors.notConnected()
221
224
  if (this.status === 'trade')
@@ -229,10 +232,14 @@ export class StellarBrokerClient {
229
232
  if (account) {
230
233
  this.trader = account
231
234
  }
232
- //ensure that a trader account address provided
235
+ if (authorization) {
236
+ this.authorization = new AuthorizationWrapper(authorization)
237
+ }
233
238
  const {trader} = this
234
- if (!trader || !StrKey.isValidEd25519PublicKey(trader))
239
+ if (!trader || !StrKey.isValidEd25519PublicKey(trader)) //ensure that a trader account address provided
235
240
  throw errors.invalidQuoteParam('account', 'Invalid trader account address: ' + (!trader ? 'missing' : trader))
241
+ if (!this.authorization)
242
+ throw errors.invalidQuoteParam('authorization', 'Client authorization not provided')
236
243
  this.tradeQuote = this.lastQuote
237
244
  this.send({
238
245
  type: 'trade',
@@ -336,9 +343,9 @@ function validateEventType(type) {
336
343
 
337
344
  /**
338
345
  * @typedef {object} ClientInitializationParams
339
- * @property {ClientAuthorizationParams} authorization - Authorization method, either account secret key or an authorization callback
340
- * @property {string} [account] - Trader account address
341
346
  * @property {string} [partnerKey] - Partner key
347
+ * @property {string} [account] - Trader account address
348
+ * @property {ClientAuthorizationParams} [authorization] - Authorization method, either account secret key or an authorization callback
342
349
  */
343
350
 
344
351
  /**
package/src/index.d.ts CHANGED
@@ -44,8 +44,9 @@ export class StellarBrokerClient {
44
44
  /**
45
45
  * Confirm current quote and start trading
46
46
  * @param {string} [account] - Trader account address (overrides value provided in the constructor)
47
+ * @param {ClientAuthorizationParams} [authorization] - Authorization params (overrides value provided in the constructor)
47
48
  */
48
- confirmQuote(account?: string): void;
49
+ confirmQuote(account?: string, authorization?: ClientAuthorizationParams): void;
49
50
 
50
51
  /**
51
52
  * Add event listener
@@ -103,17 +104,17 @@ export interface QuoteParams {
103
104
 
104
105
  export interface ClientInitializationParams {
105
106
  /**
106
- * Authorization method, either account secret key or an authorization callback
107
+ * Partner key
107
108
  */
108
- authorization: ClientAuthorizationParams;
109
+ partnerKey?: string;
109
110
  /**
110
111
  * Trader account address
111
112
  */
112
113
  account?: string;
113
114
  /**
114
- * Partner key
115
+ * Authorization method, either account secret key or an authorization callback
115
116
  */
116
- partnerKey?: string;
117
+ authorization?: ClientAuthorizationParams;
117
118
  }
118
119
 
119
120
  /**
package/src/mediator.js CHANGED
@@ -4,7 +4,7 @@ import {convertToStellarAsset} from './asset.js'
4
4
  import {AuthorizationWrapper} from './authorization.js'
5
5
 
6
6
  //additional XLM amount to cover tx fees
7
- const feesReserve = '2'
7
+ const feesReserve = '3'
8
8
 
9
9
  export class Mediator {
10
10
  /**
@@ -173,10 +173,12 @@ export class Mediator {
173
173
  }
174
174
  }))
175
175
  //create trustline for buying asset
176
- ops.push(Operation.changeTrust({
177
- source: this.mediatorAddress,
178
- asset: buyingAsset
179
- }))
176
+ if (!buyingAsset.isNative()) {
177
+ ops.push(Operation.changeTrust({
178
+ source: this.mediatorAddress,
179
+ asset: buyingAsset
180
+ }))
181
+ }
180
182
  //confirm tx
181
183
  await this.buildAndSend(sourceAccount, ops)
182
184
  //store the record in the localStorage