@strkfarm/sdk 2.0.0-dev.2 → 2.0.0-dev.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1418,8 +1418,8 @@ var strkfarm_risk_engine = (() => {
1418
1418
  const base2 = (_a21 = nearestCommonProto(...ingredients)) !== null && _a21 !== void 0 ? _a21 : Object.prototype;
1419
1419
  const mixedProto = Object.create(base2);
1420
1420
  const visitedProtos = protoChain(base2);
1421
- for (let prototype4 of ingredients) {
1422
- let protos = protoChain(prototype4);
1421
+ for (let prototype3 of ingredients) {
1422
+ let protos = protoChain(prototype3);
1423
1423
  for (let i = protos.length - 1; i >= 0; i--) {
1424
1424
  let newProto = protos[i];
1425
1425
  if (visitedProtos.indexOf(newProto) === -1) {
@@ -1451,9 +1451,9 @@ var strkfarm_risk_engine = (() => {
1451
1451
  }
1452
1452
  return void 0;
1453
1453
  };
1454
- proxyMix = (ingredients, prototype4 = Object.prototype) => new Proxy({}, {
1454
+ proxyMix = (ingredients, prototype3 = Object.prototype) => new Proxy({}, {
1455
1455
  getPrototypeOf() {
1456
- return prototype4;
1456
+ return prototype3;
1457
1457
  },
1458
1458
  setPrototypeOf() {
1459
1459
  throw Error("Cannot set prototype of Proxies created by ts-mixer");
@@ -1465,10 +1465,10 @@ var strkfarm_risk_engine = (() => {
1465
1465
  throw new Error("Cannot define new properties on Proxies created by ts-mixer");
1466
1466
  },
1467
1467
  has(_, prop) {
1468
- return getIngredientWithProp(prop, ingredients) !== void 0 || prototype4[prop] !== void 0;
1468
+ return getIngredientWithProp(prop, ingredients) !== void 0 || prototype3[prop] !== void 0;
1469
1469
  },
1470
1470
  get(_, prop) {
1471
- return (getIngredientWithProp(prop, ingredients) || prototype4)[prop];
1471
+ return (getIngredientWithProp(prop, ingredients) || prototype3)[prop];
1472
1472
  },
1473
1473
  set(_, prop, val) {
1474
1474
  const ingredientWithProp = getIngredientWithProp(prop, ingredients);
@@ -15048,9 +15048,9 @@ ${r2}}` : "}", l2;
15048
15048
  function isObject4(data) {
15049
15049
  return toString6.call(data) === "[object Object]";
15050
15050
  }
15051
- function isInstanceStrict(data, prototype4) {
15051
+ function isInstanceStrict(data, prototype3) {
15052
15052
  try {
15053
- return data instanceof prototype4;
15053
+ return data instanceof prototype3;
15054
15054
  } catch (error2) {
15055
15055
  return false;
15056
15056
  }
@@ -17640,9 +17640,9 @@ ${r2}}` : "}", l2;
17640
17640
  const { captureStackTrace } = Error;
17641
17641
  captureStackTrace && captureStackTrace(target, fn);
17642
17642
  }
17643
- function fixProto2(target, prototype4) {
17643
+ function fixProto2(target, prototype3) {
17644
17644
  const { setPrototypeOf: setPrototypeOf2 } = Object;
17645
- setPrototypeOf2 ? setPrototypeOf2(target, prototype4) : target.__proto__ = prototype4;
17645
+ setPrototypeOf2 ? setPrototypeOf2(target, prototype3) : target.__proto__ = prototype3;
17646
17646
  }
17647
17647
  var CustomError2 = class extends Error {
17648
17648
  constructor(message) {
@@ -17784,7 +17784,7 @@ ${r2}}` : "}", l2;
17784
17784
  toHexString: () => toHexString2,
17785
17785
  toStorageKey: () => toStorageKey2
17786
17786
  });
17787
- var import_utils73 = require_utils();
17787
+ var import_utils72 = require_utils();
17788
17788
  function isHex3(hex) {
17789
17789
  return /^0x[0-9a-f]*$/i.test(hex);
17790
17790
  }
@@ -17857,7 +17857,7 @@ ${r2}}` : "}", l2;
17857
17857
  if (adaptedValue.length % 2 !== 0) {
17858
17858
  adaptedValue = `0${adaptedValue}`;
17859
17859
  }
17860
- return (0, import_utils73.hexToBytes)(adaptedValue);
17860
+ return (0, import_utils72.hexToBytes)(adaptedValue);
17861
17861
  }
17862
17862
  function addPercent2(number2, percent) {
17863
17863
  const bigIntNum = BigInt(number2);
@@ -28653,11 +28653,13 @@ ${r2}}` : "}", l2;
28653
28653
  AssetOperationStatus: () => AssetOperationStatus,
28654
28654
  AssetOperationType: () => AssetOperationType,
28655
28655
  AutoCompounderSTRK: () => AutoCompounderSTRK,
28656
+ AvnuAdapter: () => AvnuAdapter,
28656
28657
  AvnuWrapper: () => AvnuWrapper,
28657
28658
  BaseAdapter: () => BaseAdapter,
28658
28659
  BaseStrategy: () => BaseStrategy,
28659
28660
  CommonAdapter: () => CommonAdapter,
28660
28661
  ContractAddr: () => ContractAddr,
28662
+ CycleType: () => CycleType,
28661
28663
  ERC20: () => ERC20,
28662
28664
  EXTENDED_CONTRACT: () => EXTENDED_CONTRACT,
28663
28665
  EXTENDED_SANITIZER: () => EXTENDED_SANITIZER,
@@ -28684,6 +28686,7 @@ ${r2}}` : "}", l2;
28684
28686
  OrderType: () => OrderType,
28685
28687
  PRICE_ROUTER: () => PRICE_ROUTER,
28686
28688
  PositionSide: () => PositionSide,
28689
+ PositionTypeAvnuExtended: () => PositionTypeAvnuExtended,
28687
28690
  Pragma: () => Pragma,
28688
28691
  Pricer: () => Pricer,
28689
28692
  PricerBase: () => PricerBase,
@@ -28727,6 +28730,7 @@ ${r2}}` : "}", l2;
28727
28730
  calculateExtendedLevergae: () => calculateExtendedLevergae,
28728
28731
  calculateVesUPositionSizeGivenExtended: () => calculateVesUPositionSizeGivenExtended,
28729
28732
  calculateVesuLeverage: () => calculateVesuLeverage,
28733
+ calculateWBTCAmountToMaintainLTV: () => calculateWBTCAmountToMaintainLTV,
28730
28734
  extensionMap: () => extensionMap,
28731
28735
  getContractDetails: () => getContractDetails,
28732
28736
  getFAQs: () => getFAQs,
@@ -38826,9 +38830,9 @@ ${JSON.stringify(data, null, 2)}`;
38826
38830
  const { captureStackTrace } = Error;
38827
38831
  captureStackTrace && captureStackTrace(target, fn);
38828
38832
  }
38829
- function fixProto(target, prototype4) {
38833
+ function fixProto(target, prototype3) {
38830
38834
  const { setPrototypeOf: setPrototypeOf2 } = Object;
38831
- setPrototypeOf2 ? setPrototypeOf2(target, prototype4) : target.__proto__ = prototype4;
38835
+ setPrototypeOf2 ? setPrototypeOf2(target, prototype3) : target.__proto__ = prototype3;
38832
38836
  }
38833
38837
  var CustomError = class extends Error {
38834
38838
  constructor(message) {
@@ -46571,14 +46575,14 @@ ${JSON.stringify(data, null, 2)}`;
46571
46575
  }
46572
46576
  };
46573
46577
 
46574
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/bind.js
46578
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/bind.js
46575
46579
  function bind(fn, thisArg) {
46576
46580
  return function wrap4() {
46577
46581
  return fn.apply(thisArg, arguments);
46578
46582
  };
46579
46583
  }
46580
46584
 
46581
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/utils.js
46585
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/utils.js
46582
46586
  var { toString: toString2 } = Object.prototype;
46583
46587
  var { getPrototypeOf } = Object;
46584
46588
  var { iterator, toStringTag } = Symbol;
@@ -46615,8 +46619,8 @@ ${JSON.stringify(data, null, 2)}`;
46615
46619
  if (kindOf(val) !== "object") {
46616
46620
  return false;
46617
46621
  }
46618
- const prototype4 = getPrototypeOf(val);
46619
- return (prototype4 === null || prototype4 === Object.prototype || Object.getPrototypeOf(prototype4) === null) && !(toStringTag in val) && !(iterator in val);
46622
+ const prototype3 = getPrototypeOf(val);
46623
+ return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(toStringTag in val) && !(iterator in val);
46620
46624
  };
46621
46625
  var isEmptyObject = (val) => {
46622
46626
  if (!isObject3(val) || isBuffer2(val)) {
@@ -46711,9 +46715,19 @@ ${JSON.stringify(data, null, 2)}`;
46711
46715
  var extend = (a, b, thisArg, { allOwnKeys } = {}) => {
46712
46716
  forEach(b, (val, key) => {
46713
46717
  if (thisArg && isFunction(val)) {
46714
- a[key] = bind(val, thisArg);
46718
+ Object.defineProperty(a, key, {
46719
+ value: bind(val, thisArg),
46720
+ writable: true,
46721
+ enumerable: true,
46722
+ configurable: true
46723
+ });
46715
46724
  } else {
46716
- a[key] = val;
46725
+ Object.defineProperty(a, key, {
46726
+ value: val,
46727
+ writable: true,
46728
+ enumerable: true,
46729
+ configurable: true
46730
+ });
46717
46731
  }
46718
46732
  }, { allOwnKeys });
46719
46733
  return a;
@@ -46724,9 +46738,14 @@ ${JSON.stringify(data, null, 2)}`;
46724
46738
  }
46725
46739
  return content;
46726
46740
  };
46727
- var inherits = (constructor, superConstructor, props, descriptors2) => {
46728
- constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
46729
- constructor.prototype.constructor = constructor;
46741
+ var inherits = (constructor, superConstructor, props, descriptors) => {
46742
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
46743
+ Object.defineProperty(constructor.prototype, "constructor", {
46744
+ value: constructor,
46745
+ writable: true,
46746
+ enumerable: false,
46747
+ configurable: true
46748
+ });
46730
46749
  Object.defineProperty(constructor, "super", {
46731
46750
  value: superConstructor.prototype
46732
46751
  });
@@ -46807,9 +46826,9 @@ ${JSON.stringify(data, null, 2)}`;
46807
46826
  var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty9 }) => (obj, prop) => hasOwnProperty9.call(obj, prop))(Object.prototype);
46808
46827
  var isRegExp = kindOfTest("RegExp");
46809
46828
  var reduceDescriptors = (obj, reducer) => {
46810
- const descriptors2 = Object.getOwnPropertyDescriptors(obj);
46829
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
46811
46830
  const reducedDescriptors = {};
46812
- forEach(descriptors2, (descriptor, name) => {
46831
+ forEach(descriptors, (descriptor, name) => {
46813
46832
  let ret;
46814
46833
  if ((ret = reducer(descriptor, name, obj)) !== false) {
46815
46834
  reducedDescriptors[name] = ret || descriptor;
@@ -46963,26 +46982,39 @@ ${JSON.stringify(data, null, 2)}`;
46963
46982
  isIterable
46964
46983
  };
46965
46984
 
46966
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/core/AxiosError.js
46967
- function AxiosError(message, code, config3, request, response) {
46968
- Error.call(this);
46969
- if (Error.captureStackTrace) {
46970
- Error.captureStackTrace(this, this.constructor);
46971
- } else {
46972
- this.stack = new Error().stack;
46985
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/core/AxiosError.js
46986
+ var AxiosError = class _AxiosError extends Error {
46987
+ static from(error2, code, config3, request, response, customProps) {
46988
+ const axiosError = new _AxiosError(error2.message, code || error2.code, config3, request, response);
46989
+ axiosError.cause = error2;
46990
+ axiosError.name = error2.name;
46991
+ customProps && Object.assign(axiosError, customProps);
46992
+ return axiosError;
46973
46993
  }
46974
- this.message = message;
46975
- this.name = "AxiosError";
46976
- code && (this.code = code);
46977
- config3 && (this.config = config3);
46978
- request && (this.request = request);
46979
- if (response) {
46980
- this.response = response;
46981
- this.status = response.status ? response.status : null;
46994
+ /**
46995
+ * Create an Error with the specified message, config, error code, request and response.
46996
+ *
46997
+ * @param {string} message The error message.
46998
+ * @param {string} [code] The error code (for example, 'ECONNABORTED').
46999
+ * @param {Object} [config] The config.
47000
+ * @param {Object} [request] The request.
47001
+ * @param {Object} [response] The response.
47002
+ *
47003
+ * @returns {Error} The created error.
47004
+ */
47005
+ constructor(message, code, config3, request, response) {
47006
+ super(message);
47007
+ this.name = "AxiosError";
47008
+ this.isAxiosError = true;
47009
+ code && (this.code = code);
47010
+ config3 && (this.config = config3);
47011
+ request && (this.request = request);
47012
+ if (response) {
47013
+ this.response = response;
47014
+ this.status = response.status;
47015
+ }
46982
47016
  }
46983
- }
46984
- utils_default.inherits(AxiosError, Error, {
46985
- toJSON: function toJSON() {
47017
+ toJSON() {
46986
47018
  return {
46987
47019
  // Standard
46988
47020
  message: this.message,
@@ -47001,51 +47033,25 @@ ${JSON.stringify(data, null, 2)}`;
47001
47033
  status: this.status
47002
47034
  };
47003
47035
  }
47004
- });
47005
- var prototype = AxiosError.prototype;
47006
- var descriptors = {};
47007
- [
47008
- "ERR_BAD_OPTION_VALUE",
47009
- "ERR_BAD_OPTION",
47010
- "ECONNABORTED",
47011
- "ETIMEDOUT",
47012
- "ERR_NETWORK",
47013
- "ERR_FR_TOO_MANY_REDIRECTS",
47014
- "ERR_DEPRECATED",
47015
- "ERR_BAD_RESPONSE",
47016
- "ERR_BAD_REQUEST",
47017
- "ERR_CANCELED",
47018
- "ERR_NOT_SUPPORT",
47019
- "ERR_INVALID_URL"
47020
- // eslint-disable-next-line func-names
47021
- ].forEach((code) => {
47022
- descriptors[code] = { value: code };
47023
- });
47024
- Object.defineProperties(AxiosError, descriptors);
47025
- Object.defineProperty(prototype, "isAxiosError", { value: true });
47026
- AxiosError.from = (error2, code, config3, request, response, customProps) => {
47027
- const axiosError = Object.create(prototype);
47028
- utils_default.toFlatObject(error2, axiosError, function filter2(obj) {
47029
- return obj !== Error.prototype;
47030
- }, (prop) => {
47031
- return prop !== "isAxiosError";
47032
- });
47033
- const msg = error2 && error2.message ? error2.message : "Error";
47034
- const errCode = code == null && error2 ? error2.code : code;
47035
- AxiosError.call(axiosError, msg, errCode, config3, request, response);
47036
- if (error2 && axiosError.cause == null) {
47037
- Object.defineProperty(axiosError, "cause", { value: error2, configurable: true });
47038
- }
47039
- axiosError.name = error2 && error2.name || "Error";
47040
- customProps && Object.assign(axiosError, customProps);
47041
- return axiosError;
47042
47036
  };
47037
+ AxiosError.ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
47038
+ AxiosError.ERR_BAD_OPTION = "ERR_BAD_OPTION";
47039
+ AxiosError.ECONNABORTED = "ECONNABORTED";
47040
+ AxiosError.ETIMEDOUT = "ETIMEDOUT";
47041
+ AxiosError.ERR_NETWORK = "ERR_NETWORK";
47042
+ AxiosError.ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
47043
+ AxiosError.ERR_DEPRECATED = "ERR_DEPRECATED";
47044
+ AxiosError.ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
47045
+ AxiosError.ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
47046
+ AxiosError.ERR_CANCELED = "ERR_CANCELED";
47047
+ AxiosError.ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
47048
+ AxiosError.ERR_INVALID_URL = "ERR_INVALID_URL";
47043
47049
  var AxiosError_default = AxiosError;
47044
47050
 
47045
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/null.js
47051
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/null.js
47046
47052
  var null_default = null;
47047
47053
 
47048
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/toFormData.js
47054
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/toFormData.js
47049
47055
  function isVisitable(thing) {
47050
47056
  return utils_default.isPlainObject(thing) || utils_default.isArray(thing);
47051
47057
  }
@@ -47160,7 +47166,7 @@ ${JSON.stringify(data, null, 2)}`;
47160
47166
  }
47161
47167
  var toFormData_default = toFormData;
47162
47168
 
47163
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/AxiosURLSearchParams.js
47169
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/AxiosURLSearchParams.js
47164
47170
  function encode2(str) {
47165
47171
  const charMap = {
47166
47172
  "!": "%21",
@@ -47179,11 +47185,11 @@ ${JSON.stringify(data, null, 2)}`;
47179
47185
  this._pairs = [];
47180
47186
  params && toFormData_default(params, this, options);
47181
47187
  }
47182
- var prototype2 = AxiosURLSearchParams.prototype;
47183
- prototype2.append = function append(name, value) {
47188
+ var prototype = AxiosURLSearchParams.prototype;
47189
+ prototype.append = function append(name, value) {
47184
47190
  this._pairs.push([name, value]);
47185
47191
  };
47186
- prototype2.toString = function toString3(encoder) {
47192
+ prototype.toString = function toString3(encoder) {
47187
47193
  const _encode = encoder ? function(value) {
47188
47194
  return encoder.call(this, value, encode2);
47189
47195
  } : encode2;
@@ -47193,7 +47199,7 @@ ${JSON.stringify(data, null, 2)}`;
47193
47199
  };
47194
47200
  var AxiosURLSearchParams_default = AxiosURLSearchParams;
47195
47201
 
47196
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/buildURL.js
47202
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/buildURL.js
47197
47203
  function encode3(val) {
47198
47204
  return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
47199
47205
  }
@@ -47202,17 +47208,15 @@ ${JSON.stringify(data, null, 2)}`;
47202
47208
  return url;
47203
47209
  }
47204
47210
  const _encode = options && options.encode || encode3;
47205
- if (utils_default.isFunction(options)) {
47206
- options = {
47207
- serialize: options
47208
- };
47209
- }
47210
- const serializeFn = options && options.serialize;
47211
+ const _options = utils_default.isFunction(options) ? {
47212
+ serialize: options
47213
+ } : options;
47214
+ const serializeFn = _options && _options.serialize;
47211
47215
  let serializedParams;
47212
47216
  if (serializeFn) {
47213
- serializedParams = serializeFn(params, options);
47217
+ serializedParams = serializeFn(params, _options);
47214
47218
  } else {
47215
- serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode);
47219
+ serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, _options).toString(_encode);
47216
47220
  }
47217
47221
  if (serializedParams) {
47218
47222
  const hashmarkIndex = url.indexOf("#");
@@ -47224,7 +47228,7 @@ ${JSON.stringify(data, null, 2)}`;
47224
47228
  return url;
47225
47229
  }
47226
47230
 
47227
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/core/InterceptorManager.js
47231
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/core/InterceptorManager.js
47228
47232
  var InterceptorManager = class {
47229
47233
  constructor() {
47230
47234
  this.handlers = [];
@@ -47234,6 +47238,7 @@ ${JSON.stringify(data, null, 2)}`;
47234
47238
  *
47235
47239
  * @param {Function} fulfilled The function to handle `then` for a `Promise`
47236
47240
  * @param {Function} rejected The function to handle `reject` for a `Promise`
47241
+ * @param {Object} options The options for the interceptor, synchronous and runWhen
47237
47242
  *
47238
47243
  * @return {Number} An ID used to remove interceptor later
47239
47244
  */
@@ -47288,23 +47293,23 @@ ${JSON.stringify(data, null, 2)}`;
47288
47293
  };
47289
47294
  var InterceptorManager_default = InterceptorManager;
47290
47295
 
47291
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/defaults/transitional.js
47296
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/defaults/transitional.js
47292
47297
  var transitional_default = {
47293
47298
  silentJSONParsing: true,
47294
47299
  forcedJSONParsing: true,
47295
47300
  clarifyTimeoutError: false
47296
47301
  };
47297
47302
 
47298
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js
47303
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js
47299
47304
  var URLSearchParams_default = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams_default;
47300
47305
 
47301
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/platform/browser/classes/FormData.js
47306
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/platform/browser/classes/FormData.js
47302
47307
  var FormData_default = typeof FormData !== "undefined" ? FormData : null;
47303
47308
 
47304
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/platform/browser/classes/Blob.js
47309
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/platform/browser/classes/Blob.js
47305
47310
  var Blob_default = typeof Blob !== "undefined" ? Blob : null;
47306
47311
 
47307
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/platform/browser/index.js
47312
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/platform/browser/index.js
47308
47313
  var browser_default = {
47309
47314
  isBrowser: true,
47310
47315
  classes: {
@@ -47315,7 +47320,7 @@ ${JSON.stringify(data, null, 2)}`;
47315
47320
  protocols: ["http", "https", "file", "blob", "url", "data"]
47316
47321
  };
47317
47322
 
47318
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/platform/common/utils.js
47323
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/platform/common/utils.js
47319
47324
  var utils_exports2 = {};
47320
47325
  __export(utils_exports2, {
47321
47326
  hasBrowserEnv: () => hasBrowserEnv,
@@ -47333,13 +47338,13 @@ ${JSON.stringify(data, null, 2)}`;
47333
47338
  })();
47334
47339
  var origin = hasBrowserEnv && window.location.href || "http://localhost";
47335
47340
 
47336
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/platform/index.js
47341
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/platform/index.js
47337
47342
  var platform_default = {
47338
47343
  ...utils_exports2,
47339
47344
  ...browser_default
47340
47345
  };
47341
47346
 
47342
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/toURLEncodedForm.js
47347
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/toURLEncodedForm.js
47343
47348
  function toURLEncodedForm(data, options) {
47344
47349
  return toFormData_default(data, new platform_default.classes.URLSearchParams(), {
47345
47350
  visitor: function(value, key, path, helpers) {
@@ -47353,7 +47358,7 @@ ${JSON.stringify(data, null, 2)}`;
47353
47358
  });
47354
47359
  }
47355
47360
 
47356
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/formDataToJSON.js
47361
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/formDataToJSON.js
47357
47362
  function parsePropPath(name) {
47358
47363
  return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
47359
47364
  return match[0] === "[]" ? "" : match[1] || match[0];
@@ -47406,7 +47411,7 @@ ${JSON.stringify(data, null, 2)}`;
47406
47411
  }
47407
47412
  var formDataToJSON_default = formDataToJSON;
47408
47413
 
47409
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/defaults/index.js
47414
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/defaults/index.js
47410
47415
  function stringifySafely(rawValue, parser, encoder) {
47411
47416
  if (utils_default.isString(rawValue)) {
47412
47417
  try {
@@ -47515,7 +47520,7 @@ ${JSON.stringify(data, null, 2)}`;
47515
47520
  });
47516
47521
  var defaults_default = defaults;
47517
47522
 
47518
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/parseHeaders.js
47523
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/parseHeaders.js
47519
47524
  var ignoreDuplicateOf = utils_default.toObjectSet([
47520
47525
  "age",
47521
47526
  "authorization",
@@ -47560,7 +47565,7 @@ ${JSON.stringify(data, null, 2)}`;
47560
47565
  return parsed;
47561
47566
  };
47562
47567
 
47563
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/core/AxiosHeaders.js
47568
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/core/AxiosHeaders.js
47564
47569
  var $internals = Symbol("internals");
47565
47570
  function normalizeHeader(header) {
47566
47571
  return header && String(header).trim().toLowerCase();
@@ -47764,11 +47769,11 @@ ${JSON.stringify(data, null, 2)}`;
47764
47769
  accessors: {}
47765
47770
  };
47766
47771
  const accessors = internals.accessors;
47767
- const prototype4 = this.prototype;
47772
+ const prototype3 = this.prototype;
47768
47773
  function defineAccessor(_header) {
47769
47774
  const lHeader = normalizeHeader(_header);
47770
47775
  if (!accessors[lHeader]) {
47771
- buildAccessors(prototype4, _header);
47776
+ buildAccessors(prototype3, _header);
47772
47777
  accessors[lHeader] = true;
47773
47778
  }
47774
47779
  }
@@ -47789,7 +47794,7 @@ ${JSON.stringify(data, null, 2)}`;
47789
47794
  utils_default.freezeMethods(AxiosHeaders);
47790
47795
  var AxiosHeaders_default = AxiosHeaders;
47791
47796
 
47792
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/core/transformData.js
47797
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/core/transformData.js
47793
47798
  function transformData(fns, response) {
47794
47799
  const config3 = this || defaults_default;
47795
47800
  const context = response || config3;
@@ -47802,22 +47807,31 @@ ${JSON.stringify(data, null, 2)}`;
47802
47807
  return data;
47803
47808
  }
47804
47809
 
47805
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/cancel/isCancel.js
47810
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/cancel/isCancel.js
47806
47811
  function isCancel(value) {
47807
47812
  return !!(value && value.__CANCEL__);
47808
47813
  }
47809
47814
 
47810
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/cancel/CanceledError.js
47811
- function CanceledError(message, config3, request) {
47812
- AxiosError_default.call(this, message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config3, request);
47813
- this.name = "CanceledError";
47814
- }
47815
- utils_default.inherits(CanceledError, AxiosError_default, {
47816
- __CANCEL__: true
47817
- });
47815
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/cancel/CanceledError.js
47816
+ var CanceledError = class extends AxiosError_default {
47817
+ /**
47818
+ * A `CanceledError` is an object that is thrown when an operation is canceled.
47819
+ *
47820
+ * @param {string=} message The message.
47821
+ * @param {Object=} config The config.
47822
+ * @param {Object=} request The request.
47823
+ *
47824
+ * @returns {CanceledError} The created error.
47825
+ */
47826
+ constructor(message, config3, request) {
47827
+ super(message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config3, request);
47828
+ this.name = "CanceledError";
47829
+ this.__CANCEL__ = true;
47830
+ }
47831
+ };
47818
47832
  var CanceledError_default = CanceledError;
47819
47833
 
47820
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/core/settle.js
47834
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/core/settle.js
47821
47835
  function settle(resolve, reject, response) {
47822
47836
  const validateStatus2 = response.config.validateStatus;
47823
47837
  if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
@@ -47833,13 +47847,13 @@ ${JSON.stringify(data, null, 2)}`;
47833
47847
  }
47834
47848
  }
47835
47849
 
47836
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/parseProtocol.js
47850
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/parseProtocol.js
47837
47851
  function parseProtocol(url) {
47838
47852
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
47839
47853
  return match && match[1] || "";
47840
47854
  }
47841
47855
 
47842
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/speedometer.js
47856
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/speedometer.js
47843
47857
  function speedometer(samplesCount, min) {
47844
47858
  samplesCount = samplesCount || 10;
47845
47859
  const bytes = new Array(samplesCount);
@@ -47875,7 +47889,7 @@ ${JSON.stringify(data, null, 2)}`;
47875
47889
  }
47876
47890
  var speedometer_default = speedometer;
47877
47891
 
47878
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/throttle.js
47892
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/throttle.js
47879
47893
  function throttle(fn, freq) {
47880
47894
  let timestamp = 0;
47881
47895
  let threshold = 1e3 / freq;
@@ -47910,7 +47924,7 @@ ${JSON.stringify(data, null, 2)}`;
47910
47924
  }
47911
47925
  var throttle_default = throttle;
47912
47926
 
47913
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/progressEventReducer.js
47927
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/progressEventReducer.js
47914
47928
  var progressEventReducer = (listener, isDownloadStream, freq = 3) => {
47915
47929
  let bytesNotified = 0;
47916
47930
  const _speedometer = speedometer_default(50, 250);
@@ -47945,7 +47959,7 @@ ${JSON.stringify(data, null, 2)}`;
47945
47959
  };
47946
47960
  var asyncDecorator = (fn) => (...args) => utils_default.asap(() => fn(...args));
47947
47961
 
47948
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/isURLSameOrigin.js
47962
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/isURLSameOrigin.js
47949
47963
  var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
47950
47964
  url = new URL(url, platform_default.origin);
47951
47965
  return origin2.protocol === url.protocol && origin2.host === url.host && (isMSIE || origin2.port === url.port);
@@ -47954,7 +47968,7 @@ ${JSON.stringify(data, null, 2)}`;
47954
47968
  platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent)
47955
47969
  ) : () => true;
47956
47970
 
47957
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/cookies.js
47971
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/cookies.js
47958
47972
  var cookies_default = platform_default.hasStandardBrowserEnv ? (
47959
47973
  // Standard browser envs support document.cookie
47960
47974
  {
@@ -48000,17 +48014,17 @@ ${JSON.stringify(data, null, 2)}`;
48000
48014
  }
48001
48015
  );
48002
48016
 
48003
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/isAbsoluteURL.js
48017
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/isAbsoluteURL.js
48004
48018
  function isAbsoluteURL(url) {
48005
48019
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
48006
48020
  }
48007
48021
 
48008
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/combineURLs.js
48022
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/combineURLs.js
48009
48023
  function combineURLs(baseURL, relativeURL) {
48010
48024
  return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
48011
48025
  }
48012
48026
 
48013
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/core/buildFullPath.js
48027
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/core/buildFullPath.js
48014
48028
  function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
48015
48029
  let isRelativeUrl = !isAbsoluteURL(requestedURL);
48016
48030
  if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
@@ -48019,7 +48033,7 @@ ${JSON.stringify(data, null, 2)}`;
48019
48033
  return requestedURL;
48020
48034
  }
48021
48035
 
48022
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/core/mergeConfig.js
48036
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/core/mergeConfig.js
48023
48037
  var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? { ...thing } : thing;
48024
48038
  function mergeConfig(config1, config22) {
48025
48039
  config22 = config22 || {};
@@ -48099,7 +48113,7 @@ ${JSON.stringify(data, null, 2)}`;
48099
48113
  return config3;
48100
48114
  }
48101
48115
 
48102
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/resolveConfig.js
48116
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/resolveConfig.js
48103
48117
  var resolveConfig_default = (config3) => {
48104
48118
  const newConfig = mergeConfig({}, config3);
48105
48119
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
@@ -48136,7 +48150,7 @@ ${JSON.stringify(data, null, 2)}`;
48136
48150
  return newConfig;
48137
48151
  };
48138
48152
 
48139
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/adapters/xhr.js
48153
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/adapters/xhr.js
48140
48154
  var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
48141
48155
  var xhr_default = isXHRAdapterSupported && function(config3) {
48142
48156
  return new Promise(function dispatchXhrRequest(resolve, reject) {
@@ -48266,7 +48280,7 @@ ${JSON.stringify(data, null, 2)}`;
48266
48280
  });
48267
48281
  };
48268
48282
 
48269
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/composeSignals.js
48283
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/composeSignals.js
48270
48284
  var composeSignals = (signals, timeout) => {
48271
48285
  const { length } = signals = signals ? signals.filter(Boolean) : [];
48272
48286
  if (timeout || length) {
@@ -48282,7 +48296,7 @@ ${JSON.stringify(data, null, 2)}`;
48282
48296
  };
48283
48297
  let timer = timeout && setTimeout(() => {
48284
48298
  timer = null;
48285
- onabort(new AxiosError_default(`timeout ${timeout} of ms exceeded`, AxiosError_default.ETIMEDOUT));
48299
+ onabort(new AxiosError_default(`timeout of ${timeout}ms exceeded`, AxiosError_default.ETIMEDOUT));
48286
48300
  }, timeout);
48287
48301
  const unsubscribe = () => {
48288
48302
  if (signals) {
@@ -48302,7 +48316,7 @@ ${JSON.stringify(data, null, 2)}`;
48302
48316
  };
48303
48317
  var composeSignals_default = composeSignals;
48304
48318
 
48305
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/trackStream.js
48319
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/trackStream.js
48306
48320
  var streamChunk = function* (chunk, chunkSize) {
48307
48321
  let len = chunk.byteLength;
48308
48322
  if (!chunkSize || len < chunkSize) {
@@ -48379,7 +48393,7 @@ ${JSON.stringify(data, null, 2)}`;
48379
48393
  });
48380
48394
  };
48381
48395
 
48382
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/adapters/fetch.js
48396
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/adapters/fetch.js
48383
48397
  var DEFAULT_CHUNK_SIZE = 64 * 1024;
48384
48398
  var { isFunction: isFunction2 } = utils_default;
48385
48399
  var globalFetchAPI = (({ Request: Request2, Response: Response2 }) => ({
@@ -48588,7 +48602,7 @@ ${JSON.stringify(data, null, 2)}`;
48588
48602
  };
48589
48603
  var adapter = getFetch();
48590
48604
 
48591
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/adapters/adapters.js
48605
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/adapters/adapters.js
48592
48606
  var knownAdapters = {
48593
48607
  http: null_default,
48594
48608
  xhr: xhr_default,
@@ -48653,7 +48667,7 @@ ${JSON.stringify(data, null, 2)}`;
48653
48667
  adapters: knownAdapters
48654
48668
  };
48655
48669
 
48656
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/core/dispatchRequest.js
48670
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/core/dispatchRequest.js
48657
48671
  function throwIfCancellationRequested(config3) {
48658
48672
  if (config3.cancelToken) {
48659
48673
  config3.cancelToken.throwIfRequested();
@@ -48698,10 +48712,10 @@ ${JSON.stringify(data, null, 2)}`;
48698
48712
  });
48699
48713
  }
48700
48714
 
48701
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/env/data.js
48702
- var VERSION = "1.13.2";
48715
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/env/data.js
48716
+ var VERSION = "1.13.4";
48703
48717
 
48704
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/validator.js
48718
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/validator.js
48705
48719
  var validators = {};
48706
48720
  ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
48707
48721
  validators[type] = function validator(thing) {
@@ -48765,7 +48779,7 @@ ${JSON.stringify(data, null, 2)}`;
48765
48779
  validators
48766
48780
  };
48767
48781
 
48768
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/core/Axios.js
48782
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/core/Axios.js
48769
48783
  var validators2 = validator_default.validators;
48770
48784
  var Axios = class {
48771
48785
  constructor(instanceConfig) {
@@ -48937,7 +48951,7 @@ ${JSON.stringify(data, null, 2)}`;
48937
48951
  });
48938
48952
  var Axios_default = Axios;
48939
48953
 
48940
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/cancel/CancelToken.js
48954
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/cancel/CancelToken.js
48941
48955
  var CancelToken = class _CancelToken {
48942
48956
  constructor(executor) {
48943
48957
  if (typeof executor !== "function") {
@@ -49035,19 +49049,19 @@ ${JSON.stringify(data, null, 2)}`;
49035
49049
  };
49036
49050
  var CancelToken_default = CancelToken;
49037
49051
 
49038
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/spread.js
49052
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/spread.js
49039
49053
  function spread(callback) {
49040
49054
  return function wrap4(arr) {
49041
49055
  return callback.apply(null, arr);
49042
49056
  };
49043
49057
  }
49044
49058
 
49045
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/isAxiosError.js
49059
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/isAxiosError.js
49046
49060
  function isAxiosError(payload) {
49047
49061
  return utils_default.isObject(payload) && payload.isAxiosError === true;
49048
49062
  }
49049
49063
 
49050
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/HttpStatusCode.js
49064
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/helpers/HttpStatusCode.js
49051
49065
  var HttpStatusCode = {
49052
49066
  Continue: 100,
49053
49067
  SwitchingProtocols: 101,
@@ -49124,7 +49138,7 @@ ${JSON.stringify(data, null, 2)}`;
49124
49138
  });
49125
49139
  var HttpStatusCode_default = HttpStatusCode;
49126
49140
 
49127
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/axios.js
49141
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/lib/axios.js
49128
49142
  function createInstance(defaultConfig2) {
49129
49143
  const context = new Axios_default(defaultConfig2);
49130
49144
  const instance = bind(Axios_default.prototype.request, context);
@@ -49157,7 +49171,7 @@ ${JSON.stringify(data, null, 2)}`;
49157
49171
  axios.default = axios;
49158
49172
  var axios_default = axios;
49159
49173
 
49160
- // node_modules/.pnpm/axios@1.13.2/node_modules/axios/index.js
49174
+ // node_modules/.pnpm/axios@1.13.4/node_modules/axios/index.js
49161
49175
  var {
49162
49176
  Axios: Axios2,
49163
49177
  AxiosError: AxiosError2,
@@ -55997,20 +56011,13 @@ ${JSON.stringify(data, null, 2)}`;
55997
56011
  async getDexPrice(baseToken, quoteToken, amount) {
55998
56012
  const lstTokenInfo = baseToken;
55999
56013
  const lstUnderlyingTokenInfo = quoteToken;
56000
- console.log("lstTokenInfo", lstTokenInfo);
56001
- console.log("lstUnderlyingTokenInfo", lstUnderlyingTokenInfo);
56002
- console.log("amount", amount);
56003
56014
  const quote = await this.getQuote(
56004
56015
  lstTokenInfo.address.address,
56005
56016
  lstUnderlyingTokenInfo.address.address,
56006
56017
  amount
56007
56018
  );
56008
- console.log("quote", quote);
56009
56019
  const outputAmount = Web3Number.fromWei(quote.total_calculated, lstUnderlyingTokenInfo.decimals);
56010
- console.log("outputAmount", outputAmount);
56011
- console.log("amount", amount);
56012
56020
  const price = outputAmount.toNumber() / amount.toNumber();
56013
- console.log("price", price);
56014
56021
  logger2.verbose(`${_EkuboQuoter.name}:: LST Dex Price: ${price}`);
56015
56022
  return price;
56016
56023
  }
@@ -56029,16 +56036,12 @@ ${JSON.stringify(data, null, 2)}`;
56029
56036
  // debt collateral
56030
56037
  async getSwapLimitAmount(fromToken, toToken, amount, max_slippage = 2e-3) {
56031
56038
  const isExactAmountIn = amount.greaterThanOrEqualTo(0);
56032
- console.log("isExactAmountIn", isExactAmountIn);
56033
56039
  logger2.verbose(`${_EkuboQuoter.name}::getSwapLimitAmount isExactAmountIn: ${isExactAmountIn}, fromToken: ${fromToken.symbol}, toToken: ${toToken.symbol}, amount: ${amount}`);
56034
56040
  const isYieldToken = this.tokenMarketData.isAPYSupported(toToken);
56035
56041
  console.log("isYieldToken", isYieldToken);
56036
56042
  const baseToken = isExactAmountIn ? toToken : fromToken;
56037
56043
  const quoteToken = isExactAmountIn ? fromToken : toToken;
56038
- console.log("baseToken", baseToken);
56039
- console.log("quoteToken", quoteToken);
56040
56044
  const dexPrice = await this.getDexPrice(baseToken, quoteToken, amount);
56041
- console.log("dexPrice", dexPrice);
56042
56045
  const trueExchangeRate = isYieldToken ? await this.tokenMarketData.getTruePrice(baseToken) : dexPrice;
56043
56046
  console.log("trueExchangeRate", trueExchangeRate);
56044
56047
  if (isExactAmountIn) {
@@ -56069,7 +56072,6 @@ ${JSON.stringify(data, null, 2)}`;
56069
56072
  return quote.splits.map((split2) => {
56070
56073
  const isNegativeAmount = BigInt(split2.amount_specified) <= 0n;
56071
56074
  const token = isNegativeAmount ? toTokenInfo : fromTokenInfo;
56072
- console.log("token for withdrawal", token, isNegativeAmount);
56073
56075
  return {
56074
56076
  route: split2.route.map((_route) => ({
56075
56077
  pool_key: {
@@ -56259,7 +56261,22 @@ ${JSON.stringify(data, null, 2)}`;
56259
56261
  `HTTP ${response.status}: ${errorData.detail || response.statusText}`
56260
56262
  );
56261
56263
  }
56262
- const data = await response.json();
56264
+ const text = await response.text();
56265
+ const MAX_SAFE_INTEGER_STR = "9007199254740991";
56266
+ const largeIntegerRegex = /"data"\s*:\s*(\d{16,})/g;
56267
+ const modifiedText = text.replace(largeIntegerRegex, (match, largeInt) => {
56268
+ if (largeInt.length > MAX_SAFE_INTEGER_STR.length || largeInt.length === MAX_SAFE_INTEGER_STR.length && largeInt > MAX_SAFE_INTEGER_STR) {
56269
+ return `"data":"${largeInt}"`;
56270
+ }
56271
+ return match;
56272
+ });
56273
+ const data = JSON.parse(modifiedText);
56274
+ if (data && typeof data.data === "string" && /^\d+$/.test(data.data)) {
56275
+ const numValue = Number(data.data);
56276
+ if (Number.isSafeInteger(numValue)) {
56277
+ data.data = numValue;
56278
+ }
56279
+ }
56263
56280
  return data;
56264
56281
  } catch (error2) {
56265
56282
  lastError = error2;
@@ -56319,6 +56336,7 @@ ${JSON.stringify(data, null, 2)}`;
56319
56336
  }
56320
56337
  /**
56321
56338
  * Initiate a withdrawal from Extended Exchange
56339
+ * Returns data as number | string to preserve precision for large integers
56322
56340
  */
56323
56341
  async withdraw(request) {
56324
56342
  return this.makeRequest("/api/v1/withdraw", {
@@ -56457,6 +56475,7 @@ ${JSON.stringify(data, null, 2)}`;
56457
56475
  }
56458
56476
  /**
56459
56477
  * Withdraw USDC (convenience method)
56478
+ * Returns data as number | string to preserve precision for large integers
56460
56479
  */
56461
56480
  async withdrawUSDC(amount) {
56462
56481
  return this.withdraw({ amount, asset: "USDC" });
@@ -56466,11 +56485,13 @@ ${JSON.stringify(data, null, 2)}`;
56466
56485
  * @param marketName - The name of the market to get funding rates for
56467
56486
  * @returns The funding rates for the specified market
56468
56487
  */
56469
- async getFundingRates(marketName, side) {
56488
+ async getFundingRates(marketName, side, startTime, endTime) {
56489
+ const endTimeParam = endTime !== void 0 ? `&end_time=${endTime}` : "";
56490
+ const startTimeParam = startTime !== void 0 ? `&start_time=${startTime}` : "";
56470
56491
  return this.makeRequest(
56471
56492
  `/api/v1/markets/funding-rates?market_name=${encodeURIComponent(
56472
56493
  marketName
56473
- )}&side=${encodeURIComponent(side)}`
56494
+ )}&side=${encodeURIComponent(side)}${startTimeParam}${endTimeParam}`
56474
56495
  );
56475
56496
  }
56476
56497
  };
@@ -73781,10 +73802,10 @@ spurious results.`);
73781
73802
  var result = symbolObservablePonyfill(root);
73782
73803
 
73783
73804
  // node_modules/.pnpm/@apollo+client@3.11.8_@types+react@19.1.11_graphql@16.9.0/node_modules/@apollo/client/utilities/observables/Observable.js
73784
- var prototype3 = Observable.prototype;
73805
+ var prototype2 = Observable.prototype;
73785
73806
  var fakeObsSymbol = "@@observable";
73786
- if (!prototype3[fakeObsSymbol]) {
73787
- prototype3[fakeObsSymbol] = function() {
73807
+ if (!prototype2[fakeObsSymbol]) {
73808
+ prototype2[fakeObsSymbol] = function() {
73788
73809
  return this;
73789
73810
  };
73790
73811
  }
@@ -91435,11 +91456,6 @@ spurious results.`);
91435
91456
  if (!this.pricer) {
91436
91457
  throw new Error("Pricer is not initialized");
91437
91458
  }
91438
- const CACHE_KEY = `positions_${blockNumber}_${this.config.poolId.shortString()}_${this.config.collateral.symbol}_${this.config.debt.symbol}`;
91439
- const cacheData = this.getCache(CACHE_KEY);
91440
- if (cacheData) {
91441
- return cacheData;
91442
- }
91443
91459
  const { contract, isV2 } = this.getVesuSingletonContract(config3, this.config.poolId);
91444
91460
  const output = await contract.call(isV2 ? "position" : "position_unsafe", [
91445
91461
  ...isV2 ? [] : [this.config.poolId.address],
@@ -91465,7 +91481,6 @@ spurious results.`);
91465
91481
  usdValue: debtAmount.multipliedBy(token2Price.price).toNumber(),
91466
91482
  remarks: "Debt"
91467
91483
  }];
91468
- this.setCache(CACHE_KEY, value, 6e4);
91469
91484
  return value.map((v) => ({ ...v, protocol: Protocols.VESU }));
91470
91485
  }
91471
91486
  async getCollateralization(config3, blockNumber = "latest") {
@@ -92384,15 +92399,14 @@ spurious results.`);
92384
92399
  var MAX_LTV_BTC_USDC = 0.8428;
92385
92400
  var MAX_LIQUIDATION_RATIO = 0.86;
92386
92401
  var VAULT_ID_EXTENDED = process.env.VAULT_ID_EXTENDED ?? 220774;
92387
- var WALLET_ADDRESS = process.env.WALLET_ADDRESS ?? "0x07b84bb6E87588BdAde0bfe6173A615b3C220F9C3803456aE183C50EA1d15Ba1";
92388
- var TESTNET_WALLET_ADDRESS = process.env.TESTNET_WALLET_ADDRESS ?? "0x07b84bb6E87588BdAde0bfe6173A615b3C220F9C3803456aE183C50EA1d15Ba1";
92389
- var TEST_WALLET_2 = process.env.TEST_WALLET_2 ?? "0x004C1bdC61DAc7947F3C93d0163d660012E2aB0521567f7155fcf502848791A7";
92402
+ var WALLET_ADDRESS = process.env.WALLET_ADDRESS ?? "0x007E24592287427aaE9d291770B17d582E8A45f3aE54228F998793Ec769B7D13";
92390
92403
  var STRK_API_TEST_RPC = process.env.STRK_API_TEST_RPC ?? "https://sepolia.starknet.a5a.ch";
92391
92404
  var STRK_API_RPC = process.env.STRK_API_RPC ?? "https://mainnet.starknet.a5a.ch";
92392
92405
  var MAX_RETRIES = Number(process.env.MAX_RETRIES ?? 3);
92393
92406
  var MAX_DELAY = Number(process.env.MAX_DELAY ?? 100);
92394
92407
  var EXTEND_MARKET_NAME = "BTC-USD";
92395
- var LIMIT_BALANCE = Number(process.env.LIMIT_BALANCE ?? 10);
92408
+ var LIMIT_BALANCE = Number(process.env.LIMIT_BALANCE ?? 0.05);
92409
+ var LIMIT_BALANCE_VALUE = 10;
92396
92410
  var REBALANCER_INTERVAL = Number(process.env.REBALANCER_INTERVAL ?? 18e4);
92397
92411
  var WITHDRAWAL_INTERVAL = Number(process.env.WITHDRAWAL_INTERVAL ?? 18e6);
92398
92412
  var INVESTING_INTERVAL = Number(process.env.INVESTING_INTERVAL ?? 18e4);
@@ -92410,8 +92424,6 @@ spurious results.`);
92410
92424
  var MINIMUM_DEBT_AMOUNT_VESU_FOR_REBALANCING = Number(process.env.MINIMUM_DEBT_AMOUNT_VESU_FOR_REBALANCING ?? 1);
92411
92425
  var MINIMUM_EXTENDED_POSITION_SIZE = 1e-4;
92412
92426
  var MINIMUM_WBTC_DIFFERENCE_FOR_AVNU_SWAP = 1e-5;
92413
- var MAX_PRICE_DIFFERENCE_BETWEEN_AVNU_AND_EXTENDED = 700;
92414
- var MIN_PRICE_DIFFERENCE_BETWEEN_AVNU_AND_EXTENDED = -100;
92415
92427
 
92416
92428
  // src/strategies/vesu-extended-strategy/utils/helper.ts
92417
92429
  var returnFormattedAmount = (amount, toTokenDecimals) => {
@@ -92431,8 +92443,7 @@ spurious results.`);
92431
92443
  vesu_leverage: 0
92432
92444
  };
92433
92445
  }
92434
- const extendedBTCExposure = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].size, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
92435
- const extendedExposureUSD = extendedBTCExposure.multipliedBy(collateralPrice);
92446
+ const extendedExposureUSD = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].value, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
92436
92447
  const vesuBTCExposureUSD = collateralUnits.multipliedBy(collateralPrice);
92437
92448
  const numerator1 = vesu_leverage * amount + vesuBTCExposureUSD.toNumber();
92438
92449
  const numerator2 = extendedExposureUSD.toNumber();
@@ -92469,7 +92480,6 @@ spurious results.`);
92469
92480
  return null;
92470
92481
  }
92471
92482
  const extendedExposureUSD = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].value, USDC_TOKEN_DECIMALS) : new Web3Number(0, USDC_TOKEN_DECIMALS);
92472
- console.log("THe collateral is", collateralPrice, collateralUnits);
92473
92483
  const vesuExposureUSD = collateralUnits.multipliedBy(collateralPrice);
92474
92484
  if (vesuExposureUSD.lessThan(0)) {
92475
92485
  return {
@@ -92526,10 +92536,10 @@ spurious results.`);
92526
92536
  const extended_leverage_max = 1 / (MAINTENANCE_MARGIN + MAX_PRICE_DROP_PERCENTAGE);
92527
92537
  return Math.floor(extended_leverage_max);
92528
92538
  };
92529
- var calculateDebtAmount = (collateralAmount, debtAmount, debtPrice, maxLtv = MAX_LTV_BTC_USDC, addedAmount, collateralPrice, isDeposit) => {
92539
+ var calculateDebtAmount = (collateralAmount, debtAmount, debtPrice, maxLtv = MAX_LIQUIDATION_RATIO, addedAmount, collateralPrice, isDeposit) => {
92530
92540
  try {
92531
- const marginAmount = addedAmount.multipliedBy(isDeposit ? 1 : -1);
92532
- const numerator1 = collateralAmount.plus(addedAmount).multipliedBy(collateralPrice).multipliedBy(maxLtv);
92541
+ const addedCollateral = addedAmount.multipliedBy(isDeposit ? 1 : -1);
92542
+ const numerator1 = collateralAmount.plus(addedCollateral).multipliedBy(collateralPrice).multipliedBy(maxLtv);
92533
92543
  const numerator2 = debtAmount.multipliedBy(debtPrice).multipliedBy(TARGET_HF);
92534
92544
  const denominator = TARGET_HF - maxLtv;
92535
92545
  const x_debt_usd = numerator1.minus(numerator2).dividedBy(denominator);
@@ -92564,19 +92574,34 @@ spurious results.`);
92564
92574
  const extendedHoldings = await client.getHoldings();
92565
92575
  const extended_leverage = calculateExtendedLevergae();
92566
92576
  const latestPosition = (await client.getPositions()).data.pop();
92567
- console.log("the latest position is", latestPosition, extendedHoldings);
92568
92577
  if (!extendedHoldings || !latestPosition) {
92569
92578
  logger2.error(`error getting extended position: extendedHoldings=${extendedHoldings}, latestPosition=${latestPosition}`);
92570
92579
  return null;
92571
92580
  }
92572
- const positionValueInUSD = latestPosition.value;
92581
+ const positionValueInUSD = new Web3Number(latestPosition.value, USDC_TOKEN_DECIMALS);
92573
92582
  const equity = extendedHoldings.data.equity;
92574
- const deposit = Number(positionValueInUSD) / extended_leverage - Number(equity);
92575
- return new Web3Number(Math.floor(deposit / 0.2) * 0.2, USDC_TOKEN_DECIMALS);
92583
+ const deposit = positionValueInUSD.dividedBy(extended_leverage).minus(equity).toFixed(2);
92584
+ return new Web3Number(deposit, USDC_TOKEN_DECIMALS);
92576
92585
  } catch (err2) {
92586
+ logger2.error(`error calculating amount deposit on extended when incurring losses: ${err2}`);
92577
92587
  return null;
92578
92588
  }
92579
92589
  };
92590
+ var calculateWBTCAmountToMaintainLTV = (collateralAmount, debtAmount, debtPrice, maxLtv = MAX_LIQUIDATION_RATIO, collateralPrice, targetHF = TARGET_HF) => {
92591
+ try {
92592
+ const numerator1 = collateralAmount.multipliedBy(collateralPrice).multipliedBy(maxLtv);
92593
+ const numerator2 = debtAmount.multipliedBy(debtPrice).multipliedBy(targetHF);
92594
+ const denominator = maxLtv;
92595
+ const collateralAmountToMaintainLTV = numerator2.minus(numerator1).dividedBy(denominator);
92596
+ let deltaCollateralAmountUnits = new Web3Number(
92597
+ collateralAmountToMaintainLTV.dividedBy(collateralPrice).toFixed(WBTC_TOKEN_DECIMALS),
92598
+ WBTC_TOKEN_DECIMALS
92599
+ );
92600
+ return { deltaCollateralAmountUnits };
92601
+ } catch (err2) {
92602
+ return { deltaCollateralAmountUnits: null };
92603
+ }
92604
+ };
92580
92605
  var calculateExposureDelta = (exposure_extended, exposure_vesu) => {
92581
92606
  const exposure_delta = new Web3Number(exposure_extended - exposure_vesu, 2);
92582
92607
  return exposure_delta.absoluteValue().toNumber();
@@ -92651,21 +92676,36 @@ spurious results.`);
92651
92676
  vaultAllocator: config3.vaultAllocator,
92652
92677
  id: ""
92653
92678
  });
92654
- this.tokenMarketData = new TokenMarketData(this.config.pricer, this.config.networkConfig);
92679
+ this.minimumVesuMovementAmount = config3.minimumVesuMovementAmount ?? 5;
92680
+ this.tokenMarketData = new TokenMarketData(
92681
+ this.config.pricer,
92682
+ this.config.networkConfig
92683
+ );
92655
92684
  }
92656
92685
  async getAPY(supportedPosition) {
92657
92686
  const CACHE_KEY = `apy_${this.config.poolId.address}_${supportedPosition.asset.symbol}`;
92658
92687
  const cacheData = this.getCache(CACHE_KEY);
92659
- console.log(`${_VesuMultiplyAdapter.name}::getAPY cacheData: ${JSON.stringify(cacheData)}`, this.vesuAdapter.config.poolId.shortString(), this.vesuAdapter.config.collateral.symbol, this.vesuAdapter.config.debt.symbol);
92688
+ console.log(
92689
+ `${_VesuMultiplyAdapter.name}::getAPY cacheData: ${JSON.stringify(
92690
+ cacheData
92691
+ )}`,
92692
+ this.vesuAdapter.config.poolId.shortString(),
92693
+ this.vesuAdapter.config.collateral.symbol,
92694
+ this.vesuAdapter.config.debt.symbol
92695
+ );
92660
92696
  if (cacheData) {
92661
92697
  return cacheData;
92662
92698
  }
92663
92699
  try {
92664
92700
  const allVesuPools = await VesuAdapter.getVesuPools();
92665
92701
  const asset = supportedPosition.asset;
92666
- const pool = allVesuPools.pools.find((p) => this.vesuAdapter.config.poolId.eqString(num_exports.getHexString(p.id)));
92702
+ const pool = allVesuPools.pools.find(
92703
+ (p) => this.vesuAdapter.config.poolId.eqString(num_exports.getHexString(p.id))
92704
+ );
92667
92705
  if (!pool) {
92668
- logger2.warn(`VesuMultiplyAdapter: Pool not found for token ${asset.symbol}`);
92706
+ logger2.warn(
92707
+ `VesuMultiplyAdapter: Pool not found for token ${asset.symbol}`
92708
+ );
92669
92709
  return {
92670
92710
  apy: 0,
92671
92711
  type: "base" /* BASE */
@@ -92675,7 +92715,9 @@ spurious results.`);
92675
92715
  (a) => a.symbol.toLowerCase() === asset.symbol.toLowerCase()
92676
92716
  )?.stats;
92677
92717
  if (!assetStats) {
92678
- logger2.warn(`VesuMultiplyAdapter: Asset stats not found for token ${asset.symbol}`);
92718
+ logger2.warn(
92719
+ `VesuMultiplyAdapter: Asset stats not found for token ${asset.symbol}`
92720
+ );
92679
92721
  return {
92680
92722
  apy: 0,
92681
92723
  type: "base" /* BASE */
@@ -92686,7 +92728,9 @@ spurious results.`);
92686
92728
  apy = Number(assetStats.borrowApr?.value || 0) / 1e18;
92687
92729
  } else {
92688
92730
  const isAssetBTC = asset.symbol.toLowerCase().includes("btc");
92689
- const baseAPY = Number(isAssetBTC ? assetStats.btcFiSupplyApr?.value + assetStats.supplyApy?.value : assetStats.supplyApy?.value || 0) / 1e18;
92731
+ const baseAPY = Number(
92732
+ isAssetBTC ? assetStats.btcFiSupplyApr?.value + assetStats.supplyApy?.value : assetStats.supplyApy?.value || 0
92733
+ ) / 1e18;
92690
92734
  const rewardAPY = Number(assetStats.defiSpringSupplyApr?.value || "0") / 1e18;
92691
92735
  const isSupported = this.tokenMarketData.isAPYSupported(asset);
92692
92736
  apy = baseAPY + rewardAPY;
@@ -92702,7 +92746,10 @@ spurious results.`);
92702
92746
  this.setCache(CACHE_KEY, result2, 3e5);
92703
92747
  return result2;
92704
92748
  } catch (error2) {
92705
- logger2.error(`VesuMultiplyAdapter: Error getting APY for ${supportedPosition.asset.symbol}:`, error2);
92749
+ logger2.error(
92750
+ `VesuMultiplyAdapter: Error getting APY for ${supportedPosition.asset.symbol}:`,
92751
+ error2
92752
+ );
92706
92753
  throw error2;
92707
92754
  }
92708
92755
  }
@@ -92715,12 +92762,16 @@ spurious results.`);
92715
92762
  try {
92716
92763
  this.vesuAdapter.networkConfig = this.config.networkConfig;
92717
92764
  this.vesuAdapter.pricer = this.config.pricer;
92718
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
92765
+ const positions = await this.vesuAdapter.getPositions(
92766
+ this.config.networkConfig
92767
+ );
92719
92768
  let position = positions.find(
92720
92769
  (p) => p.token.address.eq(supportedPosition.asset.address)
92721
92770
  );
92722
92771
  if (!position) {
92723
- logger2.warn(`VesuMultiplyAdapter: Position not found for token ${supportedPosition.asset.symbol}`);
92772
+ logger2.warn(
92773
+ `VesuMultiplyAdapter: Position not found for token ${supportedPosition.asset.symbol}`
92774
+ );
92724
92775
  return {
92725
92776
  amount: new Web3Number("0", supportedPosition.asset.decimals),
92726
92777
  remarks: "Position not found"
@@ -92733,12 +92784,18 @@ spurious results.`);
92733
92784
  this.setCache(CACHE_KEY, position, 6e4);
92734
92785
  return position;
92735
92786
  } catch (error2) {
92736
- logger2.error(`VesuMultiplyAdapter: Error getting position for ${supportedPosition.asset.symbol}:`, error2);
92787
+ logger2.error(
92788
+ `VesuMultiplyAdapter: Error getting position for ${supportedPosition.asset.symbol}:`,
92789
+ error2
92790
+ );
92737
92791
  throw error2;
92738
92792
  }
92739
92793
  }
92740
92794
  async maxBorrowableAPY() {
92741
- const collateralAPY = await this.getAPY({ asset: this.config.collateral, isDebt: false });
92795
+ const collateralAPY = await this.getAPY({
92796
+ asset: this.config.collateral,
92797
+ isDebt: false
92798
+ });
92742
92799
  const apy = collateralAPY.apy * 0.8;
92743
92800
  return apy;
92744
92801
  }
@@ -92748,9 +92805,15 @@ spurious results.`);
92748
92805
  try {
92749
92806
  this.vesuAdapter.networkConfig = this.config.networkConfig;
92750
92807
  this.vesuAdapter.pricer = this.config.pricer;
92751
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
92752
- const collateralPosition = positions.find((p) => p.token.address.eq(collateral.address));
92753
- const debtPosition = positions.find((p) => p.token.address.eq(debt.address));
92808
+ const positions = await this.vesuAdapter.getPositions(
92809
+ this.config.networkConfig
92810
+ );
92811
+ const collateralPosition = positions.find(
92812
+ (p) => p.token.address.eq(collateral.address)
92813
+ );
92814
+ const debtPosition = positions.find(
92815
+ (p) => p.token.address.eq(debt.address)
92816
+ );
92754
92817
  if (!collateralPosition || !debtPosition) {
92755
92818
  throw new Error("Could not find current positions");
92756
92819
  }
@@ -92760,13 +92823,23 @@ spurious results.`);
92760
92823
  debt,
92761
92824
  maxBorrowableAPY
92762
92825
  );
92763
- logger2.verbose(`VesuMultiplyAdapter: Max borrowable: ${maxBorrowable.toNumber()}`);
92764
- const debtCap = await this.vesuAdapter.getDebtCap(this.config.networkConfig);
92826
+ logger2.verbose(
92827
+ `VesuMultiplyAdapter: Max borrowable: ${maxBorrowable.toNumber()}`
92828
+ );
92829
+ const debtCap = await this.vesuAdapter.getDebtCap(
92830
+ this.config.networkConfig
92831
+ );
92765
92832
  logger2.verbose(`VesuMultiplyAdapter: Debt cap: ${debtCap.toNumber()}`);
92766
92833
  const actualMaxBorrowable = maxBorrowable.minimum(debtCap);
92767
- logger2.verbose(`VesuMultiplyAdapter: Actual max borrowable: ${actualMaxBorrowable.toNumber()}`);
92768
- const maxLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
92769
- const collateralPrice = await this.config.pricer.getPrice(collateral.symbol);
92834
+ logger2.verbose(
92835
+ `VesuMultiplyAdapter: Actual max borrowable: ${actualMaxBorrowable.toNumber()}`
92836
+ );
92837
+ const maxLTV = await this.vesuAdapter.getLTVConfig(
92838
+ this.config.networkConfig
92839
+ );
92840
+ const collateralPrice = await this.config.pricer.getPrice(
92841
+ collateral.symbol
92842
+ );
92770
92843
  if (collateralPrice.price === 0) {
92771
92844
  throw new Error("Collateral price is 0");
92772
92845
  }
@@ -92784,14 +92857,25 @@ spurious results.`);
92784
92857
  );
92785
92858
  const maxDepositAmount = amount ? amount.minimum(maxCollateralFromDebt) : maxCollateralFromDebt;
92786
92859
  const usdValue = await this.getUSDValue(collateral, maxDepositAmount);
92787
- logger2.verbose(`VesuMultiplyAdapter: Max deposit::USD value: ${usdValue}, amount: ${maxDepositAmount.toNumber()}`);
92788
- const apys = await Promise.all([this.getAPY({ asset: collateral, isDebt: false }), this.getAPY({ asset: debt, isDebt: true })]);
92789
- logger2.verbose(`VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`);
92860
+ logger2.verbose(
92861
+ `VesuMultiplyAdapter: Max deposit::USD value: ${usdValue}, amount: ${maxDepositAmount.toNumber()}`
92862
+ );
92863
+ const apys = await Promise.all([
92864
+ this.getAPY({ asset: collateral, isDebt: false }),
92865
+ this.getAPY({ asset: debt, isDebt: true })
92866
+ ]);
92867
+ logger2.verbose(
92868
+ `VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`
92869
+ );
92790
92870
  const borrowAmountUSD = actualMaxBorrowable.multipliedBy(debtPrice.price);
92791
- logger2.verbose(`VesuMultiplyAdapter: Borrow amount: ${actualMaxBorrowable.toNumber()}, borrow amount USD: ${borrowAmountUSD.toNumber()}`);
92871
+ logger2.verbose(
92872
+ `VesuMultiplyAdapter: Borrow amount: ${actualMaxBorrowable.toNumber()}, borrow amount USD: ${borrowAmountUSD.toNumber()}`
92873
+ );
92792
92874
  const netCollateralUSD = usdValue + borrowAmountUSD.toNumber();
92793
92875
  const netAPY = (apys[0].apy * netCollateralUSD + apys[1].apy * borrowAmountUSD.toNumber()) / usdValue;
92794
- logger2.verbose(`VesuMultiplyAdapter: Max deposit amount: ${maxDepositAmount.toNumber()}, netAPY: ${netAPY}`);
92876
+ logger2.verbose(
92877
+ `VesuMultiplyAdapter: Max deposit amount: ${maxDepositAmount.toNumber()}, netAPY: ${netAPY}`
92878
+ );
92795
92879
  return {
92796
92880
  tokenInfo: collateral,
92797
92881
  amount: maxDepositAmount,
@@ -92804,7 +92888,10 @@ spurious results.`);
92804
92888
  protocol: this.protocol
92805
92889
  };
92806
92890
  } catch (error2) {
92807
- logger2.error(`VesuMultiplyAdapter: Error calculating max deposit:`, error2);
92891
+ logger2.error(
92892
+ `VesuMultiplyAdapter: Error calculating max deposit:`,
92893
+ error2
92894
+ );
92808
92895
  throw error2;
92809
92896
  }
92810
92897
  }
@@ -92814,9 +92901,15 @@ spurious results.`);
92814
92901
  try {
92815
92902
  this.vesuAdapter.networkConfig = this.config.networkConfig;
92816
92903
  this.vesuAdapter.pricer = this.config.pricer;
92817
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
92818
- const collateralPosition = positions.find((p) => p.token.address.eq(collateral.address));
92819
- const debtPosition = positions.find((p) => p.token.address.eq(this.config.debt.address));
92904
+ const positions = await this.vesuAdapter.getPositions(
92905
+ this.config.networkConfig
92906
+ );
92907
+ const collateralPosition = positions.find(
92908
+ (p) => p.token.address.eq(collateral.address)
92909
+ );
92910
+ const debtPosition = positions.find(
92911
+ (p) => p.token.address.eq(this.config.debt.address)
92912
+ );
92820
92913
  if (!collateralPosition || !debtPosition) {
92821
92914
  throw new Error("Could not find current positions");
92822
92915
  }
@@ -92826,11 +92919,20 @@ spurious results.`);
92826
92919
  const result2 = maxWithdrawable.greaterThan(0) ? maxWithdrawable : new Web3Number("0", collateral.decimals);
92827
92920
  const usdValue = await this.getUSDValue(collateral, result2);
92828
92921
  const debtUSD = debtPosition.usdValue;
92829
- logger2.verbose(`VesuMultiplyAdapter: Debt USD: ${debtUSD}, collateral USD: ${usdValue}`);
92830
- const apys = await Promise.all([this.getAPY({ asset: collateral, isDebt: false }), this.getAPY({ asset: debt, isDebt: true })]);
92831
- logger2.verbose(`VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`);
92922
+ logger2.verbose(
92923
+ `VesuMultiplyAdapter: Debt USD: ${debtUSD}, collateral USD: ${usdValue}`
92924
+ );
92925
+ const apys = await Promise.all([
92926
+ this.getAPY({ asset: collateral, isDebt: false }),
92927
+ this.getAPY({ asset: debt, isDebt: true })
92928
+ ]);
92929
+ logger2.verbose(
92930
+ `VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`
92931
+ );
92832
92932
  const netAPY = usdValue - debtUSD > 0 ? (apys[0].apy * usdValue + apys[1].apy * debtUSD) / (usdValue - debtUSD) : 0;
92833
- logger2.verbose(`VesuMultiplyAdapter: Max withdraw amount: ${result2.toNumber()}, netAPY: ${netAPY}`);
92933
+ logger2.verbose(
92934
+ `VesuMultiplyAdapter: Max withdraw amount: ${result2.toNumber()}, netAPY: ${netAPY}`
92935
+ );
92834
92936
  return {
92835
92937
  tokenInfo: collateral,
92836
92938
  amount: result2,
@@ -92843,14 +92945,19 @@ spurious results.`);
92843
92945
  protocol: this.protocol
92844
92946
  };
92845
92947
  } catch (error2) {
92846
- logger2.error(`VesuMultiplyAdapter: Error calculating max withdraw:`, error2);
92948
+ logger2.error(
92949
+ `VesuMultiplyAdapter: Error calculating max withdraw:`,
92950
+ error2
92951
+ );
92847
92952
  throw error2;
92848
92953
  }
92849
92954
  }
92850
92955
  _getDepositLeaf() {
92851
92956
  const collateral = this.config.collateral;
92852
92957
  const debt = this.config.debt;
92853
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
92958
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
92959
+ this.config.poolId
92960
+ );
92854
92961
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
92855
92962
  return [
92856
92963
  // Approval step for collateral
@@ -92914,7 +93021,9 @@ spurious results.`);
92914
93021
  ];
92915
93022
  }
92916
93023
  _getWithdrawLeaf() {
92917
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
93024
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
93025
+ this.config.poolId
93026
+ );
92918
93027
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
92919
93028
  const collateral = this.config.collateral;
92920
93029
  const debt = this.config.debt;
@@ -92971,33 +93080,51 @@ spurious results.`);
92971
93080
  const leafConfigs = this._getDepositLeaf();
92972
93081
  const leaves = leafConfigs.map((config3) => {
92973
93082
  const { target, method, packedArguments, sanitizer, id } = config3;
92974
- const leaf = this.constructSimpleLeafData({
92975
- id,
92976
- target,
92977
- method,
92978
- packedArguments
92979
- }, sanitizer);
93083
+ const leaf = this.constructSimpleLeafData(
93084
+ {
93085
+ id,
93086
+ target,
93087
+ method,
93088
+ packedArguments
93089
+ },
93090
+ sanitizer
93091
+ );
92980
93092
  return leaf;
92981
93093
  });
92982
- return { leaves, callConstructor: this.getDepositCall.bind(this) };
93094
+ return {
93095
+ leaves,
93096
+ callConstructor: this.getDepositCall.bind(
93097
+ this
93098
+ )
93099
+ };
92983
93100
  }
92984
93101
  getWithdrawAdapter() {
92985
93102
  const leafConfigs = this._getWithdrawLeaf();
92986
93103
  const leaves = leafConfigs.map((config3) => {
92987
93104
  const { target, method, packedArguments, sanitizer, id } = config3;
92988
- const leaf = this.constructSimpleLeafData({
92989
- id,
92990
- target,
92991
- method,
92992
- packedArguments
92993
- }, sanitizer);
93105
+ const leaf = this.constructSimpleLeafData(
93106
+ {
93107
+ id,
93108
+ target,
93109
+ method,
93110
+ packedArguments
93111
+ },
93112
+ sanitizer
93113
+ );
92994
93114
  return leaf;
92995
93115
  });
92996
- return { leaves, callConstructor: this.getWithdrawCall.bind(this) };
93116
+ return {
93117
+ leaves,
93118
+ callConstructor: this.getWithdrawCall.bind(
93119
+ this
93120
+ )
93121
+ };
92997
93122
  }
92998
93123
  async getDepositCall(params) {
92999
93124
  const collateral = this.config.collateral;
93000
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
93125
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
93126
+ this.config.poolId
93127
+ );
93001
93128
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
93002
93129
  const uint256MarginAmount = uint256_exports.bnToUint256(params.amount.toWei());
93003
93130
  return [
@@ -93069,7 +93196,9 @@ spurious results.`);
93069
93196
  ];
93070
93197
  }
93071
93198
  async getWithdrawCall(params) {
93072
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
93199
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
93200
+ this.config.poolId
93201
+ );
93073
93202
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
93074
93203
  return [
93075
93204
  // Switch delegation on
@@ -93124,7 +93253,11 @@ spurious results.`);
93124
93253
  ];
93125
93254
  }
93126
93255
  async getMultiplyCallCalldata(params, isDeposit) {
93127
- logger2.verbose(`${_VesuMultiplyAdapter.name}::getMultiplyCallCalldata params: ${JSON.stringify(params)}, isDeposit: ${isDeposit}, collateral: ${this.config.collateral.symbol}, debt: ${this.config.debt.symbol}`);
93256
+ logger2.verbose(
93257
+ `${_VesuMultiplyAdapter.name}::getMultiplyCallCalldata params: ${JSON.stringify(
93258
+ params
93259
+ )}, isDeposit: ${isDeposit}, collateral: ${this.config.collateral.symbol}, debt: ${this.config.debt.symbol}`
93260
+ );
93128
93261
  const { isV2 } = getVesuSingletonAddress(this.config.poolId);
93129
93262
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
93130
93263
  const multiplyContract = new Contract({
@@ -93134,42 +93267,83 @@ spurious results.`);
93134
93267
  });
93135
93268
  let leverSwap = [];
93136
93269
  let leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
93137
- const existingPositions = await this.vesuAdapter.getPositions(this.config.networkConfig);
93138
- const collateralisation = await this.vesuAdapter.getCollateralization(this.config.networkConfig);
93270
+ const existingPositions = await this.vesuAdapter.getPositions(
93271
+ this.config.networkConfig
93272
+ );
93273
+ const collateralisation = await this.vesuAdapter.getCollateralization(
93274
+ this.config.networkConfig
93275
+ );
93139
93276
  const existingCollateralInfo = existingPositions[0];
93140
93277
  const existingDebtInfo = existingPositions[1];
93141
93278
  const isDexPriceRequired = existingDebtInfo.token.symbol !== "USDC";
93142
- logger2.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall existingCollateralInfo: ${JSON.stringify(existingCollateralInfo)},
93143
- existingDebtInfo: ${JSON.stringify(existingDebtInfo)}, collateralisation: ${JSON.stringify(collateralisation)}`);
93279
+ logger2.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall existingCollateralInfo: ${JSON.stringify(
93280
+ existingCollateralInfo
93281
+ )},
93282
+ existingDebtInfo: ${JSON.stringify(
93283
+ existingDebtInfo
93284
+ )}, collateralisation: ${JSON.stringify(collateralisation)}`);
93144
93285
  const collateralPrice = collateralisation[0].usdValue > 0 ? collateralisation[0].usdValue / existingCollateralInfo.amount.toNumber() : (await this.config.pricer.getPrice(this.config.collateral.symbol)).price;
93145
93286
  const debtPrice = collateralisation[1].usdValue > 0 ? collateralisation[1].usdValue / existingDebtInfo.amount.toNumber() : (await this.config.pricer.getPrice(this.config.debt.symbol)).price;
93146
- logger2.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`);
93147
- const legLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
93148
- const ekuboQuoter = new EkuboQuoter(this.config.networkConfig, this.config.pricer);
93149
- const dexPrice = isDexPriceRequired ? await ekuboQuoter.getDexPrice(this.config.collateral, this.config.debt, this.config.quoteAmountToFetchPrice) : 1;
93150
- logger2.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall dexPrice: ${dexPrice}, ltv: ${legLTV}`);
93287
+ logger2.debug(
93288
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`
93289
+ );
93290
+ const legLTV = await this.vesuAdapter.getLTVConfig(
93291
+ this.config.networkConfig
93292
+ );
93293
+ const ekuboQuoter = new EkuboQuoter(
93294
+ this.config.networkConfig,
93295
+ this.config.pricer
93296
+ );
93297
+ const dexPrice = isDexPriceRequired ? await ekuboQuoter.getDexPrice(
93298
+ this.config.collateral,
93299
+ this.config.debt,
93300
+ this.config.quoteAmountToFetchPrice
93301
+ ) : 1;
93302
+ logger2.verbose(
93303
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall dexPrice: ${dexPrice}, ltv: ${legLTV}`
93304
+ );
93151
93305
  const addedCollateral = params.amount.multipliedBy(isDeposit ? 1 : -1);
93152
- logger2.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall addedCollateral: ${addedCollateral}`);
93306
+ logger2.verbose(
93307
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall addedCollateral: ${addedCollateral}`
93308
+ );
93153
93309
  const numeratorPart1 = existingCollateralInfo.amount.plus(addedCollateral).multipliedBy(collateralPrice).multipliedBy(legLTV);
93154
- logger2.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}`);
93310
+ logger2.verbose(
93311
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}`
93312
+ );
93155
93313
  const numeratorPart2 = existingDebtInfo.amount.multipliedBy(debtPrice).multipliedBy(this.config.targetHealthFactor);
93156
- logger2.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart2: ${numeratorPart2}`);
93314
+ logger2.verbose(
93315
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart2: ${numeratorPart2}`
93316
+ );
93157
93317
  const denominatorPart = this.config.targetHealthFactor - legLTV / dexPrice;
93158
- logger2.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall denominatorPart: ${denominatorPart}`);
93318
+ logger2.verbose(
93319
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall denominatorPart: ${denominatorPart}`
93320
+ );
93159
93321
  const x_debt_usd = numeratorPart1.minus(numeratorPart2).dividedBy(denominatorPart);
93160
- logger2.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall x_debt_usd: ${x_debt_usd}`);
93161
- logger2.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}, numeratorPart2: ${numeratorPart2}, denominatorPart: ${denominatorPart}`);
93162
- let debtAmount = new Web3Number(x_debt_usd.dividedBy(debtPrice).toFixed(this.config.debt.decimals), this.config.debt.decimals);
93322
+ logger2.verbose(
93323
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall x_debt_usd: ${x_debt_usd}`
93324
+ );
93325
+ logger2.debug(
93326
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}, numeratorPart2: ${numeratorPart2}, denominatorPart: ${denominatorPart}`
93327
+ );
93328
+ let debtAmount = new Web3Number(
93329
+ x_debt_usd.dividedBy(debtPrice).toFixed(this.config.debt.decimals),
93330
+ this.config.debt.decimals
93331
+ );
93163
93332
  const marginAmount = addedCollateral;
93164
93333
  const collateralToken = this.config.collateral;
93165
93334
  const debtToken = this.config.debt;
93166
- const debtAmountInCollateralUnits = new Web3Number(debtAmount.multipliedBy(debtPrice).dividedBy(collateralPrice).multipliedBy(10 ** collateralToken.decimals).toFixed(0), collateralToken.decimals);
93335
+ const debtAmountInCollateralUnits = new Web3Number(
93336
+ debtAmount.multipliedBy(debtPrice).dividedBy(collateralPrice).multipliedBy(10 ** collateralToken.decimals).toFixed(0),
93337
+ collateralToken.decimals
93338
+ );
93167
93339
  const isIncrease = debtAmount.greaterThanOrEqualTo(0);
93168
93340
  if (isIncrease && debtAmount.lessThan(0)) {
93169
93341
  } else if (!isIncrease && debtAmount.greaterThan(0)) {
93170
93342
  debtAmount = Web3Number.fromWei(0, this.config.debt.decimals);
93171
93343
  }
93172
- logger2.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall debtAmount: ${debtAmount}, marginAmount: ${marginAmount}`);
93344
+ logger2.verbose(
93345
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall debtAmount: ${debtAmount}, marginAmount: ${marginAmount}`
93346
+ );
93173
93347
  if (!debtAmount.isZero()) {
93174
93348
  try {
93175
93349
  const swapQuote = await ekuboQuoter.getQuote(
@@ -93179,26 +93353,49 @@ spurious results.`);
93179
93353
  // negative for exact amount out
93180
93354
  );
93181
93355
  if (swapQuote.price_impact < 0.01) {
93182
- leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, debtToken, collateralToken);
93356
+ leverSwap = debtAmount.isNegative() ? ekuboQuoter.getVesuMultiplyQuote(
93357
+ swapQuote,
93358
+ collateralToken,
93359
+ debtToken
93360
+ ) : ekuboQuoter.getVesuMultiplyQuote(
93361
+ swapQuote,
93362
+ debtToken,
93363
+ collateralToken
93364
+ );
93183
93365
  const MAX_SLIPPAGE = 2e-3;
93184
93366
  if (debtAmount.greaterThan(0)) {
93185
93367
  leverSwapLimitAmount = debtAmount.multipliedBy(1 + MAX_SLIPPAGE);
93186
93368
  } else if (debtAmount.lessThan(0)) {
93187
93369
  leverSwapLimitAmount = debtAmount.abs().multipliedBy(1 - MAX_SLIPPAGE);
93188
93370
  } else {
93189
- leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
93371
+ leverSwapLimitAmount = Web3Number.fromWei(
93372
+ 0,
93373
+ this.config.debt.decimals
93374
+ );
93190
93375
  }
93191
93376
  await new Promise((resolve) => setTimeout(resolve, 1e4));
93192
93377
  } else {
93193
- throw new Error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
93378
+ throw new Error(
93379
+ `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`
93380
+ );
93194
93381
  }
93195
93382
  } catch (error2) {
93196
- throw new Error(`VesuMultiplyAdapter: Failed to get swap quote: ${error2}`);
93383
+ throw new Error(
93384
+ `VesuMultiplyAdapter: Failed to get swap quote: ${error2}`
93385
+ );
93197
93386
  }
93198
93387
  }
93199
- const multiplyParams = await this.getLeverParams(isIncrease, params, leverSwap, leverSwapLimitAmount);
93388
+ const multiplyParams = await this.getLeverParams(
93389
+ isIncrease,
93390
+ params,
93391
+ leverSwap,
93392
+ leverSwapLimitAmount
93393
+ );
93200
93394
  const call = multiplyContract.populate("modify_lever", {
93201
- modify_lever_params: this.formatMultiplyParams(isIncrease, multiplyParams)
93395
+ modify_lever_params: this.formatMultiplyParams(
93396
+ isIncrease,
93397
+ multiplyParams
93398
+ )
93202
93399
  });
93203
93400
  return call.calldata;
93204
93401
  }
@@ -93212,7 +93409,10 @@ spurious results.`);
93212
93409
  add_margin: params.amount,
93213
93410
  // multiplied by collateral decimals in format
93214
93411
  margin_swap: [],
93215
- margin_swap_limit_amount: Web3Number.fromWei(0, this.config.collateral.decimals),
93412
+ margin_swap_limit_amount: Web3Number.fromWei(
93413
+ 0,
93414
+ this.config.collateral.decimals
93415
+ ),
93216
93416
  lever_swap: leverSwap,
93217
93417
  lever_swap_limit_amount: leverSwapLimitAmount
93218
93418
  } : {
@@ -93226,7 +93426,10 @@ spurious results.`);
93226
93426
  lever_swap_limit_amount: leverSwapLimitAmount,
93227
93427
  lever_swap_weights: [],
93228
93428
  withdraw_swap: [],
93229
- withdraw_swap_limit_amount: Web3Number.fromWei(0, this.config.collateral.decimals),
93429
+ withdraw_swap_limit_amount: Web3Number.fromWei(
93430
+ 0,
93431
+ this.config.collateral.decimals
93432
+ ),
93230
93433
  withdraw_swap_weights: [],
93231
93434
  close_position: false
93232
93435
  };
@@ -93242,12 +93445,16 @@ spurious results.`);
93242
93445
  });
93243
93446
  let leverSwap = [];
93244
93447
  let leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
93245
- const existingPositions = await this.vesuAdapter.getPositions(this.config.networkConfig);
93448
+ const existingPositions = await this.vesuAdapter.getPositions(
93449
+ this.config.networkConfig
93450
+ );
93246
93451
  const existingCollateralInfo = existingPositions[0];
93247
93452
  const existingDebtInfo = existingPositions[1];
93248
93453
  const collateralToken = this.config.collateral;
93249
93454
  const debtToken = this.config.debt;
93250
- const collateralPrice = await this.config.pricer.getPrice(collateralToken.symbol);
93455
+ const collateralPrice = await this.config.pricer.getPrice(
93456
+ collateralToken.symbol
93457
+ );
93251
93458
  const debtPrice = await this.config.pricer.getPrice(debtToken.symbol);
93252
93459
  const { deltadebtAmountUnits: debtAmountToRepay } = calculateDebtReductionAmountForWithdrawal(
93253
93460
  existingDebtInfo.amount,
@@ -93261,8 +93468,14 @@ spurious results.`);
93261
93468
  if (!debtAmountToRepay) {
93262
93469
  throw new Error("error calculating debt amount to repay");
93263
93470
  }
93264
- const ekuboQuoter = new EkuboQuoter(this.config.networkConfig, this.config.pricer);
93265
- const debtInDebtUnits = new Web3Number(debtAmountToRepay, debtToken.decimals).dividedBy(debtPrice.price).multipliedBy(10 ** debtToken.decimals);
93471
+ const ekuboQuoter = new EkuboQuoter(
93472
+ this.config.networkConfig,
93473
+ this.config.pricer
93474
+ );
93475
+ const debtInDebtUnits = new Web3Number(
93476
+ debtAmountToRepay,
93477
+ debtToken.decimals
93478
+ ).dividedBy(debtPrice.price).multipliedBy(10 ** debtToken.decimals);
93266
93479
  const swapQuote = await ekuboQuoter.getQuote(
93267
93480
  debtToken.address.address,
93268
93481
  collateralToken.address.address,
@@ -93270,12 +93483,23 @@ spurious results.`);
93270
93483
  );
93271
93484
  const MAX_SLIPPAGE = 2e-3;
93272
93485
  if (swapQuote.price_impact < 25e-4) {
93273
- leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, collateralToken, debtToken);
93486
+ leverSwap = ekuboQuoter.getVesuMultiplyQuote(
93487
+ swapQuote,
93488
+ collateralToken,
93489
+ debtToken
93490
+ );
93274
93491
  } else {
93275
- logger2.error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
93492
+ logger2.error(
93493
+ `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`
93494
+ );
93276
93495
  }
93277
93496
  leverSwapLimitAmount = new Web3Number(debtAmountToRepay, debtToken.decimals).abs().multipliedBy(1 + MAX_SLIPPAGE);
93278
- const multiplyParams = await this.getLeverParams(false, params, leverSwap, leverSwapLimitAmount);
93497
+ const multiplyParams = await this.getLeverParams(
93498
+ false,
93499
+ params,
93500
+ leverSwap,
93501
+ leverSwapLimitAmount
93502
+ );
93279
93503
  const call = multiplyContract.populate("modify_lever", {
93280
93504
  modify_lever_params: this.formatMultiplyParams(false, multiplyParams)
93281
93505
  });
@@ -93285,100 +93509,132 @@ spurious results.`);
93285
93509
  if (isIncrease) {
93286
93510
  const _params2 = params;
93287
93511
  return {
93288
- action: new CairoCustomEnum({ IncreaseLever: {
93289
- pool_id: _params2.pool_id.toBigInt(),
93290
- collateral_asset: _params2.collateral_asset.toBigInt(),
93291
- debt_asset: _params2.debt_asset.toBigInt(),
93292
- user: _params2.user.toBigInt(),
93293
- add_margin: BigInt(_params2.add_margin.toWei()),
93294
- margin_swap: _params2.margin_swap.map((swap) => ({
93512
+ action: new CairoCustomEnum({
93513
+ IncreaseLever: {
93514
+ pool_id: _params2.pool_id.toBigInt(),
93515
+ collateral_asset: _params2.collateral_asset.toBigInt(),
93516
+ debt_asset: _params2.debt_asset.toBigInt(),
93517
+ user: _params2.user.toBigInt(),
93518
+ add_margin: BigInt(_params2.add_margin.toWei()),
93519
+ margin_swap: _params2.margin_swap.map((swap) => ({
93520
+ route: swap.route.map((route) => ({
93521
+ pool_key: {
93522
+ token0: route.pool_key.token0.toBigInt(),
93523
+ token1: route.pool_key.token1.toBigInt(),
93524
+ fee: route.pool_key.fee,
93525
+ tick_spacing: route.pool_key.tick_spacing,
93526
+ extension: BigInt(
93527
+ num_exports.hexToDecimalString(route.pool_key.extension)
93528
+ )
93529
+ },
93530
+ sqrt_ratio_limit: uint256_exports.bnToUint256(
93531
+ route.sqrt_ratio_limit.toWei()
93532
+ ),
93533
+ skip_ahead: BigInt(100)
93534
+ })),
93535
+ token_amount: {
93536
+ token: swap.token_amount.token.toBigInt(),
93537
+ amount: swap.token_amount.amount.toI129()
93538
+ }
93539
+ })),
93540
+ margin_swap_limit_amount: BigInt(
93541
+ _params2.margin_swap_limit_amount.toWei()
93542
+ ),
93543
+ lever_swap: _params2.lever_swap.map((swap) => ({
93544
+ route: swap.route.map((route) => ({
93545
+ pool_key: {
93546
+ token0: route.pool_key.token0.toBigInt(),
93547
+ token1: route.pool_key.token1.toBigInt(),
93548
+ fee: route.pool_key.fee,
93549
+ tick_spacing: route.pool_key.tick_spacing,
93550
+ extension: BigInt(
93551
+ num_exports.hexToDecimalString(route.pool_key.extension)
93552
+ )
93553
+ },
93554
+ sqrt_ratio_limit: uint256_exports.bnToUint256(
93555
+ route.sqrt_ratio_limit.toWei()
93556
+ ),
93557
+ skip_ahead: BigInt(0)
93558
+ })),
93559
+ token_amount: {
93560
+ token: swap.token_amount.token.toBigInt(),
93561
+ amount: swap.token_amount.amount.toI129()
93562
+ }
93563
+ })),
93564
+ lever_swap_limit_amount: BigInt(
93565
+ _params2.lever_swap_limit_amount.toWei()
93566
+ )
93567
+ }
93568
+ })
93569
+ };
93570
+ }
93571
+ const _params = params;
93572
+ return {
93573
+ action: new CairoCustomEnum({
93574
+ DecreaseLever: {
93575
+ pool_id: _params.pool_id.toBigInt(),
93576
+ collateral_asset: _params.collateral_asset.toBigInt(),
93577
+ debt_asset: _params.debt_asset.toBigInt(),
93578
+ user: _params.user.toBigInt(),
93579
+ sub_margin: BigInt(_params.sub_margin.toWei()),
93580
+ recipient: _params.recipient.toBigInt(),
93581
+ lever_swap: _params.lever_swap.map((swap) => ({
93295
93582
  route: swap.route.map((route) => ({
93296
93583
  pool_key: {
93297
93584
  token0: route.pool_key.token0.toBigInt(),
93298
93585
  token1: route.pool_key.token1.toBigInt(),
93299
93586
  fee: route.pool_key.fee,
93300
93587
  tick_spacing: route.pool_key.tick_spacing,
93301
- extension: BigInt(num_exports.hexToDecimalString(route.pool_key.extension))
93588
+ extension: ContractAddr.from(
93589
+ route.pool_key.extension
93590
+ ).toBigInt()
93302
93591
  },
93303
- sqrt_ratio_limit: uint256_exports.bnToUint256(route.sqrt_ratio_limit.toWei()),
93304
- skip_ahead: BigInt(100)
93592
+ sqrt_ratio_limit: uint256_exports.bnToUint256(
93593
+ route.sqrt_ratio_limit.toWei()
93594
+ ),
93595
+ skip_ahead: BigInt(route.skip_ahead.toWei())
93305
93596
  })),
93306
93597
  token_amount: {
93307
93598
  token: swap.token_amount.token.toBigInt(),
93308
93599
  amount: swap.token_amount.amount.toI129()
93309
93600
  }
93310
93601
  })),
93311
- margin_swap_limit_amount: BigInt(_params2.margin_swap_limit_amount.toWei()),
93312
- lever_swap: _params2.lever_swap.map((swap) => ({
93602
+ lever_swap_limit_amount: BigInt(
93603
+ _params.lever_swap_limit_amount.toWei()
93604
+ ),
93605
+ lever_swap_weights: _params.lever_swap_weights.map(
93606
+ (weight) => BigInt(weight.toWei())
93607
+ ),
93608
+ withdraw_swap: _params.withdraw_swap.map((swap) => ({
93313
93609
  route: swap.route.map((route) => ({
93314
93610
  pool_key: {
93315
93611
  token0: route.pool_key.token0.toBigInt(),
93316
93612
  token1: route.pool_key.token1.toBigInt(),
93317
93613
  fee: route.pool_key.fee,
93318
93614
  tick_spacing: route.pool_key.tick_spacing,
93319
- extension: BigInt(num_exports.hexToDecimalString(route.pool_key.extension))
93615
+ extension: ContractAddr.from(
93616
+ route.pool_key.extension
93617
+ ).toBigInt()
93320
93618
  },
93321
- sqrt_ratio_limit: uint256_exports.bnToUint256(route.sqrt_ratio_limit.toWei()),
93322
- skip_ahead: BigInt(0)
93619
+ sqrt_ratio_limit: uint256_exports.bnToUint256(
93620
+ route.sqrt_ratio_limit.toWei()
93621
+ ),
93622
+ skip_ahead: BigInt(route.skip_ahead.toWei())
93323
93623
  })),
93324
93624
  token_amount: {
93325
93625
  token: swap.token_amount.token.toBigInt(),
93326
93626
  amount: swap.token_amount.amount.toI129()
93327
93627
  }
93328
93628
  })),
93329
- lever_swap_limit_amount: BigInt(_params2.lever_swap_limit_amount.toWei())
93330
- } })
93331
- };
93332
- }
93333
- const _params = params;
93334
- return {
93335
- action: new CairoCustomEnum({ DecreaseLever: {
93336
- pool_id: _params.pool_id.toBigInt(),
93337
- collateral_asset: _params.collateral_asset.toBigInt(),
93338
- debt_asset: _params.debt_asset.toBigInt(),
93339
- user: _params.user.toBigInt(),
93340
- sub_margin: BigInt(_params.sub_margin.toWei()),
93341
- recipient: _params.recipient.toBigInt(),
93342
- lever_swap: _params.lever_swap.map((swap) => ({
93343
- route: swap.route.map((route) => ({
93344
- pool_key: {
93345
- token0: route.pool_key.token0.toBigInt(),
93346
- token1: route.pool_key.token1.toBigInt(),
93347
- fee: route.pool_key.fee,
93348
- tick_spacing: route.pool_key.tick_spacing,
93349
- extension: ContractAddr.from(route.pool_key.extension).toBigInt()
93350
- },
93351
- sqrt_ratio_limit: uint256_exports.bnToUint256(route.sqrt_ratio_limit.toWei()),
93352
- skip_ahead: BigInt(route.skip_ahead.toWei())
93353
- })),
93354
- token_amount: {
93355
- token: swap.token_amount.token.toBigInt(),
93356
- amount: swap.token_amount.amount.toI129()
93357
- }
93358
- })),
93359
- lever_swap_limit_amount: BigInt(_params.lever_swap_limit_amount.toWei()),
93360
- lever_swap_weights: _params.lever_swap_weights.map((weight) => BigInt(weight.toWei())),
93361
- withdraw_swap: _params.withdraw_swap.map((swap) => ({
93362
- route: swap.route.map((route) => ({
93363
- pool_key: {
93364
- token0: route.pool_key.token0.toBigInt(),
93365
- token1: route.pool_key.token1.toBigInt(),
93366
- fee: route.pool_key.fee,
93367
- tick_spacing: route.pool_key.tick_spacing,
93368
- extension: ContractAddr.from(route.pool_key.extension).toBigInt()
93369
- },
93370
- sqrt_ratio_limit: uint256_exports.bnToUint256(route.sqrt_ratio_limit.toWei()),
93371
- skip_ahead: BigInt(route.skip_ahead.toWei())
93372
- })),
93373
- token_amount: {
93374
- token: swap.token_amount.token.toBigInt(),
93375
- amount: swap.token_amount.amount.toI129()
93376
- }
93377
- })),
93378
- withdraw_swap_limit_amount: BigInt(_params.withdraw_swap_limit_amount.toWei()),
93379
- withdraw_swap_weights: _params.withdraw_swap_weights.map((weight) => BigInt(weight.toWei())),
93380
- close_position: _params.close_position
93381
- } })
93629
+ withdraw_swap_limit_amount: BigInt(
93630
+ _params.withdraw_swap_limit_amount.toWei()
93631
+ ),
93632
+ withdraw_swap_weights: _params.withdraw_swap_weights.map(
93633
+ (weight) => BigInt(weight.toWei())
93634
+ ),
93635
+ close_position: _params.close_position
93636
+ }
93637
+ })
93382
93638
  };
93383
93639
  }
93384
93640
  async getHealthFactor() {
@@ -93387,11 +93643,15 @@ spurious results.`);
93387
93643
  }
93388
93644
  async getNetAPY() {
93389
93645
  const positions = await this.getPositions();
93390
- logger2.verbose(`${this.name}::getNetAPY: positions: ${JSON.stringify(positions)}`);
93646
+ logger2.verbose(
93647
+ `${this.name}::getNetAPY: positions: ${JSON.stringify(positions)}`
93648
+ );
93391
93649
  const allZero = positions.every((p) => p.usdValue === 0);
93392
93650
  if (allZero) {
93393
93651
  const collateralUSD = 1e3;
93394
- const maxLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
93652
+ const maxLTV = await this.vesuAdapter.getLTVConfig(
93653
+ this.config.networkConfig
93654
+ );
93395
93655
  const targetHF = this.config.targetHealthFactor;
93396
93656
  const maxDebt = HealthFactorMath.getMaxDebtAmountOnLooping(
93397
93657
  new Web3Number(collateralUSD, this.config.collateral.decimals),
@@ -93420,18 +93680,20 @@ spurious results.`);
93420
93680
  super(config3, _ExtendedAdapter.name, Protocols.EXTENDED);
93421
93681
  this.config = config3;
93422
93682
  const client = new wrapper_default({
93423
- baseUrl: this.config.extendedBackendUrl,
93424
- apiKey: this.config.extendedApiKey,
93683
+ baseUrl: this.config.extendedBackendWriteUrl,
93684
+ apiKey: "",
93425
93685
  timeout: this.config.extendedTimeout,
93426
93686
  retries: this.config.extendedRetries
93427
93687
  });
93688
+ this.minimumExtendedMovementAmount = this.config.minimumExtendedMovementAmount ?? 5;
93428
93689
  this.client = client;
93690
+ this.retryDelayForOrderStatus = this.config.retryDelayForOrderStatus ?? 3e3;
93429
93691
  }
93430
93692
  //abstract means the method has no implementation in this class; instead, child classes must implement it.
93431
93693
  async getAPY(supportedPosition) {
93432
93694
  const side = supportedPosition.isDebt ? "LONG" : "SHORT";
93433
- const fundingRates = await this.client.getFundingRates(this.config.extendedMarketName, side);
93434
- if (fundingRates.status !== "OK") {
93695
+ const fundingRates = await this.getFundingRates(side);
93696
+ if (!fundingRates.success) {
93435
93697
  logger2.error("error getting funding rates", fundingRates);
93436
93698
  return { apy: 0, type: "base" /* BASE */ };
93437
93699
  }
@@ -93439,10 +93701,26 @@ spurious results.`);
93439
93701
  const apy = Number(fundingRate.f) * 365 * 24;
93440
93702
  return { apy, type: "base" /* BASE */ };
93441
93703
  }
93442
- async getPosition(supportedPosition) {
93443
- if (!this.client) {
93444
- throw new Error("Client not initialized");
93704
+ async getFundingRates(side, startTime, endTime) {
93705
+ try {
93706
+ const response = await axios_default.get(`${this.config.extendedBackendReadUrl}/fundingRates/${this.config.extendedMarketName}/${side}`, {
93707
+ params: {
93708
+ startTime: startTime ? startTime.toString() : void 0,
93709
+ endTime: endTime ? endTime.toString() : void 0
93710
+ }
93711
+ });
93712
+ if (!response.data.success) {
93713
+ logger2.error("error getting funding rates", response.data);
93714
+ return { success: false, data: [] };
93715
+ }
93716
+ logger2.info("success getting funding rates", response.data.data);
93717
+ return { success: true, data: response.data.data };
93718
+ } catch (err2) {
93719
+ logger2.error("error getting funding rates", err2);
93720
+ return { success: false, data: [] };
93445
93721
  }
93722
+ }
93723
+ async getPosition(supportedPosition) {
93446
93724
  const holdings = await this.getExtendedDepositAmount();
93447
93725
  if (!holdings) {
93448
93726
  throw new Error("No position found");
@@ -93450,7 +93728,7 @@ spurious results.`);
93450
93728
  const amount = holdings.equity;
93451
93729
  return Promise.resolve({
93452
93730
  amount: new Web3Number(amount, 0),
93453
- remarks: `${holdings.availableForWithdrawal} ${holdings.equity}`
93731
+ remarks: `Extended Equity`
93454
93732
  });
93455
93733
  }
93456
93734
  async maxDeposit(amount) {
@@ -93474,14 +93752,14 @@ spurious results.`);
93474
93752
  });
93475
93753
  }
93476
93754
  _getDepositLeaf() {
93477
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
93755
+ const usdceToken = Global.getDefaultTokens().find(
93756
+ (token) => token.symbol === "USDCe"
93757
+ );
93478
93758
  return [
93479
93759
  {
93480
93760
  target: this.config.supportedPositions[0].asset.address,
93481
93761
  method: "approve",
93482
- packedArguments: [
93483
- AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()
93484
- ],
93762
+ packedArguments: [AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()],
93485
93763
  id: `extended_approve_${this.config.supportedPositions[0].asset.symbol}`,
93486
93764
  sanitizer: AVNU_LEGACY_SANITIZER
93487
93765
  },
@@ -93512,25 +93790,33 @@ spurious results.`);
93512
93790
  const leafConfigs = this._getSwapFromLegacyLeaf();
93513
93791
  const leaves = leafConfigs.map((config3) => {
93514
93792
  const { target, method, packedArguments, sanitizer, id } = config3;
93515
- const leaf = this.constructSimpleLeafData({
93516
- id,
93517
- target,
93518
- method,
93519
- packedArguments
93520
- }, sanitizer);
93793
+ const leaf = this.constructSimpleLeafData(
93794
+ {
93795
+ id,
93796
+ target,
93797
+ method,
93798
+ packedArguments
93799
+ },
93800
+ sanitizer
93801
+ );
93521
93802
  return leaf;
93522
93803
  });
93523
- return { leaves, callConstructor: this.getSwapFromLegacyCall.bind(this) };
93804
+ return {
93805
+ leaves,
93806
+ callConstructor: this.getSwapFromLegacyCall.bind(
93807
+ this
93808
+ )
93809
+ };
93524
93810
  }
93525
93811
  _getSwapFromLegacyLeaf() {
93526
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
93812
+ const usdceToken = Global.getDefaultTokens().find(
93813
+ (token) => token.symbol === "USDCe"
93814
+ );
93527
93815
  return [
93528
93816
  {
93529
93817
  target: usdceToken.address,
93530
93818
  method: "approve",
93531
- packedArguments: [
93532
- AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()
93533
- ],
93819
+ packedArguments: [AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()],
93534
93820
  id: `extendedswaplegacyapprove_${usdceToken.symbol}`,
93535
93821
  sanitizer: AVNU_LEGACY_SANITIZER
93536
93822
  },
@@ -93549,11 +93835,13 @@ spurious results.`);
93549
93835
  async getDepositCall(params) {
93550
93836
  try {
93551
93837
  const usdcToken = this.config.supportedPositions[0].asset;
93552
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
93553
- const salt = Math.floor(
93554
- Math.random() * 10 ** usdcToken.decimals
93838
+ const usdceToken = Global.getDefaultTokens().find(
93839
+ (token) => token.symbol === "USDCe"
93840
+ );
93841
+ const salt = Math.floor(Math.random() * 10 ** usdcToken.decimals);
93842
+ const amount = uint256_exports.bnToUint256(
93843
+ params.amount.multipliedBy(10).toWei()
93555
93844
  );
93556
- const amount = uint256_exports.bnToUint256(params.amount.multipliedBy(10).toWei());
93557
93845
  const quotes = await this.config.avnuAdapter.getQuotesAvnu(
93558
93846
  usdcToken.address.toString(),
93559
93847
  usdceToken.address.toString(),
@@ -93566,7 +93854,9 @@ spurious results.`);
93566
93854
  logger2.error("error getting quotes from avnu");
93567
93855
  return [];
93568
93856
  }
93569
- const getCalldata = await this.config.avnuAdapter.getSwapCallData(quotes);
93857
+ const getCalldata = await this.config.avnuAdapter.getSwapCallData(
93858
+ quotes
93859
+ );
93570
93860
  const swapCallData = getCalldata[0];
93571
93861
  return [
93572
93862
  {
@@ -93642,8 +93932,12 @@ spurious results.`);
93642
93932
  async getSwapFromLegacyCall(params) {
93643
93933
  try {
93644
93934
  const usdcToken = this.config.supportedPositions[0].asset;
93645
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
93646
- const amount = uint256_exports.bnToUint256(params.amount.multipliedBy(10).toWei());
93935
+ const usdceToken = Global.getDefaultTokens().find(
93936
+ (token) => token.symbol === "USDCe"
93937
+ );
93938
+ const amount = uint256_exports.bnToUint256(
93939
+ params.amount.multipliedBy(10).toWei()
93940
+ );
93647
93941
  const quotes = await this.config.avnuAdapter.getQuotesAvnu(
93648
93942
  usdceToken.address.toString(),
93649
93943
  usdcToken.address.toString(),
@@ -93656,7 +93950,9 @@ spurious results.`);
93656
93950
  logger2.error("error getting quotes from avnu");
93657
93951
  return [];
93658
93952
  }
93659
- const getCalldata = await this.config.avnuAdapter.getSwapCallData(quotes);
93953
+ const getCalldata = await this.config.avnuAdapter.getSwapCallData(
93954
+ quotes
93955
+ );
93660
93956
  const swapCallData = getCalldata[0];
93661
93957
  return [
93662
93958
  {
@@ -93702,38 +93998,131 @@ spurious results.`);
93702
93998
  async withdrawFromExtended(amount) {
93703
93999
  try {
93704
94000
  if (!this.client) {
93705
- throw new Error("Client not initialized");
94001
+ logger2.error("Client not initialized");
94002
+ return {
94003
+ status: false,
94004
+ receivedTxnHash: false
94005
+ };
94006
+ }
94007
+ if (amount.lessThanOrEqualTo(0)) {
94008
+ logger2.error(
94009
+ `Invalid withdrawal amount: ${amount.toNumber()}. Amount must be positive.`
94010
+ );
94011
+ return {
94012
+ status: false,
94013
+ receivedTxnHash: false
94014
+ };
94015
+ }
94016
+ if (amount.lessThanOrEqualTo(this.minimumExtendedMovementAmount)) {
94017
+ logger2.warn(
94018
+ `Withdrawal amount ${amount.toNumber()} is below minimum Extended movement amount ${this.minimumExtendedMovementAmount}. Skipping withdrawal.`
94019
+ );
94020
+ return {
94021
+ status: false,
94022
+ receivedTxnHash: false
94023
+ };
93706
94024
  }
93707
- const withdrawalRequest = await this.client.withdrawUSDC(amount.toFixed(2));
94025
+ const holdings = await this.getExtendedDepositAmount();
94026
+ if (!holdings) {
94027
+ logger2.error(
94028
+ "Cannot get holdings - unable to validate withdrawal amount"
94029
+ );
94030
+ return {
94031
+ status: false,
94032
+ receivedTxnHash: false
94033
+ };
94034
+ }
94035
+ const availableForWithdrawal = parseFloat(
94036
+ holdings.availableForWithdrawal
94037
+ );
94038
+ if (!Number.isFinite(availableForWithdrawal) || availableForWithdrawal < 0) {
94039
+ logger2.error(
94040
+ `Invalid availableForWithdrawal: ${holdings.availableForWithdrawal}. Expected a finite, non-negative number.`
94041
+ );
94042
+ return {
94043
+ status: false,
94044
+ receivedTxnHash: false
94045
+ };
94046
+ }
94047
+ const withdrawalAmount = amount.toNumber();
94048
+ if (withdrawalAmount > availableForWithdrawal) {
94049
+ logger2.error(
94050
+ `Withdrawal amount ${withdrawalAmount} exceeds available balance ${availableForWithdrawal}`
94051
+ );
94052
+ return {
94053
+ status: false,
94054
+ receivedTxnHash: false
94055
+ };
94056
+ }
94057
+ logger2.info(
94058
+ `Withdrawing ${withdrawalAmount} from Extended. Available balance: ${availableForWithdrawal}`
94059
+ );
94060
+ const withdrawalRequest = await this.client.withdrawUSDC(
94061
+ amount.toFixed(2)
94062
+ );
93708
94063
  if (withdrawalRequest.status === "OK") {
93709
- const withdrawalStatus = await this.getDepositOrWithdrawalStatus(withdrawalRequest.data, "WITHDRAWAL" /* WITHDRAWAL */);
93710
- return withdrawalStatus;
94064
+ const withdrawalStatus = await this.getDepositOrWithdrawalStatus(
94065
+ withdrawalRequest.data,
94066
+ "WITHDRAWAL" /* WITHDRAWAL */
94067
+ );
94068
+ return {
94069
+ status: true,
94070
+ receivedTxnHash: withdrawalStatus
94071
+ };
93711
94072
  }
93712
- return false;
94073
+ logger2.error(
94074
+ `Withdrawal request failed with status: ${withdrawalRequest.status}`
94075
+ );
94076
+ return {
94077
+ status: false,
94078
+ receivedTxnHash: false
94079
+ };
93713
94080
  } catch (error2) {
93714
94081
  logger2.error(`Error creating Withdraw Call: ${error2}`);
93715
- return false;
94082
+ return {
94083
+ status: false,
94084
+ receivedTxnHash: false
94085
+ };
93716
94086
  }
93717
94087
  }
93718
94088
  async getHealthFactor() {
93719
94089
  return Promise.resolve(1);
93720
94090
  }
93721
94091
  async getExtendedDepositAmount() {
93722
- if (this.client === null) {
93723
- logger2.error("error initializing client");
93724
- return void 0;
93725
- }
93726
- const result2 = await this.client.getHoldings();
93727
- if (!result2) {
93728
- logger2.error(`error getting holdings: ${result2}`);
93729
- return void 0;
93730
- }
93731
- const holdings = result2.data;
93732
- if (!holdings) {
93733
- logger2.error(`error getting holdings: ${holdings}`);
94092
+ try {
94093
+ const result2 = await axios_default.get(`${this.config.extendedBackendReadUrl}/holdings`);
94094
+ if (!result2.data) {
94095
+ logger2.error("error getting holdings - API returned null/undefined");
94096
+ return void 0;
94097
+ }
94098
+ if (!result2.data.success) {
94099
+ logger2.error(
94100
+ `error getting holdings - API returned status: ${result2.status}`
94101
+ );
94102
+ return void 0;
94103
+ }
94104
+ const holdings = result2.data.data;
94105
+ if (!holdings) {
94106
+ logger2.warn(
94107
+ "holdings data is null/undefined - treating as zero balance"
94108
+ );
94109
+ return {
94110
+ collateral_name: "",
94111
+ balance: "0",
94112
+ equity: "0",
94113
+ availableForTrade: "0",
94114
+ availableForWithdrawal: "0",
94115
+ unrealisedPnl: "0",
94116
+ initialMargin: "0",
94117
+ marginRatio: "0",
94118
+ updatedTime: Date.now()
94119
+ };
94120
+ }
94121
+ return holdings;
94122
+ } catch (error2) {
94123
+ logger2.error(`error getting holdings - exception: ${error2}`);
93734
94124
  return void 0;
93735
94125
  }
93736
- return holdings;
93737
94126
  }
93738
94127
  async setLeverage(leverage, marketName) {
93739
94128
  if (this.client === null) {
@@ -93750,46 +94139,52 @@ spurious results.`);
93750
94139
  return false;
93751
94140
  }
93752
94141
  async getAllOpenPositions() {
93753
- if (this.client === null) {
93754
- logger2.error("error initializing client");
93755
- return null;
93756
- }
93757
- const response = await this.client.getPositionsForMarket(
93758
- this.config.extendedMarketName
93759
- );
93760
- if (response.status === "OK") {
93761
- if (response.data.length === 0) {
93762
- return [];
93763
- } else {
93764
- return response.data;
94142
+ try {
94143
+ const response = await axios_default.get(`${this.config.extendedBackendReadUrl}/positions`);
94144
+ if (response.data.success) {
94145
+ if (response.data.data.length === 0) {
94146
+ return [];
94147
+ } else {
94148
+ return response.data.data;
94149
+ }
93765
94150
  }
94151
+ return null;
94152
+ } catch (err2) {
94153
+ logger2.error("error getting all open positions", err2);
94154
+ return null;
93766
94155
  }
93767
- return null;
93768
94156
  }
93769
94157
  async getOrderHistory(marketName) {
93770
- if (this.client === null) {
93771
- logger2.error("error initializing client");
94158
+ try {
94159
+ const result2 = await axios_default.get(`${this.config.extendedBackendReadUrl}/marketOrders/${marketName}`);
94160
+ if (!result2.data.success) {
94161
+ return null;
94162
+ }
94163
+ return result2.data.data;
94164
+ } catch (err2) {
94165
+ logger2.error("error getting order history", err2);
93772
94166
  return null;
93773
94167
  }
93774
- const result2 = await this.client.getOrderHistory(marketName);
93775
- return result2.data;
93776
94168
  }
93777
94169
  async getOrderStatus(orderId, marketName) {
93778
- if (this.client === null) {
93779
- logger2.error("error initializing client");
93780
- return null;
93781
- }
93782
- const orderhistory = await this.getOrderHistory(marketName);
93783
- if (!orderhistory || orderhistory.length === 0) {
93784
- logger2.error(`error getting order: ${orderId}`);
94170
+ try {
94171
+ if (this.client === null) {
94172
+ logger2.error("error initializing client");
94173
+ return null;
94174
+ }
94175
+ const orderhistory = await this.getOrderHistory(marketName);
94176
+ if (!orderhistory || orderhistory.length === 0) {
94177
+ return null;
94178
+ }
94179
+ const order = orderhistory.slice(0, 20).find((order2) => order2.id.toString() === orderId);
94180
+ if (order) {
94181
+ return order;
94182
+ }
93785
94183
  return null;
93786
- }
93787
- const order = orderhistory.slice(0, 3).find((order2) => order2.id.toString() === orderId);
93788
- if (!order) {
93789
- logger2.error(`error getting order: ${order}`);
94184
+ } catch (error2) {
94185
+ logger2.error(`error getting order status: ${error2}`);
93790
94186
  return null;
93791
94187
  }
93792
- return order;
93793
94188
  }
93794
94189
  async fetchOrderBookBTCUSDC() {
93795
94190
  try {
@@ -93840,14 +94235,40 @@ spurious results.`);
93840
94235
  logger2.error("error depositing or setting leverage");
93841
94236
  return null;
93842
94237
  }
93843
- const positions = await this.getAllOpenPositions();
93844
- if (positions === null) {
94238
+ const { ask, bid } = await this.fetchOrderBookBTCUSDC();
94239
+ if (!ask || !bid || ask.lessThanOrEqualTo(0) || bid.lessThanOrEqualTo(0)) {
94240
+ logger2.error(
94241
+ `Invalid orderbook prices: ask=${ask?.toNumber()}, bid=${bid?.toNumber()}`
94242
+ );
93845
94243
  return null;
93846
94244
  }
93847
- const { ask, bid } = await this.fetchOrderBookBTCUSDC();
93848
94245
  const spread3 = ask.minus(bid);
93849
- let price = ask.plus(bid).div(2);
93850
- side === "SELL" /* SELL */ ? price = price.minus(spread3.times(0.2 * attempt)) : price = price.plus(spread3.times(0.2 * attempt));
94246
+ const midPrice = ask.plus(bid).div(2);
94247
+ const MAX_PRICE_DEVIATION_MULTIPLIER = 0.5;
94248
+ const priceAdjustmentMultiplier = Math.min(
94249
+ 0.2 * attempt,
94250
+ MAX_PRICE_DEVIATION_MULTIPLIER
94251
+ );
94252
+ const priceAdjustment = spread3.times(priceAdjustmentMultiplier);
94253
+ let price = midPrice;
94254
+ if (side === "SELL" /* SELL */) {
94255
+ price = midPrice.minus(priceAdjustment);
94256
+ } else {
94257
+ price = midPrice.plus(priceAdjustment);
94258
+ }
94259
+ const maxDeviation = midPrice.times(0.5);
94260
+ if (price.minus(midPrice).abs().greaterThan(maxDeviation)) {
94261
+ logger2.error(
94262
+ `Price deviation too large on attempt ${attempt}: price=${price.toNumber()}, midPrice=${midPrice.toNumber()}, deviation=${price.minus(midPrice).abs().toNumber()}`
94263
+ );
94264
+ if (attempt >= maxAttempts) {
94265
+ return null;
94266
+ }
94267
+ price = side === "SELL" /* SELL */ ? midPrice.minus(maxDeviation) : midPrice.plus(maxDeviation);
94268
+ }
94269
+ logger2.info(
94270
+ `createOrder attempt ${attempt}/${maxAttempts}: side=${side}, midPrice=${midPrice.toNumber()}, adjustedPrice=${price.toNumber()}, adjustment=${priceAdjustmentMultiplier * 100}%`
94271
+ );
93851
94272
  const amount_in_token = (btcAmount * parseInt(leverage)).toFixed(
93852
94273
  this.config.extendedPrecision
93853
94274
  );
@@ -93858,14 +94279,57 @@ spurious results.`);
93858
94279
  price.toFixed(0),
93859
94280
  side
93860
94281
  );
93861
- if (!result2) {
94282
+ if (!result2 || !result2.position_id) {
94283
+ logger2.error("Failed to create order - no position_id returned");
93862
94284
  return null;
93863
94285
  }
93864
- await new Promise((resolve) => setTimeout(resolve, 5e3));
93865
- const openOrder = await this.getOrderStatus(result2.position_id, this.config.extendedMarketName);
93866
- if (!openOrder || openOrder.status !== "FILLED" /* FILLED */) {
94286
+ const positionId = result2.position_id;
94287
+ logger2.info(
94288
+ `Order created with position_id: ${positionId}. Waiting for API to update...`
94289
+ );
94290
+ let openOrder = await this.getOrderStatus(
94291
+ positionId,
94292
+ this.config.extendedMarketName
94293
+ );
94294
+ const maxStatusRetries = 3;
94295
+ const statusRetryDelay = 5e3;
94296
+ if (!openOrder) {
94297
+ logger2.warn(
94298
+ `Order ${positionId} not found in API yet. Retrying status fetch (max ${maxStatusRetries} times)...`
94299
+ );
94300
+ for (let statusRetry = 1; statusRetry <= maxStatusRetries; statusRetry++) {
94301
+ await new Promise((resolve) => setTimeout(resolve, statusRetryDelay));
94302
+ openOrder = await this.getOrderStatus(
94303
+ positionId,
94304
+ this.config.extendedMarketName
94305
+ );
94306
+ if (openOrder) {
94307
+ logger2.info(
94308
+ `Order ${positionId} found after ${statusRetry} status retry(ies)`
94309
+ );
94310
+ break;
94311
+ }
94312
+ logger2.warn(
94313
+ `Order ${positionId} still not found after ${statusRetry}/${maxStatusRetries} status retries`
94314
+ );
94315
+ }
94316
+ }
94317
+ if (openOrder && openOrder.status === "FILLED" /* FILLED */) {
94318
+ logger2.info(
94319
+ `Order ${positionId} successfully filled with quantity ${openOrder.qty}`
94320
+ );
94321
+ return {
94322
+ position_id: positionId,
94323
+ btc_exposure: openOrder.qty
94324
+ };
94325
+ } else if (openOrder && openOrder.status !== "FILLED" /* FILLED */) {
94326
+ logger2.warn(
94327
+ `Order ${positionId} found but status is ${openOrder.status}, not FILLED. Retrying order creation...`
94328
+ );
93867
94329
  if (attempt >= maxAttempts) {
93868
- logger2.error("Max retries reached \u2014 could not verify open position");
94330
+ logger2.error(
94331
+ `Max retries reached \u2014 order ${positionId} status is ${openOrder.status}, not FILLED`
94332
+ );
93869
94333
  return null;
93870
94334
  } else {
93871
94335
  const backoff = 2e3 * attempt;
@@ -93879,13 +94343,18 @@ spurious results.`);
93879
94343
  );
93880
94344
  }
93881
94345
  } else {
94346
+ logger2.warn(
94347
+ `Order ${positionId} not found in API after ${maxStatusRetries} status retries (API update delayed ~30s). We got position_id from creation, so order exists. Returning position_id - status will be checked in next loop iteration.`
94348
+ );
93882
94349
  return {
93883
- position_id: result2.position_id,
93884
- btc_exposure: openOrder.qty
94350
+ position_id: positionId,
94351
+ btc_exposure: amount_in_token
93885
94352
  };
93886
94353
  }
93887
94354
  } catch (err2) {
93888
- logger2.error(`createShortOrder failed on attempt ${attempt}: ${err2.message}`);
94355
+ logger2.error(
94356
+ `createShortOrder failed on attempt ${attempt}: ${err2.message}`
94357
+ );
93889
94358
  if (attempt < maxAttempts) {
93890
94359
  const backoff = 1200 * attempt;
93891
94360
  logger2.info(`Retrying after ${backoff}ms...`);
@@ -93924,28 +94393,101 @@ spurious results.`);
93924
94393
  }
93925
94394
  }
93926
94395
  async getDepositOrWithdrawalStatus(orderId, operationsType) {
93927
- try {
93928
- let transferHistory = await this.client.getAssetOperations({
93929
- operationsType: [operationsType],
93930
- operationsStatus: ["COMPLETED" /* COMPLETED */]
93931
- });
93932
- if (operationsType === "DEPOSIT" /* DEPOSIT */) {
93933
- const myTransferStatus = transferHistory.data.find((operation) => operation.transactionHash === orderId);
93934
- if (!myTransferStatus) {
93935
- return true;
94396
+ const maxAttempts = 15;
94397
+ const retryDelayMs = 3e4;
94398
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
94399
+ try {
94400
+ let transferHistory = await this.client.getAssetOperations({
94401
+ operationsType: [operationsType],
94402
+ operationsStatus: ["COMPLETED" /* COMPLETED */]
94403
+ });
94404
+ if (operationsType === "DEPOSIT" /* DEPOSIT */) {
94405
+ const myTransferStatus = transferHistory.data.find(
94406
+ (operation) => operation.transactionHash?.toLowerCase() === orderId.toString().toLowerCase()
94407
+ );
94408
+ if (!myTransferStatus) {
94409
+ if (attempt < maxAttempts) {
94410
+ logger2.info(
94411
+ `Deposit operation not found for transactionHash ${orderId}, retrying (attempt ${attempt}/${maxAttempts})...`
94412
+ );
94413
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
94414
+ continue;
94415
+ }
94416
+ logger2.warn(
94417
+ `Deposit operation not found for transactionHash ${orderId} after ${maxAttempts} attempts`
94418
+ );
94419
+ return false;
94420
+ }
94421
+ if (myTransferStatus.status === "COMPLETED" /* COMPLETED */) {
94422
+ logger2.info(
94423
+ `Deposit operation ${orderId} completed successfully`
94424
+ );
94425
+ return true;
94426
+ } else {
94427
+ if (attempt < maxAttempts) {
94428
+ logger2.info(
94429
+ `Deposit operation ${orderId} found but status is ${myTransferStatus.status}, not COMPLETED. Retrying (attempt ${attempt}/${maxAttempts})...`
94430
+ );
94431
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
94432
+ continue;
94433
+ }
94434
+ logger2.warn(
94435
+ `Deposit operation ${orderId} status is ${myTransferStatus.status} after ${maxAttempts} attempts, expected COMPLETED`
94436
+ );
94437
+ return false;
94438
+ }
94439
+ } else {
94440
+ const myTransferStatus = transferHistory.data.find(
94441
+ (operation) => operation.id === orderId.toString()
94442
+ );
94443
+ if (!myTransferStatus) {
94444
+ if (attempt < maxAttempts) {
94445
+ logger2.info(
94446
+ `Withdrawal status not found for orderId ${orderId} in completed operations, retrying (attempt ${attempt}/${maxAttempts})...`
94447
+ );
94448
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
94449
+ continue;
94450
+ }
94451
+ logger2.warn(
94452
+ `Withdrawal operation not found for orderId ${orderId} after ${maxAttempts} attempts`
94453
+ );
94454
+ return false;
94455
+ }
94456
+ if (myTransferStatus.status === "COMPLETED" /* COMPLETED */) {
94457
+ logger2.info(
94458
+ `Withdrawal operation ${orderId} completed successfully`
94459
+ );
94460
+ return true;
94461
+ } else {
94462
+ if (attempt < maxAttempts) {
94463
+ logger2.info(
94464
+ `Withdrawal operation ${orderId} found but status is ${myTransferStatus.status}, not COMPLETED. Retrying (attempt ${attempt}/${maxAttempts})...`
94465
+ );
94466
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
94467
+ continue;
94468
+ }
94469
+ logger2.warn(
94470
+ `Withdrawal operation ${orderId} status is ${myTransferStatus.status} after ${maxAttempts} attempts, expected COMPLETED`
94471
+ );
94472
+ return false;
94473
+ }
93936
94474
  }
93937
- return true;
93938
- } else {
93939
- const myTransferStatus = transferHistory.data.find((operation) => operation.id.toString() === orderId.toString());
93940
- if (!myTransferStatus) {
93941
- return true;
94475
+ } catch (err2) {
94476
+ logger2.error(
94477
+ `error getting deposit or withdrawal status (attempt ${attempt}/${maxAttempts}): ${err2}`
94478
+ );
94479
+ if (attempt < maxAttempts) {
94480
+ logger2.info(`Retrying after ${retryDelayMs}ms...`);
94481
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
94482
+ continue;
93942
94483
  }
93943
- return true;
94484
+ logger2.error(
94485
+ `Max retry attempts reached for getDepositOrWithdrawalStatus`
94486
+ );
94487
+ return false;
93944
94488
  }
93945
- } catch (err2) {
93946
- logger2.error(`error getting deposit or withdrawal status: ${err2}`);
93947
- return false;
93948
94489
  }
94490
+ return false;
93949
94491
  }
93950
94492
  };
93951
94493
 
@@ -94025,12 +94567,349 @@ spurious results.`);
94025
94567
  }
94026
94568
  };
94027
94569
 
94570
+ // src/strategies/universal-adapters/avnu-adapter.ts
94571
+ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
94572
+ constructor(config3) {
94573
+ super(config3, _AvnuAdapter.name, Protocols.AVNU);
94574
+ this.config = config3;
94575
+ this.avnuWrapper = new AvnuWrapper();
94576
+ }
94577
+ //abstract means the method has no implementation in this class; instead, child classes must implement it.
94578
+ async getAPY(supportedPosition) {
94579
+ return Promise.resolve({ apy: 0, type: "base" /* BASE */ });
94580
+ }
94581
+ async getPosition(supportedPosition) {
94582
+ return Promise.resolve({ amount: new Web3Number(0, 0), remarks: "Avnu Positions" });
94583
+ }
94584
+ async maxDeposit(amount) {
94585
+ return Promise.resolve({
94586
+ tokenInfo: this.config.baseToken,
94587
+ amount: new Web3Number(0, 0),
94588
+ usdValue: 0,
94589
+ apy: { apy: 0, type: "base" /* BASE */ },
94590
+ protocol: Protocols.AVNU,
94591
+ remarks: ""
94592
+ });
94593
+ }
94594
+ async maxWithdraw() {
94595
+ return Promise.resolve({
94596
+ tokenInfo: this.config.baseToken,
94597
+ amount: new Web3Number(0, 0),
94598
+ usdValue: 0,
94599
+ apy: { apy: 0, type: "base" /* BASE */ },
94600
+ protocol: Protocols.AVNU,
94601
+ remarks: ""
94602
+ });
94603
+ }
94604
+ _getDepositLeaf() {
94605
+ const vaultAllocator = ContractAddr.from(
94606
+ this.config.vaultAllocator.address
94607
+ );
94608
+ return [
94609
+ {
94610
+ target: this.config.supportedPositions[0].asset.address,
94611
+ method: "approve",
94612
+ packedArguments: [
94613
+ AVNU_EXCHANGE.toBigInt()
94614
+ ],
94615
+ sanitizer: SIMPLE_SANITIZER,
94616
+ id: `approve_${this.config.supportedPositions[0].asset.symbol}`
94617
+ },
94618
+ {
94619
+ target: AVNU_EXCHANGE,
94620
+ method: "multi_route_swap",
94621
+ packedArguments: [
94622
+ this.config.supportedPositions[0].asset.address.toBigInt(),
94623
+ //usdc
94624
+ this.config.supportedPositions[1].asset.address.toBigInt(),
94625
+ //wbtc
94626
+ vaultAllocator.toBigInt()
94627
+ ],
94628
+ sanitizer: SIMPLE_SANITIZER,
94629
+ id: `asutb_${this.config.supportedPositions[0].asset.symbol}_${this.config.supportedPositions[1].asset.symbol}`
94630
+ }
94631
+ ];
94632
+ }
94633
+ _getWithdrawLeaf() {
94634
+ const vaultAllocator = ContractAddr.from(
94635
+ this.config.vaultAllocator.address
94636
+ );
94637
+ const toToken = this.config.supportedPositions[0].asset;
94638
+ const fromToken = this.config.supportedPositions[1].asset;
94639
+ return [
94640
+ {
94641
+ target: fromToken.address,
94642
+ method: "approve",
94643
+ packedArguments: [
94644
+ AVNU_EXCHANGE.toBigInt()
94645
+ ],
94646
+ sanitizer: SIMPLE_SANITIZER,
94647
+ id: `approve_${fromToken.symbol}`
94648
+ },
94649
+ {
94650
+ target: AVNU_EXCHANGE,
94651
+ method: "multi_route_swap",
94652
+ packedArguments: [
94653
+ fromToken.address.toBigInt(),
94654
+ //wbtc
94655
+ toToken.address.toBigInt(),
94656
+ //usdc
94657
+ vaultAllocator.toBigInt()
94658
+ ],
94659
+ sanitizer: SIMPLE_SANITIZER,
94660
+ id: `asbtu_${fromToken.symbol}_${fromToken.symbol}`
94661
+ }
94662
+ ];
94663
+ }
94664
+ _getLegacySwapLeaf() {
94665
+ return [];
94666
+ }
94667
+ async getDepositCall(params) {
94668
+ try {
94669
+ const fromToken = this.config.supportedPositions[0].asset;
94670
+ const toToken = this.config.supportedPositions[1].asset;
94671
+ const vaultAllocator = ContractAddr.from(
94672
+ this.config.vaultAllocator.address
94673
+ );
94674
+ const quote = await this.getQuotesAvnu(
94675
+ fromToken.address.toString(),
94676
+ toToken.address.toString(),
94677
+ params.amount.toNumber(),
94678
+ vaultAllocator.address.toString(),
94679
+ toToken.decimals,
94680
+ true
94681
+ );
94682
+ if (!quote) {
94683
+ logger2.error("error getting quote from avnu");
94684
+ return [];
94685
+ }
94686
+ const getCalldata = await this.avnuWrapper.getSwapCallData(
94687
+ quote,
94688
+ vaultAllocator.address
94689
+ );
94690
+ const swapCallData = getCalldata[0];
94691
+ const amount = uint256_exports.bnToUint256(quote.sellAmountInUsd * 10 ** 7);
94692
+ return [
94693
+ {
94694
+ sanitizer: SIMPLE_SANITIZER,
94695
+ call: {
94696
+ contractAddress: fromToken.address,
94697
+ selector: hash_exports.getSelectorFromName("approve"),
94698
+ calldata: [
94699
+ AVNU_EXCHANGE.toBigInt(),
94700
+ toBigInt3(amount.low.toString()),
94701
+ // amount low
94702
+ toBigInt3(amount.high.toString())
94703
+ // amount high
94704
+ ]
94705
+ }
94706
+ },
94707
+ {
94708
+ sanitizer: SIMPLE_SANITIZER,
94709
+ call: {
94710
+ contractAddress: AVNU_EXCHANGE,
94711
+ selector: hash_exports.getSelectorFromName("multi_route_swap"),
94712
+ calldata: swapCallData
94713
+ }
94714
+ }
94715
+ ];
94716
+ } catch (error2) {
94717
+ logger2.error(`Error getting Avnu quote: ${error2}`);
94718
+ return [];
94719
+ }
94720
+ }
94721
+ //Swap wbtc to usdc
94722
+ async getWithdrawCall(params) {
94723
+ try {
94724
+ const toToken = this.config.supportedPositions[0].asset;
94725
+ const fromToken = this.config.supportedPositions[1].asset;
94726
+ const vaultAllocator = ContractAddr.from(
94727
+ this.config.vaultAllocator.address
94728
+ );
94729
+ const quote = await this.getQuotesAvnu(
94730
+ fromToken.address.toString(),
94731
+ toToken.address.toString(),
94732
+ params.amount.toNumber(),
94733
+ vaultAllocator.address.toString(),
94734
+ fromToken.decimals,
94735
+ false
94736
+ );
94737
+ if (!quote) {
94738
+ logger2.error("No quotes available for this swap, error in quotes avnu");
94739
+ return [];
94740
+ }
94741
+ const getCalldata = await this.avnuWrapper.getSwapCallData(
94742
+ quote,
94743
+ vaultAllocator.address
94744
+ );
94745
+ const swapCallData = getCalldata[0];
94746
+ const amount = uint256_exports.bnToUint256(params.amount.toWei());
94747
+ return [
94748
+ {
94749
+ sanitizer: SIMPLE_SANITIZER,
94750
+ call: {
94751
+ contractAddress: fromToken.address,
94752
+ selector: hash_exports.getSelectorFromName("approve"),
94753
+ calldata: [
94754
+ AVNU_EXCHANGE.toBigInt(),
94755
+ toBigInt3(amount.low.toString()),
94756
+ // amount low
94757
+ toBigInt3(amount.high.toString())
94758
+ // amount high
94759
+ ]
94760
+ }
94761
+ },
94762
+ {
94763
+ sanitizer: SIMPLE_SANITIZER,
94764
+ call: {
94765
+ contractAddress: AVNU_EXCHANGE,
94766
+ selector: hash_exports.getSelectorFromName("multi_route_swap"),
94767
+ calldata: swapCallData
94768
+ }
94769
+ }
94770
+ ];
94771
+ } catch (error2) {
94772
+ logger2.error(`Error getting Avnu quote: ${error2}`);
94773
+ return [];
94774
+ }
94775
+ }
94776
+ async getSwapCallData(quote) {
94777
+ return await this.avnuWrapper.getSwapCallData(quote, this.config.vaultAllocator.address);
94778
+ }
94779
+ async getHealthFactor() {
94780
+ return Promise.resolve(1);
94781
+ }
94782
+ async fetchQuoteWithRetry(params, retries = 5) {
94783
+ for (let attempt = 0; attempt < retries; attempt++) {
94784
+ try {
94785
+ const response = await axios_default.get(this.config.baseUrl, { params });
94786
+ if (response.data && response.data.length > 0) {
94787
+ return response;
94788
+ }
94789
+ throw new Error("Empty response data");
94790
+ } catch (err2) {
94791
+ logger2.error(`Error fetching quote with retry: ${err2}`);
94792
+ if (attempt === retries - 1) {
94793
+ throw err2;
94794
+ }
94795
+ await new Promise((resolve) => setTimeout(resolve, MAX_DELAY));
94796
+ }
94797
+ }
94798
+ throw new Error("Failed to fetch quote after retries");
94799
+ }
94800
+ async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 5e3) {
94801
+ try {
94802
+ const fromToken = this.config.supportedPositions[0].asset;
94803
+ const toToken = this.config.supportedPositions[1].asset;
94804
+ if (!usdcToBtc) {
94805
+ const sellAmount2 = returnFormattedAmount(amount, toTokenDecimals);
94806
+ const params2 = {
94807
+ sellTokenAddress: from_token_address,
94808
+ buyTokenAddress: to_token_address,
94809
+ takerAddress,
94810
+ sellAmount: sellAmount2
94811
+ };
94812
+ const finalQuote2 = await this.fetchQuoteWithRetry(params2);
94813
+ if (!finalQuote2.data.length) {
94814
+ logger2.error("No quotes available for this swap, error in quotes avnu");
94815
+ return null;
94816
+ }
94817
+ const dataObject2 = finalQuote2.data[0];
94818
+ return dataObject2;
94819
+ }
94820
+ const btcPrice = await this.getPriceOfToken(toToken.address.toString());
94821
+ if (!btcPrice) {
94822
+ logger2.error(`error getting btc price: ${btcPrice}`);
94823
+ return null;
94824
+ }
94825
+ const estimatedUsdcAmount = Math.floor(amount * btcPrice);
94826
+ logger2.info(`${_AvnuAdapter.name}::getQuotesAvnu estimatedUsdcAmount: ${estimatedUsdcAmount}`);
94827
+ const targetBtcBig = BigInt(returnFormattedAmount(amount, toTokenDecimals));
94828
+ logger2.info(`${_AvnuAdapter.name}::getQuotesAvnu targetBtcBig: ${targetBtcBig}`);
94829
+ let low = BigInt(
94830
+ Math.floor(
94831
+ estimatedUsdcAmount * 10 ** fromToken.decimals * 0.9
94832
+ )
94833
+ );
94834
+ let high = BigInt(
94835
+ Math.floor(
94836
+ estimatedUsdcAmount * 10 ** fromToken.decimals * 1.1
94837
+ )
94838
+ );
94839
+ let mid = 0n;
94840
+ for (let i = 0; i < maxIterations; i++) {
94841
+ mid = (low + high) / 2n;
94842
+ const sellAmount2 = returnFormattedAmount(Number(mid), 0);
94843
+ const quote = await this.fetchQuoteWithRetry({
94844
+ sellTokenAddress: from_token_address,
94845
+ buyTokenAddress: to_token_address,
94846
+ takerAddress,
94847
+ sellAmount: sellAmount2
94848
+ });
94849
+ const gotBtc = BigInt(quote.data[0].buyAmount);
94850
+ if (gotBtc === targetBtcBig) return quote.data[0];
94851
+ if (gotBtc > targetBtcBig) {
94852
+ high = mid;
94853
+ } else {
94854
+ low = mid;
94855
+ }
94856
+ if (gotBtc >= targetBtcBig && gotBtc <= targetBtcBig + BigInt(tolerance)) {
94857
+ return quote.data[0];
94858
+ }
94859
+ }
94860
+ let sellAmount = returnFormattedAmount(
94861
+ Number(mid),
94862
+ 0
94863
+ );
94864
+ const params = {
94865
+ sellTokenAddress: from_token_address,
94866
+ buyTokenAddress: to_token_address,
94867
+ takerAddress,
94868
+ sellAmount
94869
+ };
94870
+ const finalQuote = await this.fetchQuoteWithRetry(params);
94871
+ if (!finalQuote.data.length) {
94872
+ logger2.error("No quotes available for this swap, error in quotes avnu");
94873
+ return null;
94874
+ }
94875
+ const dataObject = finalQuote.data[0];
94876
+ const wbtcAmountOut = parseInt(dataObject.buyAmount.toString(), 16);
94877
+ logger2.info(`${_AvnuAdapter.name}::getQuotesAvnu finalAmountOfWbtcOut : ${wbtcAmountOut} ${dataObject.buyAmount} ${dataObject.sellAmount.toString()} ${dataObject.sellAmount.toString()}`);
94878
+ return dataObject;
94879
+ } catch (err2) {
94880
+ logger2.error(`No quotes available for this swap: ${err2}`);
94881
+ return null;
94882
+ }
94883
+ }
94884
+ async getPriceOfToken(tokenAddress, retries = MAX_RETRIES) {
94885
+ try {
94886
+ const url = `https://starknet.impulse.avnu.fi/v1/tokens/${tokenAddress}/prices/line`;
94887
+ const response = await axios_default.get(url);
94888
+ const length = response.data.length;
94889
+ return response.data[length - 1].value;
94890
+ } catch (err2) {
94891
+ if (retries > 0) {
94892
+ await new Promise((resolve) => setTimeout(resolve, MAX_DELAY));
94893
+ return this.getPriceOfToken(tokenAddress, retries - 1);
94894
+ } else {
94895
+ logger2.error(`Failed to fetch price for ${tokenAddress} after ${MAX_RETRIES} attempts`);
94896
+ return null;
94897
+ }
94898
+ }
94899
+ }
94900
+ };
94901
+
94028
94902
  // src/strategies/universal-strategy.tsx
94029
94903
  var AUMTypes = /* @__PURE__ */ ((AUMTypes2) => {
94030
94904
  AUMTypes2["FINALISED"] = "finalised";
94031
94905
  AUMTypes2["DEFISPRING"] = "defispring";
94032
94906
  return AUMTypes2;
94033
94907
  })(AUMTypes || {});
94908
+ var PositionTypeAvnuExtended = /* @__PURE__ */ ((PositionTypeAvnuExtended2) => {
94909
+ PositionTypeAvnuExtended2["OPEN"] = "open";
94910
+ PositionTypeAvnuExtended2["CLOSE"] = "close";
94911
+ return PositionTypeAvnuExtended2;
94912
+ })(PositionTypeAvnuExtended || {});
94034
94913
  var UNIVERSAL_MANAGE_IDS = /* @__PURE__ */ ((UNIVERSAL_MANAGE_IDS2) => {
94035
94914
  UNIVERSAL_MANAGE_IDS2["FLASH_LOAN"] = "flash_loan_init";
94036
94915
  UNIVERSAL_MANAGE_IDS2["VESU_LEG1"] = "vesu_leg1";
@@ -97208,7 +98087,8 @@ spurious results.`);
97208
98087
  minHealthFactor: vaultSettings.minHealthFactor,
97209
98088
  quoteAmountToFetchPrice: vaultSettings.quoteAmountToFetchPrice,
97210
98089
  ...baseAdapterConfig,
97211
- supportedPositions: [{ asset: lstToken, isDebt: false }, { asset: Global.getDefaultTokens().find((token) => token.symbol === position), isDebt: true }]
98090
+ supportedPositions: [{ asset: lstToken, isDebt: false }, { asset: Global.getDefaultTokens().find((token) => token.symbol === position), isDebt: true }],
98091
+ minimumVesuMovementAmount: 0
97212
98092
  }));
97213
98093
  const unusedBalanceAdapter = new UnusedBalanceAdapter({
97214
98094
  ...baseAdapterConfig
@@ -97437,333 +98317,15 @@ spurious results.`);
97437
98317
  getStrategySettings("mRe7YIELD", "mRe7YIELD", hypermRe7YIELD, false, false)
97438
98318
  ];
97439
98319
 
97440
- // src/strategies/universal-adapters/avnu-adapter.ts
97441
- var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
97442
- constructor(config3) {
97443
- super(config3, _AvnuAdapter.name, Protocols.AVNU);
97444
- this.config = config3;
97445
- this.avnuWrapper = new AvnuWrapper();
97446
- }
97447
- //abstract means the method has no implementation in this class; instead, child classes must implement it.
97448
- async getAPY(supportedPosition) {
97449
- return Promise.resolve({ apy: 0, type: "base" /* BASE */ });
97450
- }
97451
- async getPosition(supportedPosition) {
97452
- return Promise.resolve({ amount: new Web3Number(0, 0), remarks: "" });
97453
- }
97454
- async maxDeposit(amount) {
97455
- return Promise.resolve({
97456
- tokenInfo: this.config.baseToken,
97457
- amount: new Web3Number(0, 0),
97458
- usdValue: 0,
97459
- apy: { apy: 0, type: "base" /* BASE */ },
97460
- protocol: Protocols.AVNU,
97461
- remarks: ""
97462
- });
97463
- }
97464
- async maxWithdraw() {
97465
- return Promise.resolve({
97466
- tokenInfo: this.config.baseToken,
97467
- amount: new Web3Number(0, 0),
97468
- usdValue: 0,
97469
- apy: { apy: 0, type: "base" /* BASE */ },
97470
- protocol: Protocols.AVNU,
97471
- remarks: ""
97472
- });
97473
- }
97474
- _getDepositLeaf() {
97475
- const vaultAllocator = ContractAddr.from(
97476
- this.config.vaultAllocator.address
97477
- );
97478
- return [
97479
- {
97480
- target: this.config.supportedPositions[0].asset.address,
97481
- method: "approve",
97482
- packedArguments: [
97483
- AVNU_EXCHANGE.toBigInt()
97484
- ],
97485
- sanitizer: SIMPLE_SANITIZER,
97486
- id: `approve_${this.config.supportedPositions[0].asset.symbol}`
97487
- },
97488
- {
97489
- target: AVNU_EXCHANGE,
97490
- method: "multi_route_swap",
97491
- packedArguments: [
97492
- this.config.supportedPositions[0].asset.address.toBigInt(),
97493
- //usdc
97494
- this.config.supportedPositions[1].asset.address.toBigInt(),
97495
- //wbtc
97496
- vaultAllocator.toBigInt()
97497
- ],
97498
- sanitizer: SIMPLE_SANITIZER,
97499
- id: `asutb_${this.config.supportedPositions[0].asset.symbol}_${this.config.supportedPositions[1].asset.symbol}`
97500
- }
97501
- ];
97502
- }
97503
- _getWithdrawLeaf() {
97504
- const vaultAllocator = ContractAddr.from(
97505
- this.config.vaultAllocator.address
97506
- );
97507
- const toToken = this.config.supportedPositions[0].asset;
97508
- const fromToken = this.config.supportedPositions[1].asset;
97509
- return [
97510
- {
97511
- target: fromToken.address,
97512
- method: "approve",
97513
- packedArguments: [
97514
- AVNU_EXCHANGE.toBigInt()
97515
- ],
97516
- sanitizer: SIMPLE_SANITIZER,
97517
- id: `approve_${fromToken.symbol}`
97518
- },
97519
- {
97520
- target: AVNU_EXCHANGE,
97521
- method: "multi_route_swap",
97522
- packedArguments: [
97523
- fromToken.address.toBigInt(),
97524
- //wbtc
97525
- toToken.address.toBigInt(),
97526
- //usdc
97527
- vaultAllocator.toBigInt()
97528
- ],
97529
- sanitizer: SIMPLE_SANITIZER,
97530
- id: `asbtu_${fromToken.symbol}_${fromToken.symbol}`
97531
- }
97532
- ];
97533
- }
97534
- _getLegacySwapLeaf() {
97535
- return [];
97536
- }
97537
- async getDepositCall(params) {
97538
- try {
97539
- const fromToken = this.config.supportedPositions[0].asset;
97540
- const toToken = this.config.supportedPositions[1].asset;
97541
- const vaultAllocator = ContractAddr.from(
97542
- this.config.vaultAllocator.address
97543
- );
97544
- const quote = await this.getQuotesAvnu(
97545
- fromToken.address.toString(),
97546
- toToken.address.toString(),
97547
- params.amount.toNumber(),
97548
- vaultAllocator.address.toString(),
97549
- toToken.decimals,
97550
- true
97551
- );
97552
- if (!quote) {
97553
- logger2.error("error getting quote from avnu");
97554
- return [];
97555
- }
97556
- const getCalldata = await this.avnuWrapper.getSwapCallData(
97557
- quote,
97558
- vaultAllocator.address
97559
- );
97560
- const swapCallData = getCalldata[0];
97561
- const amount = uint256_exports.bnToUint256(quote.sellAmountInUsd * 10 ** 7);
97562
- return [
97563
- {
97564
- sanitizer: SIMPLE_SANITIZER,
97565
- call: {
97566
- contractAddress: fromToken.address,
97567
- selector: hash_exports.getSelectorFromName("approve"),
97568
- calldata: [
97569
- AVNU_EXCHANGE.toBigInt(),
97570
- toBigInt3(amount.low.toString()),
97571
- // amount low
97572
- toBigInt3(amount.high.toString())
97573
- // amount high
97574
- ]
97575
- }
97576
- },
97577
- {
97578
- sanitizer: SIMPLE_SANITIZER,
97579
- call: {
97580
- contractAddress: AVNU_EXCHANGE,
97581
- selector: hash_exports.getSelectorFromName("multi_route_swap"),
97582
- calldata: swapCallData
97583
- }
97584
- }
97585
- ];
97586
- } catch (error2) {
97587
- logger2.error(`Error getting Avnu quote: ${error2}`);
97588
- return [];
97589
- }
97590
- }
97591
- //Swap wbtc to usdc
97592
- async getWithdrawCall(params) {
97593
- try {
97594
- const toToken = this.config.supportedPositions[0].asset;
97595
- const fromToken = this.config.supportedPositions[1].asset;
97596
- const vaultAllocator = ContractAddr.from(
97597
- this.config.vaultAllocator.address
97598
- );
97599
- const quote = await this.getQuotesAvnu(
97600
- fromToken.address.toString(),
97601
- toToken.address.toString(),
97602
- params.amount.toNumber(),
97603
- vaultAllocator.address.toString(),
97604
- fromToken.decimals,
97605
- false
97606
- );
97607
- if (!quote) {
97608
- logger2.error("No quotes available for this swap, error in quotes avnu");
97609
- return [];
97610
- }
97611
- const getCalldata = await this.avnuWrapper.getSwapCallData(
97612
- quote,
97613
- vaultAllocator.address
97614
- );
97615
- const swapCallData = getCalldata[0];
97616
- const amount = uint256_exports.bnToUint256(params.amount.toWei());
97617
- return [
97618
- {
97619
- sanitizer: SIMPLE_SANITIZER,
97620
- call: {
97621
- contractAddress: fromToken.address,
97622
- selector: hash_exports.getSelectorFromName("approve"),
97623
- calldata: [
97624
- AVNU_EXCHANGE.toBigInt(),
97625
- toBigInt3(amount.low.toString()),
97626
- // amount low
97627
- toBigInt3(amount.high.toString())
97628
- // amount high
97629
- ]
97630
- }
97631
- },
97632
- {
97633
- sanitizer: SIMPLE_SANITIZER,
97634
- call: {
97635
- contractAddress: AVNU_EXCHANGE,
97636
- selector: hash_exports.getSelectorFromName("multi_route_swap"),
97637
- calldata: swapCallData
97638
- }
97639
- }
97640
- ];
97641
- } catch (error2) {
97642
- logger2.error(`Error getting Avnu quote: ${error2}`);
97643
- return [];
97644
- }
97645
- }
97646
- async getSwapCallData(quote) {
97647
- return await this.avnuWrapper.getSwapCallData(quote, this.config.vaultAllocator.address);
97648
- }
97649
- async getHealthFactor() {
97650
- return Promise.resolve(1);
97651
- }
97652
- async fetchQuoteWithRetry(params, retries = 5) {
97653
- for (let attempt = 0; attempt < retries; attempt++) {
97654
- try {
97655
- const response = await axios_default.get(this.config.baseUrl, { params });
97656
- if (response.data && response.data.length > 0) {
97657
- return response;
97658
- }
97659
- throw new Error("Empty response data");
97660
- } catch (err2) {
97661
- logger2.error(`Error fetching quote with retry: ${err2}`);
97662
- if (attempt === retries - 1) {
97663
- throw err2;
97664
- }
97665
- await new Promise((resolve) => setTimeout(resolve, MAX_DELAY));
97666
- }
97667
- }
97668
- throw new Error("Failed to fetch quote after retries");
97669
- }
97670
- async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 1e4) {
97671
- try {
97672
- const fromToken = this.config.supportedPositions[0].asset;
97673
- const toToken = this.config.supportedPositions[1].asset;
97674
- if (!usdcToBtc) {
97675
- const sellAmount2 = returnFormattedAmount(amount, toTokenDecimals);
97676
- const params2 = {
97677
- sellTokenAddress: from_token_address,
97678
- buyTokenAddress: to_token_address,
97679
- takerAddress,
97680
- sellAmount: sellAmount2
97681
- };
97682
- const finalQuote2 = await this.fetchQuoteWithRetry(params2);
97683
- if (!finalQuote2.data.length) {
97684
- logger2.error("No quotes available for this swap, error in quotes avnu");
97685
- return null;
97686
- }
97687
- const dataObject2 = finalQuote2.data[0];
97688
- return dataObject2;
97689
- }
97690
- const btcPrice = await this.getPriceOfToken(toToken.address.toString());
97691
- if (!btcPrice) {
97692
- logger2.error(`error getting btc price: ${btcPrice}`);
97693
- return null;
97694
- }
97695
- const estimatedUsdcAmount = Math.floor(amount * btcPrice);
97696
- const targetBtcBig = BigInt(returnFormattedAmount(amount, toTokenDecimals));
97697
- let low = BigInt(
97698
- Math.floor(
97699
- estimatedUsdcAmount * 10 ** fromToken.decimals * 0.9
97700
- )
97701
- );
97702
- let high = BigInt(
97703
- Math.floor(
97704
- estimatedUsdcAmount * 10 ** fromToken.decimals * 1.1
97705
- )
97706
- );
97707
- let mid = 0n;
97708
- for (let i = 0; i < maxIterations; i++) {
97709
- mid = (low + high) / 2n;
97710
- const sellAmount2 = returnFormattedAmount(Number(mid), 0);
97711
- const quote = await this.fetchQuoteWithRetry({
97712
- sellTokenAddress: from_token_address,
97713
- buyTokenAddress: to_token_address,
97714
- takerAddress,
97715
- sellAmount: sellAmount2
97716
- });
97717
- const gotBtc = BigInt(quote.data[0].buyAmount);
97718
- if (gotBtc === targetBtcBig) return quote.data[0];
97719
- if (gotBtc > targetBtcBig) {
97720
- high = mid;
97721
- } else {
97722
- low = mid;
97723
- }
97724
- if (gotBtc >= targetBtcBig && gotBtc <= targetBtcBig + BigInt(tolerance)) {
97725
- return quote.data[0];
97726
- }
97727
- }
97728
- let sellAmount = returnFormattedAmount(
97729
- Number(mid),
97730
- 0
97731
- );
97732
- const params = {
97733
- sellTokenAddress: from_token_address,
97734
- buyTokenAddress: to_token_address,
97735
- takerAddress,
97736
- sellAmount
97737
- };
97738
- const finalQuote = await this.fetchQuoteWithRetry(params);
97739
- if (!finalQuote.data.length) {
97740
- logger2.error("No quotes available for this swap, error in quotes avnu");
97741
- return null;
97742
- }
97743
- const dataObject = finalQuote.data[0];
97744
- return dataObject;
97745
- } catch (err2) {
97746
- logger2.error(`No quotes available for this swap: ${err2}`);
97747
- return null;
97748
- }
97749
- }
97750
- async getPriceOfToken(tokenAddress, retries = MAX_RETRIES) {
97751
- try {
97752
- const url = `https://starknet.impulse.avnu.fi/v1/tokens/${tokenAddress}/prices/line`;
97753
- const response = await axios_default.get(url);
97754
- const length = response.data.length;
97755
- return response.data[length - 1].value;
97756
- } catch (err2) {
97757
- if (retries > 0) {
97758
- await new Promise((resolve) => setTimeout(resolve, MAX_DELAY));
97759
- return this.getPriceOfToken(tokenAddress, retries - 1);
97760
- } else {
97761
- logger2.error(`Failed to fetch price for ${tokenAddress} after ${MAX_RETRIES} attempts`);
97762
- return null;
97763
- }
97764
- }
97765
- }
97766
- };
98320
+ // src/strategies/vesu-extended-strategy/types/transaction-metadata.ts
98321
+ var CycleType = /* @__PURE__ */ ((CycleType2) => {
98322
+ CycleType2["INVESTMENT"] = "INVESTMENT";
98323
+ CycleType2["REBALANCE_PRICE_DROP"] = "REBALANCE_PRICE_DROP";
98324
+ CycleType2["REBALANCE_PRICE_RISE"] = "REBALANCE_PRICE_RISE";
98325
+ CycleType2["WITHDRAWAL"] = "WITHDRAWAL";
98326
+ CycleType2["DELTA_NEUTRAL_ADJUSTMENT"] = "DELTA_NEUTRAL_ADJUSTMENT";
98327
+ return CycleType2;
98328
+ })(CycleType || {});
97767
98329
 
97768
98330
  // src/strategies/vesu-extended-strategy/vesu-extended-strategy.tsx
97769
98331
  var import_jsx_runtime5 = __toESM(require_jsx_runtime());
@@ -97863,15 +98425,30 @@ spurious results.`);
97863
98425
  const usdceToken = Global.getDefaultTokens().find(
97864
98426
  (token) => token.symbol === "USDCe"
97865
98427
  );
98428
+ const walletBalance = await new ERC20(this.config).balanceOf(
98429
+ usdceToken.address,
98430
+ WALLET_ADDRESS,
98431
+ usdceToken.decimals
98432
+ );
98433
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::moveAssetsToVaultAllocator walletBalance: ${walletBalance}`);
98434
+ const amountToBeTransferred = amount.minimum(walletBalance);
98435
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::moveAssetsToVaultAllocator amountToBeTransferred: ${amountToBeTransferred.toNumber()}`);
98436
+ if (amountToBeTransferred.lessThan(0)) {
98437
+ logger2.error(`${_VesuExtendedMultiplierStrategy.name}::moveAssetsToVaultAllocator amountToBeTransferred is less than 0: ${amountToBeTransferred.toNumber()}`);
98438
+ return {
98439
+ calls: [],
98440
+ status: false
98441
+ };
98442
+ }
97866
98443
  const approveCall = new ERC20(this.config).approve(
97867
98444
  usdceToken.address,
97868
98445
  this.metadata.additionalInfo.vaultAllocator,
97869
- amount
98446
+ amountToBeTransferred
97870
98447
  );
97871
98448
  const transferCall = new ERC20(this.config).transfer(
97872
98449
  usdceToken.address,
97873
98450
  this.metadata.additionalInfo.vaultAllocator,
97874
- amount
98451
+ amountToBeTransferred
97875
98452
  );
97876
98453
  const proofsInfo = extendedAdapter.getProofsForFromLegacySwap(
97877
98454
  this.getMerkleTree()
@@ -97879,21 +98456,43 @@ spurious results.`);
97879
98456
  const proofGroups = proofsInfo.proofs;
97880
98457
  const call = this.getManageCall(
97881
98458
  proofGroups,
97882
- await proofsInfo.callConstructor({ amount })
98459
+ await proofsInfo.callConstructor({ amount: amountToBeTransferred })
97883
98460
  );
97884
- return [approveCall, transferCall, call];
98461
+ return {
98462
+ calls: [approveCall, transferCall, call],
98463
+ status: true
98464
+ };
97885
98465
  } catch (err2) {
97886
98466
  logger2.error(`error moving assets to vault allocator: ${err2}`);
97887
- return [];
98467
+ return {
98468
+ calls: [],
98469
+ status: false
98470
+ };
97888
98471
  }
97889
98472
  }
97890
98473
  async shouldInvest() {
97891
98474
  try {
98475
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest starting`);
97892
98476
  const vesuAdapter = await this.getVesuAdapter();
97893
98477
  const extendedAdapter = await this.getExtendedAdapter();
97894
- if (!vesuAdapter || !extendedAdapter || !extendedAdapter.client) {
98478
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest adapters fetched: vesuAdapter=${!!vesuAdapter}, extendedAdapter=${!!extendedAdapter}, extendedAdapter.client=${!!extendedAdapter?.client}`);
98479
+ if (!vesuAdapter) {
97895
98480
  logger2.error(
97896
- `vesu or extended adapter not found: vesuAdapter=${vesuAdapter}, extendedAdapter=${extendedAdapter}`
98481
+ `Vesu adapter not configured in metadata. This is a configuration issue, not a temporary failure.`
98482
+ );
98483
+ return {
98484
+ shouldInvest: false,
98485
+ vesuAmount: new Web3Number(0, 0),
98486
+ extendedAmount: new Web3Number(0, 0),
98487
+ extendedLeverage: 0,
98488
+ collateralPrice: 0,
98489
+ debtPrice: 0,
98490
+ vesuLeverage: 0
98491
+ };
98492
+ }
98493
+ if (!extendedAdapter) {
98494
+ logger2.error(
98495
+ `Extended adapter not configured in metadata. This is a configuration issue, not a temporary failure.`
97897
98496
  );
97898
98497
  return {
97899
98498
  shouldInvest: false,
@@ -97905,10 +98504,73 @@ spurious results.`);
97905
98504
  vesuLeverage: 0
97906
98505
  };
97907
98506
  }
98507
+ if (!extendedAdapter.client) {
98508
+ logger2.error(
98509
+ `Extended adapter client not initialized. This may be a temporary initialization failure - check network connectivity and API availability.`
98510
+ );
98511
+ return {
98512
+ shouldInvest: false,
98513
+ vesuAmount: new Web3Number(0, 0),
98514
+ extendedAmount: new Web3Number(0, 0),
98515
+ extendedLeverage: 0,
98516
+ collateralPrice: 0,
98517
+ debtPrice: 0,
98518
+ vesuLeverage: 0
98519
+ };
98520
+ }
98521
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest calling getUnusedBalance`);
97908
98522
  const balance = await this.getUnusedBalance();
98523
+ if (!Number.isFinite(balance.usdValue) || balance.usdValue < 0) {
98524
+ logger2.error(
98525
+ `Invalid balance.usdValue: ${balance.usdValue}. Expected a finite, non-negative number.`
98526
+ );
98527
+ return {
98528
+ shouldInvest: false,
98529
+ vesuAmount: new Web3Number(0, 0),
98530
+ extendedAmount: new Web3Number(0, 0),
98531
+ extendedLeverage: 0,
98532
+ collateralPrice: 0,
98533
+ debtPrice: 0,
98534
+ vesuLeverage: 0
98535
+ };
98536
+ }
98537
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest balance: ${balance.usdValue}`);
97909
98538
  const usdcBalanceOnExtended = await extendedAdapter.getExtendedDepositAmount();
97910
- const amountToInvest = balance.amount.plus(usdcBalanceOnExtended?.availableForWithdrawal ?? 0).minus(LIMIT_BALANCE);
97911
- if (amountToInvest.lessThan(0)) {
98539
+ if (usdcBalanceOnExtended) {
98540
+ const availableForWithdrawal = parseFloat(usdcBalanceOnExtended.availableForWithdrawal);
98541
+ if (!Number.isFinite(availableForWithdrawal) || availableForWithdrawal < 0) {
98542
+ logger2.error(
98543
+ `Invalid usdcBalanceOnExtended.availableForWithdrawal: ${usdcBalanceOnExtended.availableForWithdrawal}. Expected a finite, non-negative number.`
98544
+ );
98545
+ return {
98546
+ shouldInvest: false,
98547
+ vesuAmount: new Web3Number(0, 0),
98548
+ extendedAmount: new Web3Number(0, 0),
98549
+ extendedLeverage: 0,
98550
+ collateralPrice: 0,
98551
+ debtPrice: 0,
98552
+ vesuLeverage: 0
98553
+ };
98554
+ }
98555
+ }
98556
+ const amountToInvest = new Web3Number(balance.usdValue, USDC_TOKEN_DECIMALS).plus(usdcBalanceOnExtended?.availableForWithdrawal ?? 0).multipliedBy(1 - LIMIT_BALANCE);
98557
+ const amountToInvestNumber = amountToInvest.toNumber();
98558
+ if (!Number.isFinite(amountToInvestNumber)) {
98559
+ logger2.error(
98560
+ `Invalid amountToInvest calculation result: ${amountToInvestNumber}. Calculation may have produced NaN or Infinity.`
98561
+ );
98562
+ return {
98563
+ shouldInvest: false,
98564
+ vesuAmount: new Web3Number(0, 0),
98565
+ extendedAmount: new Web3Number(0, 0),
98566
+ extendedLeverage: 0,
98567
+ collateralPrice: 0,
98568
+ debtPrice: 0,
98569
+ vesuLeverage: 0
98570
+ };
98571
+ }
98572
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest amountToInvest: ${amountToInvestNumber}`);
98573
+ if (amountToInvest.lessThan(LIMIT_BALANCE_VALUE)) {
97912
98574
  return {
97913
98575
  shouldInvest: false,
97914
98576
  vesuAmount: new Web3Number(0, 0),
@@ -97937,6 +98599,34 @@ spurious results.`);
97937
98599
  collateralPrice,
97938
98600
  debtPrice
97939
98601
  } = await this.getAssetPrices();
98602
+ if (!Number.isFinite(collateralPrice.price) || collateralPrice.price <= 0) {
98603
+ logger2.error(
98604
+ `Invalid collateralPrice: ${collateralPrice.price}. Expected a finite, positive number.`
98605
+ );
98606
+ return {
98607
+ shouldInvest: false,
98608
+ vesuAmount: new Web3Number(0, 0),
98609
+ extendedAmount: new Web3Number(0, 0),
98610
+ extendedLeverage: 0,
98611
+ collateralPrice: 0,
98612
+ debtPrice: 0,
98613
+ vesuLeverage: 0
98614
+ };
98615
+ }
98616
+ if (!Number.isFinite(debtPrice.price) || debtPrice.price <= 0) {
98617
+ logger2.error(
98618
+ `Invalid debtPrice: ${debtPrice.price}. Expected a finite, positive number.`
98619
+ );
98620
+ return {
98621
+ shouldInvest: false,
98622
+ vesuAmount: new Web3Number(0, 0),
98623
+ extendedAmount: new Web3Number(0, 0),
98624
+ extendedLeverage: 0,
98625
+ collateralPrice: 0,
98626
+ debtPrice: 0,
98627
+ vesuLeverage: 0
98628
+ };
98629
+ }
97940
98630
  const { vesu_amount, extended_amount, extended_leverage, vesu_leverage } = await calculateAmountDistribution(
97941
98631
  amountToInvest.toNumber(),
97942
98632
  extendedAdapter.client,
@@ -97960,6 +98650,7 @@ spurious results.`);
97960
98650
  vesuLeverage: 0
97961
98651
  };
97962
98652
  }
98653
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest vesu_amount: ${vesu_amount.toNumber()}, extended_amount: ${extended_amount.toNumber()}`);
97963
98654
  return {
97964
98655
  shouldInvest: true,
97965
98656
  vesuAmount: vesu_amount,
@@ -97986,111 +98677,251 @@ spurious results.`);
97986
98677
  try {
97987
98678
  const vesuAdapter = await this.getVesuAdapter();
97988
98679
  const extendedAdapter = await this.getExtendedAdapter();
97989
- let calls = [];
97990
98680
  if (!vesuAdapter || !extendedAdapter || !extendedAdapter.client) {
97991
98681
  logger2.error(
97992
98682
  `vesu or extended adapter not found: vesuAdapter=${vesuAdapter}, extendedAdapter=${extendedAdapter}`
97993
98683
  );
97994
- return calls;
98684
+ return [];
98685
+ }
98686
+ const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
98687
+ if (!extendedHoldings) {
98688
+ logger2.error(`error getting extended holdings: ${extendedHoldings}`);
98689
+ return [];
97995
98690
  }
97996
- if (extendedAmount.lessThan(0)) {
98691
+ const usdcAmountInWallet = (await this.getUnusedBalance()).amount;
98692
+ const usdcAmountOnExtendedAvailableForWithdrawal = parseFloat(
98693
+ extendedHoldings.availableForWithdrawal
98694
+ );
98695
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::shouldMoveAssets calculating movements - Extended current: ${usdcAmountOnExtendedAvailableForWithdrawal}, Wallet: ${usdcAmountInWallet.toNumber()}, Target Extended: ${extendedAmount.toNumber()}, Target Vesu: ${vesuAmount.toNumber()}`);
98696
+ let totalExtendedWithdrawal = new Web3Number(0, USDC_TOKEN_DECIMALS);
98697
+ let totalExtendedDeposit = new Web3Number(0, USDC_TOKEN_DECIMALS);
98698
+ if (extendedAmount.isNegative() && extendedAmount.abs().greaterThan(extendedAdapter.minimumExtendedMovementAmount)) {
98699
+ totalExtendedWithdrawal = totalExtendedWithdrawal.plus(extendedAmount.abs());
98700
+ }
98701
+ const extendedTargetAmount = extendedAmount.abs();
98702
+ let projectedExtendedBalance = usdcAmountOnExtendedAvailableForWithdrawal;
98703
+ if (extendedAmount.isNegative()) {
98704
+ projectedExtendedBalance = projectedExtendedBalance - extendedAmount.abs().toNumber();
98705
+ }
98706
+ const extendedAmountDifference = extendedTargetAmount.minus(projectedExtendedBalance);
98707
+ const extendedAmountDifferenceAbs = extendedAmountDifference.abs();
98708
+ if (extendedAmountDifference.lessThan(0)) {
98709
+ totalExtendedWithdrawal = totalExtendedWithdrawal.plus(extendedAmountDifferenceAbs);
98710
+ } else if (extendedAmountDifference.greaterThan(0)) {
98711
+ totalExtendedDeposit = totalExtendedDeposit.plus(extendedAmountDifference);
98712
+ }
98713
+ const vesuTargetAmount = vesuAmount.abs();
98714
+ const projectedWalletBalance = usdcAmountInWallet.plus(totalExtendedWithdrawal).minus(totalExtendedDeposit);
98715
+ let vesuAmountDifference = vesuTargetAmount.minus(projectedWalletBalance);
98716
+ const vesuAmountDifferenceAbs = vesuAmountDifference.abs();
98717
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::shouldMoveAssets calculated movements - Extended withdrawal: ${totalExtendedWithdrawal.toNumber()}, Extended deposit: ${totalExtendedDeposit.toNumber()}, Extended diff: ${extendedAmountDifference.toNumber()}, Projected wallet: ${projectedWalletBalance.toNumber()}, Vesu diff: ${vesuAmountDifference.toNumber()}`);
98718
+ let calls = [];
98719
+ let transactionResults = [];
98720
+ if (extendedAmount.isNegative() && extendedAmount.abs().greaterThan(extendedAdapter.minimumExtendedMovementAmount)) {
97997
98721
  try {
97998
- const { calls: extendedCalls, status: extendedStatus } = await this.moveAssets(
98722
+ const { calls: extendedCalls, status: extendedStatus, transactionMetadata: extendedTransactionMetadata } = await this.moveAssets(
97999
98723
  {
98000
98724
  to: Protocols.VAULT.name,
98001
98725
  from: Protocols.EXTENDED.name,
98002
- amount: extendedAmount.abs()
98726
+ amount: extendedAmount.abs(),
98727
+ cycleType: "INVESTMENT" /* INVESTMENT */
98003
98728
  },
98004
98729
  extendedAdapter,
98005
98730
  vesuAdapter
98006
98731
  );
98007
98732
  if (extendedStatus) {
98008
- calls.push(...extendedCalls);
98733
+ transactionResults.push({
98734
+ status: extendedStatus,
98735
+ calls: extendedCalls,
98736
+ transactionMetadata: {
98737
+ ...extendedTransactionMetadata,
98738
+ transactionType: "DEPOSIT"
98739
+ }
98740
+ });
98009
98741
  } else {
98010
- return [];
98742
+ return [this.createTransactionResult([], false, { from: Protocols.EXTENDED.name, to: Protocols.VAULT.name, amount: extendedAmount.abs() }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98011
98743
  }
98012
98744
  } catch (err2) {
98013
98745
  logger2.error(`Failed moving assets to vault: ${err2}`);
98746
+ return [this.createTransactionResult([], false, { from: Protocols.EXTENDED.name, to: Protocols.VAULT.name, amount: extendedAmount.abs() }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98014
98747
  }
98015
98748
  }
98016
- if (vesuAmount.lessThan(0)) {
98749
+ if (vesuAmount.isNegative() && vesuAmount.abs().greaterThan(vesuAdapter.minimumVesuMovementAmount)) {
98017
98750
  try {
98018
- const { calls: vesuCalls, status: vesuStatus } = await this.moveAssets(
98751
+ const { calls: vesuCalls, status: vesuStatus, transactionMetadata: vesuTransactionMetadata } = await this.moveAssets(
98019
98752
  {
98020
98753
  to: Protocols.EXTENDED.name,
98021
98754
  from: Protocols.VESU.name,
98022
- amount: vesuAmount.abs()
98755
+ amount: vesuAmount.abs(),
98756
+ cycleType: "INVESTMENT" /* INVESTMENT */
98023
98757
  },
98024
98758
  extendedAdapter,
98025
98759
  vesuAdapter
98026
98760
  );
98027
- calls.push(...vesuCalls);
98028
98761
  if (!vesuStatus) {
98029
- return [];
98030
- }
98762
+ return [this.createTransactionResult([], false, { from: Protocols.VESU.name, to: Protocols.EXTENDED.name, amount: vesuAmount.abs() }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98763
+ }
98764
+ transactionResults.push({
98765
+ status: vesuStatus,
98766
+ calls: vesuCalls,
98767
+ transactionMetadata: {
98768
+ ...vesuTransactionMetadata,
98769
+ transactionType: "DEPOSIT"
98770
+ }
98771
+ });
98031
98772
  } catch (err2) {
98032
- logger2.error(`Failed moving assets to vault: ${err2}`);
98773
+ logger2.error(`Failed moving assets to extended via vault allocator: ${err2}`);
98774
+ return [this.createTransactionResult([], false, { from: Protocols.VESU.name, to: Protocols.EXTENDED.name, amount: vesuAmount.abs() }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98033
98775
  }
98034
98776
  }
98035
- const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
98036
- if (!extendedHoldings) {
98037
- logger2.error(`error getting extended holdings: ${extendedHoldings}`);
98038
- return calls;
98039
- }
98040
- const usdcAmountInWallet = (await this.getUnusedBalance()).amount;
98041
- const usdcAmountOnExtended = parseFloat(
98042
- extendedHoldings.availableForWithdrawal
98043
- );
98044
- if (extendedAmount.minus(usdcAmountOnExtended).greaterThan(0)) {
98045
- try {
98046
- const { calls: extendedCalls } = await this.moveAssets(
98047
- {
98048
- to: Protocols.EXTENDED.name,
98049
- from: Protocols.VAULT.name,
98050
- amount: extendedAmount.minus(usdcAmountOnExtended)
98051
- },
98052
- extendedAdapter,
98053
- vesuAdapter
98054
- );
98055
- calls.push(...extendedCalls);
98056
- } catch (err2) {
98057
- logger2.error(`Failed moving assets to extended: ${err2}`);
98777
+ if (extendedAmountDifferenceAbs.greaterThan(extendedAdapter.minimumExtendedMovementAmount)) {
98778
+ if (extendedAmountDifference.greaterThan(0)) {
98779
+ try {
98780
+ const { calls: extendedCalls, status: extendedStatus, transactionMetadata: extendedTransactionMetadata } = await this.moveAssets(
98781
+ {
98782
+ to: Protocols.EXTENDED.name,
98783
+ from: Protocols.VAULT.name,
98784
+ amount: extendedAmountDifference,
98785
+ cycleType: "INVESTMENT" /* INVESTMENT */
98786
+ },
98787
+ extendedAdapter,
98788
+ vesuAdapter
98789
+ );
98790
+ if (extendedStatus) {
98791
+ transactionResults.push({
98792
+ status: extendedStatus,
98793
+ calls: extendedCalls,
98794
+ transactionMetadata: extendedTransactionMetadata
98795
+ });
98796
+ } else {
98797
+ logger2.error(`Failed to move assets to extended - operation returned false status`);
98798
+ return [this.createTransactionResult([], false, { from: Protocols.VAULT.name, to: Protocols.EXTENDED.name, amount: extendedAmountDifference }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98799
+ }
98800
+ } catch (err2) {
98801
+ logger2.error(`Failed moving assets to extended: ${err2}`);
98802
+ return [this.createTransactionResult([], false, { from: Protocols.VAULT.name, to: Protocols.EXTENDED.name, amount: extendedAmountDifference }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98803
+ }
98804
+ } else if (extendedAmountDifference.lessThan(0)) {
98805
+ try {
98806
+ const { calls: extendedCalls, status: extendedStatus, transactionMetadata: extendedTransactionMetadata } = await this.moveAssets(
98807
+ {
98808
+ to: Protocols.VAULT.name,
98809
+ from: Protocols.EXTENDED.name,
98810
+ amount: extendedAmountDifferenceAbs,
98811
+ cycleType: "INVESTMENT" /* INVESTMENT */
98812
+ },
98813
+ extendedAdapter,
98814
+ vesuAdapter
98815
+ );
98816
+ if (extendedStatus) {
98817
+ transactionResults.push({
98818
+ status: extendedStatus,
98819
+ calls: extendedCalls,
98820
+ transactionMetadata: {
98821
+ ...extendedTransactionMetadata,
98822
+ transactionType: "DEPOSIT"
98823
+ }
98824
+ });
98825
+ } else {
98826
+ logger2.error(`Failed to withdraw from extended - operation returned false status`);
98827
+ return [this.createTransactionResult([], false, { from: Protocols.EXTENDED.name, to: Protocols.VAULT.name, amount: extendedAmountDifferenceAbs }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98828
+ }
98829
+ } catch (err2) {
98830
+ logger2.error(`Failed moving assets from extended to vault: ${err2}`);
98831
+ return [this.createTransactionResult([], false, { from: Protocols.EXTENDED.name, to: Protocols.VAULT.name, amount: extendedAmountDifferenceAbs }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98832
+ }
98058
98833
  }
98059
98834
  }
98060
- if (vesuAmount.minus(usdcAmountInWallet).greaterThan(0)) {
98061
- try {
98062
- const { calls: vesuCalls, status: vesuStatus } = await this.moveAssets(
98063
- {
98064
- to: Protocols.VAULT.name,
98065
- from: Protocols.EXTENDED.name,
98066
- amount: vesuAmount.minus(usdcAmountInWallet)
98067
- },
98068
- extendedAdapter,
98069
- vesuAdapter
98835
+ if (vesuAmountDifferenceAbs.greaterThan(vesuAdapter.minimumVesuMovementAmount)) {
98836
+ if (vesuAmountDifference.lessThanOrEqualTo(0)) {
98837
+ logger2.warn(
98838
+ `Vesu amount difference is negative or zero: ${vesuAmountDifference.toNumber()}. Skipping operation.`
98070
98839
  );
98071
- if (!vesuStatus) {
98072
- return [];
98840
+ } else {
98841
+ try {
98842
+ const { calls: vesuCalls, status: vesuStatus, transactionMetadata: vesuTransactionMetadata } = await this.moveAssets(
98843
+ {
98844
+ to: Protocols.VAULT.name,
98845
+ from: Protocols.EXTENDED.name,
98846
+ amount: vesuAmountDifference,
98847
+ cycleType: "INVESTMENT" /* INVESTMENT */
98848
+ },
98849
+ extendedAdapter,
98850
+ vesuAdapter
98851
+ );
98852
+ if (!vesuStatus) {
98853
+ logger2.error(`Failed to move assets to vesu - operation returned false status`);
98854
+ return [this.createTransactionResult([], false, { from: Protocols.EXTENDED.name, to: Protocols.VAULT.name, amount: vesuAmountDifference }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98855
+ }
98856
+ transactionResults.push({
98857
+ status: vesuStatus,
98858
+ calls: vesuCalls,
98859
+ transactionMetadata: {
98860
+ ...vesuTransactionMetadata,
98861
+ transactionType: "DEPOSIT"
98862
+ }
98863
+ });
98864
+ } catch (err2) {
98865
+ logger2.error(`Failed moving assets to vault: ${err2}`);
98866
+ return [this.createTransactionResult([], false, { from: Protocols.EXTENDED.name, to: Protocols.VAULT.name, amount: vesuAmountDifference }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98073
98867
  }
98074
- calls.push(...vesuCalls);
98075
- } catch (err2) {
98076
- logger2.error(`Failed moving assets to vault: ${err2}`);
98077
98868
  }
98078
98869
  }
98079
- return calls;
98870
+ return transactionResults;
98080
98871
  } catch (err2) {
98081
98872
  logger2.error(`Failed moving assets to vesu: ${err2}`);
98082
- return [];
98873
+ return [this.createTransactionResult([], false, { from: Protocols.EXTENDED.name, to: Protocols.VAULT.name, amount: new Web3Number(0, USDC_TOKEN_DECIMALS) }, "NONE", "INVESTMENT" /* INVESTMENT */)];
98874
+ }
98875
+ }
98876
+ /**
98877
+ * Helper method to create transaction result with metadata
98878
+ */
98879
+ createTransactionResult(calls, status, params, transactionType, cycleType) {
98880
+ if (status) {
98881
+ return {
98882
+ calls,
98883
+ status,
98884
+ transactionMetadata: {
98885
+ protocolFrom: params.from,
98886
+ protocolTo: params.to,
98887
+ transactionType,
98888
+ usdAmount: params.amount.abs().toFixed(),
98889
+ status: "PENDING",
98890
+ cycleType
98891
+ }
98892
+ };
98083
98893
  }
98894
+ return { calls: [], status: false, transactionMetadata: { protocolFrom: "", protocolTo: "", transactionType: "DEPOSIT", usdAmount: "0", status: "FAILED", cycleType } };
98084
98895
  }
98085
98896
  async moveAssets(params, extendedAdapter, vesuAdapter) {
98086
98897
  try {
98898
+ if (params.amount.lessThanOrEqualTo(0)) {
98899
+ logger2.error(
98900
+ `Invalid amount for moveAssets: ${params.amount.toNumber()}. Amount must be positive.`
98901
+ );
98902
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
98903
+ }
98904
+ const amountAbs = params.amount.abs();
98905
+ if (params.from === Protocols.EXTENDED.name || params.to === Protocols.EXTENDED.name) {
98906
+ if (amountAbs.lessThanOrEqualTo(extendedAdapter.minimumExtendedMovementAmount)) {
98907
+ logger2.warn(
98908
+ `Amount ${amountAbs.toNumber()} is below minimum Extended movement amount ${extendedAdapter.minimumExtendedMovementAmount}. Skipping operation.`
98909
+ );
98910
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
98911
+ }
98912
+ }
98913
+ if (params.from === Protocols.VESU.name || params.to === Protocols.VESU.name) {
98914
+ if (amountAbs.lessThanOrEqualTo(vesuAdapter.minimumVesuMovementAmount)) {
98915
+ logger2.warn(
98916
+ `Amount ${amountAbs.toNumber()} is below minimum Vesu movement amount ${vesuAdapter.minimumVesuMovementAmount}. Skipping operation.`
98917
+ );
98918
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
98919
+ }
98920
+ }
98087
98921
  const avnuAdapter = await this.getAvnuAdapter();
98088
98922
  if (!avnuAdapter) {
98089
98923
  logger2.error(`avnu adapter not found: ${avnuAdapter}`);
98090
- return {
98091
- calls: [],
98092
- status: false
98093
- };
98924
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
98094
98925
  }
98095
98926
  logger2.info(`moveAssets params, ${JSON.stringify(params)}`);
98096
98927
  const collateralToken = vesuAdapter.config.supportedPositions[0].asset;
@@ -98109,61 +98940,72 @@ spurious results.`);
98109
98940
  await proofsInfo.callConstructor({ amount: params.amount })
98110
98941
  );
98111
98942
  calls.push(call);
98112
- return {
98113
- calls: [call],
98114
- status: true
98115
- };
98943
+ return this.createTransactionResult(calls, true, params, "DEPOSIT", params.cycleType);
98116
98944
  } else if (params.to === Protocols.VAULT.name && params.from === Protocols.EXTENDED.name) {
98117
98945
  const extendedLeverage = calculateExtendedLevergae();
98118
98946
  const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
98119
98947
  if (!extendedHoldings) {
98120
98948
  logger2.error(`error getting extended holdings: ${extendedHoldings}`);
98121
- return {
98122
- calls: [],
98123
- status: false
98124
- };
98949
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
98125
98950
  }
98126
98951
  const extendedHoldingAmount = new Web3Number(
98127
98952
  extendedHoldings.availableForWithdrawal,
98128
98953
  USDC_TOKEN_DECIMALS
98129
98954
  );
98130
- const leftAmountAfterWithdrawalAmountInAccount = params.amount.minus(extendedHoldingAmount);
98131
- const btcAmount = leftAmountAfterWithdrawalAmountInAccount.dividedBy(collateralPrice.price);
98132
- const openLongPosition = await extendedAdapter.createOrder(
98133
- extendedLeverage.toString(),
98134
- btcAmount.toNumber(),
98135
- "BUY" /* BUY */
98136
- );
98137
- if (!openLongPosition) {
98138
- logger2.error(`error opening long position: ${openLongPosition}`);
98139
- return {
98140
- calls: [],
98141
- status: false
98142
- };
98955
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::moveAssets extendedHoldingAmount: ${extendedHoldingAmount.toNumber()}`);
98956
+ if (params.amount.abs().greaterThan(extendedHoldingAmount)) {
98957
+ const leftAmountAfterWithdrawalAmountInAccount = params.amount.abs().minus(extendedHoldingAmount);
98958
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::moveAssets leftAmountAfterWithdrawalAmountInAccount: ${leftAmountAfterWithdrawalAmountInAccount.toNumber()}`);
98959
+ const btcAmount = leftAmountAfterWithdrawalAmountInAccount.dividedBy(collateralPrice.price);
98960
+ const openLongPosition = btcAmount.multipliedBy(3).greaterThan(MINIMUM_EXTENDED_POSITION_SIZE) ? await extendedAdapter.createOrder(
98961
+ extendedLeverage.toString(),
98962
+ btcAmount.toNumber(),
98963
+ "BUY" /* BUY */
98964
+ ) : await extendedAdapter.createOrder(
98965
+ extendedLeverage.toString(),
98966
+ 34e-6,
98967
+ // just in case amount falls short then we need to create a withdrawal
98968
+ "BUY" /* BUY */
98969
+ );
98970
+ if (!openLongPosition) {
98971
+ logger2.error(`error opening long position: ${openLongPosition}`);
98972
+ }
98973
+ const updatedHoldings = await extendedAdapter.getExtendedDepositAmount();
98974
+ if (!updatedHoldings || new Web3Number(updatedHoldings.availableForWithdrawal, USDC_TOKEN_DECIMALS).lessThan(params.amount.abs())) {
98975
+ logger2.error(`Insufficient balance after opening position. Available: ${updatedHoldings?.availableForWithdrawal}, Needed: ${params.amount.abs()}`);
98976
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
98977
+ }
98143
98978
  }
98144
- await new Promise((resolve) => setTimeout(resolve, 5e3));
98145
- const withdrawalFromExtended = await extendedAdapter.withdrawFromExtended(params.amount);
98146
- if (withdrawalFromExtended) {
98979
+ const {
98980
+ status: withdrawalFromExtendedStatus,
98981
+ receivedTxnHash: withdrawalFromExtendedTxnHash
98982
+ } = await extendedAdapter.withdrawFromExtended(params.amount);
98983
+ logger2.info(`withdrawalFromExtendedStatus: ${withdrawalFromExtendedStatus}, withdrawalFromExtendedTxnHash: ${withdrawalFromExtendedTxnHash}`);
98984
+ if (withdrawalFromExtendedStatus && withdrawalFromExtendedTxnHash) {
98147
98985
  const extendedHoldings2 = await extendedAdapter.getExtendedDepositAmount();
98148
- logger2.info(`extendedHoldings after withdrawal ${extendedHoldings2}`);
98149
- await new Promise((resolve) => setTimeout(resolve, 1e4));
98150
- const calls = await this.moveAssetsToVaultAllocator(params.amount, extendedAdapter);
98151
- if (calls.length > 0) {
98152
- return {
98153
- calls,
98154
- status: true
98155
- };
98986
+ logger2.info(`extendedHoldings after withdrawal ${extendedHoldings2?.availableForWithdrawal}`);
98987
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
98988
+ const { calls, status } = await this.moveAssetsToVaultAllocator(params.amount, extendedAdapter);
98989
+ if (calls.length > 0 && status) {
98990
+ return this.createTransactionResult(calls, true, params, "WITHDRAWAL", params.cycleType);
98991
+ } else {
98992
+ return this.createTransactionResult([], true, params, "WITHDRAWAL", params.cycleType);
98156
98993
  }
98994
+ } else if (withdrawalFromExtendedStatus && !withdrawalFromExtendedTxnHash) {
98995
+ logger2.error("withdrawal from extended successful, but funds didn't get transferred to the wallet");
98996
+ return this.createTransactionResult([], true, params, "WITHDRAWAL", params.cycleType);
98157
98997
  } else {
98158
98998
  logger2.error("withdrawal from extended failed");
98159
- return {
98160
- calls: [],
98161
- status: false
98162
- };
98999
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
98163
99000
  }
98164
99001
  } else if (params.to === Protocols.VAULT.name && params.from === Protocols.VESU.name) {
99002
+ const isPriceDifferenceBetweenAvnuAndExtended = await this.checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter, "close" /* CLOSE */);
99003
+ if (!isPriceDifferenceBetweenAvnuAndExtended) {
99004
+ logger2.warn(`price difference between avnu and extended doesn't fit the range for close position, ${avnuAdapter.config.maximumExtendedPriceDifferenceForSwapClosing}`);
99005
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
99006
+ }
98165
99007
  const vesuAmountInBTC = new Web3Number(
98166
- params.amount.dividedBy(collateralPrice.price).toNumber(),
99008
+ params.amount.dividedBy(collateralPrice.price).toFixed(WBTC_TOKEN_DECIMALS),
98167
99009
  collateralToken.decimals
98168
99010
  );
98169
99011
  const proofsInfo = vesuAdapter.getProofs(false, this.getMerkleTree());
@@ -98181,11 +99023,13 @@ spurious results.`);
98181
99023
  await swapProofsInfo.callConstructor({ amount: vesuAmountInBTC })
98182
99024
  );
98183
99025
  calls.push(swapCall);
98184
- return {
98185
- calls,
98186
- status: true
98187
- };
99026
+ return this.createTransactionResult(calls, true, params, "WITHDRAWAL", params.cycleType);
98188
99027
  } else if (params.to === Protocols.EXTENDED.name && params.from === Protocols.VESU.name) {
99028
+ const isPriceDifferenceBetweenAvnuAndExtended = await this.checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter, "close" /* CLOSE */);
99029
+ if (!isPriceDifferenceBetweenAvnuAndExtended) {
99030
+ logger2.warn(`price difference between avnu and extended doesn't fit the range for close position, ${avnuAdapter.config.maximumExtendedPriceDifferenceForSwapClosing}`);
99031
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
99032
+ }
98189
99033
  const vesuAmountInBTC = new Web3Number(
98190
99034
  params.amount.dividedBy(collateralPrice.price).toNumber(),
98191
99035
  collateralToken.decimals
@@ -98215,131 +99059,32 @@ spurious results.`);
98215
99059
  await proofsInfoDeposit.callConstructor({ amount: params.amount })
98216
99060
  );
98217
99061
  calls.push(callDeposit);
98218
- return {
98219
- calls,
98220
- status: true
98221
- };
99062
+ return this.createTransactionResult(calls, true, params, "DEPOSIT", params.cycleType);
98222
99063
  }
98223
- return {
98224
- calls: [],
98225
- status: false
98226
- };
99064
+ logger2.error(`Unsupported assets movement: ${params.from} to ${params.to}`);
99065
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
98227
99066
  } catch (err2) {
98228
99067
  logger2.error(`error moving assets: ${err2}`);
98229
- return {
98230
- calls: [],
98231
- status: false
98232
- };
99068
+ return this.createTransactionResult([], false, params, "NONE", params.cycleType);
98233
99069
  }
98234
99070
  }
98235
99071
  async handleDeposit() {
98236
99072
  try {
98237
- const vesuAdapter = await this.getVesuAdapter();
98238
- const extendedAdapter = await this.getExtendedAdapter();
98239
- const avnuAdapter = await this.getAvnuAdapter();
98240
- if (!vesuAdapter || !extendedAdapter || !extendedAdapter.client || !avnuAdapter) {
98241
- logger2.error(
98242
- "vesu or extended adapter not found",
98243
- vesuAdapter,
98244
- extendedAdapter
98245
- );
98246
- return {
98247
- extendedAmountInBTC: new Web3Number(0, 0),
98248
- calls: []
98249
- };
98250
- }
98251
- const extendedLeverage = calculateExtendedLevergae();
98252
- const isPriceDifferenceBetweenAvnuAndExtended = await this.checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter);
98253
- if (!isPriceDifferenceBetweenAvnuAndExtended) {
98254
- logger2.error("price difference between avnu and extended doesn't fit the range");
98255
- return {
98256
- extendedAmountInBTC: new Web3Number(0, 0),
98257
- calls: []
98258
- };
98259
- }
98260
- const position = await extendedAdapter.getAllOpenPositions();
98261
- if (!position) {
98262
- logger2.error("error getting extended position", position);
98263
- return {
98264
- extendedAmountInBTC: new Web3Number(0, 0),
98265
- calls: []
98266
- };
98267
- }
98268
- const extendedPositionValue = position.length > 0 ? parseFloat(position[0].value) : 0;
98269
- const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
98270
- if (!extendedHoldings) {
98271
- logger2.error(`error getting extended holdings: ${extendedHoldings}`);
98272
- return {
98273
- extendedAmountInBTC: new Web3Number(0, 0),
98274
- calls: []
98275
- };
98276
- }
98277
- const extendedHoldingAmount = new Web3Number(
98278
- extendedHoldings.availableForWithdrawal,
98279
- USDC_TOKEN_DECIMALS
98280
- );
98281
- const {
98282
- collateralTokenAmount
98283
- } = await vesuAdapter.vesuAdapter.getAssetPrices();
98284
- const { collateralPrice } = await this.getAssetPrices();
98285
- const { vesuAmountInBTC, extendedAmountInBTC } = calculateVesUPositionSizeGivenExtended(
98286
- extendedPositionValue,
98287
- extendedHoldingAmount,
98288
- collateralTokenAmount,
98289
- collateralPrice.price
98290
- );
98291
- logger2.info(`vesuAmountInBTC ${vesuAmountInBTC}, extendedAmountInBTC ${extendedAmountInBTC}`);
98292
- let calls = [];
98293
- if (vesuAmountInBTC.greaterThan(MINIMUM_EXTENDED_POSITION_SIZE)) {
98294
- const proofsInfo = vesuAdapter.getProofs(true, this.getMerkleTree());
98295
- const proofGroups = proofsInfo.proofs;
98296
- const call = this.getManageCall(
98297
- proofGroups,
98298
- await proofsInfo.callConstructor({
98299
- amount: vesuAmountInBTC
98300
- })
98301
- );
98302
- const { amount: wbtcAmountInVaultAllocator } = await this.getUnusedBalanceWBTC();
98303
- if (wbtcAmountInVaultAllocator.lessThan(vesuAmountInBTC)) {
98304
- logger2.info(`WBTC amount in vault allocator is less than vesu amount required in WBTC thus swapping, wbtcAmountInVaultAllocator: ${wbtcAmountInVaultAllocator}, vesuAmountInBTC: ${vesuAmountInBTC}`);
98305
- const swapProofsInfo = avnuAdapter.getProofs(true, this.getMerkleTree());
98306
- const swapProofGroups = swapProofsInfo.proofs;
98307
- const swapCall = this.getManageCall(
98308
- swapProofGroups,
98309
- await swapProofsInfo.callConstructor({
98310
- amount: vesuAmountInBTC
98311
- })
98312
- );
98313
- calls.push(swapCall);
98314
- }
98315
- calls.push(call);
98316
- }
98317
- const shortPosition = extendedAmountInBTC.multipliedBy(3).abs().greaterThan(MINIMUM_EXTENDED_POSITION_SIZE) ? await extendedAdapter.createOrder(
98318
- extendedLeverage.toString(),
98319
- extendedAmountInBTC.toNumber(),
98320
- "SELL" /* SELL */
98321
- ) : null;
98322
- if (!shortPosition && extendedAmountInBTC.multipliedBy(3).abs().greaterThan(MINIMUM_EXTENDED_POSITION_SIZE)) {
98323
- logger2.error(`error creating short position thus no position to be opened on vesu: ${shortPosition}`);
98324
- return {
98325
- extendedAmountInBTC: new Web3Number(0, 0),
98326
- calls: []
98327
- };
98328
- }
98329
- return {
98330
- extendedAmountInBTC,
98331
- calls
98332
- };
99073
+ return this.createTransactionResult([], false, { from: Protocols.VAULT.name, to: Protocols.VAULT.name, amount: new Web3Number(0, 0) }, "NONE", "INVESTMENT" /* INVESTMENT */);
98333
99074
  } catch (err2) {
98334
99075
  logger2.error(`error handling deposit: ${err2}`);
98335
- return {
98336
- extendedAmountInBTC: new Web3Number(0, 0),
98337
- calls: []
98338
- };
98339
- ;
99076
+ return this.createTransactionResult([], false, { from: Protocols.VAULT.name, to: Protocols.VAULT.name, amount: new Web3Number(0, 0) }, "NONE", "INVESTMENT" /* INVESTMENT */);
98340
99077
  }
98341
99078
  }
98342
- async checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter) {
99079
+ /**
99080
+ * Check if the price difference between avnu and extended is within the acceptable range to enhance the position size or close the position
99081
+ * @param extendedAdapter - the extended adapter
99082
+ * @param vesuAdapter - the vesu adapter
99083
+ * @param avnuAdapter - the avnu adapter
99084
+ * @param positionType - the position type (open or close)
99085
+ * @returns true if the price difference is within the acceptable range, false otherwise
99086
+ */
99087
+ async checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter, positionType) {
98343
99088
  const {
98344
99089
  ask,
98345
99090
  bid
@@ -98351,13 +99096,30 @@ spurious results.`);
98351
99096
  logger2.error(`error getting btc price avnu: ${btcPriceAvnu}`);
98352
99097
  return false;
98353
99098
  }
98354
- const priceDifference = price.minus(btcPriceAvnu).toNumber();
98355
- if (priceDifference < MAX_PRICE_DIFFERENCE_BETWEEN_AVNU_AND_EXTENDED && priceDifference > MIN_PRICE_DIFFERENCE_BETWEEN_AVNU_AND_EXTENDED) {
98356
- return true;
99099
+ logger2.info(`price: ${price}`);
99100
+ logger2.info(`btcPriceAvnu: ${btcPriceAvnu}`);
99101
+ const priceDifference = new Web3Number(price.minus(btcPriceAvnu).toFixed(2), 0);
99102
+ logger2.info(`priceDifference: ${priceDifference}`);
99103
+ if (priceDifference.isNegative()) {
99104
+ return false;
99105
+ }
99106
+ if (positionType === "open" /* OPEN */) {
99107
+ logger2.info(`price difference between avnu and extended for open position: ${priceDifference.toNumber()}, minimumExtendedPriceDifferenceForSwapOpen: ${avnuAdapter.config.minimumExtendedPriceDifferenceForSwapOpen}`);
99108
+ const result2 = priceDifference.greaterThanOrEqualTo(avnuAdapter.config.minimumExtendedPriceDifferenceForSwapOpen);
99109
+ logger2.info(`result: ${result2}`);
99110
+ return result2;
99111
+ } else {
99112
+ logger2.info(`price difference between avnu and extended for close position: ${priceDifference.toNumber()}, maximumExtendedPriceDifferenceForSwapClosing: ${avnuAdapter.config.maximumExtendedPriceDifferenceForSwapClosing}`);
99113
+ const result2 = priceDifference.lessThanOrEqualTo(avnuAdapter.config.maximumExtendedPriceDifferenceForSwapClosing);
99114
+ logger2.info(`result: ${result2}`);
99115
+ return result2;
98357
99116
  }
98358
- logger2.error(`price difference between avnu and extended doesn't fit the range, priceDifference: ${priceDifference}`);
98359
- return false;
98360
99117
  }
99118
+ /**
99119
+ * Handle the withdrawal of assets from the vault
99120
+ * @param amount - the amount to withdraw in USDC
99121
+ * @returns the calls to be executed and the status of the calls generated along with the metadata for the calls
99122
+ */
98361
99123
  async handleWithdraw(amount) {
98362
99124
  try {
98363
99125
  const usdcBalanceVaultAllocator = await this.getUnusedBalance();
@@ -98369,12 +99131,8 @@ spurious results.`);
98369
99131
  const withdrawCall2 = await this.getBringLiquidityCall({
98370
99132
  amount: usdcBalanceVaultAllocator.amount
98371
99133
  });
98372
- logger2.info("withdraw call", withdrawCall2);
98373
99134
  calls.push(withdrawCall2);
98374
- return {
98375
- calls,
98376
- status: true
98377
- };
99135
+ return [this.createTransactionResult(calls, true, { from: Protocols.VAULT.name, to: Protocols.NONE.name, amount }, "WITHDRAWAL", "WITHDRAWAL" /* WITHDRAWAL */)];
98378
99136
  }
98379
99137
  const vesuAdapter = await this.getVesuAdapter();
98380
99138
  const extendedAdapter = await this.getExtendedAdapter();
@@ -98383,11 +99141,9 @@ spurious results.`);
98383
99141
  logger2.error(
98384
99142
  `vesu or extended adapter not found: vesuAdapter=${vesuAdapter}, extendedAdapter=${extendedAdapter}`
98385
99143
  );
98386
- return {
98387
- calls,
98388
- status
98389
- };
99144
+ return [this.createTransactionResult(calls, status, { from: Protocols.VAULT.name, to: Protocols.NONE.name, amount }, "NONE", "WITHDRAWAL" /* WITHDRAWAL */)];
98390
99145
  }
99146
+ let transactionResults = [];
98391
99147
  const { collateralTokenAmount } = await vesuAdapter.vesuAdapter.getAssetPrices();
98392
99148
  const {
98393
99149
  collateralPrice
@@ -98396,10 +99152,7 @@ spurious results.`);
98396
99152
  if (!extendedPositon) {
98397
99153
  status = false;
98398
99154
  logger2.error("error getting extended position", extendedPositon);
98399
- return {
98400
- calls,
98401
- status
98402
- };
99155
+ return [this.createTransactionResult(calls, status, { from: Protocols.VAULT.name, to: Protocols.NONE.name, amount }, "NONE", "WITHDRAWAL" /* WITHDRAWAL */)];
98403
99156
  }
98404
99157
  const amountDistributionForWithdrawal = await calculateAmountDistributionForWithdrawal(
98405
99158
  usdcBalanceDifference,
@@ -98412,61 +99165,70 @@ spurious results.`);
98412
99165
  logger2.error(
98413
99166
  `error calculating amount distribution for withdrawal: ${amountDistributionForWithdrawal}`
98414
99167
  );
98415
- return {
98416
- calls,
98417
- status
98418
- };
99168
+ return [this.createTransactionResult(calls, status, { from: Protocols.VAULT.name, to: Protocols.NONE.name, amount }, "NONE", "WITHDRAWAL" /* WITHDRAWAL */)];
98419
99169
  }
98420
99170
  const { vesu_amount, extended_amount } = amountDistributionForWithdrawal;
98421
99171
  if (status && vesu_amount.greaterThan(0)) {
98422
- const { calls: vesuCalls, status: vesuStatus } = await this.moveAssets(
99172
+ const { calls: vesuCalls, status: vesuStatus, transactionMetadata: vesuTransactionMetadata } = await this.moveAssets(
98423
99173
  {
98424
99174
  amount: vesu_amount,
98425
99175
  from: Protocols.VESU.name,
98426
- to: Protocols.VAULT.name
99176
+ to: Protocols.VAULT.name,
99177
+ cycleType: "WITHDRAWAL" /* WITHDRAWAL */
98427
99178
  },
98428
99179
  extendedAdapter,
98429
99180
  vesuAdapter
98430
99181
  );
98431
99182
  status = vesuStatus;
98432
- calls.push(...vesuCalls);
99183
+ transactionResults.push({
99184
+ status: vesuStatus,
99185
+ calls: vesuCalls,
99186
+ transactionMetadata: vesuTransactionMetadata
99187
+ });
98433
99188
  }
98434
99189
  if (status && extended_amount.greaterThan(0)) {
98435
- const { calls: extendedCalls, status: extendedStatus } = await this.moveAssets(
99190
+ const { calls: extendedCalls, status: extendedStatus, transactionMetadata: extendedTransactionMetadata } = await this.moveAssets(
98436
99191
  {
98437
99192
  amount: extended_amount,
98438
99193
  from: Protocols.EXTENDED.name,
98439
- to: Protocols.VAULT.name
99194
+ to: Protocols.VAULT.name,
99195
+ cycleType: "WITHDRAWAL" /* WITHDRAWAL */
98440
99196
  },
98441
99197
  extendedAdapter,
98442
99198
  vesuAdapter
98443
99199
  );
98444
99200
  status = extendedStatus;
98445
99201
  if (status) {
98446
- calls.push(...extendedCalls);
99202
+ transactionResults.push({
99203
+ status: extendedStatus,
99204
+ calls: extendedCalls,
99205
+ transactionMetadata: extendedTransactionMetadata
99206
+ });
98447
99207
  } else {
98448
99208
  logger2.error("error moving assets to vault: extendedStatus: ${extendedStatus}");
98449
- return {
98450
- calls: [],
98451
- status
98452
- };
99209
+ return [this.createTransactionResult([], status, { from: Protocols.VAULT.name, to: Protocols.NONE.name, amount }, "NONE", "WITHDRAWAL" /* WITHDRAWAL */)];
98453
99210
  }
98454
99211
  }
98455
99212
  const withdrawCall = await this.getBringLiquidityCall({
98456
99213
  amount
98457
99214
  });
98458
99215
  logger2.info("withdraw call", withdrawCall);
98459
- calls.push(withdrawCall);
98460
- return {
98461
- calls,
98462
- status
98463
- };
99216
+ transactionResults.push({
99217
+ status,
99218
+ calls: [withdrawCall],
99219
+ transactionMetadata: {
99220
+ protocolFrom: Protocols.VAULT.name,
99221
+ protocolTo: Protocols.NONE.name,
99222
+ transactionType: "WITHDRAWAL",
99223
+ usdAmount: amount.toFixed(),
99224
+ status: "PENDING",
99225
+ cycleType: "WITHDRAWAL" /* WITHDRAWAL */
99226
+ }
99227
+ });
99228
+ return transactionResults;
98464
99229
  } catch (err2) {
98465
99230
  logger2.error(`error handling withdrawal: ${err2}`);
98466
- return {
98467
- calls: [],
98468
- status: false
98469
- };
99231
+ return [this.createTransactionResult([], false, { from: Protocols.VAULT.name, to: Protocols.NONE.name, amount }, "NONE", "WITHDRAWAL" /* WITHDRAWAL */)];
98470
99232
  }
98471
99233
  }
98472
99234
  async getAUM() {
@@ -98513,8 +99275,182 @@ spurious results.`);
98513
99275
  splits: [realAUM, estimatedAUMDelta]
98514
99276
  };
98515
99277
  }
99278
+ async processTransactionDataFromSDK(txnData) {
99279
+ try {
99280
+ const txnsToBeExecuted = txnData.filter((txn) => {
99281
+ return txn.transactionMetadata.transactionType !== "NONE" && txn.transactionMetadata.protocolFrom !== "" && txn.transactionMetadata.protocolTo !== "";
99282
+ });
99283
+ const callsToBeExecutedFinal = txnsToBeExecuted.flatMap((txn) => txn.calls);
99284
+ const txnMetadata = txnsToBeExecuted.map((txn) => txn.transactionMetadata);
99285
+ return { callsToBeExecutedFinal, txnMetadata };
99286
+ } catch (err2) {
99287
+ logger2.error(`error processing transaction data from SDK: ${err2}`);
99288
+ return null;
99289
+ }
99290
+ }
99291
+ async processTransactionMetadata(txnMetadata, extendedIntentFulfilled) {
99292
+ try {
99293
+ const txnMetadataNew = txnMetadata.map((txn) => {
99294
+ const isExtendedProtocol = txn.protocolFrom === Protocols.EXTENDED.name || txn.protocolTo === Protocols.EXTENDED.name;
99295
+ if (isExtendedProtocol) {
99296
+ txn.status = extendedIntentFulfilled ? "COMPLETED" : "PENDING";
99297
+ } else {
99298
+ txn.status = "COMPLETED";
99299
+ }
99300
+ return txn;
99301
+ });
99302
+ return txnMetadataNew;
99303
+ } catch (err2) {
99304
+ logger2.error(`error processing transaction data from SDK: ${err2}`);
99305
+ return null;
99306
+ }
99307
+ }
99308
+ async getMaxBorrowableAmount() {
99309
+ const vesuAdapter = await this.getVesuAdapter();
99310
+ const extendedAdapter = await this.getExtendedAdapter();
99311
+ if (!vesuAdapter || !extendedAdapter) {
99312
+ return new Web3Number(0, 0);
99313
+ }
99314
+ const extendedFundingRate = new Web3Number((await extendedAdapter.getNetAPY()).toFixed(4), 0);
99315
+ const extendedPositions = await extendedAdapter.getAllOpenPositions();
99316
+ if (!extendedPositions || extendedPositions.length === 0) {
99317
+ logger2.info(`no extended positions found`);
99318
+ return new Web3Number(0, 0);
99319
+ }
99320
+ const extendePositionSizeUSD = new Web3Number(extendedPositions[0].value || 0, 0);
99321
+ const vesuPositions = await vesuAdapter.getPositions();
99322
+ const vesuSupplyApy = vesuPositions[0].apy.apy;
99323
+ const vesuCollateralSizeUSD = new Web3Number(vesuPositions[0].usdValue.toFixed(USDC_TOKEN_DECIMALS), USDC_TOKEN_DECIMALS);
99324
+ const vesuDebtSizeUSD = new Web3Number(vesuPositions[1].usdValue.toFixed(USDC_TOKEN_DECIMALS), USDC_TOKEN_DECIMALS);
99325
+ const num1 = extendePositionSizeUSD.multipliedBy(extendedFundingRate);
99326
+ const num2 = vesuCollateralSizeUSD.multipliedBy(vesuSupplyApy);
99327
+ const num3 = vesuDebtSizeUSD.abs();
99328
+ const maxBorrowApy = num1.plus(num2).minus(0.1).dividedBy(num3);
99329
+ const vesuMaxBorrowableAmount = await vesuAdapter.vesuAdapter.getMaxBorrowableByInterestRate(this.config, vesuAdapter.config.debt, maxBorrowApy.toNumber());
99330
+ return new Web3Number(vesuMaxBorrowableAmount.toFixed(USDC_TOKEN_DECIMALS), USDC_TOKEN_DECIMALS);
99331
+ }
99332
+ async getVesuHealthFactors() {
99333
+ const vesuAdapter = await this.getVesuAdapter();
99334
+ const extendedAdapter = await this.getExtendedAdapter();
99335
+ if (!vesuAdapter || !extendedAdapter) {
99336
+ return [0, 0];
99337
+ }
99338
+ const vesuPositions = await vesuAdapter.getPositions();
99339
+ const vesuCollateralSizeUSD = new Web3Number(vesuPositions[0].usdValue.toFixed(USDC_TOKEN_DECIMALS), 0);
99340
+ const vesuDebtSizeUSD = new Web3Number(vesuPositions[1].usdValue.toFixed(USDC_TOKEN_DECIMALS), 0);
99341
+ const actualLtv = vesuDebtSizeUSD.dividedBy(vesuCollateralSizeUSD).abs();
99342
+ logger2.info(`actualLtv: ${actualLtv.toNumber()}`);
99343
+ const maxLtv = new Web3Number(await vesuAdapter.vesuAdapter.getLTVConfig(this.config), 4);
99344
+ const healthFactor = new Web3Number(maxLtv.dividedBy(actualLtv).toFixed(4), 4);
99345
+ logger2.info(`healthFactor: ${healthFactor.toNumber()}`);
99346
+ const extendedBalance = await extendedAdapter.getExtendedDepositAmount();
99347
+ if (!extendedBalance) {
99348
+ return [0, 0];
99349
+ }
99350
+ const extendedLeverage = new Web3Number((Number(extendedBalance.marginRatio) * 100).toFixed(4), 4);
99351
+ logger2.info(`extendedLeverage: ${extendedLeverage.toNumber()}`);
99352
+ return [healthFactor.toNumber(), extendedLeverage.toNumber()];
99353
+ }
99354
+ async netAPY() {
99355
+ const allPositions = [];
99356
+ for (let adapter2 of this.metadata.additionalInfo.adapters) {
99357
+ if (adapter2.adapter.name !== ExtendedAdapter.name) {
99358
+ let positions = await adapter2.adapter.getPositions();
99359
+ if (positions.length > 0) {
99360
+ allPositions.push(...positions);
99361
+ }
99362
+ }
99363
+ }
99364
+ const extendedAdapter = await this.getExtendedAdapter();
99365
+ if (!extendedAdapter) {
99366
+ return {
99367
+ net: 0,
99368
+ splits: []
99369
+ };
99370
+ }
99371
+ let vesuPositions = allPositions.filter((item) => item.protocol === Protocols.VESU);
99372
+ vesuPositions.map((item) => {
99373
+ item.apy.apy = item.apy.apy * 0.1;
99374
+ });
99375
+ const extendedPositions = await extendedAdapter.getAllOpenPositions();
99376
+ const usdcToken = Global.getDefaultTokens().find((token) => token.symbol === "USDC");
99377
+ if (!extendedPositions || !usdcToken) {
99378
+ return {
99379
+ net: 0,
99380
+ splits: []
99381
+ };
99382
+ }
99383
+ const extendedPosition = extendedPositions[0] || 0;
99384
+ const extendedEquity = (await extendedAdapter.getExtendedDepositAmount())?.equity || 0;
99385
+ const extendedApy = await extendedAdapter.getNetAPY();
99386
+ const totalHoldingsUSDValue = allPositions.reduce((acc, curr) => acc + curr.usdValue, 0) + Number(extendedEquity);
99387
+ console.log(totalHoldingsUSDValue);
99388
+ const extendedPositionSizeMultipliedByApy = Number(extendedPosition.value) * extendedApy;
99389
+ let weightedAPYs = allPositions.reduce((acc, curr) => acc + curr.apy.apy * curr.usdValue, 0) + extendedPositionSizeMultipliedByApy;
99390
+ console.log(weightedAPYs);
99391
+ const netAPY = weightedAPYs / totalHoldingsUSDValue;
99392
+ console.log(netAPY);
99393
+ allPositions.push({
99394
+ tokenInfo: usdcToken,
99395
+ amount: new Web3Number(extendedPosition.size, 0),
99396
+ usdValue: Number(extendedEquity),
99397
+ apy: { apy: extendedApy, type: "base" /* BASE */ },
99398
+ remarks: "finalised" /* FINALISED */,
99399
+ protocol: Protocols.EXTENDED
99400
+ });
99401
+ return {
99402
+ net: netAPY,
99403
+ splits: allPositions.map((p) => ({ apy: p.apy.apy, id: p.remarks ?? "" }))
99404
+ };
99405
+ }
99406
+ async getWalletHoldings() {
99407
+ const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
99408
+ const wbtcToken = Global.getDefaultTokens().find((token) => token.symbol === "WBTC");
99409
+ const usdcToken = Global.getDefaultTokens().find((token) => token.symbol === "USDC");
99410
+ if (!usdceToken || !wbtcToken || !usdcToken) {
99411
+ return [];
99412
+ }
99413
+ const walletAddress = this.metadata.additionalInfo.walletAddress;
99414
+ const usdceWalletBalance = await new ERC20(this.config).balanceOf(
99415
+ usdceToken.address,
99416
+ walletAddress,
99417
+ usdceToken.decimals
99418
+ );
99419
+ const usdcWalletBalance = await new ERC20(this.config).balanceOf(
99420
+ usdcToken.address,
99421
+ walletAddress,
99422
+ usdcToken.decimals
99423
+ );
99424
+ const wbtcWalletBalance = await new ERC20(this.config).balanceOf(
99425
+ wbtcToken.address,
99426
+ walletAddress,
99427
+ wbtcToken.decimals
99428
+ );
99429
+ const price = await this.pricer.getPrice(usdceToken.symbol);
99430
+ const wbtcPrice = await this.pricer.getPrice(wbtcToken.symbol);
99431
+ const usdceUsdValue = Number(usdceWalletBalance.toFixed(usdceToken.decimals)) * price.price;
99432
+ const usdcUsdValue = Number(usdcWalletBalance.toFixed(usdcToken.decimals)) * price.price;
99433
+ const wbtcUsdValue = Number(wbtcWalletBalance.toFixed(wbtcToken.decimals)) * wbtcPrice.price;
99434
+ return [
99435
+ {
99436
+ tokenInfo: usdceToken,
99437
+ amount: usdceWalletBalance,
99438
+ usdValue: usdceUsdValue
99439
+ },
99440
+ {
99441
+ tokenInfo: usdcToken,
99442
+ amount: usdcWalletBalance,
99443
+ usdValue: usdcUsdValue
99444
+ },
99445
+ {
99446
+ tokenInfo: wbtcToken,
99447
+ amount: wbtcWalletBalance,
99448
+ usdValue: wbtcUsdValue
99449
+ }
99450
+ ];
99451
+ }
98516
99452
  };
98517
- function getLooperSettings2(lstSymbol, underlyingSymbol, vaultSettings, pool1, extendedBackendUrl, extendedApiKey, vaultIdExtended) {
99453
+ function getLooperSettings2(lstSymbol, underlyingSymbol, vaultSettings, pool1, extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) {
98518
99454
  vaultSettings.leafAdapters = [];
98519
99455
  const wbtcToken = Global.getDefaultTokens().find(
98520
99456
  (token) => token.symbol === lstSymbol
@@ -98538,7 +99474,9 @@ spurious results.`);
98538
99474
  ...baseAdapterConfig,
98539
99475
  avnuContract: AVNU_MIDDLEWARE,
98540
99476
  slippage: 0.01,
98541
- baseUrl: AVNU_QUOTE_URL
99477
+ baseUrl: AVNU_QUOTE_URL,
99478
+ minimumExtendedPriceDifferenceForSwapOpen,
99479
+ maximumExtendedPriceDifferenceForSwapClosing
98542
99480
  });
98543
99481
  const extendedAdapter = new ExtendedAdapter({
98544
99482
  ...baseAdapterConfig,
@@ -98547,14 +99485,17 @@ spurious results.`);
98547
99485
  ],
98548
99486
  vaultIdExtended,
98549
99487
  extendedContract: EXTENDED_CONTRACT,
98550
- extendedBackendUrl,
98551
- extendedApiKey,
99488
+ extendedBackendWriteUrl,
99489
+ extendedBackendReadUrl,
98552
99490
  extendedTimeout: 3e4,
98553
99491
  extendedRetries: 3,
98554
99492
  extendedBaseUrl: "https://api.starknet.extended.exchange",
98555
99493
  extendedMarketName: "BTC-USD",
98556
99494
  extendedPrecision: 5,
98557
- avnuAdapter
99495
+ avnuAdapter,
99496
+ retryDelayForOrderStatus: minimumExtendedRetriesDelayForOrderStatus ?? 3e3,
99497
+ minimumExtendedMovementAmount: minimumExtendedMovementAmount ?? 5
99498
+ //5 usdcs
98558
99499
  });
98559
99500
  const vesuMultiplyAdapter = new VesuMultiplyAdapter({
98560
99501
  poolId: pool1,
@@ -98567,7 +99508,9 @@ spurious results.`);
98567
99508
  supportedPositions: [
98568
99509
  { asset: wbtcToken, isDebt: false },
98569
99510
  { asset: usdcToken, isDebt: true }
98570
- ]
99511
+ ],
99512
+ minimumVesuMovementAmount: minimumVesuMovementAmount ?? 5
99513
+ //5 usdc
98571
99514
  });
98572
99515
  const unusedBalanceAdapter = new UnusedBalanceAdapter({
98573
99516
  ...baseAdapterConfig
@@ -98663,11 +99606,11 @@ spurious results.`);
98663
99606
  ] });
98664
99607
  }
98665
99608
  var re7UsdcPrimeDevansh = {
98666
- vaultAddress: ContractAddr.from("0x520a2e945dd0762e5284fc1b012f62ca04e238e105eb362d5e0ce208928729d"),
98667
- manager: ContractAddr.from("0x6abe24d31cbc16d7c4acb2421a826f96273e225b4a2d168d91e65123da0bfb9"),
98668
- vaultAllocator: ContractAddr.from("0x6e4f716e22efb164ee4a831233e513f45396ad3be4cff3c07386be0226febed"),
98669
- redeemRequestNFT: ContractAddr.from("0x66060e1874e05506b18e6029188ec49bf231a411ad57642311bbdf3cb22e5f"),
98670
- aumOracle: ContractAddr.from("0x301d883b9b45c76132638e39326b3f464c492599623263d405ec0df991e27ab"),
99609
+ vaultAddress: ContractAddr.from("0x058905be22d6a81792df79425dc9641cf3e1b77f36748631b7d7e5d713a32b55"),
99610
+ manager: ContractAddr.from("0x02648d703783feb2d967cf0520314cb5aa800d69a9426f3e3b317395af44de16"),
99611
+ vaultAllocator: ContractAddr.from("0x07d533c838eab6a4d854dd3aea96a55993fccd35821921970d00bde946b63b6f"),
99612
+ redeemRequestNFT: ContractAddr.from("0x01ef91f08fb99729c00f82fc6e0ece37917bcc43952596c19996259dc8adbbba"),
99613
+ aumOracle: ContractAddr.from("0x030b6acfec162f5d6e72b8a4d2798aedce78fb39de78a8f549f7cd277ae8bc8d"),
98671
99614
  leafAdapters: [],
98672
99615
  adapters: [],
98673
99616
  targetHealthFactor: 1.4,
@@ -98680,14 +99623,15 @@ spurious results.`);
98680
99623
  Global.getDefaultTokens().find((token) => token.symbol === "WBTC").decimals
98681
99624
  ),
98682
99625
  borrowable_assets: [Global.getDefaultTokens().find((token) => token.symbol === "WBTC")],
98683
- minimumWBTCDifferenceForAvnuSwap: MINIMUM_WBTC_DIFFERENCE_FOR_AVNU_SWAP
99626
+ minimumWBTCDifferenceForAvnuSwap: MINIMUM_WBTC_DIFFERENCE_FOR_AVNU_SWAP,
99627
+ walletAddress: WALLET_ADDRESS
98684
99628
  };
98685
- var VesuExtendedTestStrategies = (extendedBackendUrl, extendedApiKey, vaultIdExtended) => {
99629
+ var VesuExtendedTestStrategies = (extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) => {
98686
99630
  return [
98687
- getStrategySettingsVesuExtended("WBTC", "USDC", re7UsdcPrimeDevansh, false, false, extendedBackendUrl, extendedApiKey, vaultIdExtended)
99631
+ getStrategySettingsVesuExtended("WBTC", "USDC", re7UsdcPrimeDevansh, false, false, extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing)
98688
99632
  ];
98689
99633
  };
98690
- function getStrategySettingsVesuExtended(lstSymbol, underlyingSymbol, addresses, isPreview = false, isLST, extendedBackendUrl, extendedApiKey, vaultIdExtended) {
99634
+ function getStrategySettingsVesuExtended(lstSymbol, underlyingSymbol, addresses, isPreview = false, isLST, extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) {
98691
99635
  return {
98692
99636
  name: `Extended Test ${underlyingSymbol}`,
98693
99637
  description: getDescription2(lstSymbol, underlyingSymbol),
@@ -98695,7 +99639,7 @@ spurious results.`);
98695
99639
  launchBlock: 0,
98696
99640
  type: "Other",
98697
99641
  depositTokens: [Global.getDefaultTokens().find((token) => token.symbol === underlyingSymbol)],
98698
- additionalInfo: getLooperSettings2(lstSymbol, underlyingSymbol, addresses, VesuPools.Re7USDCPrime, extendedBackendUrl, extendedApiKey, vaultIdExtended),
99642
+ additionalInfo: getLooperSettings2(lstSymbol, underlyingSymbol, addresses, VesuPools.Re7USDCPrime, extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing),
98699
99643
  risk: {
98700
99644
  riskFactor: _riskFactor3,
98701
99645
  netRisk: _riskFactor3.reduce((acc, curr) => acc + curr.value * curr.weight, 0) / _riskFactor3.reduce((acc, curr) => acc + curr.weight, 0),