From 3a0004b486f767181171feb4ba1bc6786863989c Mon Sep 17 00:00:00 2001 From: Tiago Silva Date: Mon, 10 Jul 2023 09:54:01 +0100 Subject: [PATCH] Remove sdk files not needed --- src/dex/carbon/sdk/chain-cache/ChainCache.js | 698 --------- src/dex/carbon/sdk/chain-cache/ChainSync.js | 708 --------- src/dex/carbon/sdk/chain-cache/index.js | 74 - src/dex/carbon/sdk/chain-cache/types.js | 2 - src/dex/carbon/sdk/chain-cache/utils.js | 58 - src/dex/carbon/sdk/common/logger.js | 98 -- src/dex/carbon/sdk/common/types.js | 8 - src/dex/carbon/sdk/contracts-api/Composer.js | 157 -- src/dex/carbon/sdk/contracts-api/Contracts.js | 70 - .../carbon/sdk/contracts-api/ContractsApi.js | 32 - src/dex/carbon/sdk/contracts-api/Reader.js | 433 ------ src/dex/carbon/sdk/contracts-api/config.js | 8 - src/dex/carbon/sdk/contracts-api/index.js | 34 - src/dex/carbon/sdk/contracts-api/types.js | 2 - src/dex/carbon/sdk/contracts-api/utils.js | 221 --- src/dex/carbon/sdk/index.js | 44 - .../carbon/sdk/strategy-management/Toolkit.js | 1369 ----------------- .../carbon/sdk/strategy-management/index.js | 34 - .../carbon/sdk/strategy-management/stats.js | 62 - .../carbon/sdk/strategy-management/utils.js | 420 ----- src/dex/carbon/sdk/trade-matcher/index.js | 33 - src/dex/carbon/sdk/trade-matcher/match.js | 299 ---- src/dex/carbon/sdk/trade-matcher/trade.js | 136 -- src/dex/carbon/sdk/trade-matcher/utils.js | 18 - src/dex/carbon/sdk/utils/decimals.js | 166 -- src/dex/carbon/sdk/utils/encoders.js | 83 - src/dex/carbon/sdk/utils/index.js | 36 - src/dex/carbon/sdk/utils/numerics.js | 77 - src/dex/carbon/sdk/utils/serializers.js | 126 -- 29 files changed, 5506 deletions(-) delete mode 100644 src/dex/carbon/sdk/chain-cache/ChainCache.js delete mode 100644 src/dex/carbon/sdk/chain-cache/ChainSync.js delete mode 100644 src/dex/carbon/sdk/chain-cache/index.js delete mode 100644 src/dex/carbon/sdk/chain-cache/types.js delete mode 100644 src/dex/carbon/sdk/chain-cache/utils.js delete mode 100644 src/dex/carbon/sdk/common/logger.js delete mode 100644 src/dex/carbon/sdk/common/types.js delete mode 100644 src/dex/carbon/sdk/contracts-api/Composer.js delete mode 100644 src/dex/carbon/sdk/contracts-api/Contracts.js delete mode 100644 src/dex/carbon/sdk/contracts-api/ContractsApi.js delete mode 100644 src/dex/carbon/sdk/contracts-api/Reader.js delete mode 100644 src/dex/carbon/sdk/contracts-api/config.js delete mode 100644 src/dex/carbon/sdk/contracts-api/index.js delete mode 100644 src/dex/carbon/sdk/contracts-api/types.js delete mode 100644 src/dex/carbon/sdk/contracts-api/utils.js delete mode 100644 src/dex/carbon/sdk/index.js delete mode 100644 src/dex/carbon/sdk/strategy-management/Toolkit.js delete mode 100644 src/dex/carbon/sdk/strategy-management/index.js delete mode 100644 src/dex/carbon/sdk/strategy-management/stats.js delete mode 100644 src/dex/carbon/sdk/strategy-management/utils.js delete mode 100644 src/dex/carbon/sdk/trade-matcher/index.js delete mode 100644 src/dex/carbon/sdk/trade-matcher/match.js delete mode 100644 src/dex/carbon/sdk/trade-matcher/trade.js delete mode 100644 src/dex/carbon/sdk/trade-matcher/utils.js delete mode 100644 src/dex/carbon/sdk/utils/decimals.js delete mode 100644 src/dex/carbon/sdk/utils/encoders.js delete mode 100644 src/dex/carbon/sdk/utils/index.js delete mode 100644 src/dex/carbon/sdk/utils/numerics.js delete mode 100644 src/dex/carbon/sdk/utils/serializers.js diff --git a/src/dex/carbon/sdk/chain-cache/ChainCache.js b/src/dex/carbon/sdk/chain-cache/ChainCache.js deleted file mode 100644 index 237e0269c..000000000 --- a/src/dex/carbon/sdk/chain-cache/ChainCache.js +++ /dev/null @@ -1,698 +0,0 @@ -'use strict'; -var __extends = - (this && this.__extends) || - (function () { - var extendStatics = function (d, b) { - extendStatics = - Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && - function (d, b) { - d.__proto__ = b; - }) || - function (d, b) { - for (var p in b) - if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; - }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== 'function' && b !== null) - throw new TypeError( - 'Class extends value ' + String(b) + ' is not a constructor or null', - ); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = - b === null - ? Object.create(b) - : ((__.prototype = b.prototype), new __()); - }; - })(); -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator['throw'](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done - ? resolve(result.value) - : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; -var __generator = - (this && this.__generator) || - function (thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [], - }, - f, - y, - t, - g; - return ( - (g = { next: verb(0), throw: verb(1), return: verb(2) }), - typeof Symbol === 'function' && - (g[Symbol.iterator] = function () { - return this; - }), - g - ); - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError('Generator is already executing.'); - while ((g && ((g = 0), op[0] && (_ = 0)), _)) - try { - if ( - ((f = 1), - y && - (t = - op[0] & 2 - ? y['return'] - : op[0] - ? y['throw'] || ((t = y['return']) && t.call(y), 0) - : y.next) && - !(t = t.call(y, op[1])).done) - ) - return t; - if (((y = 0), t)) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if ( - !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && - (op[0] === 6 || op[0] === 2) - ) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.ChainCache = void 0; -var events_1 = require('events'); -var utils_1 = require('./utils'); -var serializers_1 = require('../utils/serializers'); -var logger_1 = require('../common/logger'); -var logger = new logger_1.Logger('ChainCache.ts'); -var schemeVersion = 4; // bump this when the serialization format changes -var ChainCache = /** @class */ (function (_super) { - __extends(ChainCache, _super); - function ChainCache() { - var _this = (_super !== null && _super.apply(this, arguments)) || this; - //#region private members - _this._strategiesByPair = {}; - _this._strategiesById = {}; - _this._ordersByDirectedPair = {}; - _this._latestBlockNumber = 0; - _this._latestTradesByPair = {}; - _this._latestTradesByDirectedPair = {}; - _this._blocksMetadata = []; - return _this; - //#endregion cache updates - } - //#endregion private members - //#region serialization for persistent caching - ChainCache.fromSerialized = function (serializedCache) { - try { - var cache = new ChainCache(); - cache._deserialize(serializedCache); - return cache; - } catch (e) { - logger.error('Failed to deserialize cache, returning clear cache', e); - } - return new ChainCache(); - }; - ChainCache.prototype._deserialize = function (serializedCache) { - var parsedCache = JSON.parse(serializedCache); - var version = parsedCache.schemeVersion; - if (version !== schemeVersion) { - logger.log( - 'Cache version mismatch, ignoring cache. Expected', - schemeVersion, - 'got', - version, - 'This may be due to a breaking change in the cache format since it was last persisted.', - ); - return; - } - this._strategiesByPair = Object.entries( - parsedCache.strategiesByPair, - ).reduce(function (acc, _a) { - var key = _a[0], - strategies = _a[1]; - acc[key] = strategies.map(serializers_1.encodedStrategyStrToBN); - return acc; - }, {}); - this._strategiesById = Object.entries(parsedCache.strategiesById).reduce( - function (acc, _a) { - var key = _a[0], - strategy = _a[1]; - acc[key] = (0, serializers_1.encodedStrategyStrToBN)(strategy); - return acc; - }, - {}, - ); - this._ordersByDirectedPair = Object.entries( - parsedCache.ordersByDirectedPair, - ).reduce(function (acc, _a) { - var directedPairKey = _a[0], - orderMap = _a[1]; - acc[directedPairKey] = Object.entries(orderMap).reduce(function ( - acc, - _a, - ) { - var strategyId = _a[0], - order = _a[1]; - acc[strategyId] = (0, serializers_1.encodedOrderStrToBN)(order); - return acc; - }, - {}); - return acc; - }, {}); - this._latestBlockNumber = parsedCache.latestBlockNumber; - this._latestTradesByPair = parsedCache.latestTradesByPair; - this._latestTradesByDirectedPair = parsedCache.latestTradesByDirectedPair; - this._blocksMetadata = parsedCache.blocksMetadata; - }; - ChainCache.prototype.serialize = function () { - var dump = { - schemeVersion: schemeVersion, - strategiesByPair: Object.entries(this._strategiesByPair).reduce(function ( - acc, - _a, - ) { - var key = _a[0], - strategies = _a[1]; - acc[key] = strategies.map(serializers_1.encodedStrategyBNToStr); - return acc; - }, - {}), - strategiesById: Object.entries(this._strategiesById).reduce(function ( - acc, - _a, - ) { - var key = _a[0], - strategy = _a[1]; - acc[key] = (0, serializers_1.encodedStrategyBNToStr)(strategy); - return acc; - }, - {}), - ordersByDirectedPair: Object.entries(this._ordersByDirectedPair).reduce( - function (acc, _a) { - var directedPairKey = _a[0], - orderMap = _a[1]; - acc[directedPairKey] = Object.entries(orderMap).reduce(function ( - acc, - _a, - ) { - var strategyId = _a[0], - order = _a[1]; - acc[strategyId] = (0, serializers_1.encodedOrderBNToStr)(order); - return acc; - }, - {}); - return acc; - }, - {}, - ), - latestBlockNumber: this._latestBlockNumber, - latestTradesByPair: this._latestTradesByPair, - latestTradesByDirectedPair: this._latestTradesByDirectedPair, - blocksMetadata: this._blocksMetadata, - }; - return JSON.stringify(dump); - }; - //#endregion serialization for persistent caching - ChainCache.prototype.setCacheMissHandler = function (handler) { - this._handleCacheMiss = handler; - }; - ChainCache.prototype._checkAndHandleCacheMiss = function (token0, token1) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this._handleCacheMiss || this.hasCachedPair(token0, token1)) - return [2 /*return*/]; - logger.debug('Cache miss for pair', token0, token1); - return [4 /*yield*/, this._handleCacheMiss(token0, token1)]; - case 1: - _a.sent(); - logger.debug('Cache miss for pair', token0, token1, 'resolved'); - return [2 /*return*/]; - } - }); - }); - }; - ChainCache.prototype.clear = function () { - var pairs = Object.keys(this._strategiesByPair).map(utils_1.fromPairKey); - this._strategiesByPair = {}; - this._strategiesById = {}; - this._ordersByDirectedPair = {}; - this._latestBlockNumber = 0; - this._latestTradesByPair = {}; - this._latestTradesByDirectedPair = {}; - this._blocksMetadata = []; - this.emit('onPairDataChanged', pairs); - }; - ChainCache.prototype.getStrategiesByPair = function (token0, token1) { - return __awaiter(this, void 0, void 0, function () { - var key; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, this._checkAndHandleCacheMiss(token0, token1)]; - case 1: - _a.sent(); - key = (0, utils_1.toPairKey)(token0, token1); - return [2 /*return*/, this._strategiesByPair[key]]; - } - }); - }); - }; - ChainCache.prototype.getStrategyById = function (id) { - return this._strategiesById[id.toString()]; - }; - ChainCache.prototype.getCachedPairs = function (onlyWithStrategies) { - if (onlyWithStrategies === void 0) { - onlyWithStrategies = true; - } - if (onlyWithStrategies) { - return Object.entries(this._strategiesByPair) - .filter(function (_a) { - var _ = _a[0], - strategies = _a[1]; - return strategies.length > 0; - }) - .map(function (_a) { - var key = _a[0], - _ = _a[1]; - return (0, utils_1.fromPairKey)(key); - }); - } - return Object.keys(this._strategiesByPair).map(utils_1.fromPairKey); - }; - /** - * returns the orders that sell targetToken for sourceToken - */ - ChainCache.prototype.getOrdersByPair = function ( - sourceToken, - targetToken, - keepNonTradable, - ) { - if (keepNonTradable === void 0) { - keepNonTradable = false; - } - return __awaiter(this, void 0, void 0, function () { - var key, orders; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - this._checkAndHandleCacheMiss(sourceToken, targetToken), - ]; - case 1: - _a.sent(); - key = (0, utils_1.toDirectionKey)(sourceToken, targetToken); - orders = this._ordersByDirectedPair[key] || {}; - if (keepNonTradable) return [2 /*return*/, orders]; - return [ - 2 /*return*/, - Object.fromEntries( - Object.entries(orders).filter(function (_a) { - var _ = _a[0], - order = _a[1]; - return (0, utils_1.isOrderTradable)(order); - }), - ), - ]; - } - }); - }); - }; - ChainCache.prototype.hasCachedPair = function (token0, token1) { - var key = (0, utils_1.toPairKey)(token0, token1); - return !!this._strategiesByPair[key]; - }; - ChainCache.prototype.getLatestTradeByPair = function (token0, token1) { - return __awaiter(this, void 0, void 0, function () { - var key; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, this._checkAndHandleCacheMiss(token0, token1)]; - case 1: - _a.sent(); - key = (0, utils_1.toPairKey)(token0, token1); - return [2 /*return*/, this._latestTradesByPair[key]]; - } - }); - }); - }; - ChainCache.prototype.getLatestTradeByDirectedPair = function ( - sourceToken, - targetToken, - ) { - return __awaiter(this, void 0, void 0, function () { - var key; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - this._checkAndHandleCacheMiss(sourceToken, targetToken), - ]; - case 1: - _a.sent(); - key = (0, utils_1.toDirectionKey)(sourceToken, targetToken); - return [2 /*return*/, this._latestTradesByDirectedPair[key]]; - } - }); - }); - }; - ChainCache.prototype.getLatestTrades = function () { - return Object.values(this._latestTradesByPair); - }; - ChainCache.prototype.getLatestBlockNumber = function () { - return this._latestBlockNumber; - }; - Object.defineProperty(ChainCache.prototype, 'blocksMetadata', { - get: function () { - return this._blocksMetadata; - }, - set: function (blocks) { - this._blocksMetadata = blocks; - }, - enumerable: false, - configurable: true, - }); - //#endregion public getters - //#region cache updates - /** - * This method is to be used when all the existing strategies of a pair are - * fetched and are to be stored in the cache. - * Once a pair is cached, the only way to update it is by using `applyBatchedUpdates`. - * If all the strategies of a pair are deleted, the pair remains in the cache and there's - * no need to add it again. - * @param {string} token0 - address of the first token of the pair - * @param {string} token1 - address of the second token of the pair - * @param {EncodedStrategy[]} strategies - the strategies to be cached - * @throws {Error} if the pair is already cached - * @returns {void} - */ - ChainCache.prototype.addPair = function ( - token0, - token1, - strategies, - noPairAddedEvent, - ) { - var _this = this; - if (noPairAddedEvent === void 0) { - noPairAddedEvent = false; - } - logger.debug('Adding pair to cache', token0, token1); - var key = (0, utils_1.toPairKey)(token0, token1); - if (this._strategiesByPair[key]) { - throw new Error('Pair '.concat(key, ' already cached')); - } - this._strategiesByPair[key] = strategies; - strategies.forEach(function (strategy) { - _this._strategiesById[strategy.id.toString()] = strategy; - _this._addStrategyOrders(strategy); - }); - if (!noPairAddedEvent) { - logger.debug('Emitting onPairAddedToCache', token0, token1); - this.emit('onPairAddedToCache', (0, utils_1.fromPairKey)(key)); - } - }; - /** - * This method is to be used when events from a range of blocks are fetched - * and are to be applied to the cache. - * All the events should belong to pairs that are already cached. - * The way to use this work flow is to first call `getLatestBlockNumber` to - * get the latest block number that was already cached, then fetch all the - * events from that block number to the latest block number, and finally - * call this method with the fetched events. - * Note: the cache can handle a case of a strategy that was created and then updated and then deleted - * @param {number} latestBlockNumber - the latest block number that was fetched - * @param {TradeData[]} latestTrades - the trades that were conducted - * @param {EncodedStrategy[]} createdStrategies - the strategies that were created - * @param {EncodedStrategy[]} updatedStrategies - the strategies that were updated - * @param {EncodedStrategy[]} deletedStrategies - the strategies that were deleted - * @throws {Error} if the pair of a strategy is not cached - * @returns {void} - */ - ChainCache.prototype.applyBatchedUpdates = function ( - latestBlockNumber, - latestTrades, - createdStrategies, - updatedStrategies, - deletedStrategies, - ) { - var _this = this; - logger.debug('Applying batched updates to cache', { - latestBlockNumber: latestBlockNumber, - latestTrades: latestTrades, - createdStrategies: createdStrategies, - updatedStrategies: updatedStrategies, - deletedStrategies: deletedStrategies, - }); - var affectedPairs = new Set(); - latestTrades.forEach(function (trade) { - _this._setLatestTrade(trade); - affectedPairs.add( - (0, utils_1.toPairKey)(trade.sourceToken, trade.targetToken), - ); - }); - createdStrategies.forEach(function (strategy) { - _this._addStrategy(strategy); - affectedPairs.add( - (0, utils_1.toPairKey)(strategy.token0, strategy.token1), - ); - }); - updatedStrategies.forEach(function (strategy) { - _this._updateStrategy(strategy); - affectedPairs.add( - (0, utils_1.toPairKey)(strategy.token0, strategy.token1), - ); - }); - deletedStrategies.forEach(function (strategy) { - _this._deleteStrategy(strategy); - affectedPairs.add( - (0, utils_1.toPairKey)(strategy.token0, strategy.token1), - ); - }); - this._setLatestBlockNumber(latestBlockNumber); - if (affectedPairs.size > 0) { - logger.debug('Emitting onPairDataChanged', affectedPairs); - this.emit( - 'onPairDataChanged', - Array.from(affectedPairs).map(utils_1.fromPairKey), - ); - } - }; - ChainCache.prototype._setLatestBlockNumber = function (blockNumber) { - this._latestBlockNumber = blockNumber; - }; - ChainCache.prototype._setLatestTrade = function (trade) { - if (!this.hasCachedPair(trade.sourceToken, trade.targetToken)) { - throw new Error( - 'Pair '.concat( - (0, utils_1.toPairKey)(trade.sourceToken, trade.targetToken), - ' is not cached, cannot set latest trade', - ), - ); - } - var key = (0, utils_1.toPairKey)(trade.sourceToken, trade.targetToken); - this._latestTradesByPair[key] = trade; - var directedKey = (0, utils_1.toDirectionKey)( - trade.sourceToken, - trade.targetToken, - ); - this._latestTradesByDirectedPair[directedKey] = trade; - }; - ChainCache.prototype._addStrategyOrders = function (strategy) { - var _a; - for ( - var _i = 0, - _b = [ - [strategy.token0, strategy.token1], - [strategy.token1, strategy.token0], - ]; - _i < _b.length; - _i++ - ) { - var tokenOrder = _b[_i]; - var key = (0, utils_1.toDirectionKey)(tokenOrder[0], tokenOrder[1]); - var order = - tokenOrder[0] === strategy.token0 ? strategy.order1 : strategy.order0; - var existingOrders = this._ordersByDirectedPair[key]; - if (existingOrders) { - existingOrders[strategy.id.toString()] = order; - } else { - this._ordersByDirectedPair[key] = - ((_a = {}), (_a[strategy.id.toString()] = order), _a); - } - } - }; - ChainCache.prototype._removeStrategyOrders = function (strategy) { - for ( - var _i = 0, - _a = [ - [strategy.token0, strategy.token1], - [strategy.token1, strategy.token0], - ]; - _i < _a.length; - _i++ - ) { - var tokenOrder = _a[_i]; - var key = (0, utils_1.toDirectionKey)(tokenOrder[0], tokenOrder[1]); - var existingOrders = this._ordersByDirectedPair[key]; - if (existingOrders) { - delete existingOrders[strategy.id.toString()]; - // if there are no orders left for this pair, remove the pair from the map - if (Object.keys(existingOrders).length === 0) { - delete this._ordersByDirectedPair.key; - } - } - } - }; - ChainCache.prototype._addStrategy = function (strategy) { - if (!this.hasCachedPair(strategy.token0, strategy.token1)) { - throw new Error( - 'Pair '.concat( - (0, utils_1.toPairKey)(strategy.token0, strategy.token1), - ' is not cached, cannot add strategy', - ), - ); - } - var key = (0, utils_1.toPairKey)(strategy.token0, strategy.token1); - if (!!this._strategiesById[strategy.id.toString()]) { - logger.debug( - 'Strategy ' - .concat(strategy.id, ' already cached, under the pair ') - .concat(key, ' - skipping'), - ); - return; - } - var strategies = this._strategiesByPair[key] || []; - strategies.push(strategy); - this._strategiesByPair[key] = strategies; - this._strategiesById[strategy.id.toString()] = strategy; - this._addStrategyOrders(strategy); - }; - ChainCache.prototype._updateStrategy = function (strategy) { - if (!this.hasCachedPair(strategy.token0, strategy.token1)) { - throw new Error( - 'Pair '.concat( - (0, utils_1.toPairKey)(strategy.token0, strategy.token1), - ' is not cached, cannot update strategy', - ), - ); - } - var key = (0, utils_1.toPairKey)(strategy.token0, strategy.token1); - var strategies = (this._strategiesByPair[key] || []).filter(function (s) { - return s.id !== strategy.id; - }); - strategies.push(strategy); - this._strategiesByPair[key] = strategies; - this._strategiesById[strategy.id.toString()] = strategy; - this._removeStrategyOrders(strategy); - this._addStrategyOrders(strategy); - }; - ChainCache.prototype._deleteStrategy = function (strategy) { - if (!this.hasCachedPair(strategy.token0, strategy.token1)) { - throw new Error( - 'Pair '.concat( - (0, utils_1.toPairKey)(strategy.token0, strategy.token1), - ' is not cached, cannot delete strategy', - ), - ); - } - var key = (0, utils_1.toPairKey)(strategy.token0, strategy.token1); - delete this._strategiesById[strategy.id.toString()]; - var strategies = (this._strategiesByPair[key] || []).filter(function (s) { - return s.id !== strategy.id; - }); - this._strategiesByPair[key] = strategies; - this._removeStrategyOrders(strategy); - }; - return ChainCache; -})(events_1.default); -exports.ChainCache = ChainCache; diff --git a/src/dex/carbon/sdk/chain-cache/ChainSync.js b/src/dex/carbon/sdk/chain-cache/ChainSync.js deleted file mode 100644 index 6d260b15a..000000000 --- a/src/dex/carbon/sdk/chain-cache/ChainSync.js +++ /dev/null @@ -1,708 +0,0 @@ -'use strict'; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator['throw'](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done - ? resolve(result.value) - : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; -var __generator = - (this && this.__generator) || - function (thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [], - }, - f, - y, - t, - g; - return ( - (g = { next: verb(0), throw: verb(1), return: verb(2) }), - typeof Symbol === 'function' && - (g[Symbol.iterator] = function () { - return this; - }), - g - ); - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError('Generator is already executing.'); - while ((g && ((g = 0), op[0] && (_ = 0)), _)) - try { - if ( - ((f = 1), - y && - (t = - op[0] & 2 - ? y['return'] - : op[0] - ? y['throw'] || ((t = y['return']) && t.call(y), 0) - : y.next) && - !(t = t.call(y, op[1])).done) - ) - return t; - if (((y = 0), t)) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if ( - !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && - (op[0] === 6 || op[0] === 2) - ) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } - }; -var __spreadArray = - (this && this.__spreadArray) || - function (to, from, pack) { - if (pack || arguments.length === 2) - for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.ChainSync = void 0; -var utils_1 = require('./utils'); -var logger_1 = require('../common/logger'); -var logger = new logger_1.Logger('index.ts'); -var BLOCKS_TO_KEEP = 3; -var ChainSync = /** @class */ (function () { - function ChainSync(fetcher, chainCache) { - this._syncCalled = false; - this._slowPollPairs = false; - this._pairs = []; - // keep the time stamp of last fetch - this._lastFetch = Date.now(); - this._initialSyncDone = false; - this._fetcher = fetcher; - this._chainCache = chainCache; - } - ChainSync.prototype.startDataSync = function () { - return __awaiter(this, arguments, void 0, function () { - var blockNumber; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('startDataSync called'); - if (this._syncCalled) { - throw new Error( - 'ChainSync.startDataSync() can only be called once', - ); - } - this._syncCalled = true; - return [4 /*yield*/, this._fetcher.getBlockNumber()]; - case 1: - blockNumber = _a.sent(); - if (this._chainCache.getLatestBlockNumber() === 0) { - logger.debug('startDataSync - cache is new', arguments); - // cache starts from scratch so we want to avoid getting events from the beginning of time - this._chainCache.applyBatchedUpdates(blockNumber, [], [], [], []); - } - return [ - 4 /*yield*/, - Promise.all([ - this._trackFees(), - this._populatePairsData(), - this._syncEvents(), - ]), - ]; - case 2: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - ChainSync.prototype._trackFees = function () { - return __awaiter(this, void 0, void 0, function () { - var tradingFeePPM; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('_trackFees called'); - return [4 /*yield*/, this._fetcher.tradingFeePPM()]; - case 1: - tradingFeePPM = _a.sent(); - this._chainCache.tradingFeePPM = tradingFeePPM; - this._fetcher.onTradingFeePPMUpdated(function ( - prevFeePPM, - newFeePPM, - ) { - logger.debug( - 'tradingFeePPM updated from', - prevFeePPM, - 'to', - newFeePPM, - ); - _this._chainCache.tradingFeePPM = newFeePPM; - }); - return [2 /*return*/]; - } - }); - }); - }; - // `_populatePairsData` sets timeout and returns immediately. It does the following: - // 1. Fetches all token pairs from the fetcher - // 2. selects a pair that's not in the cache - // 3. fetches strategies for the pair - // 4. adds the pair to the cache - // 5. sets short timeout to continue with the next pair - // 6. if there are no more pairs, it sets a timeout to call itself again - ChainSync.prototype._populatePairsData = function () { - return __awaiter(this, void 0, void 0, function () { - var processPairs; - var _this = this; - return __generator(this, function (_a) { - logger.debug('_populatePairsData called'); - this._pairs = []; - // keep the time stamp of last fetch - this._lastFetch = Date.now(); - // this indicates we want to poll for pairs only once a minute. - // Set this to false when we have an indication that new pair was created - which we want to fetch now - this._slowPollPairs = false; - processPairs = function () { - return __awaiter(_this, void 0, void 0, function () { - var _a, _b, nextPairToSync, e_1; - var _this = this; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - _c.trys.push([0, 6, , 7]); - if (!(this._pairs.length === 0)) return [3 /*break*/, 2]; - // if we have no pairs we need to fetch - unless we're in slow poll mode and less than a minute has passed since last fetch - if ( - this._slowPollPairs && - Date.now() - this._lastFetch < 60000 - ) { - // go back to sleep - setTimeout(processPairs, 1000); - return [2 /*return*/]; - } - logger.debug('_populatePairsData fetches pairs'); - _a = this; - _b = [[]]; - return [4 /*yield*/, this._fetcher.pairs()]; - case 1: - _a._pairs = __spreadArray.apply( - void 0, - _b.concat([_c.sent(), true]), - ); - logger.debug('_populatePairsData fetched pairs', this._pairs); - this._lastFetch = Date.now(); - _c.label = 2; - case 2: - nextPairToSync = (0, utils_1.findAndRemoveLeading)( - this._pairs, - function (pair) { - return !_this._chainCache.hasCachedPair(pair[0], pair[1]); - }, - ); - if (!nextPairToSync) return [3 /*break*/, 4]; - logger.debug( - '_populatePairsData adds pair to cache', - nextPairToSync, - ); - // we have a pair to sync - let's do it - add its strategies to the cache and then to minimal timeout to process the next pair - return [ - 4 /*yield*/, - this.syncPairData( - nextPairToSync[0], - nextPairToSync[1], - !this._initialSyncDone, - ), - ]; - case 3: - // we have a pair to sync - let's do it - add its strategies to the cache and then to minimal timeout to process the next pair - _c.sent(); - setTimeout(processPairs, 1); - return [3 /*break*/, 5]; - case 4: - // list is now empty and there are no more pairs to sync - we can poll them less frequently - // we will wake up once a second just to check if we're still in slow poll mode, - // but if not - we will actually poll once a minute - logger.debug( - '_populatePairsData handled all pairs and goes to slow poll mode', - ); - this._slowPollPairs = true; - this._initialSyncDone = true; - setTimeout(processPairs, 1000); - _c.label = 5; - case 5: - return [3 /*break*/, 7]; - case 6: - e_1 = _c.sent(); - logger.error('Error while syncing pairs data', e_1); - setTimeout(processPairs, 60000); - return [3 /*break*/, 7]; - case 7: - return [2 /*return*/]; - } - }); - }); - }; - setTimeout(processPairs, 1); - return [2 /*return*/]; - }); - }); - }; - ChainSync.prototype.syncPairData = function ( - token0, - token1, - noPairAddedEvent, - ) { - if (noPairAddedEvent === void 0) { - noPairAddedEvent = false; - } - return __awaiter(this, void 0, void 0, function () { - var strategies; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this._syncCalled) { - throw new Error( - 'ChainSync.startDataSync() must be called before syncPairData()', - ); - } - return [ - 4 /*yield*/, - this._fetcher.strategiesByPair(token0, token1), - ]; - case 1: - strategies = _a.sent(); - if (this._chainCache.hasCachedPair(token0, token1)) - return [2 /*return*/]; - this._chainCache.addPair( - token0, - token1, - strategies, - noPairAddedEvent, - ); - return [2 /*return*/]; - } - }); - }); - }; - // used to break the blocks between latestBlock + 1 and currentBlock to chunks of 1000 blocks - ChainSync.prototype._getBlockChunks = function ( - startBlock, - endBlock, - chunkSize, - ) { - var blockChunks = []; - for (var i = startBlock; i <= endBlock; i += chunkSize) { - var chunkStart = i; - var chunkEnd = Math.min(i + chunkSize - 1, endBlock); - blockChunks.push([chunkStart, chunkEnd]); - } - return blockChunks; - }; - ChainSync.prototype._syncEvents = function () { - return __awaiter(this, void 0, void 0, function () { - var interval, processEvents; - var _this = this; - return __generator(this, function (_a) { - logger.debug('_syncEvents called'); - interval = 1000; - processEvents = function () { - return __awaiter(_this, void 0, void 0, function () { - var latestBlock, - currentBlock, - cachedPairs_1, - blockChunks, - createdStrategiesChunks, - updatedStrategiesChunks, - deletedStrategiesChunks, - tradesChunks, - _i, - blockChunks_1, - blockChunk, - createdStrategiesChunk, - updatedStrategiesChunk, - deletedStrategiesChunk, - tradesChunk, - createdStrategies, - updatedStrategies, - deletedStrategies, - trades, - _a, - createdStrategies_1, - strategy, - err_1; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 11, , 12]); - latestBlock = this._chainCache.getLatestBlockNumber(); - return [4 /*yield*/, this._fetcher.getBlockNumber()]; - case 1: - currentBlock = _b.sent(); - if (!(currentBlock > latestBlock)) return [3 /*break*/, 10]; - return [4 /*yield*/, this._detectReorg(currentBlock)]; - case 2: - if (_b.sent()) { - logger.debug('_syncEvents detected reorg - resetting'); - this._chainCache.clear(); - this._chainCache.applyBatchedUpdates( - currentBlock, - [], - [], - [], - [], - ); - this._resetPairsFetching(); - setTimeout(processEvents, 1); - return [2 /*return*/]; - } - cachedPairs_1 = new Set( - this._chainCache.getCachedPairs().map(function (pair) { - return (0, utils_1.toPairKey)(pair[0], pair[1]); - }), - ); - logger.debug( - '_syncEvents fetches events', - latestBlock + 1, - currentBlock, - ); - blockChunks = this._getBlockChunks( - latestBlock + 1, - currentBlock, - 1000, - ); - logger.debug('_syncEvents block chunks', blockChunks); - createdStrategiesChunks = []; - updatedStrategiesChunks = []; - deletedStrategiesChunks = []; - tradesChunks = []; - (_i = 0), (blockChunks_1 = blockChunks); - _b.label = 3; - case 3: - if (!(_i < blockChunks_1.length)) return [3 /*break*/, 9]; - blockChunk = blockChunks_1[_i]; - logger.debug( - '_syncEvents fetches events for chunk', - blockChunk, - ); - return [ - 4 /*yield*/, - this._fetcher.getLatestStrategyCreatedStrategies( - blockChunk[0], - blockChunk[1], - ), - ]; - case 4: - createdStrategiesChunk = _b.sent(); - return [ - 4 /*yield*/, - this._fetcher.getLatestStrategyUpdatedStrategies( - blockChunk[0], - blockChunk[1], - ), - ]; - case 5: - updatedStrategiesChunk = _b.sent(); - return [ - 4 /*yield*/, - this._fetcher.getLatestStrategyDeletedStrategies( - blockChunk[0], - blockChunk[1], - ), - ]; - case 6: - deletedStrategiesChunk = _b.sent(); - return [ - 4 /*yield*/, - this._fetcher.getLatestTokensTradedTrades( - blockChunk[0], - blockChunk[1], - ), - ]; - case 7: - tradesChunk = _b.sent(); - createdStrategiesChunks.push(createdStrategiesChunk); - updatedStrategiesChunks.push(updatedStrategiesChunk); - deletedStrategiesChunks.push(deletedStrategiesChunk); - tradesChunks.push(tradesChunk); - logger.debug( - '_syncEvents fetched the following events for chunks', - blockChunks, - { - createdStrategiesChunk: createdStrategiesChunk, - updatedStrategiesChunk: updatedStrategiesChunk, - deletedStrategiesChunk: deletedStrategiesChunk, - tradesChunk: tradesChunk, - }, - ); - _b.label = 8; - case 8: - _i++; - return [3 /*break*/, 3]; - case 9: - createdStrategies = createdStrategiesChunks.flat(); - updatedStrategies = updatedStrategiesChunks.flat(); - deletedStrategies = deletedStrategiesChunks.flat(); - trades = tradesChunks.flat(); - logger.debug( - '_syncEvents fetched events', - createdStrategies, - updatedStrategies, - deletedStrategies, - trades, - ); - // let's check created strategies and see if we have a pair that's not cached yet, - // which means we need to set slow poll mode to false so that it will be fetched quickly - for ( - _a = 0, createdStrategies_1 = createdStrategies; - _a < createdStrategies_1.length; - _a++ - ) { - strategy = createdStrategies_1[_a]; - if ( - !this._chainCache.hasCachedPair( - strategy.token0, - strategy.token1, - ) - ) { - logger.debug( - '_syncEvents sets slow poll mode to false because of new pair', - strategy.token0, - strategy.token1, - ); - this._slowPollPairs = false; - break; - } - } - this._chainCache.applyBatchedUpdates( - currentBlock, - trades.filter(function (trade) { - return cachedPairs_1.has( - (0, utils_1.toPairKey)( - trade.sourceToken, - trade.targetToken, - ), - ); - }), - createdStrategies.filter(function (strategy) { - return cachedPairs_1.has( - (0, utils_1.toPairKey)( - strategy.token0, - strategy.token1, - ), - ); - }), - updatedStrategies.filter(function (strategy) { - return cachedPairs_1.has( - (0, utils_1.toPairKey)( - strategy.token0, - strategy.token1, - ), - ); - }), - deletedStrategies.filter(function (strategy) { - return cachedPairs_1.has( - (0, utils_1.toPairKey)( - strategy.token0, - strategy.token1, - ), - ); - }), - ); - _b.label = 10; - case 10: - return [3 /*break*/, 12]; - case 11: - err_1 = _b.sent(); - logger.error('Error syncing events:', err_1); - return [3 /*break*/, 12]; - case 12: - setTimeout(processEvents, interval); - return [2 /*return*/]; - } - }); - }); - }; - setTimeout(processEvents, 1); - return [2 /*return*/]; - }); - }); - }; - ChainSync.prototype._resetPairsFetching = function () { - this._pairs = []; - this._slowPollPairs = false; - this._initialSyncDone = false; - }; - ChainSync.prototype._detectReorg = function (currentBlock) { - return __awaiter(this, void 0, void 0, function () { - var blocksMetadata, - numberToBlockMetadata, - _i, - blocksMetadata_1, - blockMetadata, - number, - hash, - currentHash, - latestBlocksMetadata, - i, - _a, - _b; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - logger.debug('_detectReorg called'); - blocksMetadata = this._chainCache.blocksMetadata; - numberToBlockMetadata = {}; - (_i = 0), (blocksMetadata_1 = blocksMetadata); - _c.label = 1; - case 1: - if (!(_i < blocksMetadata_1.length)) return [3 /*break*/, 4]; - blockMetadata = blocksMetadata_1[_i]; - (number = blockMetadata.number), (hash = blockMetadata.hash); - if (number > currentBlock) { - logger.log( - 'reorg detected for block number', - number, - 'larger than current block', - currentBlock, - 'with hash', - hash, - ); - return [2 /*return*/, true]; - } - return [4 /*yield*/, this._fetcher.getBlock(number)]; - case 2: - currentHash = _c.sent().hash; - if (hash !== currentHash) { - logger.log( - 'reorg detected for block number', - number, - 'old hash', - hash, - 'new hash', - currentHash, - ); - return [2 /*return*/, true]; - } - // blockMetadata is valid, let's store it so that we don't have to fetch it again below - numberToBlockMetadata[number] = blockMetadata; - _c.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: - // no reorg detected - logger.debug( - '_detectReorg no reorg detected, updating blocks metadata', - ); - latestBlocksMetadata = []; - i = 0; - _c.label = 5; - case 5: - if (!(i < BLOCKS_TO_KEEP)) return [3 /*break*/, 9]; - if (!numberToBlockMetadata[currentBlock - i]) - return [3 /*break*/, 6]; - latestBlocksMetadata.push(numberToBlockMetadata[currentBlock - i]); - return [3 /*break*/, 8]; - case 6: - _b = (_a = latestBlocksMetadata).push; - return [4 /*yield*/, this._fetcher.getBlock(currentBlock - i)]; - case 7: - _b.apply(_a, [_c.sent()]); - _c.label = 8; - case 8: - i++; - return [3 /*break*/, 5]; - case 9: - this._chainCache.blocksMetadata = latestBlocksMetadata; - logger.debug('_detectReorg updated blocks metadata'); - return [2 /*return*/, false]; - } - }); - }); - }; - return ChainSync; -})(); -exports.ChainSync = ChainSync; diff --git a/src/dex/carbon/sdk/chain-cache/index.js b/src/dex/carbon/sdk/chain-cache/index.js deleted file mode 100644 index 43a529818..000000000 --- a/src/dex/carbon/sdk/chain-cache/index.js +++ /dev/null @@ -1,74 +0,0 @@ -'use strict'; -var __createBinding = - (this && this.__createBinding) || - (Object.create - ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if ( - !desc || - ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) - ) { - desc = { - enumerable: true, - get: function () { - return m[k]; - }, - }; - } - Object.defineProperty(o, k2, desc); - } - : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); -var __exportStar = - (this && this.__exportStar) || - function (m, exports) { - for (var p in m) - if (p !== 'default' && !Object.prototype.hasOwnProperty.call(exports, p)) - __createBinding(exports, m, p); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.initSyncedCache = exports.ChainSync = exports.ChainCache = void 0; -var ChainCache_1 = require('./ChainCache'); -Object.defineProperty(exports, 'ChainCache', { - enumerable: true, - get: function () { - return ChainCache_1.ChainCache; - }, -}); -var ChainSync_1 = require('./ChainSync'); -Object.defineProperty(exports, 'ChainSync', { - enumerable: true, - get: function () { - return ChainSync_1.ChainSync; - }, -}); -__exportStar(require('./types'), exports); -/** - * Initializes a cache and a syncer for the cache - this default initialization logic - * can be used in most cases. If you need to customize the initialization logic, you can - * use the ChainCache and ChainSync classes directly. - * @param {Fetcher} fetcher - fetcher to use for syncing the cache - * @param {string} cachedData - serialized cache data to initialize the cache with - * @returns an object with the initialized cache and a function to start syncing the cache - * @example - * const { cache, startDataSync } = initSyncedCache(fetcher, cachedData); - * await startDataSync(); - * // cache is now synced - */ -var initSyncedCache = function (fetcher, cachedData) { - var cache; - if (cachedData) { - cache = ChainCache_1.ChainCache.fromSerialized(cachedData); - } - // either serialized data was bad or it was not provided - if (!cache) { - cache = new ChainCache_1.ChainCache(); - } - var syncer = new ChainSync_1.ChainSync(fetcher, cache); - cache.setCacheMissHandler(syncer.syncPairData.bind(syncer)); - return { cache: cache, startDataSync: syncer.startDataSync.bind(syncer) }; -}; -exports.initSyncedCache = initSyncedCache; diff --git a/src/dex/carbon/sdk/chain-cache/types.js b/src/dex/carbon/sdk/chain-cache/types.js deleted file mode 100644 index db8b17d54..000000000 --- a/src/dex/carbon/sdk/chain-cache/types.js +++ /dev/null @@ -1,2 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); diff --git a/src/dex/carbon/sdk/chain-cache/utils.js b/src/dex/carbon/sdk/chain-cache/utils.js deleted file mode 100644 index 1e884ab19..000000000 --- a/src/dex/carbon/sdk/chain-cache/utils.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.isOrderTradable = - exports.findAndRemoveLeading = - exports.toDirectionKey = - exports.fromPairKey = - exports.toPairKey = - void 0; -// Compare tokens using the default locale -var compareTokens = function (token0, token1) { - return token0.localeCompare(token1); -}; -var SEPARATOR = '->-<-'; -// Convert two tokens to a string key -var toKey = function (tokens) { - // Check if the array has exactly two elements - if (tokens.length !== 2) { - throw new Error( - 'Invalid number of tokens: expected 2, got '.concat(tokens.length), - ); - } - // Check if tokens are the same, and throw an error if they are - if (tokens[0] === tokens[1]) { - throw new Error( - 'Cannot create key for identical tokens: '.concat(tokens[0]), - ); - } - return tokens.join(SEPARATOR); -}; -// Convert two tokens to a string key -var toPairKey = function (token0, token1) { - // Sort tokens and turn to key - return toKey([token0, token1].sort(compareTokens)); -}; -exports.toPairKey = toPairKey; -var fromPairKey = function (key) { - var tokens = key.split(SEPARATOR); - return [tokens[0], tokens[1]]; -}; -exports.fromPairKey = fromPairKey; -// Convert two tokens to a string key, order matters -var toDirectionKey = function (token0, token1) { - return toKey([token0, token1]); -}; -exports.toDirectionKey = toDirectionKey; -// find and return an element in an array, and remove it and all elements before it. If not found, remove all elements. -var findAndRemoveLeading = function (arr, predicate) { - var element = undefined; - do { - element = arr.shift(); - } while (element && !predicate(element)); - return element; -}; -exports.findAndRemoveLeading = findAndRemoveLeading; -function isOrderTradable(order) { - return order.y.gt(0) && (order.A.gt(0) || order.B.gt(0)); -} -exports.isOrderTradable = isOrderTradable; diff --git a/src/dex/carbon/sdk/common/logger.js b/src/dex/carbon/sdk/common/logger.js deleted file mode 100644 index 616c16fa1..000000000 --- a/src/dex/carbon/sdk/common/logger.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; -var __spreadArray = - (this && this.__spreadArray) || - function (to, from, pack) { - if (pack || arguments.length === 2) - for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.Logger = void 0; -var numerics_1 = require('../utils/numerics'); -var globalObject = (function () { - try { - return self; - } catch (e) { - try { - return window; - } catch (e) { - return global; - } - } -})(); -function getVerbosityLevel() { - if (globalObject !== undefined) { - return Number(globalObject.CARBON_DEFI_SDK_VERBOSITY) || 0; - } - return 0; -} -var verbosity = getVerbosityLevel(); -function isVerbose() { - return verbosity >= 1; -} -function shouldConvertBigNumbersToStrings() { - return verbosity >= 2; -} -var originalLog = console.log; -function convertBigNumbersToStrings(obj) { - if (obj instanceof numerics_1.BigNumber) { - return obj.toString(); - } - if (Array.isArray(obj)) { - return obj.map(convertBigNumbersToStrings); - } - if (typeof obj === 'object') { - return Object.fromEntries( - Object.entries(obj).map(function (_a) { - var key = _a[0], - value = _a[1]; - return [key, convertBigNumbersToStrings(value)]; - }), - ); - } - return obj; -} -if (shouldConvertBigNumbersToStrings()) { - console.debug = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var convertedArgs = args.map(convertBigNumbersToStrings); - originalLog.apply(console, convertedArgs); - }; -} -var Logger = /** @class */ (function () { - function Logger(file) { - this._prefix = '[SDK]['.concat(file, ']:'); - } - Logger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - console.error.apply(console, __spreadArray([this._prefix], args, false)); - }; - Logger.prototype.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - console.log.apply(console, __spreadArray([this._prefix], args, false)); - }; - Logger.prototype.debug = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - isVerbose() && - console.debug.apply(console, __spreadArray([this._prefix], args, false)); - }; - return Logger; -})(); -exports.Logger = Logger; diff --git a/src/dex/carbon/sdk/common/types.js b/src/dex/carbon/sdk/common/types.js deleted file mode 100644 index e3d8e5f5a..000000000 --- a/src/dex/carbon/sdk/common/types.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.MatchType = void 0; -var MatchType; -(function (MatchType) { - MatchType['Fast'] = 'Fast'; - MatchType['Best'] = 'Best'; -})((MatchType = exports.MatchType || (exports.MatchType = {}))); diff --git a/src/dex/carbon/sdk/contracts-api/Composer.js b/src/dex/carbon/sdk/contracts-api/Composer.js deleted file mode 100644 index e4286e761..000000000 --- a/src/dex/carbon/sdk/contracts-api/Composer.js +++ /dev/null @@ -1,157 +0,0 @@ -'use strict'; -var __assign = - (this && this.__assign) || - function () { - __assign = - Object.assign || - function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) - if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -var utils_1 = require('./utils'); -var logger_1 = require('../common/logger'); -var logger = new logger_1.Logger('Composer.ts'); -/** - * Class that composes and populates transactions for trade and strategy management. - */ -var Composer = /** @class */ (function () { - function Composer(contracts) { - this._contracts = contracts; - } - /** - * - * @param {string} sourceToken - The address of the token to be traded. - * @param {string} targetToken - The address of the token to be received. - * @param {TradeAction[]} tradeActions - The list of trade actions to be executed. - * @param {BigNumberish} deadline - The deadline for the trade. - * @param {BigNumberish} maxInput - The maximum amount of source token to be traded. - * @param {PayableOverrides} overrides - The overrides for the transaction. - * @returns {Promise} - The populated transaction. - */ - Composer.prototype.tradeByTargetAmount = function ( - sourceToken, - targetToken, - tradeActions, - deadline, - maxInput, - overrides, - ) { - logger.debug('tradeByTargetAmount called', arguments); - var customOverrides = (0, utils_1.buildTradeOverrides)( - sourceToken, - tradeActions, - true, - maxInput, - overrides, - ); - logger.debug('tradeByTargetAmount overrides', customOverrides); - return this._contracts.carbonController.populateTransaction.tradeByTargetAmount( - sourceToken, - targetToken, - tradeActions, - deadline, - maxInput, - customOverrides, - ); - }; - /** - * Populates a transaction to trade a given amount of source token. - * @param {string} sourceToken - The address of the token to be traded. - * @param {string} targetToken - The address of the token to be received. - * @param {TradeAction[]} tradeActions - The list of trade actions to be executed. - * @param {BigNumberish} deadline - The deadline for the trade. - * @param {BigNumberish} minReturn - The minimum amount of target token to be received. - * @param {PayableOverrides} overrides - The overrides for the transaction. - * @returns {Promise} - The populated transaction. - */ - Composer.prototype.tradeBySourceAmount = function ( - sourceToken, - targetToken, - tradeActions, - deadline, - minReturn, - overrides, - ) { - logger.debug('tradeBySourceAmount called', arguments); - var customOverrides = (0, utils_1.buildTradeOverrides)( - sourceToken, - tradeActions, - false, - -1, - overrides, - ); - logger.debug('tradeBySourceAmount overrides', customOverrides); - return this._contracts.carbonController.populateTransaction.tradeBySourceAmount( - sourceToken, - targetToken, - tradeActions, - deadline, - minReturn, - customOverrides, - ); - }; - Composer.prototype.createStrategy = function ( - token0, - token1, - order0, - order1, - overrides, - ) { - logger.debug('createStrategy called', arguments); - var customOverrides = __assign({}, overrides); - if ((0, utils_1.isETHAddress)(token0)) { - customOverrides.value = order0.y; - } else if ((0, utils_1.isETHAddress)(token1)) { - customOverrides.value = order1.y; - } - logger.debug('createStrategy overrides', customOverrides); - return this._contracts.carbonController.populateTransaction.createStrategy( - token0, - token1, - [order0, order1], - customOverrides, - ); - }; - Composer.prototype.deleteStrategy = function (id) { - return this._contracts.carbonController.populateTransaction.deleteStrategy( - id, - ); - }; - Composer.prototype.updateStrategy = function ( - strategyId, - token0, - token1, - currentOrders, - newOrders, - overrides, - ) { - var customOverrides = __assign({}, overrides); - if ( - (0, utils_1.isETHAddress)(token0) && - newOrders[0].y.gt(currentOrders[0].y) - ) { - customOverrides.value = newOrders[0].y.sub(currentOrders[0].y); - } else if ( - (0, utils_1.isETHAddress)(token1) && - newOrders[1].y.gt(currentOrders[1].y) - ) { - customOverrides.value = newOrders[1].y.sub(currentOrders[1].y); - } - logger.debug('updateStrategy overrides', customOverrides); - return this._contracts.carbonController.populateTransaction.updateStrategy( - strategyId, - currentOrders, - newOrders, - customOverrides, - ); - }; - return Composer; -})(); -exports.default = Composer; diff --git a/src/dex/carbon/sdk/contracts-api/Contracts.js b/src/dex/carbon/sdk/contracts-api/Contracts.js deleted file mode 100644 index cfca133bb..000000000 --- a/src/dex/carbon/sdk/contracts-api/Contracts.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -var types_1 = require('../abis/types'); -var config_1 = require('./config'); -var Contracts = /** @class */ (function () { - function Contracts(provider, config) { - this._config = config_1.config; - this._provider = provider; - this._config.carbonControllerAddress = - (config === null || config === void 0 - ? void 0 - : config.carbonControllerAddress) || - config_1.config.carbonControllerAddress; - this._config.multiCallAddress = - (config === null || config === void 0 - ? void 0 - : config.multiCallAddress) || config_1.config.multiCallAddress; - this._config.voucherAddress = - (config === null || config === void 0 ? void 0 : config.voucherAddress) || - config_1.config.voucherAddress; - } - Object.defineProperty(Contracts.prototype, 'carbonController', { - get: function () { - if (!this._carbonController) - this._carbonController = types_1.CarbonController__factory.connect( - this._config.carbonControllerAddress, - this._provider, - ); - return this._carbonController; - }, - enumerable: false, - configurable: true, - }); - Object.defineProperty(Contracts.prototype, 'multicall', { - get: function () { - if (!this._multiCall) - this._multiCall = types_1.Multicall__factory.connect( - this._config.multiCallAddress, - this._provider, - ); - return this._multiCall; - }, - enumerable: false, - configurable: true, - }); - Object.defineProperty(Contracts.prototype, 'voucher', { - get: function () { - if (!this._voucher) - this._voucher = types_1.Voucher__factory.connect( - this._config.voucherAddress, - this._provider, - ); - return this._voucher; - }, - enumerable: false, - configurable: true, - }); - Contracts.prototype.token = function (address) { - return types_1.Token__factory.connect(address, this._provider); - }; - Object.defineProperty(Contracts.prototype, 'provider', { - get: function () { - return this._provider; - }, - enumerable: false, - configurable: true, - }); - return Contracts; -})(); -exports.default = Contracts; diff --git a/src/dex/carbon/sdk/contracts-api/ContractsApi.js b/src/dex/carbon/sdk/contracts-api/ContractsApi.js deleted file mode 100644 index e393103e9..000000000 --- a/src/dex/carbon/sdk/contracts-api/ContractsApi.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.ContractsApi = void 0; -var Composer_1 = require('./Composer'); -var Contracts_1 = require('./Contracts'); -var Reader_1 = require('./Reader'); -/** - * Class that handles the interaction with contracts through a provider. - */ -var ContractsApi = /** @class */ (function () { - function ContractsApi(provider, config) { - var contracts = new Contracts_1.default(provider, config); - this._reader = new Reader_1.default(contracts); - this._composer = new Composer_1.default(contracts); - } - Object.defineProperty(ContractsApi.prototype, 'reader', { - get: function () { - return this._reader; - }, - enumerable: false, - configurable: true, - }); - Object.defineProperty(ContractsApi.prototype, 'composer', { - get: function () { - return this._composer; - }, - enumerable: false, - configurable: true, - }); - return ContractsApi; -})(); -exports.ContractsApi = ContractsApi; diff --git a/src/dex/carbon/sdk/contracts-api/Reader.js b/src/dex/carbon/sdk/contracts-api/Reader.js deleted file mode 100644 index 33ae3e6c2..000000000 --- a/src/dex/carbon/sdk/contracts-api/Reader.js +++ /dev/null @@ -1,433 +0,0 @@ -'use strict'; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator['throw'](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done - ? resolve(result.value) - : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; -var __generator = - (this && this.__generator) || - function (thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [], - }, - f, - y, - t, - g; - return ( - (g = { next: verb(0), throw: verb(1), return: verb(2) }), - typeof Symbol === 'function' && - (g[Symbol.iterator] = function () { - return this; - }), - g - ); - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError('Generator is already executing.'); - while ((g && ((g = 0), op[0] && (_ = 0)), _)) - try { - if ( - ((f = 1), - y && - (t = - op[0] & 2 - ? y['return'] - : op[0] - ? y['throw'] || ((t = y['return']) && t.call(y), 0) - : y.next) && - !(t = t.call(y, op[1])).done) - ) - return t; - if (((y = 0), t)) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if ( - !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && - (op[0] === 6 || op[0] === 2) - ) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } - }; -Object.defineProperty(exports, '__esModule', { value: true }); -var utils_1 = require('./utils'); -var logger_1 = require('../common/logger'); -var logger = new logger_1.Logger('Reader.ts'); -function toStrategy(res) { - var id = res[0]; - var token0 = res[2][0]; - var token1 = res[2][1]; - var y0 = res[3][0][0]; - var z0 = res[3][0][1]; - var A0 = res[3][0][2]; - var B0 = res[3][0][3]; - var y1 = res[3][1][0]; - var z1 = res[3][1][1]; - var A1 = res[3][1][2]; - var B1 = res[3][1][3]; - return { - id: id, - token0: token0, - token1: token1, - order0: { - y: y0, - z: z0, - A: A0, - B: B0, - }, - order1: { - y: y1, - z: z1, - A: A1, - B: B1, - }, - }; -} -/** - * Class that provides methods to read data from contracts. - */ -var Reader = /** @class */ (function () { - function Reader(contracts) { - var _this = this; - this.getDecimalsByAddress = function (address) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - if ((0, utils_1.isETHAddress)(address)) { - return [2 /*return*/, 18]; - } - return [2 /*return*/, this._contracts.token(address).decimals()]; - }); - }); - }; - this._getFilteredStrategies = function (eventType, fromBlock, toBlock) { - return __awaiter(_this, void 0, void 0, function () { - var filter, logs, strategies; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - filter = this._contracts.carbonController.filters[eventType]( - null, - null, - null, - null, - null, - ); - return [ - 4 /*yield*/, - this._contracts.carbonController.queryFilter( - filter, - fromBlock, - toBlock, - ), - ]; - case 1: - logs = _a.sent(); - if (logs.length === 0) return [2 /*return*/, []]; - strategies = logs.map(function (log) { - var logArgs = log.args; - return { - id: logArgs.id, - token0: logArgs.token0, - token1: logArgs.token1, - order0: { - y: logArgs.order0.y, - z: logArgs.order0.z, - A: logArgs.order0.A, - B: logArgs.order0.B, - }, - order1: { - y: logArgs.order1.y, - z: logArgs.order1.z, - A: logArgs.order1.A, - B: logArgs.order1.B, - }, - }; - }); - return [2 /*return*/, strategies]; - } - }); - }); - }; - this.getLatestStrategyCreatedStrategies = function (fromBlock, toBlock) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [ - 2 /*return*/, - this._getFilteredStrategies('StrategyCreated', fromBlock, toBlock), - ]; - }); - }); - }; - this.getLatestStrategyUpdatedStrategies = function (fromBlock, toBlock) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [ - 2 /*return*/, - this._getFilteredStrategies('StrategyUpdated', fromBlock, toBlock), - ]; - }); - }); - }; - this.getLatestStrategyDeletedStrategies = function (fromBlock, toBlock) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [ - 2 /*return*/, - this._getFilteredStrategies('StrategyDeleted', fromBlock, toBlock), - ]; - }); - }); - }; - this.getLatestTokensTradedTrades = function (fromBlock, toBlock) { - return __awaiter(_this, void 0, void 0, function () { - var filter, logs, trades; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - filter = this._contracts.carbonController.filters.TokensTraded( - null, - null, - null, - null, - null, - null, - null, - ); - return [ - 4 /*yield*/, - this._contracts.carbonController.queryFilter( - filter, - fromBlock, - toBlock, - ), - ]; - case 1: - logs = _a.sent(); - if (logs.length === 0) return [2 /*return*/, []]; - trades = logs.map(function (log) { - var res = log.args; - return { - sourceToken: res.sourceToken, - targetToken: res.targetToken, - sourceAmount: res.sourceAmount.toString(), - targetAmount: res.targetAmount.toString(), - trader: res.trader, - tradingFeeAmount: res.tradingFeeAmount.toString(), - byTargetAmount: res.byTargetAmount, - }; - }); - return [2 /*return*/, trades]; - } - }); - }); - }; - this.getBlockNumber = function () { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, this._contracts.provider.getBlockNumber()]; - }); - }); - }; - this.getBlock = function (blockNumber) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, this._contracts.provider.getBlock(blockNumber)]; - }); - }); - }; - this._contracts = contracts; - } - Reader.prototype._multicall = function (calls, blockHeight) { - return (0, utils_1.multicall)( - calls, - this._contracts.multicall, - blockHeight, - ); - }; - Reader.prototype.strategy = function (id) { - return __awaiter(this, void 0, void 0, function () { - var res; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, this._contracts.carbonController.strategy(id)]; - case 1: - res = _a.sent(); - return [2 /*return*/, toStrategy(res)]; - } - }); - }); - }; - Reader.prototype.strategies = function (ids) { - return __awaiter(this, void 0, void 0, function () { - var results; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - this._multicall( - ids.map(function (id) { - return { - contractAddress: _this._contracts.carbonController.address, - interface: _this._contracts.carbonController.interface, - methodName: 'strategy', - methodParameters: [id], - }; - }), - ), - ]; - case 1: - results = _a.sent(); - if (!results || results.length === 0) return [2 /*return*/, []]; - return [ - 2 /*return*/, - results.map(function (strategyRes) { - var strategy = strategyRes[0]; - return toStrategy(strategy); - }), - ]; - } - }); - }); - }; - Reader.prototype.pairs = function () { - return this._contracts.carbonController.pairs(); - }; - Reader.prototype.strategiesByPair = function (token0, token1) { - return __awaiter(this, void 0, void 0, function () { - var res; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - this._contracts.carbonController.strategiesByPair( - token0, - token1, - 0, - 0, - ), - ]; - case 1: - res = _a.sent(); - return [ - 2 /*return*/, - res.map(function (r) { - return toStrategy(r); - }), - ]; - } - }); - }); - }; - Reader.prototype.tokensByOwner = function (owner) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - if (!owner) return [2 /*return*/, []]; - return [ - 2 /*return*/, - this._contracts.voucher.tokensByOwner(owner, 0, 0), - ]; - }); - }); - }; - Reader.prototype.tradingFeePPM = function () { - return this._contracts.carbonController.tradingFeePPM(); - }; - Reader.prototype.onTradingFeePPMUpdated = function (listener) { - return this._contracts.carbonController.on( - 'TradingFeePPMUpdated', - function (prevFeePPM, newFeePPM) { - logger.debug('TradingFeePPMUpdated fired with', arguments); - listener(prevFeePPM, newFeePPM); - }, - ); - }; - return Reader; -})(); -exports.default = Reader; diff --git a/src/dex/carbon/sdk/contracts-api/config.js b/src/dex/carbon/sdk/contracts-api/config.js deleted file mode 100644 index f839b4b07..000000000 --- a/src/dex/carbon/sdk/contracts-api/config.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.config = void 0; -exports.config = { - carbonControllerAddress: '0xC537e898CD774e2dCBa3B14Ea6f34C93d5eA45e1', - multiCallAddress: '0x5ba1e12693dc8f9c48aad8770482f4739beed696', - voucherAddress: '0x3660F04B79751e31128f6378eAC70807e38f554E', -}; diff --git a/src/dex/carbon/sdk/contracts-api/index.js b/src/dex/carbon/sdk/contracts-api/index.js deleted file mode 100644 index b95b1d9b0..000000000 --- a/src/dex/carbon/sdk/contracts-api/index.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; -var __createBinding = - (this && this.__createBinding) || - (Object.create - ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if ( - !desc || - ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) - ) { - desc = { - enumerable: true, - get: function () { - return m[k]; - }, - }; - } - Object.defineProperty(o, k2, desc); - } - : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); -var __exportStar = - (this && this.__exportStar) || - function (m, exports) { - for (var p in m) - if (p !== 'default' && !Object.prototype.hasOwnProperty.call(exports, p)) - __createBinding(exports, m, p); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -__exportStar(require('./ContractsApi'), exports); -__exportStar(require('./types'), exports); diff --git a/src/dex/carbon/sdk/contracts-api/types.js b/src/dex/carbon/sdk/contracts-api/types.js deleted file mode 100644 index db8b17d54..000000000 --- a/src/dex/carbon/sdk/contracts-api/types.js +++ /dev/null @@ -1,2 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); diff --git a/src/dex/carbon/sdk/contracts-api/utils.js b/src/dex/carbon/sdk/contracts-api/utils.js deleted file mode 100644 index 1ff48a2fa..000000000 --- a/src/dex/carbon/sdk/contracts-api/utils.js +++ /dev/null @@ -1,221 +0,0 @@ -'use strict'; -var __assign = - (this && this.__assign) || - function () { - __assign = - Object.assign || - function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) - if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator['throw'](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done - ? resolve(result.value) - : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; -var __generator = - (this && this.__generator) || - function (thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [], - }, - f, - y, - t, - g; - return ( - (g = { next: verb(0), throw: verb(1), return: verb(2) }), - typeof Symbol === 'function' && - (g[Symbol.iterator] = function () { - return this; - }), - g - ); - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError('Generator is already executing.'); - while ((g && ((g = 0), op[0] && (_ = 0)), _)) - try { - if ( - ((f = 1), - y && - (t = - op[0] & 2 - ? y['return'] - : op[0] - ? y['throw'] || ((t = y['return']) && t.call(y), 0) - : y.next) && - !(t = t.call(y, op[1])).done) - ) - return t; - if (((y = 0), t)) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if ( - !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && - (op[0] === 6 || op[0] === 2) - ) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.buildTradeOverrides = exports.isETHAddress = exports.multicall = void 0; -var numerics_1 = require('../utils/numerics'); -var ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'.toLowerCase(); -var multicall = function (calls, multicallContract, blockHeight) { - return __awaiter(void 0, void 0, void 0, function () { - var encoded, encodedRes, error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - encoded = calls.map(function (call) { - return { - target: call.contractAddress.toLocaleLowerCase(), - callData: call.interface.encodeFunctionData( - call.methodName, - call.methodParameters, - ), - }; - }); - return [ - 4 /*yield*/, - multicallContract.tryAggregate(false, encoded, { - blockTag: blockHeight, - }), - ]; - case 1: - encodedRes = _a.sent(); - return [ - 2 /*return*/, - encodedRes.map(function (call, i) { - if (!call.success) return []; - return calls[i].interface.decodeFunctionResult( - calls[i].methodName, - call.returnData, - ); - }), - ]; - case 2: - error_1 = _a.sent(); - return [3 /*break*/, 3]; - case 3: - return [2 /*return*/]; - } - }); - }); -}; -exports.multicall = multicall; -var isETHAddress = function (address) { - return address.toLowerCase() === ETH_ADDRESS; -}; -exports.isETHAddress = isETHAddress; -var buildTradeOverrides = function ( - sourceToken, - tradeActions, - byTarget, - maxInput, - overrides, -) { - var customOverrides = __assign({}, overrides); - if ((0, exports.isETHAddress)(sourceToken)) { - if (byTarget) { - customOverrides.value = numerics_1.BigNumber.from(maxInput); - } else { - customOverrides.value = tradeActions.reduce(function (acc, cur) { - return acc.add(cur.amount); - }, numerics_1.BigNumber.from(0)); - } - } - return customOverrides; -}; -exports.buildTradeOverrides = buildTradeOverrides; diff --git a/src/dex/carbon/sdk/index.js b/src/dex/carbon/sdk/index.js deleted file mode 100644 index cfe35ad32..000000000 --- a/src/dex/carbon/sdk/index.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; -var __createBinding = - (this && this.__createBinding) || - (Object.create - ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if ( - !desc || - ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) - ) { - desc = { - enumerable: true, - get: function () { - return m[k]; - }, - }; - } - Object.defineProperty(o, k2, desc); - } - : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); -var __exportStar = - (this && this.__exportStar) || - function (m, exports) { - for (var p in m) - if (p !== 'default' && !Object.prototype.hasOwnProperty.call(exports, p)) - __createBinding(exports, m, p); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.strategyManagement = - exports.utils = - exports.tradeMatcher = - exports.chainCache = - exports.contractsApi = - void 0; -exports.contractsApi = require('./contracts-api'); -exports.chainCache = require('./chain-cache'); -exports.tradeMatcher = require('./trade-matcher'); -exports.utils = require('./utils'); -exports.strategyManagement = require('./strategy-management'); -__exportStar(require('./common/types'), exports); diff --git a/src/dex/carbon/sdk/strategy-management/Toolkit.js b/src/dex/carbon/sdk/strategy-management/Toolkit.js deleted file mode 100644 index fc8f854c3..000000000 --- a/src/dex/carbon/sdk/strategy-management/Toolkit.js +++ /dev/null @@ -1,1369 +0,0 @@ -'use strict'; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator['throw'](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done - ? resolve(result.value) - : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; -var __generator = - (this && this.__generator) || - function (thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [], - }, - f, - y, - t, - g; - return ( - (g = { next: verb(0), throw: verb(1), return: verb(2) }), - typeof Symbol === 'function' && - (g[Symbol.iterator] = function () { - return this; - }), - g - ); - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError('Generator is already executing.'); - while ((g && ((g = 0), op[0] && (_ = 0)), _)) - try { - if ( - ((f = 1), - y && - (t = - op[0] & 2 - ? y['return'] - : op[0] - ? y['throw'] || ((t = y['return']) && t.call(y), 0) - : y.next) && - !(t = t.call(y, op[1])).done) - ) - return t; - if (((y = 0), t)) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if ( - !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && - (op[0] === 6 || op[0] === 2) - ) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } - }; -var __spreadArray = - (this && this.__spreadArray) || - function (to, from, pack) { - if (pack || arguments.length === 2) - for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.Toolkit = exports.MarginalPriceOptions = void 0; -var numerics_1 = require('../utils/numerics'); -var types_1 = require('../common/types'); -var decimals_1 = require('../utils/decimals'); -// Trade matcher utilities -var trade_matcher_1 = require('../trade-matcher'); -// Stats functions -var stats_1 = require('./stats'); -// Logger -var logger_1 = require('../common/logger'); -var logger = new logger_1.Logger('index.ts'); -// Strategy utils -var utils_1 = require('./utils'); -// Encoder utility -var encoders_1 = require('../utils/encoders'); -var utils_2 = require('../utils'); -/** - * Enum representing options for the marginal price parameter of the function. - */ -var MarginalPriceOptions; -(function (MarginalPriceOptions) { - /** Indicates that the marginal price should be reset to its default value. */ - MarginalPriceOptions['reset'] = 'RESET'; - /** Indicates that the marginal price should be maintained at its current value. */ - MarginalPriceOptions['maintain'] = 'MAINTAIN'; -})( - (MarginalPriceOptions = - exports.MarginalPriceOptions || (exports.MarginalPriceOptions = {})), -); -var Toolkit = /** @class */ (function () { - /** - * Constructs a new Toolkit instance. - * - * @param {ContractsApi} api - The ContractsApi instance. - * @param {DecimalFetcher} [decimalFetcher] - Optional DecimalFetcher. - */ - function Toolkit(api, cache, decimalFetcher) { - var _this = this; - logger.debug('SDK class constructor called with', arguments); - this._api = api; - this._cache = cache; - // Create a fetcher that uses decimalFetcher if defined. - // If decimalFetcher(address) returns undefined or if decimalFetcher - // is undefined, use the default fetcher. - var fetcher = function (address) { - return __awaiter(_this, void 0, void 0, function () { - var decimals, _a; - var _b; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - return [ - 4 /*yield*/, - decimalFetcher === null || decimalFetcher === void 0 - ? void 0 - : decimalFetcher(address), - ]; - case 1: - if (!((_b = _c.sent()) !== null && _b !== void 0)) - return [3 /*break*/, 2]; - _a = _b; - return [3 /*break*/, 4]; - case 2: - return [ - 4 /*yield*/, - this._api.reader.getDecimalsByAddress(address), - ]; - case 3: - _a = _c.sent(); - _c.label = 4; - case 4: - decimals = _a; - return [2 /*return*/, decimals]; - } - }); - }); - }; - this._decimals = new decimals_1.Decimals(fetcher); - } - Toolkit.getMatchActions = function ( - amountWei, - tradeByTargetAmount, - ordersMap, - matchType, - filter, - ) { - var _a, _b; - if (matchType === void 0) { - matchType = types_1.MatchType.Fast; - } - var orders = (0, utils_2.ordersMapStrToBN)(ordersMap); - var result; - if (tradeByTargetAmount) { - result = (0, trade_matcher_1.matchByTargetAmount)( - numerics_1.BigNumber.from(amountWei), - orders, - [matchType], - filter, - ); - } else { - result = (0, trade_matcher_1.matchBySourceAmount)( - numerics_1.BigNumber.from(amountWei), - orders, - [matchType], - filter, - ); - } - return (_b = - (_a = result[matchType]) === null || _a === void 0 - ? void 0 - : _a.map(utils_2.matchActionBNToStr)) !== null && _b !== void 0 - ? _b - : []; - }; - /** - * Returns whether a pair has liquidity - * - * @param {string} sourceToken - address of the token the trade sells. - * @param {string} targetToken - address of the token the trade buys. - * - * @returns {Boolean} true or false. - * @throws {Error} If `startDataSync` has not been called. - * @throws {Error} If no orders have been found. - */ - Toolkit.prototype.hasLiquidityByPair = function (sourceToken, targetToken) { - return __awaiter(this, arguments, void 0, function () { - var orders; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('hasLiquidityByPair called', arguments); - return [ - 4 /*yield*/, - this._cache.getOrdersByPair(sourceToken, targetToken), - ]; - case 1: - orders = _a.sent(); - logger.debug('hasLiquidityByPair info:', { - orders: orders, - }); - return [2 /*return*/, Object.keys(orders).length > 0]; - } - }); - }); - }; - /** - * Returns liquidity for a given pair. - * - * @param {string} sourceToken - address of the token the trade sells. - * @param {string} targetToken - address of the token the trade buys. - * - * @returns {Promise} liquidity value as string - * @throws {Error} If `startDataSync` has not been called. - */ - Toolkit.prototype.getLiquidityByPair = function (sourceToken, targetToken) { - return __awaiter(this, arguments, void 0, function () { - var orders, liquidityWei, decimals, liquidity; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('getLiquidityByPair called', arguments); - return [ - 4 /*yield*/, - this._cache.getOrdersByPair(sourceToken, targetToken), - ]; - case 1: - orders = _a.sent(); - liquidityWei = Object.values(orders).reduce(function (acc, _a) { - var y = _a.y; - return acc.add(y); - }, numerics_1.BigNumber.from(0)); - return [4 /*yield*/, this._decimals.fetchDecimals(targetToken)]; - case 2: - decimals = _a.sent(); - liquidity = (0, numerics_1.formatUnits)(liquidityWei, decimals); - logger.debug('getLiquidityByPair info:', { - orders: orders, - liquidityWei: liquidityWei, - targetToken: targetToken, - decimals: decimals, - liquidity: liquidity, - }); - return [2 /*return*/, liquidity]; - } - }); - }); - }; - /** - * Returns the maximum source amount for a given pair. - * This is the sum of all source amounts in the orderbook. - * This number represents the maximum amount that can be traded by source. - * - * @param {string} sourceToken - Address of the token the trade sells. - * @param {string} targetToken - Address of the token the trade buys. - * - * @returns {Promise} Maximum source amount as a string. - * @throws {Error} If `startDataSync` has not been called. - */ - Toolkit.prototype.getMaxSourceAmountByPair = function ( - sourceToken, - targetToken, - ) { - return __awaiter(this, arguments, void 0, function () { - var orders, maxSourceAmountWei, decimals, maxSourceAmount; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('getMaxSourceAmountByPair called', arguments); - return [ - 4 /*yield*/, - this._cache.getOrdersByPair(sourceToken, targetToken), - ]; - case 1: - orders = _a.sent(); - maxSourceAmountWei = Object.values(orders).reduce(function ( - acc, - order, - ) { - return acc.add( - (0, trade_matcher_1.getEncodedTradeSourceAmount)( - order.y, - order, - ), - ); - }, - numerics_1.BigNumber.from(0)); - return [4 /*yield*/, this._decimals.fetchDecimals(sourceToken)]; - case 2: - decimals = _a.sent(); - maxSourceAmount = (0, numerics_1.formatUnits)( - maxSourceAmountWei, - decimals, - ); - logger.debug('getMaxSourceAmountByPair info:', { - orders: orders, - maxSourceAmountWei: maxSourceAmountWei, - sourceToken: sourceToken, - decimals: decimals, - maxSourceAmount: maxSourceAmount, - }); - return [2 /*return*/, maxSourceAmount]; - } - }); - }); - }; - /** - * Gets the strategies that are owned by the user. - * It does so by reading the voucher token and - * figuring out strategy IDs from them. - * It is possible to pass a synced cache and in that case - * the strategies will be read from the cache first. - * @param {string} user - The user who owns the strategies. - * - * @returns {Promise} An array of owned strategies. - * - */ - Toolkit.prototype.getUserStrategies = function (user) { - return __awaiter(this, arguments, void 0, function () { - var ids, - encodedStrategies, - uncachedIds, - uncachedStrategies, - decodedStrategies, - strategies; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('getUserStrategies called', arguments); - return [4 /*yield*/, this._api.reader.tokensByOwner(user)]; - case 1: - ids = _a.sent(); - encodedStrategies = []; - uncachedIds = ids; - if (this._cache) { - uncachedIds = ids.reduce(function (acc, id) { - var strategy = _this._cache.getStrategyById(id); - if (!strategy) { - acc.push(id); - } else { - encodedStrategies.push(strategy); - } - return acc; - }, []); - } - if (!(uncachedIds.length > 0)) return [3 /*break*/, 3]; - return [4 /*yield*/, this._api.reader.strategies(uncachedIds)]; - case 2: - uncachedStrategies = _a.sent(); - encodedStrategies = __spreadArray( - __spreadArray([], encodedStrategies, true), - uncachedStrategies, - true, - ); - _a.label = 3; - case 3: - decodedStrategies = encodedStrategies.map(utils_1.decodeStrategy); - return [ - 4 /*yield*/, - Promise.all( - decodedStrategies.map(function (strategy) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - (0, utils_1.parseStrategy)( - strategy, - this._decimals, - ), - ]; - case 1: - return [2 /*return*/, _a.sent()]; - } - }); - }); - }), - ), - ]; - case 4: - strategies = _a.sent(); - logger.debug('getUserStrategies info:', { - ids: ids, - encodedStrategies: encodedStrategies, - decodedStrategies: decodedStrategies, - strategies: strategies, - }); - return [2 /*return*/, strategies]; - } - }); - }); - }; - /** - * Returns the data needed to process a trade. - * `getMatchParams` returns the data for a given source and target token pair. - * You can use the result to call `matchBySourceAmount` or `matchByTargetAmount`, - * then get the actions and pass them to `getTradeDataFromActions`. - * - * @param {string} sourceToken - Address of the source token. - * @param {string} targetToken - Address of the target token. - * @param {string} amount - The amount of tokens to trade. - * @param {boolean} tradeByTargetAmount - Whether to trade by target amount (`true`) or source amount (`false`). - * - * @returns {Promise} An object containing the necessary data to process a trade. - * @property {OrdersMap} orders - The orders mapped by their IDs. - * @property {string} amountWei - The amount in wei to trade. - * @property {number} sourceDecimals - The number of decimals for the source token. - * @property {number} targetDecimals - The number of decimals for the target token. - */ - Toolkit.prototype.getMatchParams = function ( - sourceToken, - targetToken, - amount, - tradeByTargetAmount, - ) { - return __awaiter(this, arguments, void 0, function () { - var decimals, sourceDecimals, targetDecimals, orders, amountWei; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('getMatchParams called', arguments); - decimals = this._decimals; - return [4 /*yield*/, decimals.fetchDecimals(sourceToken)]; - case 1: - sourceDecimals = _a.sent(); - return [4 /*yield*/, decimals.fetchDecimals(targetToken)]; - case 2: - targetDecimals = _a.sent(); - return [ - 4 /*yield*/, - this._cache.getOrdersByPair(sourceToken, targetToken), - ]; - case 3: - orders = _a.sent(); - amountWei = (0, numerics_1.parseUnits)( - amount, - tradeByTargetAmount ? targetDecimals : sourceDecimals, - ); - return [ - 2 /*return*/, - { - orders: (0, utils_2.ordersMapBNToStr)(orders), - amountWei: amountWei.toString(), - sourceDecimals: sourceDecimals, - targetDecimals: targetDecimals, - }, - ]; - } - }); - }); - }; - /** - * Returns the off-chain match algorithm results of orders to fulfill to complete the trade. - * Each trade action is identified by the ID of the strategy that the trade order belongs to - * and the input amount to place for this order. - * - * The `getTradeData` method will match the specified `amount` of source tokens or target tokens - * with available orders from the blockchain, depending on the value of `tradeByTargetAmount`. - * It uses the provided `filter` function to filter the available orders. The resulting trade - * actions will be returned in an object, along with the unsigned transaction that can be used - * to execute the trade. - * - * It is up to the user to sign and send the transaction. - * - * @param {string} sourceToken - The source token for the trade. - * @param {string} targetToken - The target token for the trade. - * @param {string} amount - The amount of source tokens or target tokens to trade, depending on the value of `tradeByTargetAmount`. - * @param {boolean} tradeByTargetAmount - Whether to trade by target amount (`true`) or source amount (`false`). - * @param {MatchType} [matchType] - The type of match to perform. Defaults to `MatchType.Fast`. - * @param {(rate: Rate) => boolean} [filter] - Optional function to filter the available orders. - * - * @returns {Promise} An object containing the trade actions and other relevant data. - * @property {TradeAction[]} tradeActions - An array of trade actions in wei. - * @property {Action[]} actionsTokenRes - An array of trade actions in the proper token resolution. - * @property {string} totalSourceAmount - The total input amount in token resolution. - * @property {string} totalTargetAmount - The total output amount in token resolution. - * @property {string} effectiveRate - The effective rate between totalInput and totalOutput - * @property {MatchAction[]} actionsWei - An array of trade actions in wei. - * @throws {Error} If `startDataSync` has not been called. - */ - Toolkit.prototype.getTradeData = function ( - sourceToken, - targetToken, - amount, - tradeByTargetAmount, - matchType, - filter, - ) { - if (matchType === void 0) { - matchType = types_1.MatchType.Fast; - } - return __awaiter(this, arguments, void 0, function () { - var _a, orders, amountWei, actionsWei, res; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - logger.debug('getTradeData called', arguments); - return [ - 4 /*yield*/, - this.getMatchParams( - sourceToken, - targetToken, - amount, - tradeByTargetAmount, - ), - ]; - case 1: - (_a = _b.sent()), (orders = _a.orders), (amountWei = _a.amountWei); - actionsWei = Toolkit.getMatchActions( - amountWei, - tradeByTargetAmount, - orders, - matchType, - filter, - ); - return [ - 4 /*yield*/, - this.getTradeDataFromActions( - sourceToken, - targetToken, - tradeByTargetAmount, - actionsWei, - ), - ]; - case 2: - res = _b.sent(); - logger.debug('getTradeData info:', { - orders: orders, - amount: amount, - amountWei: amountWei, - res: res, - }); - return [2 /*return*/, res]; - } - }); - }); - }; - Toolkit.prototype.getTradeDataFromActions = function ( - sourceToken, - targetToken, - tradeByTargetAmount, - actionsWei, - ) { - return __awaiter(this, arguments, void 0, function () { - var feePPM, - decimals, - sourceDecimals, - targetDecimals, - tradeActions, - actionsTokenRes, - totalOutput, - totalInput, - totalSourceAmount, - totalTargetAmount, - res, - effectiveRate; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('getTradeDataFromActions called', arguments); - feePPM = this._cache.tradingFeePPM; - // intentional == instead of === - if (feePPM == undefined) - throw new Error('tradingFeePPM is undefined'); - decimals = this._decimals; - return [4 /*yield*/, decimals.fetchDecimals(sourceToken)]; - case 1: - sourceDecimals = _a.sent(); - return [4 /*yield*/, decimals.fetchDecimals(targetToken)]; - case 2: - targetDecimals = _a.sent(); - tradeActions = []; - actionsTokenRes = []; - totalOutput = numerics_1.BigNumber.from(0); - totalInput = numerics_1.BigNumber.from(0); - actionsWei.forEach(function (action) { - tradeActions.push({ - strategyId: action.id, - amount: action.input, - }); - if (tradeByTargetAmount) { - actionsTokenRes.push({ - id: action.id, - sourceAmount: (0, numerics_1.formatUnits)( - (0, utils_1.addFee)(action.output, feePPM) - .floor() - .toFixed(0), - sourceDecimals, - ), - targetAmount: (0, numerics_1.formatUnits)( - action.input, - targetDecimals, - ), - }); - } else { - actionsTokenRes.push({ - id: action.id, - sourceAmount: (0, numerics_1.formatUnits)( - action.input, - sourceDecimals, - ), - targetAmount: (0, numerics_1.formatUnits)( - (0, utils_1.subtractFee)(action.output, feePPM) - .floor() - .toFixed(0), - targetDecimals, - ), - }); - } - totalInput = totalInput.add(action.input); - totalOutput = totalOutput.add(action.output); - }); - if (tradeByTargetAmount) { - totalSourceAmount = (0, utils_1.addFee)(totalOutput, feePPM) - .floor() - .toFixed(0); - totalTargetAmount = totalInput.toString(); - } else { - totalSourceAmount = totalInput.toString(); - totalTargetAmount = (0, utils_1.subtractFee)(totalOutput, feePPM) - .floor() - .toFixed(0); - } - if ( - new numerics_1.Decimal(totalSourceAmount).isZero() || - new numerics_1.Decimal(totalTargetAmount).isZero() - ) { - res = { - tradeActions: tradeActions, - actionsTokenRes: actionsTokenRes, - totalSourceAmount: '0', - totalTargetAmount: '0', - effectiveRate: '0', - actionsWei: actionsWei, - }; - } else { - effectiveRate = new numerics_1.Decimal(totalTargetAmount) - .div(totalSourceAmount) - .times((0, numerics_1.tenPow)(sourceDecimals, targetDecimals)) - .toString(); - res = { - tradeActions: tradeActions, - actionsTokenRes: actionsTokenRes, - totalSourceAmount: (0, numerics_1.formatUnits)( - totalSourceAmount, - sourceDecimals, - ), - totalTargetAmount: (0, numerics_1.formatUnits)( - totalTargetAmount, - targetDecimals, - ), - effectiveRate: effectiveRate, - actionsWei: actionsWei, - }; - } - logger.debug('getTradeDataFromActions info:', { - sourceDecimals: sourceDecimals, - targetDecimals: targetDecimals, - actionsWei: actionsWei, - totalInput: totalInput, - totalOutput: totalOutput, - tradingFeePPM: feePPM, - res: res, - }); - return [2 /*return*/, res]; - } - }); - }); - }; - /** - * Creates an unsigned transaction to fulfill a trade using an array of trade actions. - * Each trade action is identified by the ID of the strategy that the trade order belongs to - * and the input amount to place for this order. - * - * It is up to the user to sign and send the transaction. - * - * @param {string} sourceToken - The source token for the trade. - * @param {string} targetToken - The target token for the trade. - * @param {TradeAction[]} tradeActions - An array of trade actions in wei - as received from `trade`. - * @param {string} deadline - Deadline for the trade - * @param {string} maxInput - Maximum input for the trade - * @param {Overrides} [overrides] - Optional overrides for the transaction. - * @returns {Promise} A promise that resolves to the unsigned trade transaction. - * - * @example - * // calling trade - * const tradeTx = sdk.composeTradeTransaction( - * '0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A', - * '0x6B175474E89094C44Da98b954EedeAC495271d0F', - * false, - * [] - * ); - * - * // Performing the trade by signing and sending the transaction: - * - * // Import the ethers.js library and the relevant wallet provider - * const ethers = require('ethers'); - * const provider = new ethers.providers.Web3Provider(web3.currentProvider); - * - * // Load the private key for the wallet that will sign and send the transaction - * const privateKey = '0x...'; - * const wallet = new ethers.Wallet(privateKey, provider); - * - * // Sign and send the transaction - * const signedTradeTx = await wallet.sign(tradeTx); - * const txReceipt = await provider.sendTransaction(signedTradeTx); - * console.log(txReceipt); - * // { - * // blockHash: '0x...', - * // blockNumber: 12345, - * // ... - * // } - */ - Toolkit.prototype.composeTradeByTargetTransaction = function ( - sourceToken, - targetToken, - tradeActions, - deadline, - maxInput, - overrides, - ) { - return __awaiter(this, arguments, void 0, function () { - var sourceDecimals; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('composeTradeByTargetTransaction called', arguments); - return [4 /*yield*/, this._decimals.fetchDecimals(sourceToken)]; - case 1: - sourceDecimals = _a.sent(); - return [ - 2 /*return*/, - this._api.composer.tradeByTargetAmount( - sourceToken, - targetToken, - tradeActions.map(utils_2.tradeActionStrToBN), - deadline, - (0, numerics_1.parseUnits)(maxInput, sourceDecimals), - overrides, - ), - ]; - } - }); - }); - }; - /** - * Creates an unsigned transaction to fulfill a trade using an array of trade actions. - * Each trade action is identified by the ID of the strategy that the trade order belongs to - * and the input amount to place for this order. - * - * It is up to the user to sign and send the transaction. - * - * @param {string} sourceToken - The source token for the trade. - * @param {string} targetToken - The target token for the trade. - * @param {TradeAction[]} tradeActions - An array of trade actions in wei - as received from `trade`. - * @param {string} deadline - Deadline for the trade - * @param {string} minReturn - Minimum return for the trade - * @param {Overrides} [overrides] - Optional overrides for the transaction. - * @returns {Promise} A promise that resolves to the unsigned trade transaction. - * - * @example - * // calling trade - * const tradeTx = sdk.composeTradeTransaction( - * '0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A', - * '0x6B175474E89094C44Da98b954EedeAC495271d0F', - * false, - * [] - * ); - * - * // Performing the trade by signing and sending the transaction: - * - * // Import the ethers.js library and the relevant wallet provider - * const ethers = require('ethers'); - * const provider = new ethers.providers.Web3Provider(web3.currentProvider); - * - * // Load the private key for the wallet that will sign and send the transaction - * const privateKey = '0x...'; - * const wallet = new ethers.Wallet(privateKey, provider); - * - * // Sign and send the transaction - * const signedTradeTx = await wallet.sign(tradeTx); - * const txReceipt = await provider.sendTransaction(signedTradeTx); - * console.log(txReceipt); - * // { - * // blockHash: '0x...', - * // blockNumber: 12345, - * // ... - * // } - */ - Toolkit.prototype.composeTradeBySourceTransaction = function ( - sourceToken, - targetToken, - tradeActions, - deadline, - minReturn, - overrides, - ) { - return __awaiter(this, arguments, void 0, function () { - var targetDecimals; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('composeTradeBySourceTransaction called', arguments); - return [4 /*yield*/, this._decimals.fetchDecimals(targetToken)]; - case 1: - targetDecimals = _a.sent(); - return [ - 2 /*return*/, - this._api.composer.tradeBySourceAmount( - sourceToken, - targetToken, - tradeActions.map(utils_2.tradeActionStrToBN), - deadline, - (0, numerics_1.parseUnits)(minReturn, targetDecimals), - overrides, - ), - ]; - } - }); - }); - }; - /** - * Creates an unsigned transaction to create a strategy for buying and selling tokens of `baseToken` for price in `quoteToken` per 1 `baseToken`. - * - * The `createBuySellStrategy` method creates a strategy object based on the specified parameters, encodes it according to the - * format used by the smart contracts, and returns an unsigned transaction that can be used to create the strategy on the - * blockchain. - * - * It is up to the user to sign and send the transaction. - * - * @param {string} baseToken - The address of the base token for the strategy. - * @param {string} quoteToken - The address of the quote token for the strategy. - * @param {string} buyPriceLow - The minimum buy price for the strategy, in in `quoteToken` per 1 `baseToken`, as a string. - * @param {string} buyPriceHigh - The maximum buy price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. - * @param {string} buyBudget - The maximum budget for buying tokens in the strategy, in `quoteToken`, as a string. - * @param {string} sellPriceLow - The minimum sell price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. - * @param {string} sellPriceHigh - The maximum sell price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. - * @param {string} sellBudget - The maximum budget for selling tokens in the strategy, in `baseToken`, as a string. - * @param {Overrides} [overrides] - Optional overrides for the transaction, such as gas price or nonce. - * @returns {Promise} A promise that resolves to the unsigned transaction that can be used to create the strategy. - * * - * @example - * // Import the ethers.js library and the relevant wallet provider - * const ethers = require('ethers'); - * const provider = new ethers.providers.Web3Provider(web3.currentProvider); - * - * // Load the private key for the wallet that will sign and send the transaction - * const privateKey = '0x...'; - * const wallet = new ethers.Wallet(privateKey, provider); - * - * // Call the createBuySellStrategy method to create an unsigned transaction - * const createStrategyTx = sdk.createBuySellStrategy( - * '0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A', - * '0x6B175474E89094C44Da98b954EedeAC495271d0F', - * '0.1', - * '0.2', - * '1', - * '0.5', - * '0.6', - * '2' - * ); - * - * // Sign and send the transaction - * const signedCreateStrategyTx = await wallet.sign(createStrategyTx); - * const txReceipt = await provider.sendTransaction(signedCreateStrategyTx); - */ - Toolkit.prototype.createBuySellStrategy = function ( - baseToken, - quoteToken, - buyPriceLow, - buyPriceHigh, - buyBudget, - sellPriceLow, - sellPriceHigh, - sellBudget, - overrides, - ) { - return __awaiter(this, arguments, void 0, function () { - var decimals, baseDecimals, quoteDecimals, strategy, encStrategy; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('createBuySellStrategy called', arguments); - decimals = this._decimals; - return [4 /*yield*/, decimals.fetchDecimals(baseToken)]; - case 1: - baseDecimals = _a.sent(); - return [4 /*yield*/, decimals.fetchDecimals(quoteToken)]; - case 2: - quoteDecimals = _a.sent(); - strategy = (0, utils_1.buildStrategyObject)( - baseToken, - quoteToken, - baseDecimals, - quoteDecimals, - buyPriceLow, - buyPriceHigh, - buyBudget, - sellPriceLow, - sellPriceHigh, - sellBudget, - ); - encStrategy = (0, utils_1.encodeStrategy)(strategy); - logger.debug('createBuySellStrategy info:', { - strategy: strategy, - encStrategy: encStrategy, - }); - return [ - 2 /*return*/, - this._api.composer.createStrategy( - encStrategy.token0, - encStrategy.token1, - encStrategy.order0, - encStrategy.order1, - overrides, - ), - ]; - } - }); - }); - }; - /** - * - * @param strategyId - * @param encoded - * @param param2 - * @param {MarginalPriceOptions | string} marginalPrice - The marginal price parameter. - * Can either be a value from the `MarginalPriceOptions` enum, or a "BigNumberish" string value for advanced users - - * who wish to set the marginal price themselves. - * @param overrides - * @returns - */ - Toolkit.prototype.updateStrategy = function ( - strategyId, - encoded, - _a, - buyMarginalPrice, - sellMarginalPrice, - overrides, - ) { - var buyPriceLow = _a.buyPriceLow, - buyPriceHigh = _a.buyPriceHigh, - buyBudget = _a.buyBudget, - sellPriceLow = _a.sellPriceLow, - sellPriceHigh = _a.sellPriceHigh, - sellBudget = _a.sellBudget; - return __awaiter(this, arguments, void 0, function () { - var decodedOriginal, - originalStrategy, - decimals, - baseDecimals, - quoteDecimals, - newStrategy, - newEncodedStrategy, - encodedBN; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - logger.debug('updateStrategy called', arguments); - decodedOriginal = (0, utils_1.decodeStrategy)( - (0, utils_2.encodedStrategyStrToBN)(encoded), - ); - return [ - 4 /*yield*/, - (0, utils_1.parseStrategy)(decodedOriginal, this._decimals), - ]; - case 1: - originalStrategy = _b.sent(); - decimals = this._decimals; - return [ - 4 /*yield*/, - decimals.fetchDecimals(originalStrategy.baseToken), - ]; - case 2: - baseDecimals = _b.sent(); - return [ - 4 /*yield*/, - decimals.fetchDecimals(originalStrategy.quoteToken), - ]; - case 3: - quoteDecimals = _b.sent(); - newStrategy = (0, utils_1.buildStrategyObject)( - originalStrategy.baseToken, - originalStrategy.quoteToken, - baseDecimals, - quoteDecimals, - buyPriceLow !== null && buyPriceLow !== void 0 - ? buyPriceLow - : originalStrategy.buyPriceLow, - buyPriceHigh !== null && buyPriceHigh !== void 0 - ? buyPriceHigh - : originalStrategy.buyPriceHigh, - buyBudget !== null && buyBudget !== void 0 - ? buyBudget - : originalStrategy.buyBudget, - sellPriceLow !== null && sellPriceLow !== void 0 - ? sellPriceLow - : originalStrategy.sellPriceLow, - sellPriceHigh !== null && sellPriceHigh !== void 0 - ? sellPriceHigh - : originalStrategy.sellPriceHigh, - sellBudget !== null && sellBudget !== void 0 - ? sellBudget - : originalStrategy.sellBudget, - ); - newEncodedStrategy = (0, utils_1.encodeStrategy)(newStrategy); - encodedBN = (0, utils_2.encodedStrategyStrToBN)(encoded); - if (buyBudget === undefined) { - newEncodedStrategy.order1.y = encodedBN.order1.y; - } - if (sellBudget === undefined) { - newEncodedStrategy.order0.y = encodedBN.order0.y; - } - if (buyPriceLow === undefined && buyPriceHigh === undefined) { - newEncodedStrategy.order1.A = encodedBN.order1.A; - newEncodedStrategy.order1.B = encodedBN.order1.B; - } - if (sellPriceLow === undefined && sellPriceHigh === undefined) { - newEncodedStrategy.order0.A = encodedBN.order0.A; - newEncodedStrategy.order0.B = encodedBN.order0.B; - } - if (buyBudget !== undefined) { - if ( - buyMarginalPrice === undefined || - buyMarginalPrice === MarginalPriceOptions.reset || - encodedBN.order1.y.isZero() - ) { - newEncodedStrategy.order1.z = newEncodedStrategy.order1.y; - } else if (buyMarginalPrice === MarginalPriceOptions.maintain) { - // maintain the current ratio of y/z - newEncodedStrategy.order1.z = (0, numerics_1.mulDiv)( - encodedBN.order1.z, - newEncodedStrategy.order1.y, - encodedBN.order1.y, - ); - } - } - if (sellBudget !== undefined) { - if ( - sellMarginalPrice === undefined || - sellMarginalPrice === MarginalPriceOptions.reset || - encodedBN.order0.y.isZero() - ) { - newEncodedStrategy.order0.z = newEncodedStrategy.order0.y; - } else if (sellMarginalPrice === MarginalPriceOptions.maintain) { - // maintain the current ratio of y/z - newEncodedStrategy.order0.z = (0, numerics_1.mulDiv)( - encodedBN.order0.z, - newEncodedStrategy.order0.y, - encodedBN.order0.y, - ); - } - } - if (buyPriceLow !== undefined || buyPriceHigh !== undefined) { - newEncodedStrategy.order1.z = newEncodedStrategy.order1.y; - } - if (sellPriceLow !== undefined || sellPriceHigh !== undefined) { - newEncodedStrategy.order0.z = newEncodedStrategy.order0.y; - } - if ( - buyMarginalPrice !== undefined && - buyMarginalPrice !== MarginalPriceOptions.reset && - buyMarginalPrice !== MarginalPriceOptions.maintain - ) { - // TODO: set newEncodedStrategy.order1.z according to the given marginal price - throw new Error( - 'Support for custom marginal price is not implemented yet', - ); - } - if ( - sellMarginalPrice !== undefined && - sellMarginalPrice !== MarginalPriceOptions.reset && - sellMarginalPrice !== MarginalPriceOptions.maintain - ) { - // TODO: set newEncodedStrategy.order0.z according to the given marginal price - throw new Error( - 'Support for custom marginal price is not implemented yet', - ); - } - logger.debug('updateStrategy info:', { - baseDecimals: baseDecimals, - quoteDecimals: quoteDecimals, - decodedOriginal: decodedOriginal, - originalStrategy: originalStrategy, - newStrategy: newStrategy, - newEncodedStrategy: newEncodedStrategy, - }); - return [ - 2 /*return*/, - this._api.composer.updateStrategy( - numerics_1.BigNumber.from(strategyId), - newEncodedStrategy.token0, - newEncodedStrategy.token1, - [encodedBN.order0, encodedBN.order1], - [newEncodedStrategy.order0, newEncodedStrategy.order1], - overrides, - ), - ]; - } - }); - }); - }; - Toolkit.prototype.deleteStrategy = function (strategyId) { - return __awaiter(this, arguments, void 0, function () { - return __generator(this, function (_a) { - logger.debug('deleteStrategy called', arguments); - return [ - 2 /*return*/, - this._api.composer.deleteStrategy( - numerics_1.BigNumber.from(strategyId), - ), - ]; - }); - }); - }; - /** - * Returns liquidity for a given rate. - * - * @param {string} sourceToken - address of the token the trade sells. - * @param {string} targetToken - address of the token the trade buys. - * @param {string[]} rates - the rates for which to find liquidity depth. - * - * @returns {Promise} liquidity value as string - * @throws {Error} If `startDataSync` has not been called. - */ - Toolkit.prototype.getRateLiquidityDepthsByPair = function ( - sourceToken, - targetToken, - rates, - ) { - return __awaiter(this, arguments, void 0, function () { - var orders, - _a, - _b, - decimals, - sourceDecimals, - targetDecimals, - parsedRates, - depthsWei, - depthsInTargetDecimals; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - logger.debug('getRateLiquidityDepthByPair called', arguments); - _b = (_a = Object).values; - return [ - 4 /*yield*/, - this._cache.getOrdersByPair(sourceToken, targetToken), - ]; - case 1: - orders = _b.apply(_a, [_c.sent()]).map(encoders_1.decodeOrder); - decimals = this._decimals; - return [4 /*yield*/, decimals.fetchDecimals(sourceToken)]; - case 2: - sourceDecimals = _c.sent(); - return [4 /*yield*/, decimals.fetchDecimals(targetToken)]; - case 3: - targetDecimals = _c.sent(); - parsedRates = rates.map(function (rate) { - return new numerics_1.Decimal( - (0, utils_1.normalizeRate)( - rate, - targetDecimals, - sourceDecimals, - ), - ); - }); - depthsWei = (0, stats_1.getDepths)(orders, parsedRates).map( - function (rate) { - return rate.floor().toFixed(0); - }, - ); - depthsInTargetDecimals = depthsWei.map(function (depthWei) { - return (0, numerics_1.formatUnits)(depthWei, targetDecimals); - }); - logger.debug('getRateLiquidityDepthByPair info:', { - orders: orders, - depthsWei: depthsWei, - targetDecimals: targetDecimals, - depthsInTargetDecimals: depthsInTargetDecimals, - }); - return [2 /*return*/, depthsInTargetDecimals]; - } - }); - }); - }; - Toolkit.prototype.getMinRateByPair = function (sourceToken, targetToken) { - return __awaiter(this, arguments, void 0, function () { - var orders, - _a, - _b, - minRate, - decimals, - sourceDecimals, - targetDecimals, - normalizedRate; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - logger.debug('getMinRateByPair called', arguments); - _b = (_a = Object).values; - return [ - 4 /*yield*/, - this._cache.getOrdersByPair(sourceToken, targetToken), - ]; - case 1: - orders = _b.apply(_a, [_c.sent()]).map(encoders_1.decodeOrder); - minRate = (0, stats_1.getMinRate)(orders).toString(); - decimals = this._decimals; - return [4 /*yield*/, decimals.fetchDecimals(sourceToken)]; - case 2: - sourceDecimals = _c.sent(); - return [4 /*yield*/, decimals.fetchDecimals(targetToken)]; - case 3: - targetDecimals = _c.sent(); - normalizedRate = (0, utils_1.normalizeRate)( - minRate, - sourceDecimals, - targetDecimals, - ); - logger.debug('getMinRateByPair info:', { - orders: orders, - minRate: minRate, - sourceDecimals: sourceDecimals, - targetDecimals: targetDecimals, - normalizedRate: normalizedRate, - }); - return [2 /*return*/, normalizedRate]; - } - }); - }); - }; - Toolkit.prototype.getMaxRateByPair = function (sourceToken, targetToken) { - return __awaiter(this, arguments, void 0, function () { - var orders, - _a, - _b, - maxRate, - decimals, - sourceDecimals, - targetDecimals, - normalizedRate; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - logger.debug('getMaxRateByPair called', arguments); - _b = (_a = Object).values; - return [ - 4 /*yield*/, - this._cache.getOrdersByPair(sourceToken, targetToken), - ]; - case 1: - orders = _b.apply(_a, [_c.sent()]).map(encoders_1.decodeOrder); - maxRate = (0, stats_1.getMaxRate)(orders).toString(); - decimals = this._decimals; - return [4 /*yield*/, decimals.fetchDecimals(sourceToken)]; - case 2: - sourceDecimals = _c.sent(); - return [4 /*yield*/, decimals.fetchDecimals(targetToken)]; - case 3: - targetDecimals = _c.sent(); - normalizedRate = (0, utils_1.normalizeRate)( - maxRate, - sourceDecimals, - targetDecimals, - ); - logger.debug('getMaxRateByPair info:', { - orders: orders, - maxRate: maxRate, - sourceDecimals: sourceDecimals, - targetDecimals: targetDecimals, - normalizedRate: normalizedRate, - }); - return [2 /*return*/, normalizedRate]; - } - }); - }); - }; - return Toolkit; -})(); -exports.Toolkit = Toolkit; diff --git a/src/dex/carbon/sdk/strategy-management/index.js b/src/dex/carbon/sdk/strategy-management/index.js deleted file mode 100644 index 5c3cf09b6..000000000 --- a/src/dex/carbon/sdk/strategy-management/index.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; -var __createBinding = - (this && this.__createBinding) || - (Object.create - ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if ( - !desc || - ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) - ) { - desc = { - enumerable: true, - get: function () { - return m[k]; - }, - }; - } - Object.defineProperty(o, k2, desc); - } - : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); -var __exportStar = - (this && this.__exportStar) || - function (m, exports) { - for (var p in m) - if (p !== 'default' && !Object.prototype.hasOwnProperty.call(exports, p)) - __createBinding(exports, m, p); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -__exportStar(require('./Toolkit'), exports); -__exportStar(require('./utils'), exports); diff --git a/src/dex/carbon/sdk/strategy-management/stats.js b/src/dex/carbon/sdk/strategy-management/stats.js deleted file mode 100644 index 1fd17758b..000000000 --- a/src/dex/carbon/sdk/strategy-management/stats.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.getDepths = exports.getMaxRate = exports.getMinRate = void 0; -var numerics_1 = require('../utils/numerics'); -function getMinRate(orders) { - return orders.reduce(function (rate, order) { - return numerics_1.Decimal.min(rate, order.lowestRate); - }, new numerics_1.Decimal(+Infinity)); -} -exports.getMinRate = getMinRate; -function getMaxRate(orders) { - return orders.reduce(function (rate, order) { - return numerics_1.Decimal.max(rate, order.marginalRate); - }, new numerics_1.Decimal(-Infinity)); -} -exports.getMaxRate = getMaxRate; -function getDepths(orders, rates) { - var processedOrders = orders.map(function (order) { - var min = new numerics_1.Decimal(order.lowestRate).sqrt(); - var mid = new numerics_1.Decimal(order.marginalRate).sqrt(); - return { - liq: new numerics_1.Decimal(order.liquidity), - min: min, - mid: mid, - midMinusMin: mid.sub(min), - }; - }); - return rates.map(function (rate) { - var rateRoot = rate.sqrt(); - return processedOrders.reduce(function (sum, order) { - return sum.add(getAmount(order, rateRoot)); - }, new numerics_1.Decimal(0)); - }); -} -exports.getDepths = getDepths; -/** - * Given an order with: - * - liquidity: the liquidity of the order - * - lowestRate: the most expensive rate at which the order will sell its liquidity - * - marginalRate: the rate at which the order is currently selling its liquidity - * If a given rate is: - * - more expensive (lower) than lowestRate: all of the liquidity can be bought at this rate - * - less expensive (higher) than marginalRate: none of the liquidity can be bought at this rate - * - in between lowestRate and marginalRate: some of the liquidity can be bought at this rate - * @param {ProcessedOrder} order - * @param {Decimal} rateRoot - the square root of the rate - * @returns {Decimal} the amount of liquidity that can be bought without paying more than the given rate - */ -function getAmount(order, rateRoot) { - // rate <= lowestRate - all of the liquidity can be bought at this rate - if (rateRoot.lte(order.min)) { - return order.liq; - } - // rate >= marginalRate - none of the liquidity can be bought at this rate - if (rateRoot.gte(order.mid)) { - return new numerics_1.Decimal(0); - } - // lowestRate < rate < marginalRate - return order.liq.sub( - order.liq.mul(rateRoot.sub(order.min)).div(order.midMinusMin), - ); -} diff --git a/src/dex/carbon/sdk/strategy-management/utils.js b/src/dex/carbon/sdk/strategy-management/utils.js deleted file mode 100644 index a28174865..000000000 --- a/src/dex/carbon/sdk/strategy-management/utils.js +++ /dev/null @@ -1,420 +0,0 @@ -'use strict'; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator['throw'](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done - ? resolve(result.value) - : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; -var __generator = - (this && this.__generator) || - function (thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [], - }, - f, - y, - t, - g; - return ( - (g = { next: verb(0), throw: verb(1), return: verb(2) }), - typeof Symbol === 'function' && - (g[Symbol.iterator] = function () { - return this; - }), - g - ); - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError('Generator is already executing.'); - while ((g && ((g = 0), op[0] && (_ = 0)), _)) - try { - if ( - ((f = 1), - y && - (t = - op[0] & 2 - ? y['return'] - : op[0] - ? y['throw'] || ((t = y['return']) && t.call(y), 0) - : y.next) && - !(t = t.call(y, op[1])).done) - ) - return t; - if (((y = 0), t)) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if ( - !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && - (op[0] === 6 || op[0] === 2) - ) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.subtractFee = - exports.addFee = - exports.PPM_RESOLUTION = - exports.createOrders = - exports.buildStrategyObject = - exports.parseStrategy = - exports.decodeStrategy = - exports.encodeStrategy = - exports.normalizeInvertedRate = - exports.normalizeRate = - void 0; -var numerics_1 = require('../utils/numerics'); -var logger_1 = require('../common/logger'); -var encoders_1 = require('../utils/encoders'); -var utils_1 = require('../utils'); -var logger = new logger_1.Logger('utils.ts'); -function normalizeRate(amount, amountTokenDecimals, otherTokenDecimals) { - return new numerics_1.Decimal(amount.toString()) - .times((0, numerics_1.tenPow)(amountTokenDecimals, otherTokenDecimals)) - .toFixed(); -} -exports.normalizeRate = normalizeRate; -function normalizeInvertedRate( - amount, - amountTokenDecimals, - otherTokenDecimals, -) { - if (+amount.toString() === 0) return '0'; - return new numerics_1.Decimal(1) - .div(amount.toString()) - .times((0, numerics_1.tenPow)(otherTokenDecimals, amountTokenDecimals)) - .toFixed(); -} -exports.normalizeInvertedRate = normalizeInvertedRate; -var encodeStrategy = function (strategy) { - return { - token0: strategy.token0, - token1: strategy.token1, - order0: (0, encoders_1.encodeOrder)(strategy.order0), - order1: (0, encoders_1.encodeOrder)(strategy.order1), - }; -}; -exports.encodeStrategy = encodeStrategy; -var decodeStrategy = function (strategy) { - return { - id: strategy.id, - token0: strategy.token0, - token1: strategy.token1, - order0: (0, encoders_1.decodeOrder)(strategy.order0), - order1: (0, encoders_1.decodeOrder)(strategy.order1), - encoded: strategy, - }; -}; -exports.decodeStrategy = decodeStrategy; -/** - * Converts a DecodedStrategy object to a Strategy object. - * - * @param {DecodedStrategy} strategy - The DecodedStrategy object to convert. - * @returns {Promise} - A promise that resolves to the Strategy object. - * @throws {Error} If an error occurs while fetching the decimals for the tokens. - */ -function parseStrategy(strategy, decimals) { - return __awaiter(this, arguments, void 0, function () { - var id, - token0, - token1, - order0, - order1, - encoded, - decimals0, - decimals1, - buyPriceLow, - buyPriceHigh, - sellPriceLow, - sellPriceHigh, - sellBudget, - buyBudget, - strId, - strEncoded; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - logger.debug('parseStrategy called', arguments); - (id = strategy.id), - (token0 = strategy.token0), - (token1 = strategy.token1), - (order0 = strategy.order0), - (order1 = strategy.order1), - (encoded = strategy.encoded); - return [4 /*yield*/, decimals.fetchDecimals(token0)]; - case 1: - decimals0 = _a.sent(); - return [4 /*yield*/, decimals.fetchDecimals(token1)]; - case 2: - decimals1 = _a.sent(); - buyPriceLow = normalizeRate(order1.lowestRate, decimals0, decimals1); - buyPriceHigh = normalizeRate( - order1.highestRate, - decimals0, - decimals1, - ); - sellPriceLow = normalizeInvertedRate( - order0.highestRate, - decimals1, - decimals0, - ); - sellPriceHigh = normalizeInvertedRate( - order0.lowestRate, - decimals1, - decimals0, - ); - sellBudget = (0, numerics_1.formatUnits)(order0.liquidity, decimals0); - buyBudget = (0, numerics_1.formatUnits)(order1.liquidity, decimals1); - strId = id.toString(); - strEncoded = (0, utils_1.encodedStrategyBNToStr)(encoded); - logger.debug('parseStrategy info:', { - id: strId, - token0: token0, - token1: token1, - order0: order0, - order1: order1, - decimals0: decimals0, - decimals1: decimals1, - baseToken: token0, - quoteToken: token1, - buyPriceLow: buyPriceLow, - buyPriceHigh: buyPriceHigh, - buyBudget: buyBudget, - sellPriceLow: sellPriceLow, - sellPriceHigh: sellPriceHigh, - sellBudget: sellBudget, - encoded: strEncoded, - }); - return [ - 2 /*return*/, - { - id: strId, - baseToken: token0, - quoteToken: token1, - buyPriceLow: buyPriceLow, - buyPriceHigh: buyPriceHigh, - buyBudget: buyBudget, - sellPriceLow: sellPriceLow, - sellPriceHigh: sellPriceHigh, - sellBudget: sellBudget, - encoded: strEncoded, - }, - ]; - } - }); - }); -} -exports.parseStrategy = parseStrategy; -function buildStrategyObject( - baseToken, - quoteToken, - baseDecimals, - quoteDecimals, - buyPriceLow, // in quote tkn per 1 base tkn - buyPriceHigh, // in quote tkn per 1 base tkn - buyBudget, // in quote tkn - sellPriceLow, // in quote tkn per 1 base tkn - sellPriceHigh, // in quote tkn per 1 base tkn - sellBudget, // in base tkn -) { - logger.debug('buildStrategyObject called', arguments); - if ( - new numerics_1.Decimal(buyPriceLow).isNegative() || - new numerics_1.Decimal(buyPriceHigh).isNegative() || - new numerics_1.Decimal(sellPriceLow).isNegative() || - new numerics_1.Decimal(sellPriceHigh).isNegative() - ) { - throw new Error('prices cannot be negative'); - } - if ( - new numerics_1.Decimal(buyPriceLow).gt(buyPriceHigh) || - new numerics_1.Decimal(sellPriceLow).gt(sellPriceHigh) - ) { - throw new Error('low price must be lower than or equal to high price'); - } - if ( - new numerics_1.Decimal(buyBudget).isNegative() || - new numerics_1.Decimal(sellBudget).isNegative() - ) { - throw new Error('budgets cannot be negative'); - } - var _a = createOrders( - baseDecimals, - quoteDecimals, - buyPriceLow, - buyPriceHigh, - buyBudget, - sellPriceLow, - sellPriceHigh, - sellBudget, - ), - order0 = _a.order0, - order1 = _a.order1; - logger.debug('buildStrategyObject info:', { - token0: baseToken, - token1: quoteToken, - order0: order0, - order1: order1, - }); - return { - token0: baseToken, - token1: quoteToken, - order0: order0, - order1: order1, - }; -} -exports.buildStrategyObject = buildStrategyObject; -function createOrders( - baseTokenDecimals, - quoteTokenDecimals, - buyPriceLow, - buyPriceHigh, - buyBudget, - sellPriceLow, - sellPriceHigh, - sellBudget, -) { - logger.debug('createOrders called', arguments); - // order 0 is selling the base token - // convert base token liquidity (budget) to wei - var liquidity0 = (0, numerics_1.parseUnits)(sellBudget, baseTokenDecimals); - /* this order sells base token so the rates are base token per 1 quote token, - meaning we need to do 1 over - and then low rate is 1/high price. - Converting to wei in order to factor out different decimals */ - var lowestRate0 = normalizeInvertedRate( - sellPriceHigh, - quoteTokenDecimals, - baseTokenDecimals, - ); - var highestRate0 = normalizeInvertedRate( - sellPriceLow, - quoteTokenDecimals, - baseTokenDecimals, - ); - // order 1 is selling the quote token - // convert quote token liquidity (budget) to wei - var liquidity1 = (0, numerics_1.parseUnits)(buyBudget, quoteTokenDecimals); - /* this order sells quote token so the rates are quote token per 1 base token. - Converting to wei in order to factor out different decimals */ - var lowestRate1 = normalizeRate( - buyPriceLow, - quoteTokenDecimals, - baseTokenDecimals, - ); - var highestRate1 = normalizeRate( - buyPriceHigh, - quoteTokenDecimals, - baseTokenDecimals, - ); - var order0 = { - liquidity: liquidity0.toString(), - lowestRate: lowestRate0, - highestRate: highestRate0, - marginalRate: highestRate0, - }; - var order1 = { - liquidity: liquidity1.toString(), - lowestRate: lowestRate1, - highestRate: highestRate1, - marginalRate: highestRate1, - }; - logger.debug('createOrders info:', { order0: order0, order1: order1 }); - return { order0: order0, order1: order1 }; -} -exports.createOrders = createOrders; -exports.PPM_RESOLUTION = 1000000; -function addFee(amount, tradingFeePPM) { - return new numerics_1.Decimal(amount.toString()) - .mul(exports.PPM_RESOLUTION) - .div(exports.PPM_RESOLUTION - tradingFeePPM) - .ceil(); -} -exports.addFee = addFee; -function subtractFee(amount, tradingFeePPM) { - return new numerics_1.Decimal(amount.toString()) - .mul(exports.PPM_RESOLUTION - tradingFeePPM) - .div(exports.PPM_RESOLUTION) - .floor(); -} -exports.subtractFee = subtractFee; diff --git a/src/dex/carbon/sdk/trade-matcher/index.js b/src/dex/carbon/sdk/trade-matcher/index.js deleted file mode 100644 index 91a57946f..000000000 --- a/src/dex/carbon/sdk/trade-matcher/index.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.getEncodedTradeSourceAmount = - exports.getEncodedTradeTargetAmount = - exports.matchByTargetAmount = - exports.matchBySourceAmount = - void 0; -var match_1 = require('./match'); -Object.defineProperty(exports, 'matchBySourceAmount', { - enumerable: true, - get: function () { - return match_1.matchBySourceAmount; - }, -}); -Object.defineProperty(exports, 'matchByTargetAmount', { - enumerable: true, - get: function () { - return match_1.matchByTargetAmount; - }, -}); -var trade_1 = require('./trade'); -Object.defineProperty(exports, 'getEncodedTradeTargetAmount', { - enumerable: true, - get: function () { - return trade_1.getEncodedTradeTargetAmount; - }, -}); -Object.defineProperty(exports, 'getEncodedTradeSourceAmount', { - enumerable: true, - get: function () { - return trade_1.getEncodedTradeSourceAmount; - }, -}); diff --git a/src/dex/carbon/sdk/trade-matcher/match.js b/src/dex/carbon/sdk/trade-matcher/match.js deleted file mode 100644 index 3af91ea7e..000000000 --- a/src/dex/carbon/sdk/trade-matcher/match.js +++ /dev/null @@ -1,299 +0,0 @@ -'use strict'; -var __spreadArray = - (this && this.__spreadArray) || - function (to, from, pack) { - if (pack || arguments.length === 2) - for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.matchByTargetAmount = exports.matchBySourceAmount = void 0; -var types_1 = require('../common/types'); -var encoders_1 = require('../utils/encoders'); -var numerics_1 = require('../utils/numerics'); -var trade_1 = require('./trade'); -var utils_1 = require('./utils'); -var rateBySourceAmount = function (sourceAmount, order) { - var input = sourceAmount; - var output = (0, trade_1.getEncodedTradeTargetAmount)(input, order); - if (output.gt(order.y)) { - input = (0, trade_1.getEncodedTradeSourceAmount)(order.y, order); - output = (0, trade_1.getEncodedTradeTargetAmount)(input, order); - while (output.gt(order.y)) { - input = input.sub(1); - output = (0, trade_1.getEncodedTradeTargetAmount)(input, order); - } - } - return { input: input, output: output }; -}; -var rateByTargetAmount = function (targetAmount, order) { - var input = (0, numerics_1.BigNumberMin)(targetAmount, order.y); - var output = (0, trade_1.getEncodedTradeSourceAmount)(input, order); - return { input: input, output: output }; -}; -var getParams = function (order) { - var _a = [order.y, order.z, order.A, order.B], - y = _a[0], - z = _a[1], - A = _a[2], - B = _a[3]; - return [y, z, (0, encoders_1.decodeFloat)(A), (0, encoders_1.decodeFloat)(B)]; -}; -var getLimit = function (order) { - var _a = getParams(order), - y = _a[0], - z = _a[1], - A = _a[2], - B = _a[3]; - return z.gt(0) ? y.mul(A).add(z.mul(B)).div(z) : numerics_1.BigNumber.from(0); -}; -var equalTargetAmount = function (order, limit) { - var _a = getParams(order), - y = _a[0], - z = _a[1], - A = _a[2], - B = _a[3]; - return A.gt(0) - ? y - .mul(A) - .add(z.mul(B.sub(limit))) - .div(A) - : y; -}; -var equalSourceAmount = function (order, limit) { - return (0, trade_1.getEncodedTradeSourceAmount)( - equalTargetAmount(order, limit), - order, - ); -}; -/** - * Sort the orders from best rate to worst rate: - * - Compute the rate of an order: - * - Let `x` denote the maximum tradable amount not larger than `n` - * - Let `y` denote the output amount of trading `x` - * - The rate is determined as `y / x` - * - Compute the rates of two orders: - * - If the rates are different, then the one with a better value prevails - * - If the rates are identical, then the one with a better value of `y` prevails - */ -var sortedQuotes = function (amount, ordersMap, trade, sort) { - return Object.keys(ordersMap) - .map(function (id) { - return { - id: numerics_1.BigNumber.from(id), - rate: trade(amount, ordersMap[id]), - }; - }) - .sort(function (a, b) { - return sort(a.rate, b.rate); - }); -}; -/** - * Compute a list of {order id, trade amount} tuples: - * - Let `n` denote the initial input amount - * - Iterate the orders from best rate to worst rate: - * - Let `m` denote the maximum tradable amount not larger than `n` - * - Add the id of the order along with `m` to the output matching - * - If `m < n` then subtract `m` from `n` and continue, otherwise break - */ -var matchFast = function (amount, ordersMap, quotes, filter, trade) { - var actions = []; - for (var _i = 0, quotes_1 = quotes; _i < quotes_1.length; _i++) { - var quote = quotes_1[_i]; - if (amount.gt(quote.rate.input)) { - if (filter(quote.rate)) { - actions.push({ - id: quote.id, - input: quote.rate.input, - output: quote.rate.output, - }); - amount = amount.sub(quote.rate.input); - } - } else if (amount.eq(quote.rate.input)) { - if (filter(quote.rate)) { - actions.push({ - id: quote.id, - input: quote.rate.input, - output: quote.rate.output, - }); - } - break; - } /* if (amount.lt(rate.input)) */ else { - var adjustedRate = { - input: amount, - output: trade(amount, ordersMap[quote.id.toString()]).output, - }; - if (filter(adjustedRate)) { - actions.push({ - id: quote.id, - input: adjustedRate.input, - output: adjustedRate.output, - }); - } - break; - } - } - return actions; -}; -/** - * Compute a list of {order id, trade amount} tuples: - * - Iterate the orders from best rate to worst rate: - * - Calculate a trade which brings orders `0` thru `n - 1` to the rate of order `n` - * - If the result is larger than or equal to the requested trade amount, then stop - * - If the result is larger than the requested trade amount: - * - Determine a rate `r` between the rate of order `n - 1` and the rate of order `n` - * - Calculate a trade which brings orders `0` thru `n - 1` to the rate `r` - * - If the result is equal to the requested trade amount, then stop - */ -var matchBest = function (amount, ordersMap, quotes, filter, trade, equalize) { - var order0 = { - y: numerics_1.BigNumber.from(0), - z: numerics_1.BigNumber.from(0), - A: numerics_1.BigNumber.from(0), - B: numerics_1.BigNumber.from(0), - }; - var orders = quotes - .map(function (quote) { - return ordersMap[quote.id.toString()]; - }) - .concat(order0); - var rates = []; - var limit = numerics_1.BigNumber.from(0); - var total = numerics_1.BigNumber.from(0); - var delta = numerics_1.BigNumber.from(0); - for (var n = 1; n < orders.length; n++) { - limit = getLimit(orders[n]); - rates = orders.slice(0, n).map(function (order) { - return trade(equalize(order, limit), order); - }); - total = rates.reduce(function (sum, rate) { - return sum.add(rate.input); - }, numerics_1.BigNumber.from(0)); - delta = total.sub(amount); - if (delta.eq(0)) { - break; - } - if (delta.gt(0)) { - var lo = limit; - var hi = getLimit(orders[n - 1]); - while (lo.add(1).lt(hi)) { - limit = lo.add(hi).div(2); - rates = orders.slice(0, n).map(function (order) { - return trade(equalize(order, limit), order); - }); - total = rates.reduce(function (sum, rate) { - return sum.add(rate.input); - }, numerics_1.BigNumber.from(0)); - delta = total.sub(amount); - if (delta.gt(0)) { - lo = limit; - } else if (delta.lt(0)) { - hi = limit; - } /* if (delta.eq(0)) */ else { - break; - } - } - break; - } - } - if (delta.gt(0)) { - for (var i = rates.length - 1; i >= 0; i--) { - var rate = trade(rates[i].input.sub(delta), orders[i]); - delta = delta.add(rate.input.sub(rates[i].input)); - rates[i] = rate; - if (delta.lte(0)) { - break; - } - } - } else if (delta.lt(0)) { - for (var i = 0; i <= rates.length - 1; i++) { - var rate = trade(rates[i].input.sub(delta), orders[i]); - delta = delta.add(rate.input.sub(rates[i].input)); - if (delta.gt(0)) { - break; - } - rates[i] = rate; - } - } - return __spreadArray([], Array(rates.length).keys(), true) - .filter(function (i) { - return filter(rates[i]); - }) - .map(function (i) { - return { - id: quotes[i].id, - input: rates[i].input, - output: rates[i].output, - }; - }); -}; -var matchBy = function ( - amount, - ordersMap, - matchTypes, - filter, - trade, - sort, - equalize, -) { - var quotes = sortedQuotes(amount, ordersMap, trade, sort); - var res = {}; - if (matchTypes.includes(types_1.MatchType.Fast)) { - res[types_1.MatchType.Fast] = matchFast( - amount, - ordersMap, - quotes, - filter, - trade, - ); - } - if (matchTypes.includes(types_1.MatchType.Best)) { - res[types_1.MatchType.Best] = matchBest( - amount, - ordersMap, - quotes, - filter, - trade, - equalize, - ); - } - return res; -}; -var defaultFilter = function (rate) { - return rate.input.gt(0) && rate.output.gt(0); -}; -var matchBySourceAmount = function (amount, ordersMap, matchTypes, filter) { - if (filter === void 0) { - filter = defaultFilter; - } - return matchBy( - amount, - ordersMap, - matchTypes, - filter, - rateBySourceAmount, - utils_1.sortByMinRate, - equalSourceAmount, - ); -}; -exports.matchBySourceAmount = matchBySourceAmount; -var matchByTargetAmount = function (amount, ordersMap, matchTypes, filter) { - if (filter === void 0) { - filter = defaultFilter; - } - return matchBy( - amount, - ordersMap, - matchTypes, - filter, - rateByTargetAmount, - utils_1.sortByMaxRate, - equalTargetAmount, - ); -}; -exports.matchByTargetAmount = matchByTargetAmount; diff --git a/src/dex/carbon/sdk/trade-matcher/trade.js b/src/dex/carbon/sdk/trade-matcher/trade.js deleted file mode 100644 index 8d7d1ed99..000000000 --- a/src/dex/carbon/sdk/trade-matcher/trade.js +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.getDecodedTradeSourceAmount = - exports.getDecodedTradeTargetAmount = - exports.getEncodedTradeSourceAmount = - exports.getEncodedTradeTargetAmount = - void 0; -var numerics_1 = require('../utils/numerics'); -var encoders_1 = require('../utils/encoders'); -var C = numerics_1.BigNumber.from(numerics_1.ONE); -var MAX_UINT128 = numerics_1.BigNumber.from(2).pow(128).sub(1); -var MAX_UINT256 = numerics_1.BigNumber.from(2).pow(256).sub(1); -function check(val, max) { - if (val.gte(0) && val.lte(max)) { - return val; - } - throw null; -} -var uint128 = function (n) { - return check(n, MAX_UINT128); -}; -var add = function (a, b) { - return check(a.add(b), MAX_UINT256); -}; -var sub = function (a, b) { - return check(a.sub(b), MAX_UINT256); -}; -var mul = function (a, b) { - return check(a.mul(b), MAX_UINT256); -}; -var mulDivF = function (a, b, c) { - return check(a.mul(b).div(c), MAX_UINT256); -}; -var mulDivC = function (a, b, c) { - return check(a.mul(b).add(c).sub(1).div(c), MAX_UINT256); -}; -// -// x * (A * y + B * z) ^ 2 -// --------------------------------- -// A * x * (A * y + B * z) + z ^ 2 -// -var getEncodedTradeBySourceAmount = function (x, y, z, A, B) { - if (A.eq(0)) { - return mulDivF(x, mul(B, B), mul(C, C)); - } - var temp1 = mul(z, C); - var temp2 = add(mul(y, A), mul(z, B)); - var temp3 = mul(temp2, x); - var factor1 = mulDivC(temp1, temp1, MAX_UINT256); - var factor2 = mulDivC(temp3, A, MAX_UINT256); - var factor = (0, numerics_1.BigNumberMax)(factor1, factor2); - var temp4 = mulDivC(temp1, temp1, factor); - var temp5 = mulDivC(temp3, A, factor); - return mulDivF(temp2, temp3.div(factor), add(temp4, temp5)); -}; -// -// x * z ^ 2 -// ------------------------------------------- -// (A * y + B * z) * (A * y + B * z - A * x) -// -var getEncodedTradeByTargetAmount = function (x, y, z, A, B) { - if (A.eq(0)) { - return mulDivC(x, mul(C, C), mul(B, B)); - } - var temp1 = mul(z, C); - var temp2 = add(mul(y, A), mul(z, B)); - var temp3 = sub(temp2, mul(x, A)); - var factor1 = mulDivC(temp1, temp1, MAX_UINT256); - var factor2 = mulDivC(temp2, temp3, MAX_UINT256); - var factor = (0, numerics_1.BigNumberMax)(factor1, factor2); - var temp4 = mulDivC(temp1, temp1, factor); - var temp5 = mulDivF(temp2, temp3, factor); - return mulDivC(x, temp4, temp5); -}; -// -// M * M * x * y -// --------------------- -// M * (M - L) * x + y -// -var getDecodedTradeBySourceAmount = function (x, y, L, M) { - var n = M.mul(M).mul(x).mul(y); - var d = M.mul(M.sub(L)).mul(x).add(y); - return n.div(d); -}; -// -// x * y -// ----------------------------- -// M * (L - M) * x + M * M * y -// -var getDecodedTradeByTargetAmount = function (x, y, L, M) { - var n = x.mul(y); - var d = M.mul(L.sub(M)).mul(x).add(M.mul(M).mul(y)); - return n.div(d); -}; -var getEncodedTradeTargetAmount = function (amount, order) { - var x = amount; - var y = order.y; - var z = order.z; - var A = (0, encoders_1.decodeFloat)(order.A); - var B = (0, encoders_1.decodeFloat)(order.B); - try { - return uint128(getEncodedTradeBySourceAmount(x, y, z, A, B)); - } catch (error) { - return numerics_1.BigNumber.from(0); /* rate = zero / amount = zero */ - } -}; -exports.getEncodedTradeTargetAmount = getEncodedTradeTargetAmount; -var getEncodedTradeSourceAmount = function (amount, order) { - var x = amount; - var y = order.y; - var z = order.z; - var A = (0, encoders_1.decodeFloat)(order.A); - var B = (0, encoders_1.decodeFloat)(order.B); - try { - return uint128(getEncodedTradeByTargetAmount(x, y, z, A, B)); - } catch (error) { - return MAX_UINT128; /* rate = amount / infinity = zero */ - } -}; -exports.getEncodedTradeSourceAmount = getEncodedTradeSourceAmount; -var getDecodedTradeTargetAmount = function (amount, order) { - var x = amount; - var y = new numerics_1.Decimal(order.liquidity); - var L = new numerics_1.Decimal(order.lowestRate).sqrt(); - var M = new numerics_1.Decimal(order.marginalRate).sqrt(); - return getDecodedTradeBySourceAmount(x, y, L, M); -}; -exports.getDecodedTradeTargetAmount = getDecodedTradeTargetAmount; -var getDecodedTradeSourceAmount = function (amount, order) { - var x = amount; - var y = new numerics_1.Decimal(order.liquidity); - var L = new numerics_1.Decimal(order.lowestRate).sqrt(); - var M = new numerics_1.Decimal(order.marginalRate).sqrt(); - return getDecodedTradeByTargetAmount(x, y, L, M); -}; -exports.getDecodedTradeSourceAmount = getDecodedTradeSourceAmount; diff --git a/src/dex/carbon/sdk/trade-matcher/utils.js b/src/dex/carbon/sdk/trade-matcher/utils.js deleted file mode 100644 index be8cbca9c..000000000 --- a/src/dex/carbon/sdk/trade-matcher/utils.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.sortByMaxRate = exports.sortByMinRate = void 0; -var sortByMinRate = function (x, y) { - var lhs = x.output.mul(y.input); - var rhs = y.output.mul(x.input); - var lt = lhs.lt(rhs); - var gt = lhs.gt(rhs); - var eq = !lt && !gt; - var is_lt = lt || (eq && x.output.lt(y.output)); - var is_gt = gt || (eq && x.output.gt(y.output)); - return +is_lt - +is_gt; -}; -exports.sortByMinRate = sortByMinRate; -var sortByMaxRate = function (x, y) { - return (0, exports.sortByMinRate)(y, x); -}; -exports.sortByMaxRate = sortByMaxRate; diff --git a/src/dex/carbon/sdk/utils/decimals.js b/src/dex/carbon/sdk/utils/decimals.js deleted file mode 100644 index 5f50a0a43..000000000 --- a/src/dex/carbon/sdk/utils/decimals.js +++ /dev/null @@ -1,166 +0,0 @@ -'use strict'; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator['throw'](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done - ? resolve(result.value) - : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; -var __generator = - (this && this.__generator) || - function (thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [], - }, - f, - y, - t, - g; - return ( - (g = { next: verb(0), throw: verb(1), return: verb(2) }), - typeof Symbol === 'function' && - (g[Symbol.iterator] = function () { - return this; - }), - g - ); - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError('Generator is already executing.'); - while ((g && ((g = 0), op[0] && (_ = 0)), _)) - try { - if ( - ((f = 1), - y && - (t = - op[0] & 2 - ? y['return'] - : op[0] - ? y['throw'] || ((t = y['return']) && t.call(y), 0) - : y.next) && - !(t = t.call(y, op[1])).done) - ) - return t; - if (((y = 0), t)) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if ( - !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && - (op[0] === 6 || op[0] === 2) - ) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } - }; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.Decimals = void 0; -var Decimals = /** @class */ (function () { - function Decimals(fetcher) { - this._cachedDecimals = new Map(); - this._fetcher = fetcher; - } - Decimals.prototype.fetchDecimals = function (address) { - return __awaiter(this, void 0, void 0, function () { - var decimal; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - decimal = this._cachedDecimals.get(address); - if (decimal !== undefined) return [2 /*return*/, decimal]; - return [4 /*yield*/, this._fetcher(address)]; - case 1: - decimal = _a.sent(); - if (decimal === undefined) { - throw new Error( - 'Could not fetch decimals for token '.concat(address), - ); - } - this._cachedDecimals.set(address, decimal); - return [2 /*return*/, decimal]; - } - }); - }); - }; - return Decimals; -})(); -exports.Decimals = Decimals; diff --git a/src/dex/carbon/sdk/utils/encoders.js b/src/dex/carbon/sdk/utils/encoders.js deleted file mode 100644 index b08e90959..000000000 --- a/src/dex/carbon/sdk/utils/encoders.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.decodeOrder = - exports.encodeOrder = - exports.decodeFloat = - exports.encodeFloat = - exports.decodeRate = - exports.encodeRate = - void 0; -var numerics_1 = require('./numerics'); -function bitLength(value) { - return value.gt(0) - ? numerics_1.Decimal.log2(value.toString()).add(1).floor().toNumber() - : 0; -} -var encodeRate = function (value) { - var data = (0, numerics_1.DecToBn)(value.sqrt().mul(numerics_1.ONE).floor()); - var length = bitLength(data.div(numerics_1.ONE)); - return (0, numerics_1.BnToDec)(data.shr(length).shl(length)); -}; -exports.encodeRate = encodeRate; -var decodeRate = function (value) { - return value.div(numerics_1.ONE).pow(2); -}; -exports.decodeRate = decodeRate; -var encodeFloat = function (value) { - var exponent = bitLength(value.div(numerics_1.ONE)); - var mantissa = value.shr(exponent); - return numerics_1.BigNumber.from(numerics_1.ONE).mul(exponent).or(mantissa); -}; -exports.encodeFloat = encodeFloat; -var decodeFloat = function (value) { - return value.mod(numerics_1.ONE).shl(value.div(numerics_1.ONE).toNumber()); -}; -exports.decodeFloat = decodeFloat; -var encodeOrder = function (order) { - var liquidity = new numerics_1.Decimal(order.liquidity); - var lowestRate = new numerics_1.Decimal(order.lowestRate); - var highestRate = new numerics_1.Decimal(order.highestRate); - var marginalRate = new numerics_1.Decimal(order.marginalRate); - if ( - !( - (highestRate.gte(marginalRate) && marginalRate.gt(lowestRate)) || - (highestRate.eq(marginalRate) && marginalRate.eq(lowestRate)) - ) - ) { - throw new Error( - 'Either one of the following must hold:\n' + - '- highestRate >= marginalRate > lowestRate\n' + - '- highestRate == marginalRate == lowestRate\n' + - '(highestRate = ' - .concat(highestRate, ', marginalRate = ') - .concat(marginalRate, ', lowestRate = ') - .concat(lowestRate, ')'), - ); - } - var y = (0, numerics_1.DecToBn)(liquidity); - var L = (0, numerics_1.DecToBn)((0, exports.encodeRate)(lowestRate)); - var H = (0, numerics_1.DecToBn)((0, exports.encodeRate)(highestRate)); - var M = (0, numerics_1.DecToBn)((0, exports.encodeRate)(marginalRate)); - return { - y: y, - z: H.eq(M) ? y : y.mul(H.sub(L)).div(M.sub(L)), - A: (0, exports.encodeFloat)(H.sub(L)), - B: (0, exports.encodeFloat)(L), - }; -}; -exports.encodeOrder = encodeOrder; -var decodeOrder = function (order) { - var y = (0, numerics_1.BnToDec)(order.y); - var z = (0, numerics_1.BnToDec)(order.z); - var A = (0, numerics_1.BnToDec)((0, exports.decodeFloat)(order.A)); - var B = (0, numerics_1.BnToDec)((0, exports.decodeFloat)(order.B)); - return { - liquidity: y.toString(), - lowestRate: (0, exports.decodeRate)(B).toString(), - highestRate: (0, exports.decodeRate)(B.add(A)).toString(), - marginalRate: (0, exports.decodeRate)( - y.eq(z) ? B.add(A) : B.add(A.mul(y).div(z)), - ).toString(), - }; -}; -exports.decodeOrder = decodeOrder; diff --git a/src/dex/carbon/sdk/utils/index.js b/src/dex/carbon/sdk/utils/index.js deleted file mode 100644 index 3baf757be..000000000 --- a/src/dex/carbon/sdk/utils/index.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; -var __createBinding = - (this && this.__createBinding) || - (Object.create - ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if ( - !desc || - ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) - ) { - desc = { - enumerable: true, - get: function () { - return m[k]; - }, - }; - } - Object.defineProperty(o, k2, desc); - } - : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); -var __exportStar = - (this && this.__exportStar) || - function (m, exports) { - for (var p in m) - if (p !== 'default' && !Object.prototype.hasOwnProperty.call(exports, p)) - __createBinding(exports, m, p); - }; -Object.defineProperty(exports, '__esModule', { value: true }); -__exportStar(require('./decimals'), exports); -__exportStar(require('./encoders'), exports); -__exportStar(require('./serializers'), exports); -__exportStar(require('./numerics'), exports); diff --git a/src/dex/carbon/sdk/utils/numerics.js b/src/dex/carbon/sdk/utils/numerics.js deleted file mode 100644 index 75c5fe2c9..000000000 --- a/src/dex/carbon/sdk/utils/numerics.js +++ /dev/null @@ -1,77 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.formatUnits = - exports.parseUnits = - exports.mulDiv = - exports.DecToBn = - exports.BnToDec = - exports.tenPow = - exports.TEN = - exports.ONE = - exports.BigNumberMax = - exports.BigNumberMin = - exports.BigNumber = - exports.Decimal = - void 0; -var bignumber_1 = require('@ethersproject/bignumber'); -Object.defineProperty(exports, 'BigNumber', { - enumerable: true, - get: function () { - return bignumber_1.BigNumber; - }, -}); -var units_1 = require('@ethersproject/units'); -var decimal_js_1 = require('decimal.js'); -exports.Decimal = decimal_js_1.default; -decimal_js_1.default.set({ - precision: 100, - rounding: decimal_js_1.default.ROUND_HALF_DOWN, - toExpNeg: -30, - toExpPos: 30, -}); -var BigNumberMin = function (a, b) { - return a.lt(b) ? a : b; -}; -exports.BigNumberMin = BigNumberMin; -var BigNumberMax = function (a, b) { - return a.gt(b) ? a : b; -}; -exports.BigNumberMax = BigNumberMax; -exports.ONE = Math.pow(2, 48); -exports.TEN = new decimal_js_1.default(10); -var tenPow = function (dec0, dec1) { - var diff = dec0 - dec1; - return exports.TEN.pow(diff); -}; -exports.tenPow = tenPow; -var BnToDec = function (x) { - return new decimal_js_1.default(x.toString()); -}; -exports.BnToDec = BnToDec; -var DecToBn = function (x) { - return bignumber_1.BigNumber.from(x.toFixed()); -}; -exports.DecToBn = DecToBn; -var mulDiv = function (x, y, z) { - return y.eq(z) ? x : x.mul(y).div(z); -}; -exports.mulDiv = mulDiv; -function trimDecimal(input, precision) { - var decimalIdx = input.indexOf('.'); - if (decimalIdx !== -1) { - return input.slice(0, decimalIdx + precision + 1); - } - return input; -} -// A take on parseUnits that supports floating point -function parseUnits(amount, decimals) { - var trimmed = trimDecimal(amount, decimals); - return (0, units_1.parseUnits)(trimmed, decimals); -} -exports.parseUnits = parseUnits; -function formatUnits(amount, decimals) { - var res = (0, units_1.formatUnits)(amount, decimals); - // remove trailing 000 - return new decimal_js_1.default(res).toFixed(); -} -exports.formatUnits = formatUnits; diff --git a/src/dex/carbon/sdk/utils/serializers.js b/src/dex/carbon/sdk/utils/serializers.js deleted file mode 100644 index d4ca9bc12..000000000 --- a/src/dex/carbon/sdk/utils/serializers.js +++ /dev/null @@ -1,126 +0,0 @@ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.tradeActionStrToBN = - exports.tradeActionBNToStr = - exports.matchActionStrToBN = - exports.matchActionBNToStr = - exports.ordersMapStrToBN = - exports.ordersMapBNToStr = - exports.encodedStrategyStrToBN = - exports.encodedStrategyBNToStr = - exports.encodedOrderStrToBN = - exports.encodedOrderBNToStr = - exports.replaceBigNumbersWithStrings = - exports.deserialize = - void 0; -var numerics_1 = require('./numerics'); -/** - * Helper utility to deserialize a value that was contains BigNumber instances - * @returns - */ -var deserialize = function (value) { - if ( - typeof value === 'object' && - value !== null && - value.type === 'BigNumber' && - value.hex !== null - ) { - return numerics_1.BigNumber.from(value.hex); - } - if (Array.isArray(value)) { - return value.map(exports.deserialize); - } - if (typeof value === 'object' && value !== null) { - var deserializedObj = {}; - for (var key in value) { - if (Object.prototype.hasOwnProperty.call(value, key)) { - deserializedObj[key] = (0, exports.deserialize)(value[key]); - } - } - return deserializedObj; - } - return value; -}; -exports.deserialize = deserialize; -var replaceBigNumbersWithStrings = function (obj) { - function replace(obj) { - if (numerics_1.BigNumber.isBigNumber(obj)) { - return obj.toString(); - } - if (typeof obj === 'object' && obj !== null) { - var newObj = Array.isArray(obj) ? [] : {}; - for (var key in obj) { - newObj[key] = replace(obj[key]); - } - return newObj; - } - return obj; - } - return replace(obj); -}; -exports.replaceBigNumbersWithStrings = replaceBigNumbersWithStrings; -var encodedOrderBNToStr = function (order) { - return (0, exports.replaceBigNumbersWithStrings)(order); -}; -exports.encodedOrderBNToStr = encodedOrderBNToStr; -var encodedOrderStrToBN = function (order) { - return { - y: numerics_1.BigNumber.from(order.y), - z: numerics_1.BigNumber.from(order.z), - A: numerics_1.BigNumber.from(order.A), - B: numerics_1.BigNumber.from(order.B), - }; -}; -exports.encodedOrderStrToBN = encodedOrderStrToBN; -var encodedStrategyBNToStr = function (strategy) { - return (0, exports.replaceBigNumbersWithStrings)(strategy); -}; -exports.encodedStrategyBNToStr = encodedStrategyBNToStr; -var encodedStrategyStrToBN = function (strategy) { - return { - id: numerics_1.BigNumber.from(strategy.id), - token0: strategy.token0, - token1: strategy.token1, - order0: (0, exports.encodedOrderStrToBN)(strategy.order0), - order1: (0, exports.encodedOrderStrToBN)(strategy.order1), - }; -}; -exports.encodedStrategyStrToBN = encodedStrategyStrToBN; -var ordersMapBNToStr = function (ordersMap) { - return (0, exports.replaceBigNumbersWithStrings)(ordersMap); -}; -exports.ordersMapBNToStr = ordersMapBNToStr; -var ordersMapStrToBN = function (ordersMap) { - var deserialized = {}; - for (var _i = 0, _a = Object.entries(ordersMap); _i < _a.length; _i++) { - var _b = _a[_i], - id = _b[0], - order = _b[1]; - deserialized[id] = (0, exports.encodedOrderStrToBN)(order); - } - return deserialized; -}; -exports.ordersMapStrToBN = ordersMapStrToBN; -var matchActionBNToStr = function (action) { - return (0, exports.replaceBigNumbersWithStrings)(action); -}; -exports.matchActionBNToStr = matchActionBNToStr; -var matchActionStrToBN = function (action) { - return { - id: numerics_1.BigNumber.from(action.id), - input: numerics_1.BigNumber.from(action.input), - output: numerics_1.BigNumber.from(action.output), - }; -}; -exports.matchActionStrToBN = matchActionStrToBN; -var tradeActionBNToStr = function (action) { - return (0, exports.replaceBigNumbersWithStrings)(action); -}; -exports.tradeActionBNToStr = tradeActionBNToStr; -var tradeActionStrToBN = function (action) { - return { - strategyId: numerics_1.BigNumber.from(action.strategyId), - amount: numerics_1.BigNumber.from(action.amount), - }; -}; -exports.tradeActionStrToBN = tradeActionStrToBN;