@stellar-broker/client 0.4.0 → 0.5.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/LICENSE +21 -0
- 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 +14 -12
- package/src/asset.js +51 -47
- package/src/authorization.js +65 -0
- package/src/client.js +353 -369
- package/src/errors.js +55 -53
- package/src/index.d.ts +95 -25
- package/src/index.js +4 -3
- package/src/mediator.js +309 -0
- package/src/quote-request.js +56 -60
- package/src/tx-processor.js +133 -161
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 StellarBroker
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
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(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("@stellar/stellar-sdk")):"function"==typeof define&&define.amd?define(["@stellar/stellar-sdk"],e):"object"==typeof exports?exports.stellarbroker=e(require("@stellar/stellar-sdk")):t.stellarbroker=e(t["@stellar/stellar-sdk"])}(this,(t=>(()=>{"use strict";var e={346:e=>{e.exports=t}},
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("@stellar/stellar-sdk")):"function"==typeof define&&define.amd?define(["@stellar/stellar-sdk"],e):"object"==typeof exports?exports.stellarbroker=e(require("@stellar/stellar-sdk")):t.stellarbroker=e(t["@stellar/stellar-sdk"])}(this,(t=>(()=>{"use strict";var e={346:e=>{e.exports=t}},s={};function r(t){var o=s[t];if(void 0!==o)return o.exports;var i=s[t]={exports:{}};return e[t](i,i.exports,r),i.exports}r.d=(t,e)=>{for(var s in e)r.o(e,s)&&!r.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var o={};r.d(o,{default:()=>b});var i=r(346);class n extends Error{constructor(t,e){super(e),this.code=t}code=0}const a={invalidInitParam:t=>new n(1,`Invalid parameter value: "${t}"`),invalidAuthorizationParam:()=>new n(2,"Invalid authorization secret key or callback provided"),notConnected:()=>new n(3,"Client not connected to the server"),quoteNotSet:()=>new n(11,"Price quote not available"),quoteExpired:()=>new n(12,"Price quote expired"),quoteError:t=>new n(13,"Price quotation error: "+t),invalidQuoteParam:(t="asset",e)=>new n(14,`Invalid quote request parameter: "${t}". ${e}`),tradeInProgress:()=>new n(20,"Cannot change quote while trade is in progress"),invalidSwapTx:()=>new n(21,"Invalid swap transaction received from the server"),failedToSignTx:()=>new n(22,"Failed to sign received transaction"),unsupportedEventType:t=>new n(31,"Unknown event type: "+t),serverError:t=>new n(101,t)};function u(t,e,s){const r=new CustomEvent(t,{detail:e});return r[s||t]=e,r}function c(t,e){if("string"==typeof t){if("XLM"===t||"xlm"===t||"native"===t)return"XLM";if(t.includes(":")){const[s,r]=t.split(":");return d(s),l(r,e),s+"-"+r}if(t.includes("-")){const[s,r]=t.split("-");return d(s),l(r,e),t}}throw a.invalidQuoteParam(e,"Invalid asset")}function d(t,e){if(!/^[a-zA-Z0-9]{1,12}$/.test(t))throw a.invalidQuoteParam(e,"Invalid asset code: "+(t||"missing"));return t}function l(t,e){if(!t||!i.StrKey.isValidEd25519PublicKey(t))throw a.invalidQuoteParam(e,"Invalid account address: "+(t||"missing"));return t}function h(t){const{sellingAsset:e,selling_asset:s,buyingAsset:r,buying_asset:o,sellingAmount:i,selling_amount:n,buyingAmount:u,buying_amount:d,slippageTolerance:l,slippage_tolerance:h,...g}=t,m={sellingAsset:c(e||s,"sellingAsset"),buyingAsset:c(r||o,"buyingAsset"),sellingAmount:p(i||n,"sellingAmount"),slippageTolerance:f(l||h||.02,"slippageTolerance")};if(m.buyingAsset===m.sellingAsset)throw a.invalidQuoteParam("buyingAsset","Buying asset can't be the same as selling asset");if(void 0===m.sellingAmount)throw a.invalidQuoteParam("sellingAmount",'Parameter "sellingAmount" parameter is required');return Object.assign(m,g),Object.freeze(m),m}function p(t,e){if(void 0===t)return;const s=parseFloat(t);if(isNaN(s)||s<=0)throw a.invalidQuoteParam(e,"Invalid asset amount: "+t);return t}function f(t,e){const s=parseFloat(t);if(isNaN(s))throw a.invalidQuoteParam(e,"Invalid slippage tolerance, number expected");if(s<0)throw a.invalidQuoteParam(e,"Slippage tolerance is too small, expected value >= 0");if(s>.5)throw a.invalidQuoteParam(e,"Slippage tolerance is too large, expected value < 0.5 (50%)");return s}function g(t,e){return t.authorization.authorize(e).then((e=>{if("string"==typeof e&&(e=i.TransactionBuilder.fromXDR(e,t.network)),!e||e.signatures?.length<1)throw new Error("Transaction was not signed");return e})).catch((t=>{throw console.error(t),a.failedToSignTx()}))}class m{constructor(t){if("string"==typeof t)try{return void(this.authorization=i.Keypair.fromSecret(t))}catch(t){throw a.invalidAuthorizationParam()}else if("function"==typeof t)return void(this.authorization=t);throw a.invalidAuthorizationParam()}authorization;async authorize(t){return this.authorization instanceof i.Keypair?t.sign?(t.sign(this.authorization),t):this.authorization.sign(t):await function(t){if(!(t instanceof Promise)){if(!t)return Promise.reject();t=Promise.resolve(t)}return t}(this.authorization(t))}}class v{constructor(t){if(this.partnerKey=t.partnerKey,this.emitter=new EventTarget,this.network=i.Networks.PUBLIC,!t.account||!i.StrKey.isValidEd25519PublicKey(t.account))throw a.invalidQuoteParam("account","Invalid trader account address: "+(t.account?t.account:"missing"));this.trader=t.account,this.authorization=new m(t.authorization)}uid;status="disconnected";socket;emitter;origin="https://api.stellar.broker";network="";quoteRequest;lastQuote;tradeQuote;partnerKey;authorization;trader;connect(){return this.socket?.readyState===WebSocket.OPEN?Promise.resolve(this):(this.socket=new WebSocket(this.origin+"/ws?partner="+encodeURIComponent(this.partnerKey)),this.socket.onmessage=this.processMessage.bind(this),this.socket.onclose=()=>{"disconnected"!==this.status&&(this.status="disconnected",this.notifyError(a.notConnected())),console.log("Connection closed")},this.socket.onerror=t=>console.error(t),new Promise(((t,e)=>{const s=setTimeout((()=>e(this)),2e3);this.onSocketOpen=()=>{this.status="ready",this.heartbeat(),this.onSocketOpen=void 0,clearTimeout(s),t(this)}})))}processMessage(t){const e=JSON.parse(t.data);switch(e.type){case"connected":this.uid=e.uid,this.onSocketOpen&&this.onSocketOpen(),"disconnected"===this.status&&(this.status="ready");break;case"quote":this.lastQuote=e.quote,this.lastQuote.ts=new Date,this.emitter.dispatchEvent(u("quote",this.lastQuote));break;case"paused":this.emitter.dispatchEvent(u("paused",{}));break;case"tx":if("trade"!==this.status)return void console.log("Received tx in non-trading state",this.status,e);(async function(t,e){let s;try{s=i.TransactionBuilder.fromXDR(e.xdr,t.network)}catch(t){throw a.invalidSwapTx()}if(!function(t,e){for(let s of e.operations)if("invokeHostFunction"!==s.type){if("pathPaymentStrictSend"!==s.type&&"pathPaymentStrictReceive"!==s.type)return!1;if(s.destination!==t.trader){if("pathPaymentStrictSend"!==s.type)return!1;if(s.source&&s.source!==t.trader)return!1}else if(s.source&&s.source!==s.destination||s.destination!==t.trader)return!1}return!0}(t,s))throw a.invalidSwapTx();if(s.operations[0].auth?.length>0){if(!s.signatures.length)return await async function(t,e){const s=e.operations[0].auth[0],r=s.credentials().address();r.signatureExpirationLedger(e.ledgerBounds.maxLedger+1);const o=(0,i.hash)(Buffer.from(e.networkPassphrase)),n=i.xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(new i.xdr.HashIdPreimageSorobanAuthorization({networkId:o,nonce:r.nonce(),invocation:s.rootInvocation(),signatureExpirationLedger:r.signatureExpirationLedger()})),a=(0,i.hash)(n.toXDR()),u=await t.authorization.authorize(a),c=i.StrKey.encodeEd25519PublicKey(r.address().accountId().value()),d=(0,i.nativeToScVal)({public_key:i.StrKey.decodeEd25519PublicKey(c),signature:u},{type:{public_key:["symbol",null],signature:["symbol",null]}});r.signature(i.xdr.ScVal.scvVec([d]))}(t,s),s=await g(t,s),s.toXDR()}else s=await g(t,s);let r=i.TransactionBuilder.buildFeeBumpTransaction(t.trader,e.networkFee,s,t.network);return r=await g(t,r),r.toXDR()})(this,e).then((t=>{this.send({type:"tx",hash:e.hash,xdr:t})})).catch((t=>this.notifyError(t)));break;case"stop":this.emitter.dispatchEvent(u("finished",{status:e.status,sold:e.sold,bought:e.bought},"result")),this.status="ready",this.tradeQuote=void 0;break;case"progress":this.emitter.dispatchEvent(u("progress",{sold:e.sold,bought:e.bought},"status"));break;case"ping":e.uid===this.uid&&(this.heartbeat(),this.send({type:"pong",uid:this.uid}));break;case"error":this.stop(),this.notifyError(e.error);break;default:console.log("Unknown message type: "+e.type)}}quote(t){if("trade"===this.status)throw a.tradeInProgress();this.quoteRequest=h(t),this.status="quote",this.connect().then((()=>{this.status="quote",this.send({type:"quote",...this.quoteRequest})}))}confirmQuote(){if("disconnected"===this.status)throw a.notConnected();if("trade"===this.status)throw a.tradeInProgress();if("quote"!==this.status||!this.lastQuote)throw a.quoteNotSet();if(new Date-this.lastQuote.ts>1e4)throw a.quoteExpired();if("success"!==this.lastQuote.status)throw a.quoteError(this.lastQuote.error||"quote not available");this.tradeQuote=this.lastQuote,this.send({type:"trade",account:this.trader}),this.status="trade"}stop(){"trade"!==this.status&&"quote"!==this.status||(this.send({type:"stop"}),this.tradeQuote=void 0,this.status="ready")}send(t){this.socket.send(JSON.stringify(t))}heartbeat(){clearTimeout(this.pingHandler),this.pingHandler=setTimeout((()=>{console.warn("Lost connection with the server"),this.socket.close()}),7e3)}on(t,e){y(t),this.emitter.addEventListener(t,e)}once(t,e){y(t),this.emitter.addEventListener(t,e,{once:!0})}off(t,e){y(t),this.emitter.removeEventListener(t,e)}close(){try{this.status="disconnected",this.socket.close()}catch(t){}}notifyError(t){console.error(t);try{this.emitter.dispatchEvent(u("error",t instanceof Error?t.message:t))}catch(t){console.error(t)}}}function y(t){if(!w.includes(t))throw a.unsupportedEventType(t)}const w=["quote","paused","progress","finished","error"];v.estimateSwap=async function(t){const e=Object.entries(h(t)).filter((t=>void 0!==t[1])).map((([t,e])=>encodeURIComponent(t)+"="+encodeURIComponent(e))),s=(t.origin||"https://api.stellar.broker")+"/quote?"+e.join("&");try{const t=await fetch(s).then((t=>t.json()));if("success"!==t.status)throw a.quoteError(t.error||"Quote not available");return t}catch(t){if(t instanceof n)throw t;throw a.quoteError("Failed to fetch quote")}};const b=v;return o.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,EAA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,CACJ,EAGJ,SAAS0G,EAAkBnK,GACvB,IAAKwK,EAAoB9J,SAASV,GAC9B,MAAMe,EAAOhB,qBAAqBC,EAC1C,CAEO,MAAMwK,EAAsB,CAAC,QAAS,SAAU,WAAY,WAAY,SCtU/EnG,EAAoBoG,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","f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ClBzC,KAAKgH,QAAQgG,oBAAoBvK,EAAMkK,EAC3C,CAKAF,KAAAA,GACI,IAEIzM,KAAKsH,OAAS,eACdtH,KAAKuH,OAAOkF,OAChB,CAAE,MAAOxG,GACT,CACJ,CAMAoC,WAAAA,CAAYpC,GACRC,QAAQC,MAAMF,GACd,IACIjG,KAAKgH,QAAQoC,cAAczG,EAAW,QAASsD,aAAa3E,MAAQ2E,EAAExE,QAAUwE,GACpF,CAAE,MAAOA,GACLC,QAAQC,MAAMF,EAClB,CACJ,EAGJ,SAAS2G,EAAkBnK,GACvB,IAAKwK,EAAoB9J,SAASV,GAC9B,MAAMe,EAAOhB,qBAAqBC,EAC1C,CAEO,MAAMwK,EAAsB,CAAC,QAAS,SAAU,WAAY,WAAY,SClU/EnG,EAAoBoG,aCKb7D,eAA4BvF,GAC/B,MAAMqJ,EAAQvM,OAAOwM,QAAQvJ,EAAqBC,IAC7CuJ,QAAOC,QAAgBhN,IAAVgN,EAAG,KAChBC,KAAI,EAAE3L,EAAOyJ,KAAWrD,mBAAmBpG,GAAS,IAAMoG,mBAAmBqD,KAC5EmC,GAAO1J,EAAO0D,QAAU,8BAAgC,UAAY2F,EAAMM,KAAK,KACrF,IACI,MAAM/I,QAAYgJ,MAAMF,GAAK9H,MAAKiI,GAAKA,EAAEC,SACzC,GAAmB,YAAflJ,EAAI4C,OACJ,MAAM9D,EAAOvB,WAAWyC,EAAIyB,OAAS,uBACzC,OAAOzB,CACX,CAAE,MAAOuB,GACL,GAAIA,aAAa5E,EACb,MAAM4E,EACV,MAAMzC,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/authorization.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 {\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","/**\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'\nimport errors from './errors.js'\n\n/**\n * @param {string|Asset|{}} asset\n * @return {Asset}\n */\nexport function convertToStellarAsset(asset) {\n if (asset instanceof Asset)\n return asset\n if (asset === 'xlm' || asset === 'XLM' || asset.asset_type === 'native')\n return Asset.native()\n if (asset.asset_type)\n return new Asset(asset.asset_code, asset.asset_issuer)\n const [code, issuer] = asset.includes('-') ?\n asset.split('-') :\n asset.split(':')\n return new Asset(code, issuer)\n}\n\nexport function parseAsset(asset, parameter) {\n if (typeof asset === 'string') {\n if (asset === 'XLM' || asset === 'xlm' || asset === 'native')\n return 'XLM'\n if (asset.includes(':')) {\n const [code, issuer] = asset.split(':')\n validateCode(code)\n validateAccount(issuer, parameter)\n return code + '-' + issuer\n }\n if (asset.includes('-')) {\n const [code, issuer] = asset.split('-')\n validateCode(code)\n validateAccount(issuer, parameter)\n return asset\n }\n }\n throw errors.invalidQuoteParam(parameter, 'Invalid asset')\n}\n\nfunction validateCode(code, parameter) {\n if (!/^[a-zA-Z0-9]{1,12}$/.test(code))\n throw errors.invalidQuoteParam(parameter, 'Invalid asset code: ' + (!code ? 'missing' : code))\n return code\n}\n\nfunction validateAccount(account, param) {\n if (!account || !StrKey.isValidEd25519PublicKey(account))\n throw errors.invalidQuoteParam(param, 'Invalid account address: ' + (!account ? 'missing' : account))\n return account\n}\n","import errors from './errors.js'\nimport {parseAsset} from './asset.js'\n\n/**\n * @typedef {object} SwapQuoteParams\n * @property {string} sellingAsset - Asset to sell\n * @property {string} buyingAsset - Asset to buy\n * @property {string} [sellingAmount] - Amount of selling asset\n * @property {number} [slippageTolerance] - Swap slippage tolerance (0.02 by default - 2%)\n */\n\n/**\n * @param {SwapQuoteParams} params\n * @return {SwapQuoteParams}\n */\nexport function validateQuoteRequest(params) {\n const {\n sellingAsset, selling_asset, buyingAsset, buying_asset, sellingAmount, selling_amount,\n buyingAmount, buying_amount, slippageTolerance, slippage_tolerance, ...other\n } = params\n const res = {\n sellingAsset: parseAsset(sellingAsset || selling_asset, 'sellingAsset'),\n buyingAsset: parseAsset(buyingAsset || buying_asset, 'buyingAsset'),\n sellingAmount: parseAmount(sellingAmount || selling_amount, 'sellingAmount'),\n //buyingAmount: parseAmount(buyingAmount || buying_amount, 'buyingAmount'),\n slippageTolerance: parseSlippageTolerance(slippageTolerance || slippage_tolerance || 0.02, 'slippageTolerance')\n }\n if (res.buyingAsset === res.sellingAsset)\n throw errors.invalidQuoteParam('buyingAsset', 'Buying asset can\\'t be the same as selling asset')\n if (res.sellingAmount === undefined)\n throw errors.invalidQuoteParam('sellingAmount', 'Parameter \"sellingAmount\" parameter is required')\n /*if (res.buyingAmount !== undefined && res.sellingAmount !== undefined)\n throw errors.invalidQuoteParam('sellingAmount', 'Parameters \"buyingAmount\" and \"sellingAmount\" are mutually exclusive')*/\n Object.assign(res, other) //add remaining optional params\n Object.freeze(res)\n return res\n}\n\nfunction parseAmount(amount, parameter) {\n if (amount === undefined)\n return undefined\n const parsed = parseFloat(amount)\n if (isNaN(parsed) || parsed <= 0)\n throw errors.invalidQuoteParam(parameter, 'Invalid asset amount: ' + amount)\n return amount\n}\n\nfunction parseSlippageTolerance(src, parameter) {\n const tolerance = parseFloat(src)\n if (isNaN(tolerance))\n throw errors.invalidQuoteParam(parameter, 'Invalid slippage tolerance, number expected')\n if (tolerance < 0)\n throw errors.invalidQuoteParam(parameter, 'Slippage tolerance is too small, expected value >= 0')\n if (tolerance > 0.5)\n throw errors.invalidQuoteParam(parameter, 'Slippage tolerance is too large, expected value < 0.5 (50%)')\n return tolerance\n}","import {hash, Keypair, nativeToScVal, StrKey, TransactionBuilder, xdr} from '@stellar/stellar-sdk'\nimport errors from './errors.js'\n\n/**\n * @param {StellarBrokerClient} client\n * @param {{xdr: string, hash: string, networkFee: string, [confirmed]: boolean}} txRequest\n * @return {Promise<string>}\n */\nexport async function processTxRequest(client, txRequest) {\n //parse incoming transaction\n let tx\n try {\n tx = TransactionBuilder.fromXDR(txRequest.xdr, client.network)\n } catch (e) {\n throw errors.invalidSwapTx()\n }\n //check that transaction is correct\n if (!validateTransaction(client, tx))\n throw errors.invalidSwapTx()\n //if transaction has not been authorized yet by the channel account\n const isSorobanTx = tx.operations[0].auth?.length > 0\n if (isSorobanTx) {\n //send tx back to the server\n if (!tx.signatures.length) {\n //sign auth\n await authorizeInvocation(client, tx)\n tx = await signTx(client, tx)\n return tx.toXDR()//wait for the signed tx from the server to wrap it with fee bump tx\n }\n } else {\n //sign transaction\n tx = await signTx(client, tx)\n }\n //wrap with fee bump\n let wrapped = TransactionBuilder.buildFeeBumpTransaction(client.trader, txRequest.networkFee, tx, client.network)\n //sign fee bump wrapper tx\n wrapped = await signTx(client, wrapped)\n //respond with signed transaction\n return wrapped.toXDR()\n}\n\n/**\n * @param {StellarBrokerClient} client\n * @param {TransactionI} tx\n * @return {Promise<TransactionI>}\n * @private\n */\nasync function authorizeInvocation(client, tx) {\n //from https://github.com/stellar/js-stellar-base/blob/e3d6fc3351e7d242b374c7c6057668366364a279/src/auth.js#L97\n const auth = tx.operations[0].auth[0]\n /** @type {xdr.SorobanAddressCredentials} */\n const addrAuth = auth.credentials().address()\n addrAuth.signatureExpirationLedger(tx.ledgerBounds.maxLedger + 1)\n\n const networkId = hash(Buffer.from(tx.networkPassphrase))\n const preimage = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(\n new xdr.HashIdPreimageSorobanAuthorization({\n networkId,\n nonce: addrAuth.nonce(),\n invocation: auth.rootInvocation(),\n signatureExpirationLedger: addrAuth.signatureExpirationLedger()\n })\n )\n const payload = hash(preimage.toXDR())\n const signature = await client.authorization.authorize(payload)\n const publicKey = StrKey.encodeEd25519PublicKey(addrAuth.address().accountId().value())\n const sigScVal = nativeToScVal(\n {\n public_key: StrKey.decodeEd25519PublicKey(publicKey),\n signature\n },\n {\n type: {\n public_key: ['symbol', null],\n signature: ['symbol', null]\n }\n }\n )\n\n addrAuth.signature(xdr.ScVal.scvVec([sigScVal]))\n}\n\n/**\n * @param {StellarBrokerClient} client\n * @param {TransactionI} tx\n * @return {Promise<TransactionI>}\n * @private\n */\nfunction signTx(client, tx) {\n return client.authorization.authorize(tx)\n .then(tx => {\n if (typeof tx === 'string') { //normalize response\n tx = TransactionBuilder.fromXDR(tx, client.network)\n }\n if (!tx || tx.signatures?.length < 1)\n throw new Error(`Transaction was not signed`)\n return tx\n })\n .catch(e => {\n console.error(e)\n throw errors.failedToSignTx()\n })\n}\n\n/**\n * @param {StellarBrokerClient} client\n * @param {Transaction} tx\n * @throws {StellarBrokerError} Invalid swap transaction received\n */\nfunction validateTransaction(client, tx) {\n /*if (!(tx instanceof FeeBumpTransaction))\n return false\n const {innerTransaction} = tx\n if (tx.feeSource !== this.source)\n return false*/\n for (let swap of tx.operations) {\n if (swap.type === 'invokeHostFunction')\n continue //TODO: add additional validation\n if (swap.type !== 'pathPaymentStrictSend' && swap.type !== 'pathPaymentStrictReceive')\n return false\n const isFee = swap.destination !== client.trader\n if (isFee) {\n if (swap.type !== 'pathPaymentStrictSend')\n return false\n if ((swap.source && swap.source !== client.trader))\n return false\n } else {\n if ((swap.source && swap.source !== swap.destination) || swap.destination !== client.trader)\n return false\n }\n }\n //TODO: check assets and amounts\n return true\n}","import {Keypair} from '@stellar/stellar-sdk'\nimport errors from './errors.js'\n\nexport class AuthorizationWrapper {\n /**\n * @param {ClientAuthorizationParams} authorization\n */\n constructor(authorization) {\n if (typeof authorization === 'string') {\n try {\n this.authorization = Keypair.fromSecret(authorization)\n return\n } catch (e) {\n throw errors.invalidAuthorizationParam()\n }\n } else if (typeof authorization === 'function') {\n this.authorization = authorization\n return\n }\n throw errors.invalidAuthorizationParam()\n }\n\n /**\n * @type {Keypair|ClientAuthorizationCallback}\n * @private\n */\n authorization\n\n /**\n * Authorize transaction or invocation footprint hash\n * @param {TransactionI|Buffer} payload\n * @return {Promise<TransactionI|Buffer>}\n */\n async authorize(payload) {\n if (this.authorization instanceof Keypair) {\n if (payload.sign){\n payload.sign(this.authorization)\n return payload\n }\n return this.authorization.sign(payload)\n }\n return await promisify(this.authorization(payload))\n }\n}\n\n/**\n * @param {*|Promise} callResult\n * @return {Promise}\n */\nfunction promisify(callResult) {\n if (!(callResult instanceof Promise)) {\n if (!callResult)\n return Promise.reject()\n callResult = Promise.resolve(callResult)\n }\n return callResult\n}\n\n/**\n * @typedef {function(TransactionI|Buffer):Promise<TransactionI|Buffer>} ClientAuthorizationCallback - Async authorization callback\n */\n\n/**\n * @typedef {string|ClientAuthorizationCallback} ClientAuthorizationParams - Authorization method, either account secret key or an authorization callback\n */","import {Networks, StrKey} from '@stellar/stellar-sdk'\nimport errors from './errors.js'\nimport {buildEvent} from './events.js'\nimport {validateQuoteRequest} from './quote-request.js'\nimport {processTxRequest} from './tx-processor.js'\nimport {AuthorizationWrapper} from './authorization.js'\n\nexport default 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 {ClientStatus}\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 {SwapQuoteParams}\n * @readonly\n */\n quoteRequest\n /**\n * Last quote received from the sever\n * @type {SwapQuoteResult}\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 = raw.quote\n this.lastQuote.ts = new Date()\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 {SwapQuoteParams} 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\nfunction validateEventType(type) {\n if (!StellarBrokerEvents.includes(type))\n throw errors.unsupportedEventType(type)\n}\n\nexport const StellarBrokerEvents = ['quote', 'paused', 'progress', 'finished', 'error']\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'} ClientStatus\n */\n\n/**\n * @typedef {'quote'|'paused'|'progress'|'finished'|'error'} StellarBrokerClientEvent\n */\n\n/**\n * @typedef {object} SwapQuoteResult\n * @property {string} ts - Quote timestamp formatted as ISO date\n * @property {string} sellingAsset - Asset to sell\n * @property {string} buyingAsset - Asset to buy\n * @property {number} slippageTolerance - Swap slippage tolerance\n * @property {string} sellingAmount - Amount of the selling asset\n * @property {string} [estimatedBuyingAmount] - Estimated amount of buyingAsset to receive\n * @property {{selling: string, buying: string, path: string[]}} [directTrade] - Equivalent direct path_payment trade estimate\n * @property {string} [error] - Error details from the server (for failed quotes)\n */\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","sellingAsset","selling_asset","buyingAsset","buying_asset","sellingAmount","selling_amount","buyingAmount","buying_amount","slippageTolerance","slippage_tolerance","other","res","parseAmount","parseSlippageTolerance","assign","freeze","amount","parsed","parseFloat","isNaN","src","tolerance","signTx","client","tx","authorization","authorize","then","TransactionBuilder","fromXDR","network","signatures","length","catch","e","console","error","AuthorizationWrapper","Keypair","fromSecret","payload","sign","callResult","Promise","reject","resolve","promisify","StellarBrokerClient","partnerKey","emitter","EventTarget","Networks","PUBLIC","trader","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","async","txRequest","xdr","swap","operations","destination","source","validateTransaction","auth","addrAuth","credentials","address","signatureExpirationLedger","ledgerBounds","maxLedger","networkId","hash","Buffer","from","networkPassphrase","preimage","HashIdPreimage","envelopeTypeSorobanAuthorization","HashIdPreimageSorobanAuthorization","nonce","invocation","rootInvocation","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":""}
|
package/package.json
CHANGED
|
@@ -1,31 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stellar-broker/client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Client library for StellarBroker service",
|
|
5
|
+
"author": "team@stellar.broker",
|
|
6
|
+
"homepage": "https://stellar.broker",
|
|
7
|
+
"license": "MIT",
|
|
5
8
|
"type": "module",
|
|
6
9
|
"main": "lib/index.js",
|
|
7
10
|
"module": "src/index.js",
|
|
8
11
|
"types": "src/index.d.ts",
|
|
9
12
|
"scripts": {
|
|
10
|
-
"
|
|
11
|
-
"
|
|
13
|
+
"test": "jest",
|
|
14
|
+
"prepare": "webpack --mode=production --config webpack.config.cjs"
|
|
12
15
|
},
|
|
13
16
|
"repository": {
|
|
14
17
|
"type": "git",
|
|
15
18
|
"url": "https://github.com/stellar-broker/client"
|
|
16
19
|
},
|
|
17
|
-
"author": "StellarBroker",
|
|
18
|
-
"license": "MIT",
|
|
19
20
|
"peerDependencies": {
|
|
20
|
-
"@stellar/stellar-sdk": ">=
|
|
21
|
+
"@stellar/stellar-sdk": ">=13"
|
|
21
22
|
},
|
|
22
23
|
"devDependencies": {
|
|
23
|
-
"@babel/core": "^7.
|
|
24
|
-
"@babel/preset-env": "^7.
|
|
25
|
-
"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",
|
|
26
28
|
"jest": "^29.7.0",
|
|
27
|
-
"typescript": "^5.
|
|
28
|
-
"webpack": "^5.
|
|
29
|
+
"typescript": "^5.7.3",
|
|
30
|
+
"webpack": "^5.97.1",
|
|
29
31
|
"webpack-cli": "^5.1.4",
|
|
30
32
|
"ws": "^8.17.1"
|
|
31
33
|
}
|