@keetanetwork/anchor 0.0.111 → 0.0.113
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/lib/chaining.d.ts +8 -0
- package/lib/chaining.d.ts.map +1 -1
- package/lib/chaining.js +111 -3
- package/lib/chaining.js.map +1 -1
- package/lib/http-server/common.d.ts +3 -2
- package/lib/http-server/common.d.ts.map +1 -1
- package/lib/http-server/common.js +9 -13
- package/lib/http-server/common.js.map +1 -1
- package/lib/http-server/index.d.ts +21 -1
- package/lib/http-server/index.d.ts.map +1 -1
- package/lib/http-server/index.js +84 -36
- package/lib/http-server/index.js.map +1 -1
- package/lib/http-server/replay-guard.d.ts +29 -0
- package/lib/http-server/replay-guard.d.ts.map +1 -0
- package/lib/http-server/replay-guard.js +58 -0
- package/lib/http-server/replay-guard.js.map +1 -0
- package/lib/http-server/request-signing.d.ts +53 -0
- package/lib/http-server/request-signing.d.ts.map +1 -0
- package/lib/http-server/request-signing.js +130 -0
- package/lib/http-server/request-signing.js.map +1 -0
- package/lib/queue/drivers/queue_postgres.d.ts +7 -1
- package/lib/queue/drivers/queue_postgres.d.ts.map +1 -1
- package/lib/queue/drivers/queue_postgres.js +12 -4
- package/lib/queue/drivers/queue_postgres.js.map +1 -1
- package/lib/utils/signing.d.ts +5 -0
- package/lib/utils/signing.d.ts.map +1 -1
- package/lib/utils/signing.js +6 -1
- package/lib/utils/signing.js.map +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/services/asset-movement/client.d.ts +5 -4
- package/services/asset-movement/client.d.ts.map +1 -1
- package/services/asset-movement/client.js +27 -13
- package/services/asset-movement/client.js.map +1 -1
- package/services/asset-movement/common.generated.js +1 -1
- package/services/asset-movement/common.server.generated.js +50 -50
- package/services/asset-movement/server.d.ts.map +1 -1
- package/services/asset-movement/server.js +22 -4
- package/services/asset-movement/server.js.map +1 -1
- package/services/fx/client.d.ts +91 -13
- package/services/fx/client.d.ts.map +1 -1
- package/services/fx/client.js +328 -98
- package/services/fx/client.js.map +1 -1
- package/services/fx/common.d.ts +16 -0
- package/services/fx/common.d.ts.map +1 -1
- package/services/fx/common.js +44 -1
- package/services/fx/common.js.map +1 -1
- package/services/fx/server.d.ts.map +1 -1
- package/services/fx/server.js +45 -38
- package/services/fx/server.js.map +1 -1
- package/services/kyc/client.d.ts +8 -3
- package/services/kyc/client.d.ts.map +1 -1
- package/services/kyc/client.js +24 -23
- package/services/kyc/client.js.map +1 -1
- package/services/kyc/common.d.ts +0 -7
- package/services/kyc/common.d.ts.map +1 -1
- package/services/kyc/common.js +0 -8
- package/services/kyc/common.js.map +1 -1
- package/services/kyc/server.d.ts +3 -1
- package/services/kyc/server.d.ts.map +1 -1
- package/services/kyc/server.js +15 -33
- package/services/kyc/server.js.map +1 -1
- package/services/notification/client.d.ts.map +1 -1
- package/services/notification/client.js +39 -33
- package/services/notification/client.js.map +1 -1
- package/services/notification/server.js +10 -10
- package/services/notification/server.js.map +1 -1
- package/services/storage/client.d.ts +3 -0
- package/services/storage/client.d.ts.map +1 -1
- package/services/storage/client.js +41 -11
- package/services/storage/client.js.map +1 -1
- package/services/storage/server.d.ts.map +1 -1
- package/services/storage/server.js +12 -11
- package/services/storage/server.js.map +1 -1
- package/services/username/client.d.ts +12 -1
- package/services/username/client.d.ts.map +1 -1
- package/services/username/client.js +36 -30
- package/services/username/client.js.map +1 -1
- package/services/username/server.d.ts.map +1 -1
- package/services/username/server.js +7 -6
- package/services/username/server.js.map +1 -1
package/services/fx/client.js
CHANGED
|
@@ -95,6 +95,31 @@ async function getEndpoints(resolver, request, _ignored_account, sharedCriteria,
|
|
|
95
95
|
const retval = Object.fromEntries(await Promise.all(serviceInfoPromises));
|
|
96
96
|
return (retval);
|
|
97
97
|
}
|
|
98
|
+
function resolveDefaultLimits(input) {
|
|
99
|
+
const resolved = {
|
|
100
|
+
maxCostBps: input?.maxCostBps === undefined ? 100 : input.maxCostBps,
|
|
101
|
+
maxEstimateBoundBps: input?.maxEstimateBoundBps === undefined ? 500 : input.maxEstimateBoundBps
|
|
102
|
+
};
|
|
103
|
+
for (const [name, value] of Object.entries(resolved)) {
|
|
104
|
+
if (value !== null && (!Number.isInteger(value) || value < 0)) {
|
|
105
|
+
throw (new Error(`defaultLimits.${name} must be a non-negative integer or null`));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (resolved.maxEstimateBoundBps !== null && resolved.maxEstimateBoundBps > 10000) {
|
|
109
|
+
throw (new Error('defaultLimits.maxEstimateBoundBps must be at most 10000'));
|
|
110
|
+
}
|
|
111
|
+
return (resolved);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The amounts an exchange block sends and receives for a conversion, given
|
|
115
|
+
* the converted amount it commits to and its fee.
|
|
116
|
+
*/
|
|
117
|
+
function exchangeTerms(conversion, convertedAmount, cost) {
|
|
118
|
+
if (conversion.affinity === 'to') {
|
|
119
|
+
return ({ sendAmount: convertedAmount, receiveAmount: conversion.amount, costAmount: cost.amount, costToken: cost.token });
|
|
120
|
+
}
|
|
121
|
+
return ({ sendAmount: conversion.amount, receiveAmount: convertedAmount, costAmount: cost.amount, costToken: cost.token });
|
|
122
|
+
}
|
|
98
123
|
class KeetaFXAnchorBase {
|
|
99
124
|
logger;
|
|
100
125
|
client;
|
|
@@ -109,22 +134,181 @@ export class KeetaFXAnchorProviderBase extends KeetaFXAnchorBase {
|
|
|
109
134
|
conversion;
|
|
110
135
|
options;
|
|
111
136
|
parent;
|
|
137
|
+
#defaultLimits;
|
|
112
138
|
constructor(serviceInfo, providerID, conversion, parent, options) {
|
|
113
139
|
const parentPrivate = parent._internals(KeetaFXAnchorClientAccessToken);
|
|
114
140
|
super(parentPrivate);
|
|
141
|
+
this.#defaultLimits = parentPrivate.defaultLimits;
|
|
115
142
|
this.serviceInfo = serviceInfo;
|
|
116
143
|
this.providerID = providerID;
|
|
117
144
|
this.conversion = conversion;
|
|
118
145
|
this.parent = parent;
|
|
119
146
|
this.options = options;
|
|
120
147
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
148
|
+
/**
|
|
149
|
+
* Checks that the anchor's echoed request matches this conversion and
|
|
150
|
+
* returns `this.conversion`. Throws when any field differs.
|
|
151
|
+
*/
|
|
152
|
+
#bindConversion(echoed) {
|
|
153
|
+
const own = this.conversion;
|
|
154
|
+
const mismatched = [];
|
|
155
|
+
if (!KeetaNetLib.Account.toAccount(echoed.from).comparePublicKey(own.from)) {
|
|
156
|
+
mismatched.push('from');
|
|
157
|
+
}
|
|
158
|
+
if (!KeetaNetLib.Account.toAccount(echoed.to).comparePublicKey(own.to)) {
|
|
159
|
+
mismatched.push('to');
|
|
160
|
+
}
|
|
161
|
+
if (BigInt(echoed.amount) !== own.amount) {
|
|
162
|
+
mismatched.push('amount');
|
|
163
|
+
}
|
|
164
|
+
if (echoed.affinity !== own.affinity) {
|
|
165
|
+
mismatched.push('affinity');
|
|
166
|
+
}
|
|
167
|
+
if (echoed.preferredCostAsset !== own.preferredCostAsset) {
|
|
168
|
+
mismatched.push('preferredCostAsset');
|
|
169
|
+
}
|
|
170
|
+
if (mismatched.length > 0) {
|
|
171
|
+
throw (new FXErrors.ResponseMismatch(`FX provider ${String(this.providerID)} answered for a different conversion than requested (${mismatched.join(', ')})`));
|
|
172
|
+
}
|
|
173
|
+
return (own);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Checks that the anchor's amounts are possible: a positive converted
|
|
177
|
+
* amount and bound, and a fee range that is not negative or reversed.
|
|
178
|
+
*/
|
|
179
|
+
#assertAmounts(convertedAmount, convertedAmountBound, costMin, costMax) {
|
|
180
|
+
const isConvertedInvalid = convertedAmount <= 0n || (convertedAmountBound ?? 1n) <= 0n;
|
|
181
|
+
const isCostInvalid = costMin < 0n || costMax < costMin;
|
|
182
|
+
if (isConvertedInvalid || isCostInvalid) {
|
|
183
|
+
throw (new FXErrors.ResponseMismatch(`FX provider ${String(this.providerID)} gave invalid amounts (converted ${convertedAmount}, bound ${convertedAmountBound ?? 'none'}, fee ${costMin} to ${costMax})`));
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Checks that a non-zero fee is in a token the user expects to pay
|
|
188
|
+
* with: the `from` or `to` token, the network base token, or the
|
|
189
|
+
* requested `preferredCostAsset`. Throws when it is any other token.
|
|
190
|
+
*/
|
|
191
|
+
#assertCostToken(cost) {
|
|
192
|
+
if (cost.amount === 0n) {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const own = this.conversion;
|
|
196
|
+
const allowed = [own.from, own.to, this.client.baseToken];
|
|
197
|
+
if (own.preferredCostAsset !== undefined) {
|
|
198
|
+
allowed.push(KeetaNetLib.Account.fromPublicKeyString(own.preferredCostAsset));
|
|
199
|
+
}
|
|
200
|
+
const isAllowed = allowed.some(function (token) {
|
|
201
|
+
return (token.comparePublicKey(cost.token));
|
|
127
202
|
});
|
|
203
|
+
if (!isAllowed) {
|
|
204
|
+
throw (new FXErrors.ResponseMismatch(`FX provider ${String(this.providerID)} charges its fee in a token that is not part of the conversion (${cost.token.publicKeyString.get()})`));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Checks that an estimate's bound is on the safe side of its converted
|
|
209
|
+
* amount: no more for affinity `from`, no less for affinity `to`.
|
|
210
|
+
* Throws when it is on the other side.
|
|
211
|
+
*/
|
|
212
|
+
#assertEstimateBound(convertedAmount, convertedAmountBound) {
|
|
213
|
+
if (convertedAmountBound === undefined) {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const affinity = this.conversion.affinity;
|
|
217
|
+
const isInvalid = affinity === 'from' ? convertedAmountBound > convertedAmount : convertedAmountBound < convertedAmount;
|
|
218
|
+
if (isInvalid) {
|
|
219
|
+
throw (new FXErrors.ResponseMismatch(`FX provider ${String(this.providerID)} gave an estimate bound of ${convertedAmountBound} that is on the wrong side of its converted amount ${convertedAmount} for affinity "${affinity}"`));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Checks every amount the anchor sets in the block against the
|
|
224
|
+
* caller's limits and the client's default caps. Both must hold, so
|
|
225
|
+
* a limit copied from the anchor's own quote cannot lift a default.
|
|
226
|
+
* Throws when an amount is not bounded or is past its bound. See
|
|
227
|
+
* {@link KeetaFXAnchorExchangeLimits}.
|
|
228
|
+
*/
|
|
229
|
+
#assertSigningLimits(terms, estimate, limits) {
|
|
230
|
+
this.#assertAmountLimits(terms, limits);
|
|
231
|
+
if (estimate !== undefined) {
|
|
232
|
+
this.#assertBoundCap(estimate.convertedAmount, estimate.convertedAmountBound);
|
|
233
|
+
}
|
|
234
|
+
this.#assertCostLimits(terms, limits?.maxCost);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Checks the amounts sent and received against the caller's limits.
|
|
238
|
+
* The side the provider sets must have a limit: `maxSend` for affinity
|
|
239
|
+
* `to`, `minReceive` for affinity `from`.
|
|
240
|
+
*/
|
|
241
|
+
#assertAmountLimits(terms, limits) {
|
|
242
|
+
const affinity = this.conversion.affinity;
|
|
243
|
+
if (affinity === 'to' && limits?.maxSend === undefined) {
|
|
244
|
+
throw (new FXErrors.ExchangeLimitExceeded('FX exchange with affinity "to" needs limits.maxSend, because the provider sets the amount sent'));
|
|
245
|
+
}
|
|
246
|
+
if (affinity === 'from' && limits?.minReceive === undefined) {
|
|
247
|
+
throw (new FXErrors.ExchangeLimitExceeded('FX exchange with affinity "from" needs limits.minReceive, because the provider sets the amount received'));
|
|
248
|
+
}
|
|
249
|
+
if (limits?.maxSend !== undefined && terms.sendAmount > limits.maxSend) {
|
|
250
|
+
throw (new FXErrors.ExchangeLimitExceeded(`FX exchange would send ${terms.sendAmount}, more than the limit of ${limits.maxSend}`));
|
|
251
|
+
}
|
|
252
|
+
if (limits?.minReceive !== undefined && terms.receiveAmount < limits.minReceive) {
|
|
253
|
+
throw (new FXErrors.ExchangeLimitExceeded(`FX exchange would receive ${terms.receiveAmount}, less than the limit of ${limits.minReceive}`));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Checks that an estimate's bound is within the default cap of its
|
|
258
|
+
* converted amount.
|
|
259
|
+
*/
|
|
260
|
+
#assertBoundCap(convertedAmount, convertedAmountBound) {
|
|
261
|
+
const maxBps = this.#defaultLimits.maxEstimateBoundBps;
|
|
262
|
+
if (maxBps === null) {
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const distance = convertedAmount > convertedAmountBound ? convertedAmount - convertedAmountBound : convertedAmountBound - convertedAmount;
|
|
266
|
+
if (distance * 10000n > convertedAmount * BigInt(maxBps)) {
|
|
267
|
+
throw (new FXErrors.ExchangeLimitExceeded(`FX estimate bound of ${convertedAmountBound} is more than ${maxBps} basis points from its converted amount ${convertedAmount}; raise defaultLimits.maxEstimateBoundBps to accept it`));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Checks a non-zero fee against the caller's `maxCost` and, for a fee
|
|
272
|
+
* in `from` or `to`, against the default fee cap. A fee in any other
|
|
273
|
+
* token needs `maxCost`.
|
|
274
|
+
*/
|
|
275
|
+
#assertCostLimits(terms, maxCost) {
|
|
276
|
+
if (terms.costAmount === 0n) {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (maxCost !== undefined) {
|
|
280
|
+
if (!maxCost.token.comparePublicKey(terms.costToken)) {
|
|
281
|
+
throw (new FXErrors.ExchangeLimitExceeded(`FX exchange fee is in ${terms.costToken.publicKeyString.get()}, not in the limit token ${maxCost.token.publicKeyString.get()}`));
|
|
282
|
+
}
|
|
283
|
+
if (terms.costAmount > maxCost.amount) {
|
|
284
|
+
throw (new FXErrors.ExchangeLimitExceeded(`FX exchange fee of ${terms.costAmount} is more than the limit of ${maxCost.amount}`));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const base = this.#costBase(terms);
|
|
288
|
+
if (base === null) {
|
|
289
|
+
if (maxCost === undefined) {
|
|
290
|
+
throw (new FXErrors.ExchangeLimitExceeded(`FX exchange fee is in ${terms.costToken.publicKeyString.get()}, which is not part of the conversion; set limits.maxCost to accept it`));
|
|
291
|
+
}
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const maxBps = this.#defaultLimits.maxCostBps;
|
|
295
|
+
if (maxBps !== null && terms.costAmount * 10000n > base * BigInt(maxBps)) {
|
|
296
|
+
throw (new FXErrors.ExchangeLimitExceeded(`FX exchange fee of ${terms.costAmount} is more than ${maxBps} basis points of ${base}; raise defaultLimits.maxCostBps to accept it`));
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* The amount a fee is capped against: what the conversion sends when
|
|
301
|
+
* the fee is in `from`, what it receives when the fee is in `to`, or
|
|
302
|
+
* `null` for a fee in any other token.
|
|
303
|
+
*/
|
|
304
|
+
#costBase(terms) {
|
|
305
|
+
if (terms.costToken.comparePublicKey(this.conversion.from)) {
|
|
306
|
+
return (terms.sendAmount);
|
|
307
|
+
}
|
|
308
|
+
if (terms.costToken.comparePublicKey(this.conversion.to)) {
|
|
309
|
+
return (terms.receiveAmount);
|
|
310
|
+
}
|
|
311
|
+
return (null);
|
|
128
312
|
}
|
|
129
313
|
async #parseResponseError(data) {
|
|
130
314
|
if (typeof data !== 'object' || data === null) {
|
|
@@ -176,8 +360,8 @@ export class KeetaFXAnchorProviderBase extends KeetaFXAnchorBase {
|
|
|
176
360
|
}
|
|
177
361
|
this.logger?.debug(`FX estimate request successful, to provider ${estimateURL} for ${JSON.stringify(KeetaNetLib.Utils.Conversion.toJSONSerializable(this.conversion))}`);
|
|
178
362
|
const estimateJSON = requestInformationJSON.estimate;
|
|
179
|
-
|
|
180
|
-
request: this.#
|
|
363
|
+
const estimate = {
|
|
364
|
+
request: this.#bindConversion(estimateJSON.request),
|
|
181
365
|
convertedAmount: BigInt(estimateJSON.convertedAmount),
|
|
182
366
|
expectedCost: {
|
|
183
367
|
min: BigInt(estimateJSON.expectedCost.min),
|
|
@@ -204,7 +388,12 @@ export class KeetaFXAnchorProviderBase extends KeetaFXAnchorBase {
|
|
|
204
388
|
});
|
|
205
389
|
}
|
|
206
390
|
})()
|
|
207
|
-
}
|
|
391
|
+
};
|
|
392
|
+
const estimateCost = { amount: estimate.expectedCost.max, token: estimate.expectedCost.token };
|
|
393
|
+
this.#assertAmounts(estimate.convertedAmount, estimate.convertedAmountBound, estimate.expectedCost.min, estimate.expectedCost.max);
|
|
394
|
+
this.#assertEstimateBound(estimate.convertedAmount, estimate.convertedAmountBound);
|
|
395
|
+
this.#assertCostToken(estimateCost);
|
|
396
|
+
return (estimate);
|
|
208
397
|
}
|
|
209
398
|
/**
|
|
210
399
|
* Get a quote from the provider. If an estimate is provided, it will
|
|
@@ -248,8 +437,8 @@ export class KeetaFXAnchorProviderBase extends KeetaFXAnchorBase {
|
|
|
248
437
|
}
|
|
249
438
|
this.logger?.debug(`FX quote request successful, to provider ${serviceURL} for ${JSON.stringify(KeetaNetLib.Utils.Conversion.toJSONSerializable(this.conversion))}`);
|
|
250
439
|
const quoteJSON = requestInformationJSON.quote;
|
|
251
|
-
|
|
252
|
-
request: this.#
|
|
440
|
+
const quote = {
|
|
441
|
+
request: this.#bindConversion(quoteJSON.request),
|
|
253
442
|
account: KeetaNetLib.Account.fromPublicKeyString(quoteJSON.account),
|
|
254
443
|
convertedAmount: BigInt(quoteJSON.convertedAmount),
|
|
255
444
|
cost: {
|
|
@@ -257,99 +446,112 @@ export class KeetaFXAnchorProviderBase extends KeetaFXAnchorBase {
|
|
|
257
446
|
token: KeetaNetLib.Account.fromPublicKeyString(quoteJSON.cost.token)
|
|
258
447
|
},
|
|
259
448
|
signed: quoteJSON.signed
|
|
260
|
-
}
|
|
449
|
+
};
|
|
450
|
+
this.#assertAmounts(quote.convertedAmount, undefined, quote.cost.amount, quote.cost.amount);
|
|
451
|
+
this.#assertCostToken(quote.cost);
|
|
452
|
+
return (quote);
|
|
261
453
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
}
|
|
285
|
-
else {
|
|
286
|
-
liquidityProvider = input.quote.account;
|
|
287
|
-
request = input.quote.request;
|
|
288
|
-
convertedAmountBound = input.quote.convertedAmount;
|
|
289
|
-
}
|
|
290
|
-
let sendAmount;
|
|
291
|
-
let receiveAmount;
|
|
292
|
-
if (request.affinity === 'to') {
|
|
293
|
-
sendAmount = convertedAmountBound;
|
|
294
|
-
receiveAmount = request.amount;
|
|
295
|
-
}
|
|
296
|
-
else if (request.affinity === 'from') {
|
|
297
|
-
sendAmount = request.amount;
|
|
298
|
-
receiveAmount = convertedAmountBound;
|
|
299
|
-
}
|
|
300
|
-
else {
|
|
301
|
-
throw (new Error('Invalid affinity in conversion request'));
|
|
302
|
-
}
|
|
303
|
-
/* Construct the required operations for the swap request */
|
|
304
|
-
const builder = this.client.initBuilder(this.options);
|
|
305
|
-
let costAmount = 0n;
|
|
306
|
-
let costToken;
|
|
307
|
-
if ('quote' in input) {
|
|
308
|
-
costAmount = input.quote.cost.amount;
|
|
309
|
-
costToken = input.quote.cost.token;
|
|
310
|
-
}
|
|
311
|
-
else {
|
|
312
|
-
costAmount = input.estimate.expectedCost.max;
|
|
313
|
-
costToken = input.estimate.expectedCost.token;
|
|
314
|
-
}
|
|
315
|
-
/*
|
|
316
|
-
* When the fee is charged in the same token as the swap send,
|
|
317
|
-
* combine them into a single SEND. The principal send carries an
|
|
318
|
-
* external, so the builder will not merge a separate cost send
|
|
319
|
-
* of the same token into that operation.
|
|
320
|
-
*/
|
|
321
|
-
const costUsesSendToken = costAmount > 0n && costToken.comparePublicKey(request.from);
|
|
322
|
-
if (costAmount > 0n && !costUsesSendToken) {
|
|
323
|
-
builder.send(liquidityProvider, costAmount, costToken);
|
|
324
|
-
}
|
|
325
|
-
builder.receive(liquidityProvider, receiveAmount, request.to, request.affinity === 'to');
|
|
326
|
-
/*
|
|
327
|
-
* Tag the principal send with an anchor external naming the FX
|
|
328
|
-
* provider and a client-chosen correlation id.
|
|
329
|
-
*/
|
|
330
|
-
const correlationId = crypto.randomUUID();
|
|
331
|
-
const externalBuilder = new AnchorExternalBuilder().setAnchor(liquidityProvider, { transactionId: correlationId });
|
|
332
|
-
for (const inputReference of options?.inputs ?? []) {
|
|
333
|
-
externalBuilder.addInput(inputReference.blockHash, inputReference.operationIndex);
|
|
454
|
+
/**
|
|
455
|
+
* Checks the terms of a quote or estimate as `createExchange` would
|
|
456
|
+
* before it signs, without building or sending anything. Throws the
|
|
457
|
+
* same errors `createExchange` would.
|
|
458
|
+
*/
|
|
459
|
+
checkExchange(input, options) {
|
|
460
|
+
this.#bindConversion('quote' in input ? input.quote.request : input.estimate.request);
|
|
461
|
+
this.#checkExchangeTerms(input, options?.limits);
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Every check `createExchange` runs on the anchor's terms before it
|
|
465
|
+
* builds the block. Returns the terms the block commits to.
|
|
466
|
+
*/
|
|
467
|
+
#checkExchangeTerms(input, limits) {
|
|
468
|
+
let liquidityProvider;
|
|
469
|
+
let convertedAmountBound;
|
|
470
|
+
let costAmount;
|
|
471
|
+
let costToken;
|
|
472
|
+
let estimateTerms;
|
|
473
|
+
if ('estimate' in input) {
|
|
474
|
+
if (input.estimate.canPerformExchange === false) {
|
|
475
|
+
throw (new KeetaAnchorUserError('The provided estimate indicates that the exchange cannot be performed'));
|
|
334
476
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
builder.send(liquidityProvider, taggedSendAmount, request.from, external);
|
|
338
|
-
const blocks = await builder.computeBlocks();
|
|
339
|
-
if (blocks.blocks.length !== 1) {
|
|
340
|
-
throw (new Error('Creating Swap Generated more than 1 block'));
|
|
477
|
+
if (input.estimate.requiresQuote !== false) {
|
|
478
|
+
throw (new FXErrors.QuoteRequired());
|
|
341
479
|
}
|
|
342
|
-
|
|
480
|
+
liquidityProvider = input.estimate.account;
|
|
481
|
+
convertedAmountBound = input.estimate.convertedAmountBound ?? input.estimate.convertedAmount;
|
|
482
|
+
costAmount = input.estimate.expectedCost.max;
|
|
483
|
+
costToken = input.estimate.expectedCost.token;
|
|
484
|
+
this.#assertAmounts(input.estimate.convertedAmount, input.estimate.convertedAmountBound, input.estimate.expectedCost.min, costAmount);
|
|
485
|
+
this.#assertEstimateBound(input.estimate.convertedAmount, input.estimate.convertedAmountBound);
|
|
486
|
+
estimateTerms = { convertedAmount: input.estimate.convertedAmount, convertedAmountBound: convertedAmountBound };
|
|
343
487
|
}
|
|
344
|
-
|
|
488
|
+
else {
|
|
489
|
+
liquidityProvider = input.quote.account;
|
|
490
|
+
convertedAmountBound = input.quote.convertedAmount;
|
|
491
|
+
costAmount = input.quote.cost.amount;
|
|
492
|
+
costToken = input.quote.cost.token;
|
|
493
|
+
this.#assertAmounts(input.quote.convertedAmount, undefined, costAmount, costAmount);
|
|
494
|
+
}
|
|
495
|
+
this.#assertCostToken({ amount: costAmount, token: costToken });
|
|
496
|
+
const terms = exchangeTerms(this.conversion, convertedAmountBound, { amount: costAmount, token: costToken });
|
|
497
|
+
this.#assertSigningLimits(terms, estimateTerms, limits);
|
|
498
|
+
return ({ liquidityProvider, terms });
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Builds the swap block from this conversion and the anchor's checked
|
|
502
|
+
* terms. Throws when a term fails a check; see `checkExchange`.
|
|
503
|
+
*/
|
|
504
|
+
async #buildSwapBlock(input, options) {
|
|
505
|
+
const request = this.conversion;
|
|
506
|
+
const { liquidityProvider, terms } = this.#checkExchangeTerms(input, options?.limits);
|
|
507
|
+
const { sendAmount, receiveAmount, costAmount, costToken } = terms;
|
|
508
|
+
/* Construct the required operations for the swap request */
|
|
509
|
+
const builder = this.client.initBuilder(this.options);
|
|
510
|
+
/*
|
|
511
|
+
* When the fee is charged in the same token as the swap send,
|
|
512
|
+
* combine them into a single SEND. The principal send carries an
|
|
513
|
+
* external, so the builder will not merge a separate cost send
|
|
514
|
+
* of the same token into that operation.
|
|
515
|
+
*/
|
|
516
|
+
const costUsesSendToken = costAmount > 0n && costToken.comparePublicKey(request.from);
|
|
517
|
+
if (costAmount > 0n && !costUsesSendToken) {
|
|
518
|
+
builder.send(liquidityProvider, costAmount, costToken);
|
|
519
|
+
}
|
|
520
|
+
builder.receive(liquidityProvider, receiveAmount, request.to, request.affinity === 'to');
|
|
521
|
+
/*
|
|
522
|
+
* Tag the principal send with an anchor external naming the FX
|
|
523
|
+
* provider and a client-chosen correlation id.
|
|
524
|
+
*/
|
|
525
|
+
const correlationId = crypto.randomUUID();
|
|
526
|
+
const externalBuilder = new AnchorExternalBuilder().setAnchor(liquidityProvider, { transactionId: correlationId });
|
|
527
|
+
for (const inputReference of options?.inputs ?? []) {
|
|
528
|
+
externalBuilder.addInput(inputReference.blockHash, inputReference.operationIndex);
|
|
529
|
+
}
|
|
530
|
+
const external = await externalBuilder.build();
|
|
531
|
+
const taggedSendAmount = costUsesSendToken ? sendAmount + costAmount : sendAmount;
|
|
532
|
+
builder.send(liquidityProvider, taggedSendAmount, request.from, external);
|
|
533
|
+
const blocks = await builder.computeBlocks();
|
|
534
|
+
if (blocks.blocks.length !== 1) {
|
|
535
|
+
throw (new Error('Creating Swap Generated more than 1 block'));
|
|
536
|
+
}
|
|
537
|
+
const swapBlock = blocks.blocks[0];
|
|
538
|
+
if (swapBlock === undefined) {
|
|
345
539
|
throw (new Error('User Swap Block is undefined'));
|
|
346
540
|
}
|
|
541
|
+
return (swapBlock);
|
|
542
|
+
}
|
|
543
|
+
async createExchange(input, block, options) {
|
|
544
|
+
const request = this.#bindConversion('quote' in input ? input.quote.request : input.estimate.request);
|
|
545
|
+
if (block !== undefined && options?.limits !== undefined) {
|
|
546
|
+
throw (new KeetaAnchorUserError('createExchange applies limits only to a block it builds, not to a given block'));
|
|
547
|
+
}
|
|
548
|
+
const swapBlock = block ?? await this.#buildSwapBlock(input, options);
|
|
347
549
|
let bodyAdditionalData;
|
|
348
550
|
if ('quote' in input) {
|
|
349
|
-
bodyAdditionalData = { quote: input.quote };
|
|
551
|
+
bodyAdditionalData = { quote: { ...input.quote, request } };
|
|
350
552
|
}
|
|
351
553
|
else {
|
|
352
|
-
bodyAdditionalData = { request
|
|
554
|
+
bodyAdditionalData = { request };
|
|
353
555
|
}
|
|
354
556
|
const serviceURL = await this.#getEndpoint('createExchange');
|
|
355
557
|
const requestInformation = await fetch(serviceURL, {
|
|
@@ -365,7 +567,11 @@ export class KeetaFXAnchorProviderBase extends KeetaFXAnchorBase {
|
|
|
365
567
|
}
|
|
366
568
|
})
|
|
367
569
|
});
|
|
368
|
-
const
|
|
570
|
+
const exchange = await this.#parseExchangeResponse(await requestInformation.json(), swapBlock);
|
|
571
|
+
this.logger?.debug(`FX exchange request successful, to provider ${serviceURL} for ${swapBlock.hash.toString()}`);
|
|
572
|
+
return (exchange);
|
|
573
|
+
}
|
|
574
|
+
async #parseExchangeResponse(requestInformationJSON, swapBlock) {
|
|
369
575
|
// Ensure status defaults to 'completed' if not provided (for backward compatibility)
|
|
370
576
|
if (typeof requestInformationJSON === 'object' && requestInformationJSON !== null && !('status' in requestInformationJSON)) {
|
|
371
577
|
Object.assign(requestInformationJSON, { status: 'completed' });
|
|
@@ -378,7 +584,6 @@ export class KeetaFXAnchorProviderBase extends KeetaFXAnchorBase {
|
|
|
378
584
|
if (!requestInformationJSON.ok) {
|
|
379
585
|
throw (await this.#parseResponseError(requestInformationJSON));
|
|
380
586
|
}
|
|
381
|
-
this.logger?.debug(`FX exchange request successful, to provider ${serviceURL} for ${swapBlock.hash.toString()}`);
|
|
382
587
|
return (requestInformationJSON);
|
|
383
588
|
}
|
|
384
589
|
async getMarketPrices(request) {
|
|
@@ -463,6 +668,13 @@ class KeetaFXAnchorQuoteWithProvider {
|
|
|
463
668
|
const exchange = await this.provider.createExchange({ quote: this.quote }, block, options);
|
|
464
669
|
return (new KeetaFXAnchorExchangeWithProvider(this.provider, exchange));
|
|
465
670
|
}
|
|
671
|
+
/**
|
|
672
|
+
* Checks this quote's terms as `createExchange` would, without
|
|
673
|
+
* signing. See {@link KeetaFXAnchorProviderBase.checkExchange}.
|
|
674
|
+
*/
|
|
675
|
+
checkExchange(options) {
|
|
676
|
+
this.provider.checkExchange({ quote: this.quote }, options);
|
|
677
|
+
}
|
|
466
678
|
/**
|
|
467
679
|
* Re-fetch the quote from the provider.
|
|
468
680
|
*
|
|
@@ -492,6 +704,13 @@ class KeetaFXAnchorEstimateWithProvider {
|
|
|
492
704
|
const exchange = await this.provider.createExchange({ estimate: this.estimate }, block, options);
|
|
493
705
|
return (new KeetaFXAnchorExchangeWithProvider(this.provider, exchange));
|
|
494
706
|
}
|
|
707
|
+
/**
|
|
708
|
+
* Checks this estimate's terms as `createExchange` would, without
|
|
709
|
+
* signing. See {@link KeetaFXAnchorProviderBase.checkExchange}.
|
|
710
|
+
*/
|
|
711
|
+
checkExchange(options) {
|
|
712
|
+
this.provider.checkExchange({ estimate: this.estimate }, options);
|
|
713
|
+
}
|
|
495
714
|
/**
|
|
496
715
|
* Re-fetch the estimate from the provider.
|
|
497
716
|
*
|
|
@@ -522,6 +741,7 @@ class KeetaFXAnchorClient extends KeetaFXAnchorBase {
|
|
|
522
741
|
#signer;
|
|
523
742
|
#account;
|
|
524
743
|
#getPricesBatching;
|
|
744
|
+
#defaultLimits;
|
|
525
745
|
#pendingGetMarketPricesBatches = new Map();
|
|
526
746
|
static #resolveGetPricesBatching(input) {
|
|
527
747
|
if (input === false) {
|
|
@@ -542,6 +762,7 @@ class KeetaFXAnchorClient extends KeetaFXAnchorBase {
|
|
|
542
762
|
this.resolver = config.resolver ?? getDefaultResolver(client, config);
|
|
543
763
|
this.id = config.id ?? crypto.randomUUID();
|
|
544
764
|
this.#getPricesBatching = KeetaFXAnchorClient.#resolveGetPricesBatching(config.getPricesBatching);
|
|
765
|
+
this.#defaultLimits = resolveDefaultLimits(config.defaultLimits);
|
|
545
766
|
if (!Number.isFinite(this.#getPricesBatching.waitMs) || this.#getPricesBatching.waitMs < 0) {
|
|
546
767
|
throw (new Error('getPricesBatching.waitMs must be a non-negative finite number'));
|
|
547
768
|
}
|
|
@@ -796,7 +1017,12 @@ class KeetaFXAnchorClient extends KeetaFXAnchorBase {
|
|
|
796
1017
|
return (new KeetaFXAnchorEstimateWithProvider(provider, estimate));
|
|
797
1018
|
}
|
|
798
1019
|
catch (error) {
|
|
799
|
-
|
|
1020
|
+
if (FXErrors.ResponseMismatch.isInstance(error)) {
|
|
1021
|
+
this.logger?.warn(`Ignoring estimate from FX provider ${String(provider.providerID)}:`, error);
|
|
1022
|
+
}
|
|
1023
|
+
else {
|
|
1024
|
+
this.logger?.error(`Failed to get estimate from provider ${String(provider.providerID)}:`, error);
|
|
1025
|
+
}
|
|
800
1026
|
return (null);
|
|
801
1027
|
}
|
|
802
1028
|
}));
|
|
@@ -822,6 +1048,9 @@ class KeetaFXAnchorClient extends KeetaFXAnchorBase {
|
|
|
822
1048
|
return ({ provider, quote: new KeetaFXAnchorQuoteWithProvider(provider, quote) });
|
|
823
1049
|
}
|
|
824
1050
|
catch (error) {
|
|
1051
|
+
if (FXErrors.ResponseMismatch.isInstance(error)) {
|
|
1052
|
+
this.logger?.warn(`Ignoring quote from FX provider ${String(provider.providerID)}:`, error);
|
|
1053
|
+
}
|
|
825
1054
|
return ({ provider, quote: null, error });
|
|
826
1055
|
}
|
|
827
1056
|
})));
|
|
@@ -1086,7 +1315,8 @@ class KeetaFXAnchorClient extends KeetaFXAnchorBase {
|
|
|
1086
1315
|
logger: this.logger,
|
|
1087
1316
|
client: this.client,
|
|
1088
1317
|
signer: this.#signer,
|
|
1089
|
-
account: this.#account
|
|
1318
|
+
account: this.#account,
|
|
1319
|
+
defaultLimits: this.#defaultLimits
|
|
1090
1320
|
});
|
|
1091
1321
|
}
|
|
1092
1322
|
}
|