@stellar-broker/client 0.4.1 → 0.6.0
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.
- package/README.md +160 -109
- package/jest.config.cjs +4 -0
- package/lib/stellarbroker.js +1 -1
- package/lib/stellarbroker.js.map +1 -1
- package/package.json +10 -9
- package/src/asset.js +51 -47
- package/src/authorization.js +65 -0
- package/src/client.js +344 -369
- package/src/errors.js +55 -53
- package/src/estimate.js +4 -3
- package/src/index.d.ts +146 -40
- package/src/index.js +5 -4
- package/src/mediator.js +309 -0
- package/src/quote-request.js +56 -60
- package/src/quote-result.js +93 -0
- package/src/tx-processor.js +133 -161
package/README.md
CHANGED
|
@@ -1,110 +1,161 @@
|
|
|
1
|
-
# @stellar-broker/client
|
|
2
|
-
|
|
3
|
-
## Installation
|
|
4
|
-
|
|
5
|
-
```
|
|
6
|
-
npm i @stellar-broker/client
|
|
7
|
-
```
|
|
8
|
-
|
|
9
|
-
## Usage
|
|
10
|
-
|
|
11
|
-
###
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
price quote updates
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
"
|
|
51
|
-
"
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
"
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
.
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
//
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
1
|
+
# @stellar-broker/client
|
|
2
|
+
|
|
3
|
+
## Installation
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
npm i @stellar-broker/client
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Usage
|
|
10
|
+
|
|
11
|
+
### Interactive Sessions
|
|
12
|
+
|
|
13
|
+
Using an interactive session is the preferred way for the majority of integrations.
|
|
14
|
+
A client connects to the router server and maintains the connection open, receiving price quote updates and other
|
|
15
|
+
notifications from the server without delays. Trading, retries, and results confirmations get processed in the
|
|
16
|
+
background.
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
import {StellarBrokerClient} from '@stellar-broker/client'
|
|
20
|
+
|
|
21
|
+
//create client instance
|
|
22
|
+
const client = new StellarBrokerClient({partnerKey: '<your_partner_key>'})
|
|
23
|
+
|
|
24
|
+
//subscribe to the quote notifications
|
|
25
|
+
client.on('quote', e => {
|
|
26
|
+
console.log('Received route quote from the server', e.quote)
|
|
27
|
+
/*{
|
|
28
|
+
"status": "success",
|
|
29
|
+
"sellingAsset": "USDC-GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN",
|
|
30
|
+
"buyingAsset": "XLM",
|
|
31
|
+
"slippageTolerance": 0.5,
|
|
32
|
+
"directTrade": {
|
|
33
|
+
"selling": "10",
|
|
34
|
+
"buying": "100.23505",
|
|
35
|
+
"path": []
|
|
36
|
+
},
|
|
37
|
+
"sellingAmount": "10",
|
|
38
|
+
"estimatedBuyingAmount": "100.688121",
|
|
39
|
+
"ts": "2024-08-13T23:13:21.275Z"
|
|
40
|
+
}*/
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
client.on('paused', e => {
|
|
44
|
+
console.log('Quotation paused due to inactivity. Call `quote` method to resume.')
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
client.on('finished', e => {
|
|
48
|
+
console.log('Trade finished', e.result)
|
|
49
|
+
/*{
|
|
50
|
+
"status": "success",
|
|
51
|
+
"sold": "10",
|
|
52
|
+
"bought": "100.6704597"
|
|
53
|
+
}*/
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
client.on('progress', e => {
|
|
57
|
+
console.log('Progress', e.status)
|
|
58
|
+
/*{
|
|
59
|
+
"sold": "10",
|
|
60
|
+
"bought": "100.6704597"
|
|
61
|
+
}*/
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
client.on('error', e => {
|
|
65
|
+
console.warn('StellarBroker error', e.error)
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
//connect
|
|
69
|
+
client.connect() //only once
|
|
70
|
+
.then(() => console.log('StellarBroker connected'))
|
|
71
|
+
.catch(e => console.error(e))
|
|
72
|
+
|
|
73
|
+
//request a price quote
|
|
74
|
+
client.quote({
|
|
75
|
+
sellingAsset: 'xlm',
|
|
76
|
+
buyingAsset: 'USD-GDK2GNB4Q6FKNW2GNJIQFARI4RMSHV5DN5G4BBXX2F24RT5I4QT7TWZ7',
|
|
77
|
+
sellingAmount: '1000', //1000.0000000 XLM
|
|
78
|
+
slippageTolerance: 0.02 //2%
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
//once the quote received from the server, we can confirm the quote
|
|
82
|
+
async function signTx(payload) { //async signing callback - implement custom logic here
|
|
83
|
+
const kp = Keypair.fromSecret('<account_secret>')
|
|
84
|
+
if (payload.sign) { //sign transaction
|
|
85
|
+
payload.sign(kp)
|
|
86
|
+
return payload
|
|
87
|
+
}
|
|
88
|
+
//it's authorization payload
|
|
89
|
+
return kp.sign(payload)
|
|
90
|
+
}
|
|
91
|
+
client.confirmQuote('<account_address>', signTx) //provide trader account address
|
|
92
|
+
|
|
93
|
+
//trade can be interrupted from the client by calling
|
|
94
|
+
client.stop()
|
|
95
|
+
|
|
96
|
+
//cleanup resources and close connection once the trading has been finished
|
|
97
|
+
client.close()
|
|
98
|
+
//do not forget to call .off() for every attached event listener to avoid memory leaks
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Swap Estimate
|
|
102
|
+
|
|
103
|
+
Swap estimates may be handy in scenarios when a client has no intention to trade or receive price quote updates,
|
|
104
|
+
and just wants to get a single price quote instead.
|
|
105
|
+
|
|
106
|
+
```js
|
|
107
|
+
import {estimateSwap} from '@stellar-broker/client'
|
|
108
|
+
|
|
109
|
+
estimateSwap({
|
|
110
|
+
sellingAsset: 'xlm',
|
|
111
|
+
buyingAsset: 'USD-GDK2GNB4Q6FKNW2GNJIQFARI4RMSHV5DN5G4BBXX2F24RT5I4QT7TWZ7',
|
|
112
|
+
sellingAmount: '1000',
|
|
113
|
+
slippageTolerance: 0.02 //2%
|
|
114
|
+
})
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Delegated Signing and Multisig
|
|
118
|
+
|
|
119
|
+
StellarBroker trading sessions rely on fast transactions signing in order to immediately react on market changes.
|
|
120
|
+
In scenarios when a client app cannot sign transactions directly or requires multisig aggregation, it's still possible
|
|
121
|
+
to utilize StellarBroker using a mediator account.
|
|
122
|
+
|
|
123
|
+
Mediator flow implies creation of a temporary auxiliary account that will hold tokens until the swap process is executed
|
|
124
|
+
in full, then transfers all funds back to the source account and gets merged into it, releasing temporary blocked XLM
|
|
125
|
+
funds.
|
|
126
|
+
|
|
127
|
+
This package contains a reference implementation of such mediator account, but it's up to developers whether to use it
|
|
128
|
+
directly or create alternative logic based on it.
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
```js
|
|
132
|
+
import {Mediator} from '@stellar-broker/client'
|
|
133
|
+
|
|
134
|
+
const sellingAsset = 'XLM'
|
|
135
|
+
const buyingAsset = 'AQUA-GBNZILSTVQZ4R7IKQDGHYGY2QXL5QOFJYQMXPKWRRM5PAV7Y4M67AQUA'
|
|
136
|
+
const sellingAmount = '10'
|
|
137
|
+
|
|
138
|
+
//once the quote received from the server, we can confirm the quote
|
|
139
|
+
async function signTx(tx) { //async signing callback - implement custom logic here
|
|
140
|
+
const kp = Keypair.fromSecret('<account_secret>')
|
|
141
|
+
tx.sign(kp)
|
|
142
|
+
return tx
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
//fabric for meditor account creation
|
|
146
|
+
const mediator = new Mediator(source, sellingAsset, buyingAsset, sellingAmount, signTx)
|
|
147
|
+
|
|
148
|
+
//create new mediator account
|
|
149
|
+
const mediatorSecret = await mediator.init()
|
|
150
|
+
console.log('Created mediator account ' + Keypair.fromSecret(mediatorSecret).publicKey())
|
|
151
|
+
|
|
152
|
+
//use it for trading, and dispose once finished -- all funds and XLM reserves will be returned to the source account
|
|
153
|
+
await mediator.dispose()
|
|
154
|
+
console.log('Mediator account disposed')
|
|
155
|
+
|
|
156
|
+
//if the user left the session in the process or there were connection problems,
|
|
157
|
+
//funds from previously created mediator accounts can be recovered like this
|
|
158
|
+
if (mediator.hasObsoleteMediators) {
|
|
159
|
+
await mediator.disposeObsoleteMediators()
|
|
160
|
+
}
|
|
110
161
|
```
|
package/jest.config.cjs
ADDED
package/lib/stellarbroker.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(
|
|
1
|
+
!function(e,r){"object"==typeof exports&&"object"==typeof module?module.exports=r(require("@stellar/stellar-sdk")):"function"==typeof define&&define.amd?define(["@stellar/stellar-sdk"],r):"object"==typeof exports?exports.stellarbroker=r(require("@stellar/stellar-sdk")):e.stellarbroker=r(e["@stellar/stellar-sdk"])}(this,(e=>(()=>{"use strict";var r={346:r=>{r.exports=e}},t={},s={};return function e(s){var o=t[s];if(void 0!==o)return o.exports;var l=t[s]={exports:{}};return r[s](l,l.exports,e),l.exports}(346),Error,new Set(["quote","paused","progress","finished","error"]),s.default})()));
|
|
2
2
|
//# sourceMappingURL=stellarbroker.js.map
|
package/lib/stellarbroker.js.map
CHANGED
|
@@ -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,EAGhC,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,CCrBAQ,EAAoBK,EAAI,CAACb,EAASc,KACjC,IAAI,IAAIC,KAAOD,EACXN,EAAoBQ,EAAEF,EAAYC,KAASP,EAAoBQ,EAAEhB,EAASe,IAC5EE,OAAOC,eAAelB,EAASe,EAAK,CAAE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oG,aCKb3H,eAA4BzB,GAC/B,MAAMqJ,EAAQvM,OAAOwM,QAAQvJ,EAAqBC,IAC7CuJ,QAAOC,QAAgBhN,IAAVgN,EAAG,KAChBC,KAAI,EAAE3L,EAAOyJ,KAAWpD,mBAAmBrG,GAAS,IAAMqG,mBAAmBoD,KAC5EmC,GAAO1J,EAAO2D,QAAU,8BAAgC,UAAY0F,EAAMM,KAAK,KACrF,IACI,MAAM9I,QAAY+I,MAAMF,GAAKpH,MAAKuH,GAAKA,EAAEC,SACzC,GAAmB,YAAfjJ,EAAI4C,OACJ,MAAM/D,EAAOvB,WAAW0C,EAAIiC,OAAS,uBACzC,OAAOjC,CACX,CAAE,MAAOuB,GACL,GAAIA,aAAa7E,EACb,MAAM6E,EACV,MAAM1C,EAAOvB,WAAW,wBAE5B,CACJ,EDnBA,U","sources":["webpack://stellarbroker/webpack/universalModuleDefinition","webpack://stellarbroker/external umd \"@stellar/stellar-sdk\"","webpack://stellarbroker/webpack/bootstrap","webpack://stellarbroker/webpack/runtime/define property getters","webpack://stellarbroker/webpack/runtime/hasOwnProperty shorthand","webpack://stellarbroker/./src/errors.js","webpack://stellarbroker/./src/events.js","webpack://stellarbroker/./src/asset.js","webpack://stellarbroker/./src/quote-request.js","webpack://stellarbroker/./src/tx-processor.js","webpack://stellarbroker/./src/client.js","webpack://stellarbroker/./src/cjs.js","webpack://stellarbroker/./src/estimate.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","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","export class StellarBrokerError extends Error {\r\n constructor(code, message) {\r\n super(message)\r\n this.code = code\r\n }\r\n\r\n /**\r\n * Numeric error code\r\n * @type {number}\r\n * @readonly\r\n */\r\n code = 0\r\n}\r\n\r\nconst errors = {\r\n invalidInitParam(param) {\r\n return new StellarBrokerError(1, `Invalid parameter value: \"${param}\"`)\r\n },\r\n invalidAuthorizationParam() {\r\n return new StellarBrokerError(2, 'Invalid authorization secret key or callback provided')\r\n },\r\n notConnected() {\r\n return new StellarBrokerError(3, 'Client not connected to the server')\r\n },\r\n quoteNotSet() {\r\n return new StellarBrokerError(11, 'Price quote not available')\r\n },\r\n quoteExpired() {\r\n return new StellarBrokerError(12, 'Price quote expired')\r\n },\r\n quoteError(message) {\r\n return new StellarBrokerError(13, 'Price quotation error: ' + message)\r\n },\r\n invalidQuoteParam(invalidParamName = 'asset', details) {\r\n return new StellarBrokerError(14, `Invalid quote request parameter: \"${invalidParamName}\". ${details}`)\r\n },\r\n tradeInProgress() {\r\n return new StellarBrokerError(20, 'Cannot change quote while trade is in progress')\r\n },\r\n invalidSwapTx() {\r\n return new StellarBrokerError(21, 'Invalid swap transaction received from the server')\r\n },\r\n failedToSignTx() {\r\n return new StellarBrokerError(22, 'Failed to sign received transaction')\r\n },\r\n unsupportedEventType(type) {\r\n return new StellarBrokerError(31, 'Unknown event type: ' + type)\r\n },\r\n serverError(message) {\r\n return new StellarBrokerError(101, message)\r\n }\r\n}\r\n\r\nexport default errors","/**\r\n * @param {string} type\r\n * @param {{}} data\r\n * @param {string} [key]\r\n * @return {CustomEvent}\r\n */\r\nexport function buildEvent(type, data, key) {\r\n const evt = new CustomEvent(type, {detail: data})\r\n evt[key || type] = data\r\n return evt\r\n}","import {Asset, StrKey} from '@stellar/stellar-sdk'\r\nimport errors from './errors.js'\r\n\r\n/**\r\n * @param {string} asset\r\n * @return {Asset}\r\n */\r\nexport function convertToStellarAsset(asset) {\r\n if (asset === 'xlm' || asset === 'XLM')\r\n return Asset.native()\r\n const [code, issuer] = asset.includes('-') ?\r\n asset.split('-') :\r\n asset.split(':')\r\n return new Asset(code, issuer)\r\n}\r\n\r\nexport function parseAsset(asset, parameter) {\r\n if (typeof asset === 'string') {\r\n if (asset === 'XLM' || asset === 'xlm' || asset === 'native')\r\n return 'XLM'\r\n if (asset.includes(':')) {\r\n const [code, issuer] = asset.split(':')\r\n validateCode(code)\r\n validateAccount(issuer, parameter)\r\n return code + '-' + issuer\r\n }\r\n if (asset.includes('-')) {\r\n const [code, issuer] = asset.split('-')\r\n validateCode(code)\r\n validateAccount(issuer, parameter)\r\n return asset\r\n }\r\n }\r\n throw errors.invalidQuoteParam(parameter, 'Invalid asset')\r\n}\r\n\r\nfunction validateCode(code, parameter) {\r\n if (!/^[a-zA-Z0-9]{1,12}$/.test(code))\r\n throw errors.invalidQuoteParam(parameter, 'Invalid asset code: ' + (!code ? 'missing' : code))\r\n return code\r\n}\r\n\r\nfunction validateAccount(account, param) {\r\n if (!account || !StrKey.isValidEd25519PublicKey(account))\r\n throw errors.invalidQuoteParam(param, 'Invalid account address: ' + (!account ? 'missing' : account))\r\n return account\r\n}\r\n","import {StrKey} from '@stellar/stellar-sdk'\r\nimport errors from './errors.js'\r\nimport {parseAsset} from './asset.js'\r\n\r\n/**\r\n * @typedef {object} SwapQuoteParams\r\n * @property {string} sellingAsset - Asset to sell\r\n * @property {string} buyingAsset - Asset to buy\r\n * @property {string} [sellingAmount] - Amount of selling asset\r\n * @property {string} [buyingAmount] - Amount of buying asset\r\n * @property {number} [slippageTolerance] - Swap slippage tolerance (0.02 by default - 2%)\r\n * @property {string} [destination] - Trader account address\r\n */\r\n\r\n/**\r\n * @param {SwapQuoteParams} params\r\n * @return {SwapQuoteParams}\r\n */\r\nexport function validateQuoteRequest(params) {\r\n const {\r\n destination, sellingAsset, selling_asset, buyingAsset, buying_asset, sellingAmount, selling_amount,\r\n buyingAmount, buying_amount, slippageTolerance, slippage_tolerance, ...other\r\n } = params\r\n const res = {\r\n sellingAsset: parseAsset(sellingAsset || selling_asset, 'sellingAsset'),\r\n buyingAsset: parseAsset(buyingAsset || buying_asset, 'buyingAsset'),\r\n sellingAmount: parseAmount(sellingAmount || selling_amount, 'sellingAmount'),\r\n buyingAmount: parseAmount(buyingAmount || buying_amount, 'buyingAmount'),\r\n slippageTolerance: parseSlippageTolerance(slippageTolerance || slippage_tolerance || 0.02, 'slippageTolerance'),\r\n flow: 'direct'\r\n }\r\n if (res.buyingAsset === res.sellingAsset)\r\n throw errors.invalidQuoteParam('buyingAsset', 'Buying asset can\\'t be the same as selling asset')\r\n if (res.buyingAmount === undefined && res.sellingAmount === undefined)\r\n throw errors.invalidQuoteParam('sellingAmount', 'Either \"buyingAmount\" or \"sellingAmount\" parameter is required')\r\n if (res.buyingAmount !== undefined && res.sellingAmount !== undefined)\r\n throw errors.invalidQuoteParam('sellingAmount', 'Parameters \"buyingAmount\" and \"sellingAmount\" are mutually exclusive')\r\n Object.assign(res, other) //add remaining optional params\r\n Object.freeze(res)\r\n return res\r\n}\r\n\r\nfunction parseAmount(amount, parameter) {\r\n if (amount === undefined)\r\n return undefined\r\n const parsed = parseFloat(amount)\r\n if (isNaN(parsed) || parsed <= 0)\r\n throw errors.invalidQuoteParam(parameter, 'Invalid asset amount: ' + amount)\r\n return amount\r\n}\r\n\r\nfunction parseSlippageTolerance(src, parameter) {\r\n const tolerance = parseFloat(src)\r\n if (isNaN(tolerance))\r\n throw errors.invalidQuoteParam(parameter, 'Invalid slippage tolerance, number expected')\r\n if (tolerance < 0)\r\n throw errors.invalidQuoteParam(parameter, 'Slippage tolerance is too small, expected value >= 0')\r\n if (tolerance > 0.5)\r\n throw errors.invalidQuoteParam(parameter, 'Slippage tolerance is too large, expected value < 0.5 (50%)')\r\n return tolerance\r\n}","import {hash, Keypair, nativeToScVal, StrKey, TransactionBuilder, xdr} from '@stellar/stellar-sdk'\r\nimport errors from './errors.js'\r\n\r\n/**\r\n * @param {StellarBrokerClient} client\r\n * @param {{xdr: string, hash: string, networkFee: string, [confirmed]: boolean}} txRequest\r\n * @return {Promise<string>}\r\n */\r\nexport async function processTxRequest(client, txRequest) {\r\n //parse incoming transaction\r\n let tx\r\n try {\r\n tx = TransactionBuilder.fromXDR(txRequest.xdr, client.network)\r\n } catch (e) {\r\n throw errors.invalidSwapTx()\r\n }\r\n //check that transaction is correct\r\n if (!validateTransaction(client, tx))\r\n throw errors.invalidSwapTx()\r\n //if transaction has not been authorized yet by the channel account\r\n const isSorobanTx = tx.operations[0].auth?.length > 0\r\n if (isSorobanTx) {\r\n //send tx back to the server\r\n if (!tx.signatures.length) {\r\n //sign auth\r\n await authorizeInvocation(client, tx)\r\n tx = await signTx(client, tx)\r\n return tx.toXDR()//wait for the signed tx from the server to wrap it with fee bump tx\r\n }\r\n } else {\r\n //sign transaction\r\n tx = await signTx(client, tx)\r\n }\r\n //wrap with fee bump\r\n let wrapped = TransactionBuilder.buildFeeBumpTransaction(client.trader, txRequest.networkFee, tx, client.network)\r\n //sign fee bump wrapper tx\r\n wrapped = await signTx(client, wrapped)\r\n //respond with signed transaction\r\n return wrapped.toXDR()\r\n}\r\n\r\n/**\r\n * @param {StellarBrokerClient} client\r\n * @param {TransactionI} tx\r\n * @return {Promise<TransactionI>}\r\n * @private\r\n */\r\nasync function authorizeInvocation(client, tx) {\r\n //from https://github.com/stellar/js-stellar-base/blob/e3d6fc3351e7d242b374c7c6057668366364a279/src/auth.js#L97\r\n const auth = tx.operations[0].auth[0]\r\n /** @type {xdr.SorobanAddressCredentials} */\r\n const addrAuth = auth.credentials().address()\r\n addrAuth.signatureExpirationLedger(tx.ledgerBounds.maxLedger + 1)\r\n\r\n const networkId = hash(Buffer.from(tx.networkPassphrase))\r\n const preimage = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(\r\n new xdr.HashIdPreimageSorobanAuthorization({\r\n networkId,\r\n nonce: addrAuth.nonce(),\r\n invocation: auth.rootInvocation(),\r\n signatureExpirationLedger: addrAuth.signatureExpirationLedger()\r\n })\r\n )\r\n const payload = hash(preimage.toXDR())\r\n let signature\r\n if (client.authorization instanceof Keypair) {\r\n signature = client.authorization.sign(payload)\r\n } else {\r\n signature = await promisify(client.authorization(payload))\r\n }\r\n const publicKey = StrKey.encodeEd25519PublicKey(addrAuth.address().accountId().value())\r\n const sigScVal = nativeToScVal(\r\n {\r\n public_key: StrKey.decodeEd25519PublicKey(publicKey),\r\n signature\r\n },\r\n {\r\n type: {\r\n public_key: ['symbol', null],\r\n signature: ['symbol', null]\r\n }\r\n }\r\n )\r\n\r\n addrAuth.signature(xdr.ScVal.scvVec([sigScVal]))\r\n}\r\n\r\n/**\r\n * @param {StellarBrokerClient} client\r\n * @param {TransactionI} tx\r\n * @return {Promise<TransactionI>}\r\n * @private\r\n */\r\nasync function signTx(client, tx) {\r\n let promise\r\n if (client.authorization instanceof Keypair) {\r\n promise = new Promise((resolve, reject) => {\r\n try {\r\n tx.sign(client.authorization)\r\n resolve(tx)\r\n } catch (e) {\r\n reject(e)\r\n }\r\n })\r\n } else {\r\n //normalize external auth result\r\n promise = promisify(client.authorization(tx))\r\n }\r\n return promise\r\n .then(tx => {\r\n if (typeof tx === 'string') { //normalize response\r\n tx = TransactionBuilder.fromXDR(tx, client.network)\r\n }\r\n if (!tx || tx.signatures?.length < 1)\r\n throw new Error(`Transaction was not signed`)\r\n return tx\r\n })\r\n .catch(e => {\r\n console.error(e)\r\n throw errors.failedToSignTx()\r\n })\r\n}\r\n\r\n/**\r\n * @param {StellarBrokerClient} client\r\n * @param {Transaction} tx\r\n * @throws {StellarBrokerError} Invalid swap transaction received\r\n */\r\nfunction validateTransaction(client, tx) {\r\n /*if (!(tx instanceof FeeBumpTransaction))\r\n return false\r\n const {innerTransaction} = tx\r\n if (tx.feeSource !== this.source)\r\n return false*/\r\n for (let swap of tx.operations) {\r\n if (swap.type === 'invokeHostFunction')\r\n continue //TODO: add additional validation\r\n if (swap.type !== 'pathPaymentStrictSend' && swap.type !== 'pathPaymentStrictReceive')\r\n return false\r\n const isFee = swap.destination !== client.trader\r\n if (isFee) {\r\n if (swap.type !== 'pathPaymentStrictSend')\r\n return false\r\n if ((swap.source && swap.source !== client.trader))\r\n return false\r\n } else {\r\n if ((swap.source && swap.source !== swap.destination) || swap.destination !== client.trader)\r\n return false\r\n }\r\n }\r\n //TODO: check assets and amounts\r\n return true\r\n}\r\n\r\nfunction promisify(callResult) {\r\n if (!(callResult instanceof Promise)) {\r\n if (!callResult)\r\n return Promise.reject()\r\n callResult = Promise.resolve(callResult)\r\n }\r\n return callResult\r\n}","import {Networks, Keypair, TransactionI, StrKey} from '@stellar/stellar-sdk'\r\nimport errors from './errors.js'\r\nimport {buildEvent} from './events.js'\r\nimport {validateQuoteRequest} from './quote-request.js'\r\nimport {processTxRequest} from './tx-processor.js'\r\n\r\nexport default class StellarBrokerClient {\r\n /**\r\n * @param {ClientInitializationParams} params\r\n */\r\n constructor(params) {\r\n this.partnerKey = params.partnerKey\r\n this.emitter = new EventTarget()\r\n this.network = Networks[(params.network || 'PUBLIC').toUpperCase()] || params.network\r\n this.flow = params.flow || 'direct'\r\n if (!params.account || !StrKey.isValidEd25519PublicKey(params.account))\r\n throw errors.invalidQuoteParam('account', 'Invalid trader account address: ' + (!params.account ? 'missing' : params.account))\r\n this.trader = params.account\r\n if (typeof params.authorization === 'string') {\r\n try {\r\n this.authorization = Keypair.fromSecret(params.authorization)\r\n } catch (e) {\r\n throw errors.invalidAuthorizationParam()\r\n }\r\n } else if (typeof params.authorization === 'function') {\r\n this.authorization = params.authorization\r\n }\r\n }\r\n\r\n /**\r\n * @type {string}\r\n * @private\r\n */\r\n uid\r\n /**\r\n * @type {ClientStatus}\r\n * @readonly\r\n */\r\n status = 'disconnected'\r\n /**\r\n * @type {WebSocket}\r\n * @private\r\n */\r\n socket\r\n /**\r\n * @type {EventTarget}\r\n * @private\r\n */\r\n emitter\r\n /**\r\n * @type {string}\r\n * @private\r\n */\r\n origin = 'https://api.stellar.broker'\r\n /**\r\n * Stellar network passphrase\r\n * @type {string}\r\n * @readonly\r\n */\r\n network = ''\r\n /**\r\n * Last quote request submitted by the client\r\n * @type {SwapQuoteParams}\r\n * @readonly\r\n */\r\n quoteRequest\r\n /**\r\n * Last quote received from the sever\r\n * @type {SwapQuoteResult}\r\n * @readonly\r\n */\r\n lastQuote\r\n /**\r\n * Current quote accepted for the trading\r\n * @private\r\n */\r\n tradeQuote\r\n /**\r\n * API key of the partner\r\n * @type {string}\r\n * @readonly\r\n */\r\n partnerKey\r\n /**\r\n * Account secret key (for direct swap flow)\r\n * @type {Keypair|ClientAuthorizationCallback}\r\n * @private\r\n */\r\n authorization\r\n /**\r\n * Trader account public key\r\n * @type {string}\r\n * @readonly\r\n */\r\n trader\r\n\r\n /**\r\n * Connect to the StellarBroker server\r\n * @return {Promise<StellarBrokerClient>}\r\n */\r\n connect() {\r\n if (this.socket?.readyState === WebSocket.OPEN)\r\n return Promise.resolve(this) //already opened\r\n this.socket = new WebSocket(this.origin + '/ws?partner=' + encodeURIComponent(this.partnerKey))\r\n this.socket.onmessage = this.processMessage.bind(this)\r\n this.socket.onclose = () => {\r\n if (this.status !== 'disconnected') {\r\n this.status = 'disconnected'\r\n this.notifyError(errors.notConnected())\r\n }\r\n console.log('Connection closed')\r\n }\r\n\r\n this.socket.onerror = e => console.error(e)\r\n\r\n return new Promise((confirm, reject) => { //TODO: use 'once'\r\n const expirationTimeout = setTimeout(() => reject(this), 2000) // 2s timeout\r\n this.onSocketOpen = () => {\r\n this.status = 'ready'\r\n this.heartbeat()\r\n this.onSocketOpen = undefined\r\n clearTimeout(expirationTimeout)\r\n confirm(this)\r\n }\r\n })\r\n }\r\n\r\n /**\r\n * Process incoming message\r\n * @param message\r\n * @private\r\n */\r\n processMessage(message) {\r\n const raw = JSON.parse(message.data)\r\n switch (raw.type) {\r\n case 'connected':\r\n this.uid = raw.uid\r\n if (this.onSocketOpen) {\r\n this.onSocketOpen()\r\n }\r\n if (this.status === 'disconnected') {\r\n this.status = 'ready'\r\n }\r\n break\r\n case 'quote':\r\n this.lastQuote = raw.quote\r\n this.lastQuote.ts = new Date()\r\n //send event to the client app\r\n this.emitter.dispatchEvent(buildEvent('quote', this.lastQuote))\r\n break\r\n case 'paused':\r\n //quotation paused due to inactivity\r\n this.emitter.dispatchEvent(buildEvent('paused', {}))\r\n break\r\n case 'tx':\r\n if (this.status !== 'trade') {\r\n console.log('Received tx in non-trading state', this.status, raw)\r\n return //skip unless trading is in progress\r\n }\r\n processTxRequest(this, raw)\r\n .then(xdr => {\r\n this.send({\r\n type: 'tx',\r\n hash: raw.hash,\r\n xdr\r\n })\r\n })\r\n .catch(e => this.notifyError(e))\r\n break\r\n case 'stop':\r\n this.emitter.dispatchEvent(buildEvent('finished', {\r\n status: raw.status,\r\n sold: raw.sold,\r\n bought: raw.bought\r\n }, 'result'))\r\n this.status = 'ready'\r\n this.tradeQuote = undefined\r\n break\r\n case 'progress':\r\n this.emitter.dispatchEvent(buildEvent('progress', {\r\n sold: raw.sold,\r\n bought: raw.bought\r\n }, 'status'))\r\n break\r\n case 'ping':\r\n if (raw.uid === this.uid) {\r\n this.heartbeat()\r\n this.send({type: 'pong', uid: this.uid})\r\n }\r\n break\r\n case 'error':\r\n this.stop()\r\n this.notifyError(raw.error)\r\n break\r\n default:\r\n console.log('Unknown message type: ' + raw.type)\r\n break\r\n }\r\n }\r\n\r\n /**\r\n * Request swap quote\r\n * @param {SwapQuoteParams} params - Quote parameters\r\n */\r\n quote(params) {\r\n if (this.status === 'trade')\r\n throw errors.tradeInProgress()\r\n this.quoteRequest = validateQuoteRequest(params)\r\n this.status = 'quote'\r\n this.connect()\r\n .then(() => {\r\n this.status = 'quote'\r\n this.send({\r\n type: 'quote',\r\n ...this.quoteRequest\r\n })\r\n })\r\n }\r\n\r\n confirmQuote() {\r\n if (this.status === 'disconnected')\r\n throw errors.notConnected()\r\n if (this.status === 'trade')\r\n throw errors.tradeInProgress()\r\n if (this.status !== 'quote' || !this.lastQuote)\r\n throw errors.quoteNotSet()\r\n if ((new Date() - this.lastQuote.ts) > 7000) //do not allow stale quotes quoted more than 7s ago\r\n throw errors.quoteExpired()\r\n if (this.lastQuote.status !== 'success')\r\n throw errors.quoteError(this.lastQuote.error || 'quote not available')\r\n\r\n this.tradeQuote = this.lastQuote\r\n this.send({\r\n type: 'trade',\r\n account: this.trader\r\n })\r\n this.status = 'trade'\r\n }\r\n\r\n /**\r\n * Stop quotation/trading\r\n */\r\n stop() {\r\n if (this.status !== 'trade' && this.status !== 'quote')\r\n return\r\n this.send({type: 'stop'})\r\n this.tradeQuote = undefined\r\n this.status = 'ready'\r\n }\r\n\r\n /**\r\n * @param {{}} data\r\n * @private\r\n */\r\n send(data) {\r\n this.socket.send(JSON.stringify(data))\r\n }\r\n\r\n /**\r\n * @private\r\n */\r\n heartbeat() {\r\n clearTimeout(this.pingHandler)\r\n this.pingHandler = setTimeout(() => {\r\n console.warn('Lost connection with the server')\r\n this.socket.close()\r\n }, 7_000) // 7 seconds heartbeat timeout\r\n }\r\n\r\n /**\r\n * Add event listener\r\n * @param {StellarBrokerClientEvent} type\r\n * @param {function} callback\r\n */\r\n on(type, callback) {\r\n validateEventType(type)\r\n this.emitter.addEventListener(type, callback)\r\n }\r\n\r\n /**\r\n * Add event listener that will be executed once\r\n * @param {StellarBrokerClientEvent} type\r\n * @param {function} callback\r\n */\r\n once(type, callback) {\r\n validateEventType(type)\r\n this.emitter.addEventListener(type, callback, {once: true})\r\n }\r\n\r\n /**\r\n * Remove event listener\r\n * @param {StellarBrokerClientEvent} type\r\n * @param {function} callback\r\n */\r\n off(type, callback) {\r\n validateEventType(type)\r\n this.emitter.removeEventListener(type, callback)\r\n }\r\n\r\n /**\r\n * Close underlying connection and finalize the client\r\n */\r\n close() {\r\n try {\r\n this.status = 'disconnected'\r\n this.socket.close()\r\n } catch (e) {\r\n }\r\n }\r\n\r\n /**\r\n * @param {Error} e\r\n * @private\r\n */\r\n notifyError(e) {\r\n console.error(e)\r\n try {\r\n this.emitter.dispatchEvent(buildEvent('error', e instanceof Error ? e.message : e))\r\n } catch (e) {\r\n console.error(e)\r\n }\r\n }\r\n}\r\n\r\nfunction validateEventType(type) {\r\n if (!StellarBrokerEvents.includes(type))\r\n throw errors.unsupportedEventType(type)\r\n}\r\n\r\nexport const StellarBrokerEvents = ['quote', 'paused', 'progress', 'finished', 'error']\r\n\r\n/**\r\n * @typedef {object} ClientInitializationParams\r\n * @property {string} [network] - Stellar network identifier or passphrase\r\n * @property {string} [partnerKey] - Partner key\r\n * @property {SwapFlowMode} [flow] - Swap flow mode\r\n * @property {string} account - Trader account address\r\n * @property {string|ClientAuthorizationCallback} authorization - Authorization method, either account secret key or an authorization callback\r\n */\r\n\r\n/**\r\n * @typedef {'disconnected'|'ready'|'quote'|'trade'} ClientStatus\r\n */\r\n\r\n/**\r\n * @typedef {'quote'|'paused'|'progress'|'finished'|'error'} StellarBrokerClientEvent\r\n */\r\n\r\n/**\r\n * @typedef {'direct'} SwapFlowMode\r\n */\r\n\r\n/**\r\n * @typedef {object} SwapQuoteResult\r\n * @property {string} sellingAsset\r\n * @property {string} buyingAsset\r\n * @property {number} slippageTolerance\r\n * @property {string} destination\r\n * @property {number} ledger\r\n * @property {string} [sellingAmount]\r\n * @property {string} [estimatedBuyingAmount]\r\n * @property {string} [buyingAmount]\r\n * @property {string} [estimatedSellingAmount]\r\n * @property {{selling: string, buying: string, path: string[]}} [directTrade]\r\n */\r\n\r\n/**\r\n * @typedef {function(TransactionI|Buffer):Promise<TransactionI|Buffer>} ClientAuthorizationCallback\r\n */","import StellarBrokerClient from './client.js'\r\nimport {estimateSwap} from './estimate.js'\r\n\r\nStellarBrokerClient.estimateSwap = estimateSwap\r\n\r\nexport default StellarBrokerClient","import errors, {StellarBrokerError} from './errors.js'\r\nimport {validateQuoteRequest} from './quote-request.js'\r\n\r\n/**\r\n * Request single swap quote estimate without trading\r\n * @param {SwapQuoteParams} params\r\n * @return {Promise<SwapQuoteResult>}\r\n */\r\nexport async function estimateSwap(params) {\r\n const query = Object.entries(validateQuoteRequest(params))\r\n .filter(kv => kv[1] !== undefined)\r\n .map(([param, value]) => encodeURIComponent(param) + '=' + encodeURIComponent(value))\r\n const url = (params.origin || 'https://api.stellar.broker') + '/quote?' + query.join('&')\r\n try {\r\n const res = await fetch(url).then(r => r.json())\r\n if (res.status !== 'success')\r\n throw errors.quoteError(res.error || 'Quote not available')\r\n return res\r\n } catch (e) {\r\n if (e instanceof StellarBrokerError)\r\n throw e\r\n throw errors.quoteError('Failed to fetch quote')\r\n return null\r\n }\r\n}"],"names":["root","factory","exports","module","require","define","amd","this","__WEBPACK_EXTERNAL_MODULE__346__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","d","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","StellarBrokerError","Error","constructor","code","message","super","invalidInitParam","param","invalidAuthorizationParam","notConnected","quoteNotSet","quoteExpired","quoteError","invalidQuoteParam","invalidParamName","details","tradeInProgress","invalidSwapTx","failedToSignTx","unsupportedEventType","type","serverError","buildEvent","data","evt","CustomEvent","detail","parseAsset","asset","parameter","includes","issuer","split","validateCode","validateAccount","errors","test","account","StrKey","isValidEd25519PublicKey","validateQuoteRequest","params","destination","sellingAsset","selling_asset","buyingAsset","buying_asset","sellingAmount","selling_amount","buyingAmount","buying_amount","slippageTolerance","slippage_tolerance","other","res","parseAmount","parseSlippageTolerance","flow","assign","freeze","amount","parsed","parseFloat","isNaN","src","tolerance","async","signTx","client","tx","promise","authorization","Keypair","Promise","resolve","reject","sign","e","promisify","then","TransactionBuilder","fromXDR","network","signatures","length","catch","console","error","callResult","StellarBrokerClient","partnerKey","emitter","EventTarget","Networks","toUpperCase","trader","fromSecret","uid","status","socket","origin","quoteRequest","lastQuote","tradeQuote","connect","readyState","WebSocket","OPEN","encodeURIComponent","onmessage","processMessage","bind","onclose","notifyError","log","onerror","confirm","expirationTimeout","setTimeout","onSocketOpen","heartbeat","clearTimeout","raw","JSON","parse","quote","ts","Date","dispatchEvent","txRequest","xdr","swap","operations","source","validateTransaction","auth","addrAuth","credentials","address","signatureExpirationLedger","ledgerBounds","maxLedger","networkId","hash","Buffer","from","networkPassphrase","preimage","HashIdPreimage","envelopeTypeSorobanAuthorization","HashIdPreimageSorobanAuthorization","nonce","invocation","rootInvocation","payload","toXDR","signature","publicKey","encodeEd25519PublicKey","accountId","value","sigScVal","nativeToScVal","public_key","decodeEd25519PublicKey","ScVal","scvVec","authorizeInvocation","wrapped","buildFeeBumpTransaction","networkFee","processTxRequest","send","sold","bought","stop","confirmQuote","stringify","pingHandler","warn","close","on","callback","validateEventType","addEventListener","once","off","removeEventListener","StellarBrokerEvents","estimateSwap","query","entries","filter","kv","map","url","join","fetch","r","json"],"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,MCmUZ,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 if (!params.account || !StrKey.isValidEd25519PublicKey(params.account))\n throw errors.invalidQuoteParam('account', 'Invalid trader account address: ' + (!params.account ? 'missing' : params.account))\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 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 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 */\n confirmQuote() {\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\n this.tradeQuote = this.lastQuote\n this.send({\n type: 'trade',\n account: this.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} account - Trader account address\n * @property {ClientAuthorizationParams} authorization - Authorization method, either account secret key or an authorization callback\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":""}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stellar-broker/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Client library for StellarBroker service",
|
|
5
5
|
"author": "team@stellar.broker",
|
|
6
6
|
"homepage": "https://stellar.broker",
|
|
@@ -10,23 +10,24 @@
|
|
|
10
10
|
"module": "src/index.js",
|
|
11
11
|
"types": "src/index.d.ts",
|
|
12
12
|
"scripts": {
|
|
13
|
-
"
|
|
14
|
-
"
|
|
13
|
+
"test": "jest",
|
|
14
|
+
"prepare": "webpack --mode=production --config webpack.config.cjs"
|
|
15
15
|
},
|
|
16
16
|
"repository": {
|
|
17
17
|
"type": "git",
|
|
18
18
|
"url": "https://github.com/stellar-broker/client"
|
|
19
19
|
},
|
|
20
20
|
"peerDependencies": {
|
|
21
|
-
"@stellar/stellar-sdk": ">=
|
|
21
|
+
"@stellar/stellar-sdk": ">=13"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@babel/core": "^7.
|
|
25
|
-
"@babel/preset-env": "^7.
|
|
26
|
-
"babel-loader": "^9.1
|
|
24
|
+
"@babel/core": "^7.26.7",
|
|
25
|
+
"@babel/preset-env": "^7.26.7",
|
|
26
|
+
"babel-loader": "^9.2.1",
|
|
27
|
+
"babel-jest": "^29.7.0",
|
|
27
28
|
"jest": "^29.7.0",
|
|
28
|
-
"typescript": "^5.
|
|
29
|
-
"webpack": "^5.
|
|
29
|
+
"typescript": "^5.7.3",
|
|
30
|
+
"webpack": "^5.97.1",
|
|
30
31
|
"webpack-cli": "^5.1.4",
|
|
31
32
|
"ws": "^8.17.1"
|
|
32
33
|
}
|
package/src/asset.js
CHANGED
|
@@ -1,47 +1,51 @@
|
|
|
1
|
-
import {Asset, StrKey} from '@stellar/stellar-sdk'
|
|
2
|
-
import errors from './errors.js'
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* @param {string} asset
|
|
6
|
-
* @return {Asset}
|
|
7
|
-
*/
|
|
8
|
-
export function convertToStellarAsset(asset) {
|
|
9
|
-
if (asset
|
|
10
|
-
return
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
1
|
+
import {Asset, StrKey} from '@stellar/stellar-sdk'
|
|
2
|
+
import errors from './errors.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @param {string|Asset|{}} asset
|
|
6
|
+
* @return {Asset}
|
|
7
|
+
*/
|
|
8
|
+
export function convertToStellarAsset(asset) {
|
|
9
|
+
if (asset instanceof Asset)
|
|
10
|
+
return asset
|
|
11
|
+
if (asset === 'xlm' || asset === 'XLM' || asset.asset_type === 'native')
|
|
12
|
+
return Asset.native()
|
|
13
|
+
if (asset.asset_type)
|
|
14
|
+
return new Asset(asset.asset_code, asset.asset_issuer)
|
|
15
|
+
const [code, issuer] = asset.includes('-') ?
|
|
16
|
+
asset.split('-') :
|
|
17
|
+
asset.split(':')
|
|
18
|
+
return new Asset(code, issuer)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function parseAsset(asset, parameter) {
|
|
22
|
+
if (typeof asset === 'string') {
|
|
23
|
+
if (asset === 'XLM' || asset === 'xlm' || asset === 'native')
|
|
24
|
+
return 'XLM'
|
|
25
|
+
if (asset.includes(':')) {
|
|
26
|
+
const [code, issuer] = asset.split(':')
|
|
27
|
+
validateCode(code)
|
|
28
|
+
validateAccount(issuer, parameter)
|
|
29
|
+
return code + '-' + issuer
|
|
30
|
+
}
|
|
31
|
+
if (asset.includes('-')) {
|
|
32
|
+
const [code, issuer] = asset.split('-')
|
|
33
|
+
validateCode(code)
|
|
34
|
+
validateAccount(issuer, parameter)
|
|
35
|
+
return asset
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
throw errors.invalidQuoteParam(parameter, 'Invalid asset')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function validateCode(code, parameter) {
|
|
42
|
+
if (!/^[a-zA-Z0-9]{1,12}$/.test(code))
|
|
43
|
+
throw errors.invalidQuoteParam(parameter, 'Invalid asset code: ' + (!code ? 'missing' : code))
|
|
44
|
+
return code
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function validateAccount(account, param) {
|
|
48
|
+
if (!account || !StrKey.isValidEd25519PublicKey(account))
|
|
49
|
+
throw errors.invalidQuoteParam(param, 'Invalid account address: ' + (!account ? 'missing' : account))
|
|
50
|
+
return account
|
|
51
|
+
}
|