@strkfarm/sdk 2.0.0-dev.29 → 2.0.0-dev.30

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.
@@ -64,9 +64,9 @@ var strkfarm_risk_engine = (() => {
64
64
  "use strict";
65
65
  (function(globalObj) {
66
66
  "use strict";
67
- var BigNumber3, isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, notBool = " not a boolean or binary digit", roundingMode = "rounding mode", tooManyDigits = "number type has more than 15 significant digits", ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_", BASE = 1e14, LOG_BASE = 14, MAX_SAFE_INTEGER = 9007199254740991, POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE = 1e7, MAX = 1e9;
67
+ var BigNumber4, isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, notBool = " not a boolean or binary digit", roundingMode = "rounding mode", tooManyDigits = "number type has more than 15 significant digits", ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_", BASE = 1e14, LOG_BASE = 14, MAX_SAFE_INTEGER = 9007199254740991, POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE = 1e7, MAX = 1e9;
68
68
  function constructorFactory(config3) {
69
- var div, parseNumeric, id2 = 0, P = BigNumber4.prototype, ONE = new BigNumber4(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, ERRORS = true, isValidInt = intValidatorWithErrors, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = {
69
+ var div, parseNumeric, id2 = 0, P = BigNumber5.prototype, ONE = new BigNumber5(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, ERRORS = true, isValidInt = intValidatorWithErrors, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = {
70
70
  decimalSeparator: ".",
71
71
  groupSeparator: ",",
72
72
  groupSize: 3,
@@ -75,14 +75,14 @@ var strkfarm_risk_engine = (() => {
75
75
  // non-breaking space
76
76
  fractionGroupSize: 0
77
77
  };
78
- function BigNumber4(n2, b2) {
78
+ function BigNumber5(n2, b2) {
79
79
  var c, e, i, num2, len, str, x = this;
80
- if (!(x instanceof BigNumber4)) {
80
+ if (!(x instanceof BigNumber5)) {
81
81
  if (ERRORS) raise(26, "constructor call without new", n2);
82
- return new BigNumber4(n2, b2);
82
+ return new BigNumber5(n2, b2);
83
83
  }
84
84
  if (b2 == null || !isValidInt(b2, 2, 64, id2, "base")) {
85
- if (n2 instanceof BigNumber4) {
85
+ if (n2 instanceof BigNumber5) {
86
86
  x.s = n2.s;
87
87
  x.e = n2.e;
88
88
  x.c = (n2 = n2.c) ? n2.slice() : n2;
@@ -107,7 +107,7 @@ var strkfarm_risk_engine = (() => {
107
107
  b2 = b2 | 0;
108
108
  str = n2 + "";
109
109
  if (b2 == 10) {
110
- x = new BigNumber4(n2 instanceof BigNumber4 ? n2 : str);
110
+ x = new BigNumber5(n2 instanceof BigNumber5 ? n2 : str);
111
111
  return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);
112
112
  }
113
113
  if ((num2 = typeof n2 == "number") && n2 * 0 != 0 || !new RegExp("^-?" + (c = "[" + ALPHABET.slice(0, b2) + "]+") + "(?:\\." + c + ")?$", b2 < 37 ? "i" : "").test(str)) {
@@ -168,18 +168,18 @@ var strkfarm_risk_engine = (() => {
168
168
  }
169
169
  id2 = 0;
170
170
  }
171
- BigNumber4.another = constructorFactory;
172
- BigNumber4.ROUND_UP = 0;
173
- BigNumber4.ROUND_DOWN = 1;
174
- BigNumber4.ROUND_CEIL = 2;
175
- BigNumber4.ROUND_FLOOR = 3;
176
- BigNumber4.ROUND_HALF_UP = 4;
177
- BigNumber4.ROUND_HALF_DOWN = 5;
178
- BigNumber4.ROUND_HALF_EVEN = 6;
179
- BigNumber4.ROUND_HALF_CEIL = 7;
180
- BigNumber4.ROUND_HALF_FLOOR = 8;
181
- BigNumber4.EUCLID = 9;
182
- BigNumber4.config = BigNumber4.set = function() {
171
+ BigNumber5.another = constructorFactory;
172
+ BigNumber5.ROUND_UP = 0;
173
+ BigNumber5.ROUND_DOWN = 1;
174
+ BigNumber5.ROUND_CEIL = 2;
175
+ BigNumber5.ROUND_FLOOR = 3;
176
+ BigNumber5.ROUND_HALF_UP = 4;
177
+ BigNumber5.ROUND_HALF_DOWN = 5;
178
+ BigNumber5.ROUND_HALF_EVEN = 6;
179
+ BigNumber5.ROUND_HALF_CEIL = 7;
180
+ BigNumber5.ROUND_HALF_FLOOR = 8;
181
+ BigNumber5.EUCLID = 9;
182
+ BigNumber5.config = BigNumber5.set = function() {
183
183
  var v, p, i = 0, r = {}, a = arguments, o = a[0], has = o && typeof o == "object" ? function() {
184
184
  if (o.hasOwnProperty(p)) return (v = o[p]) != null;
185
185
  } : function() {
@@ -262,13 +262,13 @@ var strkfarm_risk_engine = (() => {
262
262
  r[p] = FORMAT;
263
263
  return r;
264
264
  };
265
- BigNumber4.max = function() {
265
+ BigNumber5.max = function() {
266
266
  return maxOrMin(arguments, P.lt);
267
267
  };
268
- BigNumber4.min = function() {
268
+ BigNumber5.min = function() {
269
269
  return maxOrMin(arguments, P.gt);
270
270
  };
271
- BigNumber4.random = (function() {
271
+ BigNumber5.random = (function() {
272
272
  var pow2_53 = 9007199254740992;
273
273
  var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() {
274
274
  return mathfloor(Math.random() * pow2_53);
@@ -276,7 +276,7 @@ var strkfarm_risk_engine = (() => {
276
276
  return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0);
277
277
  };
278
278
  return function(dp) {
279
- var a, b2, e, k, v, i = 0, c = [], rand = new BigNumber4(ONE);
279
+ var a, b2, e, k, v, i = 0, c = [], rand = new BigNumber5(ONE);
280
280
  dp = dp == null || !isValidInt(dp, 0, MAX, 14) ? DECIMAL_PLACES : dp | 0;
281
281
  k = mathceil(dp / LOG_BASE);
282
282
  if (CRYPTO) {
@@ -343,7 +343,7 @@ var strkfarm_risk_engine = (() => {
343
343
  k = POW_PRECISION;
344
344
  POW_PRECISION = 0;
345
345
  str = str.replace(".", "");
346
- y = new BigNumber4(baseIn);
346
+ y = new BigNumber5(baseIn);
347
347
  x = y.pow(str.length - i);
348
348
  POW_PRECISION = k;
349
349
  y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e), 10, baseOut);
@@ -428,7 +428,7 @@ var strkfarm_risk_engine = (() => {
428
428
  return function(x, y, dp, rm, base2) {
429
429
  var cmp, e, i, more, n2, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c;
430
430
  if (!xc || !xc[0] || !yc || !yc[0]) {
431
- return new BigNumber4(
431
+ return new BigNumber5(
432
432
  // Return NaN if either NaN, or both Infinity or 0.
433
433
  !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : (
434
434
  // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
@@ -436,7 +436,7 @@ var strkfarm_risk_engine = (() => {
436
436
  )
437
437
  );
438
438
  }
439
- q = new BigNumber4(s);
439
+ q = new BigNumber5(s);
440
440
  qc = q.c = [];
441
441
  e = x.e - y.e;
442
442
  s = dp + e + 1;
@@ -540,7 +540,7 @@ var strkfarm_risk_engine = (() => {
540
540
  str = coeffToString(n2.c);
541
541
  str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG ? toExponential(str, ne) : toFixedPoint(str, ne);
542
542
  } else {
543
- n2 = round(new BigNumber4(n2), i, rm);
543
+ n2 = round(new BigNumber5(n2), i, rm);
544
544
  e = n2.e;
545
545
  str = coeffToString(n2.c);
546
546
  len = str.length;
@@ -566,9 +566,9 @@ var strkfarm_risk_engine = (() => {
566
566
  function maxOrMin(args, method) {
567
567
  var m, n2, i = 0;
568
568
  if (isArray3(args[0])) args = args[0];
569
- m = new BigNumber4(args[0]);
569
+ m = new BigNumber5(args[0]);
570
570
  for (; ++i < args.length; ) {
571
- n2 = new BigNumber4(args[i]);
571
+ n2 = new BigNumber5(args[i]);
572
572
  if (!n2.s) {
573
573
  m = n2;
574
574
  break;
@@ -614,7 +614,7 @@ var strkfarm_risk_engine = (() => {
614
614
  base2 = b2;
615
615
  s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1");
616
616
  }
617
- if (str != s) return new BigNumber4(s, base2);
617
+ if (str != s) return new BigNumber5(s, base2);
618
618
  }
619
619
  if (ERRORS) raise(id2, "not a" + (b2 ? " base " + b2 : "") + " number", str);
620
620
  x.s = null;
@@ -771,16 +771,16 @@ var strkfarm_risk_engine = (() => {
771
771
  return x;
772
772
  }
773
773
  P.absoluteValue = P.abs = function() {
774
- var x = new BigNumber4(this);
774
+ var x = new BigNumber5(this);
775
775
  if (x.s < 0) x.s = 1;
776
776
  return x;
777
777
  };
778
778
  P.ceil = function() {
779
- return round(new BigNumber4(this), this.e + 1, 2);
779
+ return round(new BigNumber5(this), this.e + 1, 2);
780
780
  };
781
781
  P.comparedTo = P.cmp = function(y, b2) {
782
782
  id2 = 1;
783
- return compare(this, new BigNumber4(y, b2));
783
+ return compare(this, new BigNumber5(y, b2));
784
784
  };
785
785
  P.decimalPlaces = P.dp = function() {
786
786
  var n2, v, c = this.c;
@@ -792,26 +792,26 @@ var strkfarm_risk_engine = (() => {
792
792
  };
793
793
  P.dividedBy = P.div = function(y, b2) {
794
794
  id2 = 3;
795
- return div(this, new BigNumber4(y, b2), DECIMAL_PLACES, ROUNDING_MODE);
795
+ return div(this, new BigNumber5(y, b2), DECIMAL_PLACES, ROUNDING_MODE);
796
796
  };
797
797
  P.dividedToIntegerBy = P.divToInt = function(y, b2) {
798
798
  id2 = 4;
799
- return div(this, new BigNumber4(y, b2), 0, 1);
799
+ return div(this, new BigNumber5(y, b2), 0, 1);
800
800
  };
801
801
  P.equals = P.eq = function(y, b2) {
802
802
  id2 = 5;
803
- return compare(this, new BigNumber4(y, b2)) === 0;
803
+ return compare(this, new BigNumber5(y, b2)) === 0;
804
804
  };
805
805
  P.floor = function() {
806
- return round(new BigNumber4(this), this.e + 1, 3);
806
+ return round(new BigNumber5(this), this.e + 1, 3);
807
807
  };
808
808
  P.greaterThan = P.gt = function(y, b2) {
809
809
  id2 = 6;
810
- return compare(this, new BigNumber4(y, b2)) > 0;
810
+ return compare(this, new BigNumber5(y, b2)) > 0;
811
811
  };
812
812
  P.greaterThanOrEqualTo = P.gte = function(y, b2) {
813
813
  id2 = 7;
814
- return (b2 = compare(this, new BigNumber4(y, b2))) === 1 || b2 === 0;
814
+ return (b2 = compare(this, new BigNumber5(y, b2))) === 1 || b2 === 0;
815
815
  };
816
816
  P.isFinite = function() {
817
817
  return !!this.c;
@@ -830,27 +830,27 @@ var strkfarm_risk_engine = (() => {
830
830
  };
831
831
  P.lessThan = P.lt = function(y, b2) {
832
832
  id2 = 8;
833
- return compare(this, new BigNumber4(y, b2)) < 0;
833
+ return compare(this, new BigNumber5(y, b2)) < 0;
834
834
  };
835
835
  P.lessThanOrEqualTo = P.lte = function(y, b2) {
836
836
  id2 = 9;
837
- return (b2 = compare(this, new BigNumber4(y, b2))) === -1 || b2 === 0;
837
+ return (b2 = compare(this, new BigNumber5(y, b2))) === -1 || b2 === 0;
838
838
  };
839
839
  P.minus = P.sub = function(y, b2) {
840
840
  var i, j, t, xLTy, x = this, a = x.s;
841
841
  id2 = 10;
842
- y = new BigNumber4(y, b2);
842
+ y = new BigNumber5(y, b2);
843
843
  b2 = y.s;
844
- if (!a || !b2) return new BigNumber4(NaN);
844
+ if (!a || !b2) return new BigNumber5(NaN);
845
845
  if (a != b2) {
846
846
  y.s = -b2;
847
847
  return x.plus(y);
848
848
  }
849
849
  var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
850
850
  if (!xe || !ye) {
851
- if (!xc || !yc) return xc ? (y.s = -b2, y) : new BigNumber4(yc ? x : NaN);
851
+ if (!xc || !yc) return xc ? (y.s = -b2, y) : new BigNumber5(yc ? x : NaN);
852
852
  if (!xc[0] || !yc[0]) {
853
- return yc[0] ? (y.s = -b2, y) : new BigNumber4(xc[0] ? x : (
853
+ return yc[0] ? (y.s = -b2, y) : new BigNumber5(xc[0] ? x : (
854
854
  // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
855
855
  ROUNDING_MODE == 3 ? -0 : 0
856
856
  ));
@@ -902,11 +902,11 @@ var strkfarm_risk_engine = (() => {
902
902
  P.modulo = P.mod = function(y, b2) {
903
903
  var q, s, x = this;
904
904
  id2 = 11;
905
- y = new BigNumber4(y, b2);
905
+ y = new BigNumber5(y, b2);
906
906
  if (!x.c || !y.s || y.c && !y.c[0]) {
907
- return new BigNumber4(NaN);
907
+ return new BigNumber5(NaN);
908
908
  } else if (!y.c || x.c && !x.c[0]) {
909
- return new BigNumber4(x);
909
+ return new BigNumber5(x);
910
910
  }
911
911
  if (MODULO_MODE == 9) {
912
912
  s = y.s;
@@ -920,24 +920,24 @@ var strkfarm_risk_engine = (() => {
920
920
  return x.minus(q.times(y));
921
921
  };
922
922
  P.negated = P.neg = function() {
923
- var x = new BigNumber4(this);
923
+ var x = new BigNumber5(this);
924
924
  x.s = -x.s || null;
925
925
  return x;
926
926
  };
927
927
  P.plus = P.add = function(y, b2) {
928
928
  var t, x = this, a = x.s;
929
929
  id2 = 12;
930
- y = new BigNumber4(y, b2);
930
+ y = new BigNumber5(y, b2);
931
931
  b2 = y.s;
932
- if (!a || !b2) return new BigNumber4(NaN);
932
+ if (!a || !b2) return new BigNumber5(NaN);
933
933
  if (a != b2) {
934
934
  y.s = -b2;
935
935
  return x.minus(y);
936
936
  }
937
937
  var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
938
938
  if (!xe || !ye) {
939
- if (!xc || !yc) return new BigNumber4(a / 0);
940
- if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber4(xc[0] ? x : a * 0);
939
+ if (!xc || !yc) return new BigNumber5(a / 0);
940
+ if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber5(xc[0] ? x : a * 0);
941
941
  }
942
942
  xe = bitFloor(xe);
943
943
  ye = bitFloor(ye);
@@ -984,7 +984,7 @@ var strkfarm_risk_engine = (() => {
984
984
  return n2;
985
985
  };
986
986
  P.round = function(dp, rm) {
987
- var n2 = new BigNumber4(this);
987
+ var n2 = new BigNumber5(this);
988
988
  if (dp == null || isValidInt(dp, 0, MAX, 15)) {
989
989
  round(n2, ~~dp + this.e + 1, rm == null || !isValidInt(rm, 0, 8, 15, roundingMode) ? ROUNDING_MODE : rm | 0);
990
990
  }
@@ -992,12 +992,12 @@ var strkfarm_risk_engine = (() => {
992
992
  };
993
993
  P.shift = function(k) {
994
994
  var n2 = this;
995
- return isValidInt(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, "argument") ? n2.times("1e" + truncate(k)) : new BigNumber4(n2.c && n2.c[0] && (k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER) ? n2.s * (k < 0 ? 0 : 1 / 0) : n2);
995
+ return isValidInt(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, "argument") ? n2.times("1e" + truncate(k)) : new BigNumber5(n2.c && n2.c[0] && (k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER) ? n2.s * (k < 0 ? 0 : 1 / 0) : n2);
996
996
  };
997
997
  P.squareRoot = P.sqrt = function() {
998
- var m, n2, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber4("0.5");
998
+ var m, n2, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber5("0.5");
999
999
  if (s !== 1 || !c || !c[0]) {
1000
- return new BigNumber4(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);
1000
+ return new BigNumber5(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);
1001
1001
  }
1002
1002
  s = Math.sqrt(+x);
1003
1003
  if (s == 0 || s == 1 / 0) {
@@ -1011,9 +1011,9 @@ var strkfarm_risk_engine = (() => {
1011
1011
  n2 = s.toExponential();
1012
1012
  n2 = n2.slice(0, n2.indexOf("e") + 1) + e;
1013
1013
  }
1014
- r = new BigNumber4(n2);
1014
+ r = new BigNumber5(n2);
1015
1015
  } else {
1016
- r = new BigNumber4(s + "");
1016
+ r = new BigNumber5(s + "");
1017
1017
  }
1018
1018
  if (r.c[0]) {
1019
1019
  e = r.e;
@@ -1049,7 +1049,7 @@ var strkfarm_risk_engine = (() => {
1049
1049
  return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);
1050
1050
  };
1051
1051
  P.times = P.mul = function(y, b2) {
1052
- var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base2, sqrtBase, x = this, xc = x.c, yc = (id2 = 17, y = new BigNumber4(y, b2)).c;
1052
+ var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base2, sqrtBase, x = this, xc = x.c, yc = (id2 = 17, y = new BigNumber5(y, b2)).c;
1053
1053
  if (!xc || !yc || !xc[0] || !yc[0]) {
1054
1054
  if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
1055
1055
  y.c = y.e = y.s = null;
@@ -1094,7 +1094,7 @@ var strkfarm_risk_engine = (() => {
1094
1094
  return normalise(y, zc, e);
1095
1095
  };
1096
1096
  P.toDigits = function(sd, rm) {
1097
- var n2 = new BigNumber4(this);
1097
+ var n2 = new BigNumber5(this);
1098
1098
  sd = sd == null || !isValidInt(sd, 1, MAX, 18, "precision") ? null : sd | 0;
1099
1099
  rm = rm == null || !isValidInt(rm, 0, 8, 18, roundingMode) ? ROUNDING_MODE : rm | 0;
1100
1100
  return sd ? round(n2, sd, rm) : n2;
@@ -1132,10 +1132,10 @@ var strkfarm_risk_engine = (() => {
1132
1132
  return str;
1133
1133
  };
1134
1134
  P.toFraction = function(md) {
1135
- var arr, d0, d2, e, exp, n2, n0, q, s, k = ERRORS, x = this, xc = x.c, d = new BigNumber4(ONE), n1 = d0 = new BigNumber4(ONE), d1 = n0 = new BigNumber4(ONE);
1135
+ var arr, d0, d2, e, exp, n2, n0, q, s, k = ERRORS, x = this, xc = x.c, d = new BigNumber5(ONE), n1 = d0 = new BigNumber5(ONE), d1 = n0 = new BigNumber5(ONE);
1136
1136
  if (md != null) {
1137
1137
  ERRORS = false;
1138
- n2 = new BigNumber4(md);
1138
+ n2 = new BigNumber5(md);
1139
1139
  ERRORS = k;
1140
1140
  if (!(k = n2.isInt()) || n2.lt(ONE)) {
1141
1141
  if (ERRORS) {
@@ -1155,7 +1155,7 @@ var strkfarm_risk_engine = (() => {
1155
1155
  md = !md || n2.cmp(d) > 0 ? e > 0 ? d : n1 : n2;
1156
1156
  exp = MAX_EXP;
1157
1157
  MAX_EXP = 1 / 0;
1158
- n2 = new BigNumber4(s);
1158
+ n2 = new BigNumber5(s);
1159
1159
  n0.c[0] = 0;
1160
1160
  for (; ; ) {
1161
1161
  q = div(n2, d, 0, 1);
@@ -1186,11 +1186,11 @@ var strkfarm_risk_engine = (() => {
1186
1186
  var k, y, z, i = mathfloor(n2 < 0 ? -n2 : +n2), x = this;
1187
1187
  if (m != null) {
1188
1188
  id2 = 23;
1189
- m = new BigNumber4(m);
1189
+ m = new BigNumber5(m);
1190
1190
  }
1191
1191
  if (!isValidInt(n2, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, "exponent") && (!isFinite(n2) || i > MAX_SAFE_INTEGER && (n2 /= 0) || parseFloat(n2) != n2 && !(n2 = NaN)) || n2 == 0) {
1192
1192
  k = Math.pow(+x, n2);
1193
- return new BigNumber4(m ? k % m : k);
1193
+ return new BigNumber5(m ? k % m : k);
1194
1194
  }
1195
1195
  if (m) {
1196
1196
  if (n2 > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt()) {
@@ -1202,7 +1202,7 @@ var strkfarm_risk_engine = (() => {
1202
1202
  } else if (POW_PRECISION) {
1203
1203
  k = mathceil(POW_PRECISION / LOG_BASE + 2);
1204
1204
  }
1205
- y = new BigNumber4(ONE);
1205
+ y = new BigNumber5(ONE);
1206
1206
  for (; ; ) {
1207
1207
  if (i % 2) {
1208
1208
  y = y.times(x);
@@ -1250,7 +1250,7 @@ var strkfarm_risk_engine = (() => {
1250
1250
  return str;
1251
1251
  };
1252
1252
  P.truncated = P.trunc = function() {
1253
- return round(new BigNumber4(this), this.e + 1, 1);
1253
+ return round(new BigNumber5(this), this.e + 1, 1);
1254
1254
  };
1255
1255
  P.valueOf = P.toJSON = function() {
1256
1256
  var str, n2 = this, e = n2.e;
@@ -1260,8 +1260,8 @@ var strkfarm_risk_engine = (() => {
1260
1260
  return n2.s < 0 ? "-" + str : str;
1261
1261
  };
1262
1262
  P.isBigNumber = true;
1263
- if (config3 != null) BigNumber4.config(config3);
1264
- return BigNumber4;
1263
+ if (config3 != null) BigNumber5.config(config3);
1264
+ return BigNumber5;
1265
1265
  }
1266
1266
  function bitFloor(n2) {
1267
1267
  var i = n2 | 0;
@@ -1337,17 +1337,17 @@ var strkfarm_risk_engine = (() => {
1337
1337
  n2 = parseFloat(n2);
1338
1338
  return n2 < 0 ? mathceil(n2) : mathfloor(n2);
1339
1339
  }
1340
- BigNumber3 = constructorFactory();
1341
- BigNumber3["default"] = BigNumber3.BigNumber = BigNumber3;
1340
+ BigNumber4 = constructorFactory();
1341
+ BigNumber4["default"] = BigNumber4.BigNumber = BigNumber4;
1342
1342
  if (typeof define == "function" && define.amd) {
1343
1343
  define(function() {
1344
- return BigNumber3;
1344
+ return BigNumber4;
1345
1345
  });
1346
1346
  } else if (typeof module2 != "undefined" && module2.exports) {
1347
- module2.exports = BigNumber3;
1347
+ module2.exports = BigNumber4;
1348
1348
  } else {
1349
1349
  if (!globalObj) globalObj = typeof self != "undefined" ? self : Function("return this")();
1350
- globalObj.BigNumber = BigNumber3;
1350
+ globalObj.BigNumber = BigNumber4;
1351
1351
  }
1352
1352
  })(exports);
1353
1353
  }
@@ -17800,7 +17800,7 @@ ${r2}}` : "}", l2;
17800
17800
  toHexString: () => toHexString2,
17801
17801
  toStorageKey: () => toStorageKey2
17802
17802
  });
17803
- var import_utils162 = require_utils();
17803
+ var import_utils163 = require_utils();
17804
17804
  function isHex3(hex) {
17805
17805
  return /^0x[0-9a-f]*$/i.test(hex);
17806
17806
  }
@@ -17873,7 +17873,7 @@ ${r2}}` : "}", l2;
17873
17873
  if (adaptedValue.length % 2 !== 0) {
17874
17874
  adaptedValue = `0${adaptedValue}`;
17875
17875
  }
17876
- return (0, import_utils162.hexToBytes)(adaptedValue);
17876
+ return (0, import_utils163.hexToBytes)(adaptedValue);
17877
17877
  }
17878
17878
  function addPercent2(number22, percent) {
17879
17879
  const bigIntNum = BigInt(number22);
@@ -93101,7 +93101,7 @@ spurious results.`);
93101
93101
  async _callQuoterApi(fromToken, toToken, amount, retry = 0) {
93102
93102
  try {
93103
93103
  const url = this.ENDPOINT.replace("{{AMOUNT}}", amount.toWei()).replace("{{TOKEN_FROM_ADDRESS}}", fromToken).replace("{{TOKEN_TO_ADDRESS}}", toToken);
93104
- logger2.verbose(`EkuboQuoter::_callQuoterApi url: ${url}`);
93104
+ logger2.info(`EkuboQuoter::_callQuoterApi url: ${url}`);
93105
93105
  const quote = await axios_default.get(url);
93106
93106
  return quote.data;
93107
93107
  } catch (error2) {
@@ -93273,6 +93273,9 @@ spurious results.`);
93273
93273
  }
93274
93274
  };
93275
93275
 
93276
+ // src/modules/ExtendedWrapperSDk/wrapper.ts
93277
+ var import_bignumber5 = __toESM(require_bignumber());
93278
+
93276
93279
  // src/modules/ExtendedWrapperSDk/types.ts
93277
93280
  var OrderSide = /* @__PURE__ */ ((OrderSide2) => {
93278
93281
  OrderSide2["BUY"] = "BUY";
@@ -93357,8 +93360,60 @@ spurious results.`);
93357
93360
  })(AssetOperationStatus || {});
93358
93361
 
93359
93362
  // src/modules/ExtendedWrapperSDk/wrapper.ts
93363
+ function asRecord(v) {
93364
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
93365
+ }
93366
+ function pickTradingConfig(row) {
93367
+ const tc = row.trading_config ?? row.tradingConfig;
93368
+ return asRecord(tc);
93369
+ }
93370
+ function readTcString(tc, snake, camel) {
93371
+ const v = tc[snake] ?? tc[camel];
93372
+ if (v === void 0 || v === null) return void 0;
93373
+ return String(v).trim();
93374
+ }
93375
+ function tradingRulesFromMarketRow(marketName, row) {
93376
+ const r = asRecord(row);
93377
+ if (!r) {
93378
+ throw new Error(`ExtendedWrapper: invalid market payload for ${marketName}`);
93379
+ }
93380
+ const tc = pickTradingConfig(r);
93381
+ if (!tc) {
93382
+ throw new Error(`ExtendedWrapper: missing tradingConfig for market ${marketName}`);
93383
+ }
93384
+ const minS = readTcString(tc, "min_order_size", "minOrderSize");
93385
+ const qtyStep = readTcString(tc, "min_order_size_change", "minOrderSizeChange");
93386
+ const pxStep = readTcString(tc, "min_price_change", "minPriceChange");
93387
+ if (!minS || !qtyStep || !pxStep) {
93388
+ throw new Error(`ExtendedWrapper: incomplete tradingConfig for market ${marketName}`);
93389
+ }
93390
+ const minOrderSize = new import_bignumber5.default(minS);
93391
+ const qty = new import_bignumber5.default(qtyStep);
93392
+ const px = new import_bignumber5.default(pxStep);
93393
+ if (!minOrderSize.isFinite() || minOrderSize.lte(0)) {
93394
+ throw new Error(`ExtendedWrapper: invalid minOrderSize for ${marketName}`);
93395
+ }
93396
+ if (!qty.isFinite() || qty.lte(0)) {
93397
+ throw new Error(`ExtendedWrapper: invalid minOrderSizeChange for ${marketName}`);
93398
+ }
93399
+ if (!px.isFinite() || px.lte(0)) {
93400
+ throw new Error(`ExtendedWrapper: invalid minPriceChange for ${marketName}`);
93401
+ }
93402
+ return { minOrderSize, qtyStep: qty, priceStep: px };
93403
+ }
93404
+ function roundToStepBn(value, step) {
93405
+ if (step.lte(0)) return value;
93406
+ return value.div(step).round(0, import_bignumber5.default.ROUND_HALF_UP).times(step);
93407
+ }
93408
+ function formatBnForApi(bn, step) {
93409
+ const dp = Math.max(step.decimalPlaces() ?? 0, bn.decimalPlaces() ?? 0, 0);
93410
+ return Number(bn.toFixed(Math.min(80, dp))).toString();
93411
+ }
93360
93412
  var ExtendedWrapper = class {
93361
93413
  constructor(config3) {
93414
+ /** Per-market rules from GET /markets (tradingConfig); retained for process lifetime (no TTL). */
93415
+ this.marketTradingRulesCache = /* @__PURE__ */ new Map();
93416
+ this.marketTradingRulesInflight = /* @__PURE__ */ new Map();
93362
93417
  this.apiKey = config3.apiKey;
93363
93418
  this.timeout = config3.timeout || 3e4;
93364
93419
  this.retries = config3.retries || 3;
@@ -93422,13 +93477,75 @@ spurious results.`);
93422
93477
  }
93423
93478
  throw lastError || new Error("Request failed after all retries");
93424
93479
  }
93480
+ async resolveTradingRules(marketName) {
93481
+ const cached = this.marketTradingRulesCache.get(marketName);
93482
+ if (cached) return cached;
93483
+ const existing = this.marketTradingRulesInflight.get(marketName);
93484
+ if (existing) return existing;
93485
+ const inflight = (async () => {
93486
+ const res = await this.getMarkets(marketName);
93487
+ if (res.status !== "OK") {
93488
+ throw new Error(
93489
+ `ExtendedWrapper: getMarkets failed for ${marketName}: ${res.message}`
93490
+ );
93491
+ }
93492
+ const rows = res.data;
93493
+ if (!Array.isArray(rows) || rows.length === 0) {
93494
+ throw new Error(
93495
+ `ExtendedWrapper: empty markets response for ${marketName}`
93496
+ );
93497
+ }
93498
+ const row = rows.find((m) => asRecord(m)?.name === marketName);
93499
+ if (!row) {
93500
+ throw new Error(
93501
+ `ExtendedWrapper: market ${marketName} not found in markets list`
93502
+ );
93503
+ }
93504
+ const rules = tradingRulesFromMarketRow(marketName, row);
93505
+ this.marketTradingRulesCache.set(marketName, rules);
93506
+ return rules;
93507
+ })();
93508
+ this.marketTradingRulesInflight.set(marketName, inflight);
93509
+ void inflight.finally(() => {
93510
+ if (this.marketTradingRulesInflight.get(marketName) === inflight) {
93511
+ this.marketTradingRulesInflight.delete(marketName);
93512
+ }
93513
+ });
93514
+ return inflight;
93515
+ }
93425
93516
  /**
93426
93517
  * Create a new order on Extended Exchange
93427
93518
  */
93428
93519
  async createOrder(request) {
93520
+ const rules = await this.resolveTradingRules(request.market_name);
93521
+ const amountBn = new import_bignumber5.default(String(request.amount).trim());
93522
+ const priceBn = new import_bignumber5.default(String(request.price).trim());
93523
+ if (!amountBn.isFinite() || amountBn.lte(0)) {
93524
+ throw new Error(`ExtendedWrapper: invalid order amount=${request.amount}`);
93525
+ }
93526
+ if (!priceBn.isFinite() || priceBn.lte(0)) {
93527
+ throw new Error(`ExtendedWrapper: invalid order price=${request.price}`);
93528
+ }
93529
+ if (amountBn.lt(rules.minOrderSize)) {
93530
+ throw new Error(
93531
+ `ExtendedWrapper: order amount ${request.amount} is below minOrderSize ${rules.minOrderSize.toFixed()} for ${request.market_name}`
93532
+ );
93533
+ }
93534
+ const adjAmount = roundToStepBn(amountBn, rules.qtyStep);
93535
+ const adjPrice = roundToStepBn(priceBn, rules.priceStep);
93536
+ if (adjAmount.lt(rules.minOrderSize)) {
93537
+ throw new Error(
93538
+ `ExtendedWrapper: amount after tick rounding ${formatBnForApi(adjAmount, rules.qtyStep)} is below minOrderSize ${rules.minOrderSize.toFixed()} (${request.market_name})`
93539
+ );
93540
+ }
93541
+ const payload = {
93542
+ ...request,
93543
+ amount: formatBnForApi(adjAmount, rules.qtyStep),
93544
+ price: formatBnForApi(adjPrice, rules.priceStep)
93545
+ };
93429
93546
  return this.makeRequest("/api/v1/orders", false, {
93430
93547
  method: "POST",
93431
- body: JSON.stringify(request)
93548
+ body: JSON.stringify(payload)
93432
93549
  });
93433
93550
  }
93434
93551
  /**
@@ -95392,6 +95509,7 @@ spurious results.`);
95392
95509
  var CacheClass = class {
95393
95510
  constructor() {
95394
95511
  this.cache = /* @__PURE__ */ new Map();
95512
+ this.isCacheEnabled = true;
95395
95513
  }
95396
95514
  setCache(key, data, ttl = 6e4) {
95397
95515
  const timestamp = Date.now();
@@ -95399,7 +95517,7 @@ spurious results.`);
95399
95517
  }
95400
95518
  getCache(key) {
95401
95519
  const cachedData = this.cache.get(key);
95402
- if (!cachedData || !this.isCacheValid(key)) {
95520
+ if (!cachedData || !this.isCacheValid(key) || !this.isCacheEnabled) {
95403
95521
  return null;
95404
95522
  }
95405
95523
  return cachedData.data;
@@ -95410,6 +95528,12 @@ spurious results.`);
95410
95528
  const { timestamp, ttl } = cachedData;
95411
95529
  return Date.now() - timestamp <= ttl;
95412
95530
  }
95531
+ disableCache() {
95532
+ this.isCacheEnabled = false;
95533
+ }
95534
+ enableCache() {
95535
+ this.isCacheEnabled = true;
95536
+ }
95413
95537
  };
95414
95538
 
95415
95539
  // src/strategies/base-strategy.ts
@@ -116181,7 +116305,7 @@ spurious results.`);
116181
116305
  throw new Error("LTV is 0");
116182
116306
  }
116183
116307
  this.setCache(CACHE_KEY, ltv, 3e5);
116184
- return this.getCache(CACHE_KEY);
116308
+ return ltv;
116185
116309
  }
116186
116310
  async getPositions(config3, blockNumber = "latest") {
116187
116311
  if (!this.pricer) {
@@ -116265,6 +116389,9 @@ spurious results.`);
116265
116389
  debtPrice = (await pricer.getPrice(this.config.debt.priceProxySymbol || this.config.debt.symbol)).price;
116266
116390
  }
116267
116391
  logger2.verbose(`VesuAdapter::getAssetPrices collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`);
116392
+ if (isNaN(collateralPrice) || isNaN(debtPrice) || collateralPrice == 0 || debtPrice == 0) {
116393
+ throw new Error(`VesuAdapter::getAssetPrices collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`);
116394
+ }
116268
116395
  return {
116269
116396
  collateralTokenAmount,
116270
116397
  collateralUSDAmount,
@@ -121897,20 +122024,23 @@ spurious results.`);
121897
122024
  }
121898
122025
  _buildZeroAmountSwapsWithWeights(quote, token, reverseRoutes = false) {
121899
122026
  const swaps = quote.splits.map((split4) => {
121900
- const routeNodes = split4.route.map((_route) => ({
121901
- pool_key: {
121902
- token0: ContractAddr.from(_route.pool_key.token0),
121903
- token1: ContractAddr.from(_route.pool_key.token1),
121904
- fee: _route.pool_key.fee,
121905
- tick_spacing: _route.pool_key.tick_spacing.toString(),
121906
- extension: _route.pool_key.extension
121907
- },
121908
- sqrt_ratio_limit: Web3Number.fromWei(_route.sqrt_ratio_limit, 18),
121909
- skip_ahead: Web3Number.fromWei(_route.skip_ahead, 0)
121910
- }));
121911
- if (reverseRoutes) {
121912
- routeNodes.reverse();
121913
- }
122027
+ let sellToken = token.address;
122028
+ const routeNodes = split4.route.map((_route) => {
122029
+ let isSellToken0 = sellToken.eqString(_route.pool_key.token0);
122030
+ isSellToken0 = reverseRoutes ? !isSellToken0 : isSellToken0;
122031
+ sellToken = isSellToken0 ? ContractAddr.from(_route.pool_key.token1) : ContractAddr.from(_route.pool_key.token0);
122032
+ return {
122033
+ pool_key: {
122034
+ token0: ContractAddr.from(_route.pool_key.token0),
122035
+ token1: ContractAddr.from(_route.pool_key.token1),
122036
+ fee: _route.pool_key.fee,
122037
+ tick_spacing: _route.pool_key.tick_spacing.toString(),
122038
+ extension: _route.pool_key.extension
122039
+ },
122040
+ sqrt_ratio_limit: isSellToken0 ? Web3Number.fromWei(MIN_SQRT_RATIO_LIMIT.toString(), 18) : Web3Number.fromWei(MAX_SQRT_RATIO_LIMIT.toString(), 18),
122041
+ skip_ahead: Web3Number.fromWei(_route.skip_ahead, 0)
122042
+ };
122043
+ });
121914
122044
  return {
121915
122045
  route: routeNodes,
121916
122046
  token_amount: {
@@ -122232,6 +122362,7 @@ spurious results.`);
122232
122362
  collateralToken.address.address,
122233
122363
  requiredAmount
122234
122364
  );
122365
+ logger2.info(`VesuMultiplyAdapter::_getIncreaseCalldata requiredAmount: ${requiredAmount}`);
122235
122366
  if (marginSwapQuote.price_impact > 0.01) {
122236
122367
  throw new Error(
122237
122368
  `VesuMultiplyAdapter: Margin swap price impact too high (${marginSwapQuote.price_impact})`
@@ -122258,7 +122389,7 @@ spurious results.`);
122258
122389
  legLTV,
122259
122390
  dexPrice
122260
122391
  );
122261
- logger2.verbose(
122392
+ logger2.info(
122262
122393
  `${_VesuMultiplyAdapter.name}::_getIncreaseCalldata debtAmount: ${debtAmount}, addedCollateral: ${addedCollateral}`
122263
122394
  );
122264
122395
  let leverSwap = [];
@@ -122276,8 +122407,10 @@ spurious results.`);
122276
122407
  collateralToken.address.address,
122277
122408
  params.leverSwap?.exactOutput?.abs()
122278
122409
  );
122410
+ logger2.info(`VesuMultiplyAdapter::_getIncreaseCalldata amount: ${params.leverSwap?.exactOutput?.abs()}`);
122279
122411
  debtAmount = Web3Number.fromWei(swapQuote.total_calculated, debtToken.decimals).abs();
122280
122412
  }
122413
+ logger2.info(`VesuMultiplyAdapter::_getIncreaseCalldata debtAmount: ${debtAmount}`);
122281
122414
  swapQuote = await ekuboQuoter.getQuoteExactInput(
122282
122415
  debtToken.address.address,
122283
122416
  collateralToken.address.address,
@@ -122304,7 +122437,7 @@ spurious results.`);
122304
122437
  await new Promise((resolve) => setTimeout(resolve, 1e4));
122305
122438
  } else {
122306
122439
  throw new Error(
122307
- `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`
122440
+ `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap, debtAmount=${debtAmount.toNumber()}, collateralPrice=${collateralPrice}, debtPrice=${debtPrice}`
122308
122441
  );
122309
122442
  }
122310
122443
  } catch (error2) {
@@ -123669,14 +123802,6 @@ spurious results.`);
123669
123802
  logger2.error("error initializing client");
123670
123803
  return null;
123671
123804
  }
123672
- const setLeverage = await this.setLeverage(
123673
- leverage,
123674
- this.config.extendedMarketName
123675
- );
123676
- if (!setLeverage) {
123677
- logger2.error("error depositing or setting leverage");
123678
- return null;
123679
- }
123680
123805
  const { ask, bid } = await this.fetchOrderBookFromExtended();
123681
123806
  if (!ask || !bid || ask.lessThanOrEqualTo(0) || bid.lessThanOrEqualTo(0)) {
123682
123807
  logger2.error(
@@ -123816,13 +123941,13 @@ spurious results.`);
123816
123941
  async createExtendedPositon(client, marketName, amount, price, side) {
123817
123942
  try {
123818
123943
  const result2 = side === "SELL" /* SELL */ ? await client.createSellOrder(marketName, amount, price, {
123819
- postOnly: false,
123820
- reduceOnly: false,
123821
- timeInForce: "IOC" /* IOC */
123944
+ post_only: false,
123945
+ reduce_only: false,
123946
+ time_in_force: "IOC" /* IOC */
123822
123947
  }) : await client.createBuyOrder(marketName, amount, price, {
123823
- postOnly: false,
123824
- reduceOnly: true,
123825
- timeInForce: "IOC" /* IOC */
123948
+ post_only: false,
123949
+ reduce_only: true,
123950
+ time_in_force: "IOC" /* IOC */
123826
123951
  });
123827
123952
  if (result2.data.id) {
123828
123953
  const position_id = result2.data.id.toString();
@@ -129274,20 +129399,42 @@ spurious results.`);
129274
129399
  dTransferVesuToExt: a.dTransferVesuToExt + b2.dTransferVesuToExt
129275
129400
  };
129276
129401
  }
129277
- function drawFunds(need, keys, pool) {
129402
+ function routableDrawAmount(avail, need, minRoutable) {
129403
+ if (avail <= 0 || need <= 0) return 0;
129404
+ const raw = Math.min(avail, need);
129405
+ if (raw <= 0) return 0;
129406
+ if (minRoutable <= 0) return raw;
129407
+ return raw > minRoutable ? raw : 0;
129408
+ }
129409
+ function drawFunds(need, keys, pool, minRoutable) {
129278
129410
  const draws = {};
129279
129411
  let unmet = need;
129280
129412
  for (const k of keys) {
129281
129413
  if (unmet <= 0) break;
129282
129414
  const avail = pool[k];
129283
- if (avail <= 0) continue;
129284
- const take = Math.min(avail, unmet);
129415
+ const take = routableDrawAmount(avail, unmet, minRoutable);
129416
+ if (take <= 0) continue;
129285
129417
  draws[k] = take;
129286
129418
  pool[k] -= take;
129287
129419
  unmet -= take;
129288
129420
  }
129289
129421
  return { draws, filled: need - unmet, unmet };
129290
129422
  }
129423
+ function drawExtendedAggregated(need, pool, minRoutable) {
129424
+ const draws = {};
129425
+ if (need <= 0) return { draws, filled: 0, unmet: 0 };
129426
+ const totalCap = Math.max(0, pool.extAvlWithdraw) + Math.max(0, pool.extUpnl);
129427
+ const want = routableDrawAmount(totalCap, need, minRoutable);
129428
+ if (want <= 0) return { draws, filled: 0, unmet: need };
129429
+ const fromAvl = Math.min(Math.max(0, pool.extAvlWithdraw), want);
129430
+ pool.extAvlWithdraw -= fromAvl;
129431
+ const fromUpnl = Math.min(Math.max(0, pool.extUpnl), want - fromAvl);
129432
+ pool.extUpnl -= fromUpnl;
129433
+ if (fromAvl > 0) draws.extAvlWithdraw = fromAvl;
129434
+ if (fromUpnl > 0) draws.extUpnl = fromUpnl;
129435
+ const filled = fromAvl + fromUpnl;
129436
+ return { draws, filled, unmet: need - filled };
129437
+ }
129291
129438
  function sumKeys(draws, keys) {
129292
129439
  return keys.reduce((s, k) => s + (draws[k] ?? 0), 0);
129293
129440
  }
@@ -129298,33 +129445,39 @@ spurious results.`);
129298
129445
  d.dExtAvlWithdraw += sign2 * (draws.extAvlWithdraw ?? 0);
129299
129446
  d.dExtUpnl += sign2 * (draws.extUpnl ?? 0);
129300
129447
  }
129301
- function fixExtMargin(ext, price, pool) {
129448
+ function fixExtMargin(ext, price, pool, config3) {
129302
129449
  const d = emptyDeltas();
129303
129450
  const deficit = computeExtDeficit(ext, price);
129304
129451
  if (deficit <= 0) return { d, unmet: 0 };
129305
- const { draws, filled, unmet } = drawFunds(deficit, ["walletUsd", "vaUsd", "vesuBorrowCapacity"], pool);
129452
+ const minR = config3.minRoutableUsd ?? 0;
129453
+ const { draws, filled, unmet } = drawFunds(deficit, ["walletUsd", "vaUsd", "vesuBorrowCapacity"], pool, minR);
129306
129454
  applyDrawsToDeltas(d, draws, -1);
129307
129455
  d.dExtAvlWithdraw += filled;
129308
129456
  const fromVesu = draws.vesuBorrowCapacity ?? 0;
129309
129457
  if (fromVesu > 0) d.dTransferVesuToExt += fromVesu;
129310
129458
  return { d, unmet };
129311
129459
  }
129312
- function fixVesuMargin(vesu, price, pool, hfBuffer) {
129460
+ function fixVesuMargin(vesu, price, pool, hfBuffer, config3) {
129313
129461
  const d = emptyDeltas();
129314
129462
  const hf = computeVesuHF(vesu, price);
129315
129463
  if (hf >= vesu.targetHF - hfBuffer) return { d, unmet: 0 };
129316
129464
  const repayTokens = computeVesuDebtRepay(vesu, price);
129317
129465
  const repayUsd = repayTokens * vesu.debtPrice;
129318
- const { draws, filled, unmet } = drawFunds(repayUsd, ["vaUsd", "walletUsd", "extAvlWithdraw", "extUpnl"], pool);
129319
- applyDrawsToDeltas(d, draws, -1);
129466
+ const minR = config3.minRoutableUsd ?? 0;
129467
+ const rMain = drawFunds(repayUsd, ["vaUsd", "walletUsd"], pool, minR);
129468
+ applyDrawsToDeltas(d, rMain.draws, -1);
129469
+ const rExt = drawExtendedAggregated(rMain.unmet, pool, minR);
129470
+ applyDrawsToDeltas(d, rExt.draws, -1);
129471
+ const filled = rMain.filled + rExt.filled;
129472
+ const unmet = rExt.unmet;
129320
129473
  d.dVesuDebt -= filled / vesu.debtPrice;
129321
- const fromExt = sumKeys(draws, ["extAvlWithdraw", "extUpnl"]);
129474
+ const fromExt = sumKeys(rExt.draws, ["extAvlWithdraw", "extUpnl"]);
129322
129475
  if (fromExt > 0) d.dTransferVesuToExt -= fromExt;
129323
129476
  return { d, unmet };
129324
129477
  }
129325
129478
  function phase1(ext, vesu, price, pool, config3) {
129326
- const extResult = fixExtMargin(ext, price, pool);
129327
- const vesuResult = fixVesuMargin(vesu, price, pool, config3.hfBuffer);
129479
+ const extResult = fixExtMargin(ext, price, pool, config3);
129480
+ const vesuResult = fixVesuMargin(vesu, price, pool, config3.hfBuffer, config3);
129328
129481
  return {
129329
129482
  deltas: mergeDeltas(extResult.d, vesuResult.d),
129330
129483
  extDeficitRemaining: extResult.unmet,
@@ -129364,26 +129517,31 @@ spurious results.`);
129364
129517
  }
129365
129518
  return Math.max(0, Math.min(fFromExt, fFromVesu));
129366
129519
  }
129367
- function phase2(extPos, vesuPos, extEquity, vesuDebt, vesu, extLev, price, pool, precision) {
129520
+ function phase2(extPos, vesuPos, extEquity, vesuDebt, vesu, extLev, price, pool, config3) {
129368
129521
  const d = emptyDeltas();
129522
+ const precision = config3.positionPrecision;
129523
+ const minR = config3.minRoutableUsd ?? 0;
129369
129524
  const targetLTV = computeVesuTargetLTV(vesu);
129370
129525
  const imbalance = extPos - vesuPos;
129371
129526
  let fundedGrowthBtc = 0;
129372
129527
  if (!isNegligible(imbalance, precision)) {
129373
129528
  if (imbalance > 0) {
129374
129529
  const equityCostUsd = computeVesuGrowthCost(imbalance, vesu, price);
129375
- const { draws, filled } = drawFunds(equityCostUsd, ["vaUsd", "walletUsd", "extAvlWithdraw", "extUpnl"], pool);
129376
- applyDrawsToDeltas(d, draws, -1);
129530
+ const rMain = drawFunds(equityCostUsd, ["vaUsd", "walletUsd"], pool, minR);
129531
+ applyDrawsToDeltas(d, rMain.draws, -1);
129532
+ const rExt = drawExtendedAggregated(rMain.unmet, pool, minR);
129533
+ applyDrawsToDeltas(d, rExt.draws, -1);
129534
+ const filled = rMain.filled + rExt.filled;
129377
129535
  const grownBtc = computeVesuGrowthFromEquity(filled, vesu, price);
129378
129536
  d.dVesuPosition += grownBtc;
129379
129537
  fundedGrowthBtc = grownBtc;
129380
129538
  d.dVesuDebt += computeVesuGrowthDebt(grownBtc, vesu, price);
129381
- const fromExt = sumKeys(draws, ["extAvlWithdraw", "extUpnl"]);
129539
+ const fromExt = sumKeys(rExt.draws, ["extAvlWithdraw", "extUpnl"]);
129382
129540
  if (fromExt > 0) d.dTransferVesuToExt -= fromExt;
129383
129541
  } else {
129384
129542
  const absImbalance = -imbalance;
129385
129543
  const marginCostUsd = absImbalance * price / extLev;
129386
- const { draws, filled } = drawFunds(marginCostUsd, ["walletUsd", "vaUsd", "vesuBorrowCapacity"], pool);
129544
+ const { draws, filled } = drawFunds(marginCostUsd, ["walletUsd", "vaUsd", "vesuBorrowCapacity"], pool, minR);
129387
129545
  applyDrawsToDeltas(d, draws, -1);
129388
129546
  const grownBtc = filled * extLev / price;
129389
129547
  d.dExtPosition += grownBtc;
@@ -129424,6 +129582,7 @@ spurious results.`);
129424
129582
  return d;
129425
129583
  }
129426
129584
  function rebalance(inputs) {
129585
+ logger2.info(`ltv-imbalance-rebalance-math::rebalance inputs=${JSON.stringify(inputs)}`);
129427
129586
  const { ext, vesu, btcPrice, config: config3 } = inputs;
129428
129587
  const pool = { ...inputs.funding };
129429
129588
  const p1 = phase1(ext, vesu, btcPrice, pool, config3);
@@ -129440,7 +129599,7 @@ spurious results.`);
129440
129599
  ext.leverage,
129441
129600
  btcPrice,
129442
129601
  pool,
129443
- config3.positionPrecision
129602
+ config3
129444
129603
  );
129445
129604
  return mergeDeltas(p1.deltas, p2);
129446
129605
  }
@@ -130021,15 +130180,15 @@ spurious results.`);
130021
130180
  return this.vesuPoolStates[0];
130022
130181
  }
130023
130182
  // ── Derived getters (buffered where applicable) ─────────────────────
130024
- /** Buffered VA USD: strategy-asset slot + optional USDC slot. */
130183
+ /** Buffered VA USD: non-stable asset slot (if any) + USDC slot. */
130025
130184
  get vaUsd() {
130026
- return this.bufferedTokenUsd(this.vaultAssetBalance) + this.bufferedTokenUsd(this.vaultUsdcBalance);
130185
+ return this.bufferedTokenUsd(this.vaultUsdcBalance);
130027
130186
  }
130028
130187
  /** Buffered USD in VA strategy-asset bucket only. */
130029
130188
  get vaAssetUsd() {
130030
130189
  return this.bufferedTokenUsd(this.vaultAssetBalance);
130031
130190
  }
130032
- /** Buffered USD in VA USDC bucket (0 when asset === USDC). */
130191
+ /** Buffered USD in VA USDC bucket (includes full VA idle when asset === USDC). */
130033
130192
  get vaUsdcUsd() {
130034
130193
  return this.bufferedTokenUsd(this.vaultUsdcBalance);
130035
130194
  }
@@ -130111,9 +130270,13 @@ spurious results.`);
130111
130270
  get vesuRebalanceFlags() {
130112
130271
  return this.shouldVesuRebalance;
130113
130272
  }
130114
- /** Raw USD in VA (USDC slot + asset slot); spend caps when executing transfers. */
130273
+ /** Raw USD in VA (USDC slot + non-stable asset slot when distinct); spend caps when executing transfers. */
130115
130274
  _vaRawUsd() {
130116
- return this._rawTokenUsd(this.vaultUsdcBalance) + this._rawTokenUsd(this.vaultAssetBalance);
130275
+ return this._rawTokenUsd(this.vaultUsdcBalance);
130276
+ }
130277
+ /** VA liquidity usable for repay / {@link spendVaRawUsd} (matches nominal balances after any {@link applyBuffer} scaling). */
130278
+ get vaRawUsd() {
130279
+ return this._vaRawUsd();
130117
130280
  }
130118
130281
  _walletRawUsd() {
130119
130282
  return this._rawTokenUsd(this.walletBalance);
@@ -130189,7 +130352,7 @@ spurious results.`);
130189
130352
  rem -= fromUsdc;
130190
130353
  }
130191
130354
  if (rem > 0 && this.vaultAssetBalance) {
130192
- this._deductUsdFromTokenBalance(this.vaultAssetBalance, rem);
130355
+ throw new Error(`Not implemented: spendVA with vaultAssetBalance`);
130193
130356
  }
130194
130357
  this._recomputeUnusedBalance();
130195
130358
  logger2.debug(`SolveBudget::spendVA usedRaw=${usedRaw}, vaUsd=${this.vaUsd}, totalUnused=${this.totalUnused}`);
@@ -130199,7 +130362,10 @@ spurious results.`);
130199
130362
  * Spend nominal/raw USD from VA (e.g. Vesu repay, on-chain USDC). Does not apply the safety buffer to the cap.
130200
130363
  */
130201
130364
  spendVaRawUsd(rawUsdDesired) {
130202
- const capRaw = this._rawTokenUsd(this.vaultUsdcBalance) + this._rawTokenUsd(this.vaultAssetBalance);
130365
+ const capRaw = (
130366
+ // this._rawTokenUsd(this.vaultUsdcBalance) + this._rawTokenUsd(this.vaultAssetBalance);
130367
+ this._rawTokenUsd(this.vaultUsdcBalance)
130368
+ );
130203
130369
  const usedRaw = Math.min(capRaw, Math.max(0, rawUsdDesired));
130204
130370
  if (usedRaw <= CASE_THRESHOLD_USD) return 0;
130205
130371
  let rem = usedRaw;
@@ -130209,7 +130375,7 @@ spurious results.`);
130209
130375
  rem -= fromUsdc;
130210
130376
  }
130211
130377
  if (rem > 0 && this.vaultAssetBalance) {
130212
- this._deductUsdFromTokenBalance(this.vaultAssetBalance, rem);
130378
+ throw new Error(`Not implemented: spendVaRawUsd with vaultAssetBalance`);
130213
130379
  }
130214
130380
  this._recomputeUnusedBalance();
130215
130381
  logger2.debug(`SolveBudget::spendVaRawUsd usedRaw=${usedRaw}, vaUsd=${this.vaUsd}, totalUnused=${this.totalUnused}`);
@@ -130224,7 +130390,7 @@ spurious results.`);
130224
130390
  if (this.vaultUsdcBalance) {
130225
130391
  this._addUsdToTokenBalance(this.vaultUsdcBalance, rawUsd);
130226
130392
  } else if (this.vaultAssetBalance) {
130227
- this._addUsdToTokenBalance(this.vaultAssetBalance, rawUsd);
130393
+ throw new Error(`Not implemented: addToVA with vaultAssetBalance`);
130228
130394
  }
130229
130395
  this._recomputeUnusedBalance();
130230
130396
  logger2.debug(`SolveBudget::addToVA rawUsd=${rawUsd}, vaUsd=${this.vaUsd}, totalUnused=${this.totalUnused}`);
@@ -130263,7 +130429,7 @@ spurious results.`);
130263
130429
  if (isSpend) {
130264
130430
  const capRaw = this.extendedBalance?.availableForWithdrawal?.toNumber() ?? 0;
130265
130431
  const useRaw = Math.min(capRaw, desiredRaw);
130266
- if (useRaw <= CASE_THRESHOLD_USD) return 0;
130432
+ if (useRaw <= 0) return 0;
130267
130433
  rawDelta = -useRaw;
130268
130434
  } else {
130269
130435
  rawDelta = desiredRaw;
@@ -130283,7 +130449,7 @@ spurious results.`);
130283
130449
  if (isSpend) {
130284
130450
  const capRaw = this.extendedBalance?.unrealisedPnl?.toNumber() ?? 0;
130285
130451
  const useRaw = Math.min(capRaw, desiredRaw);
130286
- if (useRaw <= CASE_THRESHOLD_USD) return 0;
130452
+ if (useRaw <= 0) return 0;
130287
130453
  rawDelta = -useRaw;
130288
130454
  } else {
130289
130455
  rawDelta = desiredRaw;
@@ -130298,10 +130464,12 @@ spurious results.`);
130298
130464
  return rawDelta;
130299
130465
  }
130300
130466
  spendExtAvailTrade(rawDesired) {
130301
- const used = this._updateExtAvailWithdraw(rawDesired, true);
130302
- const usedUpnl = this._updateExtAvailUpnl(rawDesired, true);
130303
- logger2.debug(`SolveBudget::updateExtAvailTrade rawSum=${used + usedUpnl}, extAvailTrade=${this.extAvailTrade}, totalUnused=${this.totalUnused}`);
130304
- return used + usedUpnl;
130467
+ const usedWd = this._updateExtAvailWithdraw(rawDesired, true);
130468
+ const tookWd = Math.abs(usedWd);
130469
+ const rem = rawDesired - tookWd;
130470
+ const usedUpnl = rem > 0 ? this._updateExtAvailUpnl(rem, true) : 0;
130471
+ logger2.debug(`SolveBudget::updateExtAvailTrade rawSum=${usedWd + usedUpnl}, extAvailTrade=${this.extAvailTrade}, totalUnused=${this.totalUnused}`);
130472
+ return usedWd + usedUpnl;
130305
130473
  }
130306
130474
  // simply reduces available amounts, but maintains equity and balance.
130307
130475
  spendExtAvailTradeToEquityOnly(rawDesired) {
@@ -130621,7 +130789,7 @@ spurious results.`);
130621
130789
  this._fetchExtendedPositions()
130622
130790
  ]);
130623
130791
  logger2.verbose(
130624
- `${this._tag}::_refresh VA asset ${vaultAssetBalance.token.symbol}=$${vaultAssetBalance.usdValue.toFixed(2)}${vaultUsdcBalance ? `, VA USDC=$${vaultUsdcBalance.usdValue.toFixed(2)}` : ""}, wallet=${walletBalance.usdValue}`
130792
+ `${this._tag}::_refresh ${vaultAssetBalance ? `VA asset ${vaultAssetBalance.token.symbol}=$${vaultAssetBalance.usdValue.toFixed(2)}, ` : ""}VA USDC=${vaultUsdcBalance.usdValue.toFixed(2)}, wallet=${walletBalance.usdValue}`
130625
130793
  );
130626
130794
  const unusedBalance = this._computeUnusedBalances(
130627
130795
  vaultAssetBalance,
@@ -130646,23 +130814,28 @@ spurious results.`);
130646
130814
  },
130647
130815
  vesuPoolStates
130648
130816
  });
130817
+ this._budget.logStateSummary();
130649
130818
  const totalUnusedUsd = unusedBalance.reduce(
130650
130819
  (acc, b2) => acc + b2.usdValue,
130651
130820
  0
130652
130821
  );
130653
130822
  logger2.info(
130654
- `${this._tag}::_refresh completed \u2014 unusedBalances: ${unusedBalance.length} tokens, totalUnusedUsd: ${totalUnusedUsd.toFixed(2)}, extendedPositions: ${extendedPositions.length}, vesuPools: ${vesuPoolStates.length} - availableForTrade: ${extendedBalance?.availableForTrade.toNumber()} - availableForWithdrawal: ${extendedBalance?.availableForWithdrawal.toNumber()} - unrealisedPnl: ${extendedBalance?.unrealisedPnl.toNumber()} - extendedBalance::balance: ${extendedBalance?.balance.toNumber()} - extendedBalance::pendingDeposit: ${extendedBalance?.pendingDeposit.toNumber()} - extendedBalance::equity: ${extendedBalance?.equity.toNumber()}`
130823
+ `${this._tag}::_refresh completed \u2014 unusedBalances: ${unusedBalance.length} tokens [${unusedBalance.map((b2) => `${b2.token.symbol}=$${b2.usdValue.toFixed(2)}`).join(", ")}], totalUnusedUsd: ${totalUnusedUsd.toFixed(2)}, extendedPositions: ${extendedPositions.length} [${extendedPositions.map((p) => `${p.instrument}=${p.size.toFixed(6)} ${p.side}, ${p.valueUsd.toFixed(6)} ${p.instrument}`).join(", ")}], vesuPools: ${vesuPoolStates.length} [${vesuPoolStates.map((p) => `${p.poolId.shortString()}=${p.debtAmount.toFixed(6)} ${p.debtToken.symbol}, ${p.collateralAmount.toFixed(6)} ${p.collateralToken.symbol}`).join(", ")}], availableForTrade: ${extendedBalance?.availableForTrade.toNumber()} - availableForWithdrawal: ${extendedBalance?.availableForWithdrawal.toNumber()} - unrealisedPnl: ${extendedBalance?.unrealisedPnl.toNumber()} - extendedBalance::balance: ${extendedBalance?.balance.toNumber()} - extendedBalance::pendingDeposit: ${extendedBalance?.pendingDeposit.toNumber()} - extendedBalance::equity: ${extendedBalance?.equity.toNumber()}`
130655
130824
  );
130656
130825
  }
130657
130826
  // todo add communication check with python server of extended. if not working, throw error in solve function.
130658
- /** True when strategy asset and USDC share one token — VA USDC slot is unused (all in asset balance). */
130827
+ /** True when strategy asset and USDC share one token — VA idle balance is tracked as USDC, not as asset. */
130659
130828
  _vaultAssetAndUsdcAreSameToken() {
130660
130829
  return this._config.assetToken.address.eq(this._config.usdcToken.address);
130661
130830
  }
130662
130831
  /**
130663
- * Reads the {@link StateManagerConfig.assetToken} balance idle in the vault allocator.
130832
+ * Reads idle {@link StateManagerConfig.assetToken} in the vault allocator when it differs from USDC.
130833
+ * When asset and USDC are the same token, returns null (that balance is reported via {@link _fetchVaultAllocatorUsdcBalanceIfDistinct} only).
130664
130834
  */
130665
130835
  async _fetchVaultAllocatorAssetBalance() {
130836
+ if (this._vaultAssetAndUsdcAreSameToken()) {
130837
+ return null;
130838
+ }
130666
130839
  const { assetToken, vaultAllocator, networkConfig, pricer } = this._config;
130667
130840
  const balance = await new ERC20(networkConfig).balanceOf(
130668
130841
  assetToken.address,
@@ -130674,11 +130847,9 @@ spurious results.`);
130674
130847
  return { token: assetToken, amount: balance, usdValue };
130675
130848
  }
130676
130849
  /**
130677
- * Reads {@link StateManagerConfig.usdcToken} in the vault allocator when it differs from
130678
- * {@link StateManagerConfig.assetToken}. Otherwise returns null (treat VA USDC as 0; stablecoin is only under asset).
130850
+ * Reads {@link StateManagerConfig.usdcToken} idle in the vault allocator (always distinct asset or USDC-as-asset).
130679
130851
  */
130680
130852
  async _fetchVaultAllocatorUsdcBalanceIfDistinct() {
130681
- if (this._vaultAssetAndUsdcAreSameToken()) return null;
130682
130853
  const { usdcToken, vaultAllocator, networkConfig, pricer } = this._config;
130683
130854
  const balance = await new ERC20(networkConfig).balanceOf(
130684
130855
  usdcToken.address,
@@ -130692,7 +130863,7 @@ spurious results.`);
130692
130863
  return { token: usdcToken, amount: balance, usdValue };
130693
130864
  }
130694
130865
  /**
130695
- * Merges vault-allocator asset, optional vault-allocator USDC, and operator wallet
130866
+ * Merges vault-allocator asset (if any), vault-allocator USDC, and operator wallet
130696
130867
  * balances into entries keyed by token address.
130697
130868
  */
130698
130869
  _computeUnusedBalances(vaultAssetBalance, vaultUsdcBalance, walletBalance) {
@@ -130704,8 +130875,8 @@ spurious results.`);
130704
130875
  usdValue: tb.usdValue
130705
130876
  });
130706
130877
  };
130707
- put(vaultAssetBalance);
130708
- if (vaultUsdcBalance) put(vaultUsdcBalance);
130878
+ if (vaultAssetBalance) put(vaultAssetBalance);
130879
+ put(vaultUsdcBalance);
130709
130880
  const key = walletBalance.token.address.toString();
130710
130881
  const existing = balanceMap.get(key);
130711
130882
  if (existing) {
@@ -131224,7 +131395,10 @@ spurious results.`);
131224
131395
  // ── ExecutionRoute-building helpers ─────────────────────────────────────────────
131225
131396
  // ── Atomic route builders ────────────────────────────────────────────
131226
131397
  _buildVesuRepayRoutes(totalUsd, routes) {
131227
- const { used, spendsByPool } = this._budget.repayVesuBorrowCapacity(totalUsd);
131398
+ const vaCap = this._budget.vaRawUsd;
131399
+ const repayUsd = Math.min(totalUsd, vaCap);
131400
+ if (repayUsd <= CASE_THRESHOLD_USD) return;
131401
+ const { used, spendsByPool } = this._budget.repayVesuBorrowCapacity(repayUsd);
131228
131402
  for (const route of spendsByPool) {
131229
131403
  routes.push({ type: "VESU_REPAY" /* VESU_REPAY */, ...route, priority: routes.length });
131230
131404
  }
@@ -131318,7 +131492,7 @@ spurious results.`);
131318
131492
  return { routes, remaining: tryAmount };
131319
131493
  }
131320
131494
  _getVAToEXTENDEDRoute(tryAmount, routes, shouldAddWaitRoute = true) {
131321
- const usable = Math.min(tryAmount, this._budget.vaUsd);
131495
+ const usable = Math.min(tryAmount, this._budget.vaUsdcUsd);
131322
131496
  if (usable > CASE_THRESHOLD_USD) {
131323
131497
  const vaUsed = this._budget.spendVA(usable);
131324
131498
  this._budget.addToExtAvailTrade(vaUsed);
@@ -131333,7 +131507,7 @@ spurious results.`);
131333
131507
  }
131334
131508
  _getExtendedToWalletRoute(tryAmount, routes, shouldAddWaitRoute = true) {
131335
131509
  if (tryAmount <= CASE_THRESHOLD_USD) return { routes, remaining: tryAmount };
131336
- const rawCap = this._budget.extAvailWithdraw + this._budget.extAvailUpnl;
131510
+ const rawCap = this._budget.extAvailWithdraw + Math.max(0, this._budget.extAvailUpnl);
131337
131511
  const rawSpend = Math.min(tryAmount, rawCap);
131338
131512
  if (rawSpend <= CASE_THRESHOLD_USD) return { routes, remaining: tryAmount };
131339
131513
  const rawOut = this._budget.spendExtAvailTrade(rawSpend);
@@ -131523,7 +131697,9 @@ spurious results.`);
131523
131697
  * Design: accumulate all ext-to-wallet moves, add transfer routes at the end (principle #3).
131524
131698
  */
131525
131699
  /**
131526
- * Unified LTV classifier. Computes both Vesu repay and Extended margin needs,
131700
+ * Unified LTV / exposure classifier: `rebalance()` drives both LTV (debt, margin,
131701
+ * funding) and Vesu↔Extended position alignment. There is no separate imbalance pass.
131702
+ * Computes both Vesu repay and Extended margin needs,
131527
131703
  * then builds all routes in a single pass with no duplicate transfers.
131528
131704
  *
131529
131705
  * Vesu repay priority: VA > Wallet > ExtAvl > ExtUpnl
@@ -131579,7 +131755,8 @@ spurious results.`);
131579
131755
  },
131580
131756
  config: {
131581
131757
  positionPrecision: COLLATERAL_PRECISION,
131582
- hfBuffer: 0.05
131758
+ hfBuffer: 0.05,
131759
+ minRoutableUsd: CASE_THRESHOLD_USD
131583
131760
  }
131584
131761
  };
131585
131762
  }
@@ -131590,8 +131767,9 @@ spurious results.`);
131590
131767
  }
131591
131768
  /**
131592
131769
  * Turn pure rebalance() deltas into execution routes.
131593
- * Order: Vesu multiply (decrease/increase) → Extended lever → aggregated transfers
131594
- * (REALISE_PNL, EXTENDED_TO_WALLET + WAIT, WALLET_TO_VA, VESU_BORROW, VESU_REPAY, VA_TO_EXTENDED).
131770
+ * Order: Vesu multiply decrease → Extended decrease → aggregated transfers
131771
+ * (REALISE_PNL, EXTENDED_TO_WALLET + WAIT, WALLET_TO_VA, VESU_BORROW, VESU_REPAY, VA_TO_EXTENDED),
131772
+ * then Vesu multiply increase and Extended increase (need VA / Extended funded first).
131595
131773
  */
131596
131774
  _buildLtvRoutesFromRebalanceDeltas(d) {
131597
131775
  const routes = [];
@@ -131603,6 +131781,7 @@ spurious results.`);
131603
131781
  const targetLtv = VesuConfig.targetLtv;
131604
131782
  const btcEps = 10 ** -COLLATERAL_PRECISION;
131605
131783
  let multiplyDebtRepayUsd = 0;
131784
+ logger2.info(`${this._tag}::_buildLtvRoutesFromRebalanceDeltas d=${JSON.stringify(d)}`);
131606
131785
  if (d.dVesuPosition < -btcEps) {
131607
131786
  const xBtc = -d.dVesuPosition;
131608
131787
  const transferUsdFromVesu = Math.max(0, d.dTransferVesuToExt);
@@ -131621,12 +131800,28 @@ spurious results.`);
131621
131800
  if (d.dVesuDebt < 0) {
131622
131801
  const needRepayUsd = -d.dVesuDebt * debtPrice;
131623
131802
  const multiplyRepayUsd = Math.min(needRepayUsd, swapLegMaxRepayUsd);
131803
+ logger2.info(`${this._tag}::_buildLtvRoutesFromRebalanceDeltas ${JSON.stringify({
131804
+ needRepayUsd,
131805
+ multiplyRepayUsd
131806
+ })}`);
131624
131807
  debtTokenDelta = -(multiplyRepayUsd / debtPrice);
131625
131808
  } else {
131626
131809
  debtTokenDelta = -debtUsdFallback;
131627
131810
  }
131628
131811
  const debtAmtW3 = new Web3Number(debtTokenDelta.toFixed(USDC_TOKEN_DECIMALS), USDC_TOKEN_DECIMALS);
131629
131812
  multiplyDebtRepayUsd = Math.abs(debtTokenDelta) * debtPrice;
131813
+ logger2.info(`${this._tag}::_buildLtvRoutesFromRebalanceDeltas ${JSON.stringify({
131814
+ debtTokenDelta,
131815
+ debtUsdFallback,
131816
+ swapLegMaxRepayUsd,
131817
+ xBtc,
131818
+ marginBtc,
131819
+ swappedBtc,
131820
+ transferUsdFromVesu,
131821
+ debtPrice,
131822
+ targetLtv,
131823
+ multiplyDebtRepayUsd
131824
+ })}`);
131630
131825
  routes.push({
131631
131826
  type: "VESU_MULTIPLY_DECREASE_LEVER" /* VESU_MULTIPLY_DECREASE_LEVER */,
131632
131827
  poolId: vesuAdapter.config.poolId,
@@ -131647,19 +131842,68 @@ spurious results.`);
131647
131842
  if (transferUsdFromVesu > CASE_THRESHOLD_USD) {
131648
131843
  this._budget.addToVA(transferUsdFromVesu);
131649
131844
  }
131650
- } else if (d.dVesuPosition > btcEps) {
131845
+ }
131846
+ if (d.dExtPosition < -btcEps) {
131847
+ const amt = new Web3Number(d.dExtPosition.toFixed(COLLATERAL_PRECISION), 8);
131848
+ routes.push({
131849
+ type: "EXTENDED_DECREASE_LEVER" /* EXTENDED_DECREASE_LEVER */,
131850
+ amount: amt,
131851
+ instrument,
131852
+ priority: routes.length
131853
+ });
131854
+ this._budget.applyExtendedExposureDelta(instrument, amt, price);
131855
+ }
131856
+ const negUpnl = Math.min(0, d.dExtUpnl);
131857
+ const negExtAvl = Math.min(0, d.dExtAvlWithdraw);
131858
+ let hadExtendedOut = false;
131859
+ if (negUpnl < -CASE_THRESHOLD_USD) {
131860
+ this._getUpnlRoute(Math.abs(negUpnl), routes);
131861
+ hadExtendedOut = true;
131862
+ }
131863
+ const extToWalletUsd = (negExtAvl < -CASE_THRESHOLD_USD ? Math.abs(negExtAvl) : 0) + (negUpnl < -CASE_THRESHOLD_USD ? Math.abs(negUpnl) : 0);
131864
+ logger2.info(`${this._tag}::_buildLtvRoutesFromRebalanceDeltas extToWalletUsd=${extToWalletUsd}, negExtAvl=${negExtAvl}, negUpnl=${negUpnl}`);
131865
+ if (extToWalletUsd > CASE_THRESHOLD_USD) {
131866
+ this._getExtendedToWalletRoute(extToWalletUsd, routes);
131867
+ hadExtendedOut = true;
131868
+ } else {
131869
+ if (d.dVesuDebt < 0) {
131870
+ d.dVesuDebt += (negExtAvl < 0 && negExtAvl > -CASE_THRESHOLD_USD ? Math.abs(negExtAvl) : 0) + (negUpnl < 0 && negUpnl > -CASE_THRESHOLD_USD ? Math.abs(negUpnl) : 0);
131871
+ }
131872
+ }
131873
+ logger2.info(`${this._tag}::_buildLtvRoutesFromRebalanceDeltas d=${JSON.stringify(d)}`);
131874
+ const walletPull = Math.abs(Math.min(0, d.dWalletUsd));
131875
+ const walletToVaUsd = walletPull + extToWalletUsd;
131876
+ if (walletToVaUsd > CASE_THRESHOLD_USD) {
131877
+ this._getWALLETToVARoute(walletToVaUsd, routes);
131878
+ }
131879
+ if (d.dVesuBorrowCapacity < -CASE_THRESHOLD_USD) {
131880
+ this._buildVesuBorrowRoutes(Math.abs(d.dVesuBorrowCapacity), routes);
131881
+ }
131882
+ const totalDebtRepayUsd = d.dVesuDebt < 0 ? -d.dVesuDebt * debtPrice : 0;
131883
+ logger2.info(`${this._tag}::_buildLtvRoutesFromRebalanceDeltas totalDebtRepayUsd=${totalDebtRepayUsd}`);
131884
+ let standaloneRepayUsd = Math.max(0, totalDebtRepayUsd - multiplyDebtRepayUsd);
131885
+ logger2.info(`${this._tag}::_buildLtvRoutesFromRebalanceDeltas standaloneRepayUsd=${standaloneRepayUsd}`);
131886
+ if (standaloneRepayUsd > this._budget.vaRawUsd) {
131887
+ if (Math.abs(standaloneRepayUsd - this._budget.vaRawUsd) < CASE_THRESHOLD_USD) {
131888
+ standaloneRepayUsd = this._budget.vaRawUsd;
131889
+ } else {
131890
+ throw new Error(`${this._tag}::_buildLtvRoutesFromRebalanceDeltas standaloneRepayUsd=${standaloneRepayUsd} > vaRawUsd=${this._budget.vaRawUsd}`);
131891
+ }
131892
+ }
131893
+ if (standaloneRepayUsd > CASE_THRESHOLD_USD) {
131894
+ this._buildVesuRepayRoutes(standaloneRepayUsd, routes);
131895
+ }
131896
+ const posExtEq = Math.max(0, d.dExtAvlWithdraw);
131897
+ const vaToExtUsd = posExtEq > CASE_THRESHOLD_USD ? posExtEq : 0;
131898
+ if (vaToExtUsd > CASE_THRESHOLD_USD) {
131899
+ this._getVAToEXTENDEDRoute(vaToExtUsd, routes, hadExtendedOut);
131900
+ }
131901
+ if (d.dVesuPosition > btcEps) {
131651
131902
  const vesuDepositAmount = new Web3Number(
131652
131903
  (d.dVesuPosition * price * (1 - targetLtv)).toFixed(USDC_TOKEN_DECIMALS),
131653
131904
  USDC_TOKEN_DECIMALS
131654
131905
  );
131655
131906
  if (vesuDepositAmount.toNumber() > CASE_THRESHOLD_USD) {
131656
- routes.push({
131657
- type: "AVNU_DEPOSIT_SWAP" /* AVNU_DEPOSIT_SWAP */,
131658
- priority: routes.length,
131659
- fromToken: vesuAdapter.config.collateral.symbol,
131660
- fromAmount: vesuDepositAmount,
131661
- toToken: vesuAdapter.config.debt.symbol
131662
- });
131663
131907
  }
131664
131908
  const collateralDelta = new Web3Number(
131665
131909
  d.dVesuPosition.toFixed(COLLATERAL_PRECISION),
@@ -131670,8 +131914,9 @@ spurious results.`);
131670
131914
  new Web3Number(Math.min(availableBorrowCapacity, vesuDepositAmount.toNumber()).toFixed(USDC_TOKEN_DECIMALS), USDC_TOKEN_DECIMALS)
131671
131915
  );
131672
131916
  const collPx = pool.collateralPrice || 1;
131917
+ const marginUsdAmount = externalDepositAmount.toNumber() * (pool.debtPrice ?? 1);
131673
131918
  const swappedAmount = new Web3Number(
131674
- (externalDepositAmount.toNumber() * (pool.debtPrice ?? 1) / collPx).toFixed(6),
131919
+ (marginUsdAmount / collPx).toFixed(6),
131675
131920
  vesuAdapter.config.collateral.decimals
131676
131921
  );
131677
131922
  const debtDeltaTokens = new Web3Number(
@@ -131695,17 +131940,9 @@ spurious results.`);
131695
131940
  collateralDelta,
131696
131941
  debtDeltaTokens
131697
131942
  );
131943
+ this._budget.spendVA(marginUsdAmount);
131698
131944
  }
131699
- if (d.dExtPosition < -btcEps) {
131700
- const amt = new Web3Number(d.dExtPosition.toFixed(COLLATERAL_PRECISION), 8);
131701
- routes.push({
131702
- type: "EXTENDED_DECREASE_LEVER" /* EXTENDED_DECREASE_LEVER */,
131703
- amount: amt,
131704
- instrument,
131705
- priority: routes.length
131706
- });
131707
- this._budget.applyExtendedExposureDelta(instrument, amt, price);
131708
- } else if (d.dExtPosition > btcEps) {
131945
+ if (d.dExtPosition > btcEps) {
131709
131946
  const amt = new Web3Number(d.dExtPosition.toFixed(COLLATERAL_PRECISION), 8);
131710
131947
  routes.push({
131711
131948
  type: "EXTENDED_INCREASE_LEVER" /* EXTENDED_INCREASE_LEVER */,
@@ -131715,36 +131952,6 @@ spurious results.`);
131715
131952
  });
131716
131953
  this._budget.applyExtendedExposureDelta(instrument, amt, price);
131717
131954
  }
131718
- const negUpnl = Math.min(0, d.dExtUpnl);
131719
- const negExtAvl = Math.min(0, d.dExtAvlWithdraw);
131720
- let hadExtendedOut = false;
131721
- if (negUpnl < -CASE_THRESHOLD_USD) {
131722
- this._getUpnlRoute(Math.abs(negUpnl), routes);
131723
- hadExtendedOut = true;
131724
- }
131725
- const extToWalletUsd = (negExtAvl < -CASE_THRESHOLD_USD ? Math.abs(negExtAvl) : 0) + (negUpnl < -CASE_THRESHOLD_USD ? Math.abs(negUpnl) : 0);
131726
- if (extToWalletUsd > CASE_THRESHOLD_USD) {
131727
- this._getExtendedToWalletRoute(extToWalletUsd, routes);
131728
- hadExtendedOut = true;
131729
- }
131730
- const walletPull = Math.abs(Math.min(0, d.dWalletUsd));
131731
- const walletToVaUsd = walletPull + extToWalletUsd;
131732
- if (walletToVaUsd > CASE_THRESHOLD_USD) {
131733
- this._getWALLETToVARoute(walletToVaUsd, routes);
131734
- }
131735
- if (d.dVesuBorrowCapacity < -CASE_THRESHOLD_USD) {
131736
- this._buildVesuBorrowRoutes(Math.abs(d.dVesuBorrowCapacity), routes);
131737
- }
131738
- const totalDebtRepayUsd = d.dVesuDebt < 0 ? -d.dVesuDebt * debtPrice : 0;
131739
- const standaloneRepayUsd = Math.max(0, totalDebtRepayUsd - multiplyDebtRepayUsd);
131740
- if (standaloneRepayUsd > CASE_THRESHOLD_USD) {
131741
- this._buildVesuRepayRoutes(standaloneRepayUsd, routes);
131742
- }
131743
- const posExtEq = Math.max(0, d.dExtAvlWithdraw);
131744
- const vaToExtUsd = posExtEq > CASE_THRESHOLD_USD ? posExtEq : 0;
131745
- if (vaToExtUsd > CASE_THRESHOLD_USD) {
131746
- this._getVAToEXTENDEDRoute(vaToExtUsd, routes, hadExtendedOut);
131747
- }
131748
131955
  return routes;
131749
131956
  }
131750
131957
  // ── LTV Vesu route builders ───────────────────────────────────────────
@@ -131903,48 +132110,76 @@ spurious results.`);
131903
132110
  const extendedTarget = total / (1 + extendedLeverage / vesuLeverage);
131904
132111
  const extendedInitial = extAvlWithdraw + extUpnl;
131905
132112
  let delta = extendedTarget - extendedInitial;
131906
- let dExtAvlWithdraw = 0, dExtUpnl = 0, dVaUsd = 0, dWalletUsd = 0, dVesuBorrowCapacity = 0;
132113
+ let dExtAvlWithdraw = 0, dExtUpnl = 0, dVaUsd = 0, dWalletUsd = 0, dVesuBorrowCapacity = 0, finalVaUsd = vaUsd, finalExtended = extAvlWithdraw + Math.max(extUpnl, 0);
131907
132114
  if (delta > 0) {
131908
132115
  let need = delta;
131909
- const takeWalletUsd = Math.min(walletUsd, need);
132116
+ const eps = CASE_THRESHOLD_USD;
132117
+ const takeWalletUsd = routableDrawAmount(walletUsd, need, eps);
131910
132118
  dWalletUsd -= takeWalletUsd;
131911
132119
  need -= takeWalletUsd;
131912
- const takeVaUsd = Math.min(vaUsd, need);
132120
+ const takeVaUsd = routableDrawAmount(vaUsd, need, eps);
131913
132121
  dVaUsd -= takeVaUsd;
131914
132122
  need -= takeVaUsd;
131915
- const takeVesuBorrowCapacity = Math.min(vesuBorrowCapacity, need);
132123
+ finalVaUsd -= takeVaUsd;
132124
+ finalVaUsd += walletUsd - takeWalletUsd;
132125
+ const takeVesuBorrowCapacity = routableDrawAmount(vesuBorrowCapacity, need, eps);
131916
132126
  dVesuBorrowCapacity -= takeVesuBorrowCapacity;
131917
132127
  need -= takeVesuBorrowCapacity;
132128
+ finalVaUsd += vesuBorrowCapacity - takeVesuBorrowCapacity;
131918
132129
  const received = delta - need;
131919
132130
  const eco1Sum = extAvlWithdraw + extUpnl;
132131
+ finalExtended += received;
131920
132132
  if (eco1Sum >= 0) {
131921
132133
  dExtAvlWithdraw += received;
131922
132134
  } else {
131923
- throw new Error(`${this._tag}: Unexpected case`);
132135
+ const hole = -eco1Sum;
132136
+ const fillUpnl = Math.min(received, hole);
132137
+ dExtUpnl += fillUpnl;
132138
+ dExtAvlWithdraw += received - fillUpnl;
132139
+ finalExtended -= fillUpnl;
131924
132140
  }
131925
- if (need > 0) {
132141
+ if (need > CASE_THRESHOLD_USD) {
131926
132142
  throw new Error(`${this._tag}: Insufficient funds to cover margin needs`);
131927
132143
  }
131928
132144
  } else if (delta < 0) {
131929
132145
  let need = -delta;
131930
- const takeExtAvlWithdraw = Math.min(extAvlWithdraw, need);
132146
+ const takeExtAvlWithdraw = Math.min(Math.max(extAvlWithdraw, 0), need);
131931
132147
  dExtAvlWithdraw -= takeExtAvlWithdraw;
131932
- need -= takeExtAvlWithdraw;
131933
- const takeExtUpnl = Math.min(extUpnl, need);
132148
+ const takeExtUpnl = Math.min(Math.max(extUpnl, 0), need);
131934
132149
  dExtUpnl -= takeExtUpnl;
131935
- need -= takeExtUpnl;
132150
+ const netDrawableAmount = takeExtAvlWithdraw + takeExtUpnl;
132151
+ if (netDrawableAmount > CASE_THRESHOLD_USD) {
132152
+ need -= netDrawableAmount;
132153
+ finalExtended -= netDrawableAmount;
132154
+ }
131936
132155
  const sent = -delta - need;
131937
132156
  const eco2Sum = vaUsd + walletUsd + vesuBorrowCapacity;
132157
+ const netWalletUsd = walletUsd < CASE_THRESHOLD_USD ? 0 : walletUsd;
132158
+ finalVaUsd += sent + netWalletUsd;
131938
132159
  if (eco2Sum >= 0) {
131939
132160
  dWalletUsd += sent;
131940
132161
  } else {
131941
132162
  throw new Error(`${this._tag}: Unexpected case`);
131942
132163
  }
131943
- if (need > 0) {
132164
+ if (need > CASE_THRESHOLD_USD) {
131944
132165
  throw new Error(`${this._tag}: Insufficient funds to cover margin needs`);
131945
132166
  }
131946
132167
  }
131947
- return { dExtAvlWithdraw, dExtUpnl, dVaUsd, dWalletUsd, dVesuBorrowCapacity, isExtendedToVesu: delta < 0 };
132168
+ return { dExtAvlWithdraw, dExtUpnl, dVaUsd, dWalletUsd, dVesuBorrowCapacity, finalVaUsd, finalExtended, isExtendedToVesu: delta < 0 };
132169
+ }
132170
+ _scaleVesuPoolDeltasByFactor(deltas, scale) {
132171
+ if (scale >= 1 - 1e-15) return deltas;
132172
+ return deltas.map((d) => ({
132173
+ ...d,
132174
+ collateralDelta: new Web3Number(
132175
+ (d.collateralDelta.toNumber() * scale).toFixed(COLLATERAL_PRECISION),
132176
+ d.collateralToken.decimals
132177
+ ),
132178
+ debtDelta: new Web3Number(
132179
+ (d.debtDelta.toNumber() * scale).toFixed(USDC_TOKEN_DECIMALS),
132180
+ USDC_TOKEN_DECIMALS
132181
+ )
132182
+ }));
131948
132183
  }
131949
132184
  /**
131950
132185
  * 3. New Deposits / Excess Funds
@@ -131960,6 +132195,11 @@ spurious results.`);
131960
132195
  * Computes allocation split between Vesu and Extended, then sources
131961
132196
  * funds and creates lever-increase routes.
131962
132197
  *
132198
+ * Order: {@link _rebalanceFunds} first → project VA / Extended liquid after the same funding
132199
+ * routes (wallet→VA, borrow→VA, VA→Extended, Extended→wallet→VA) → ideal Vesu/Extended deltas
132200
+ * from distributable split → cap common BTC by min(Vesu fundable, Extended fundable) → scale
132201
+ * Vesu deltas and recompute Extended deltas so both sides stay matched.
132202
+ *
131963
132203
  * Fund flow (single pass — avoid VA→Extended then Extended→wallet round-trips):
131964
132204
  * 1) Treat Vesu borrow headroom that the multiply route will consume as covering
131965
132205
  * part of the Vesu USDC need (no standalone VESU_BORROW for that slice). Cap
@@ -131982,15 +132222,9 @@ spurious results.`);
131982
132222
  withdrawAmount
131983
132223
  );
131984
132224
  if (distributableAmount.toNumber() <= CASE_THRESHOLD_USD) return [];
131985
- const { vesuAllocationUsd, extendedAllocationUsd } = this._computeAllocationSplit(distributableAmount);
131986
- const vesuDeltas = this._computePerPoolCollateralDeltas(
131987
- vesuAllocationUsd
131988
- );
131989
- const extendedPositionDeltas = this._computeExtendedPositionDeltas(vesuDeltas);
131990
- const vesuDepositAmount = this._computeVesuDepositAmount(vesuDeltas);
131991
132225
  const vesuLeverage = calculateVesuLeverage();
131992
132226
  const extendedLeverage = calculateExtendedLevergae();
131993
- const { dExtAvlWithdraw, dExtUpnl, dVaUsd, dWalletUsd, dVesuBorrowCapacity, isExtendedToVesu } = this._rebalanceFunds({
132227
+ const { dExtAvlWithdraw, dExtUpnl, dVaUsd, dWalletUsd, dVesuBorrowCapacity, isExtendedToVesu, finalVaUsd, finalExtended } = this._rebalanceFunds({
131994
132228
  extAvlWithdraw: this._budget.extAvailWithdraw,
131995
132229
  extUpnl: this._budget.extAvailUpnl,
131996
132230
  vaUsd: this._budget.vaUsd,
@@ -131999,6 +132233,23 @@ spurious results.`);
131999
132233
  vesuLeverage,
132000
132234
  extendedLeverage
132001
132235
  });
132236
+ logger2.info(`${this._tag}::_classifyDeposits dExtAvlWithdraw=${dExtAvlWithdraw}, dExtUpnl=${dExtUpnl}, dVaUsd=${dVaUsd}, dWalletUsd=${dWalletUsd}, dVesuBorrowCapacity=${dVesuBorrowCapacity}, isExtendedToVesu=${isExtendedToVesu}, finalVaUsd=${finalVaUsd}`);
132237
+ let vesuDeltas = this._computePerPoolCollateralDeltas(new Web3Number(finalVaUsd.toFixed(USDC_TOKEN_DECIMALS), USDC_TOKEN_DECIMALS));
132238
+ const collateralPrice = this._budget.vesuPools[0]?.collateralPrice ?? 0;
132239
+ const collateralDecimals = this._budget.vesuPools[0]?.collateralToken.decimals ?? 0;
132240
+ let _extendedPositionDelta = new Web3Number((finalExtended * extendedLeverage / collateralPrice).toFixed(USDC_TOKEN_DECIMALS), collateralDecimals).toFixedRoundDown(COLLATERAL_PRECISION);
132241
+ logger2.info(`${this._tag}::_classifyDeposits extendedPositionDelta=${_extendedPositionDelta}`);
132242
+ logger2.info(`${this._tag}::_classifyDeposits vesuDeltas=${JSON.stringify(vesuDeltas)}`);
132243
+ assert3(vesuDeltas.length == 1, "vesuDeltas should have only one delta");
132244
+ const minPositionDelta = Math.min(vesuDeltas[0].collateralDelta.toNumber(), Number(_extendedPositionDelta));
132245
+ logger2.info(`${this._tag}::_classifyDeposits minPositionDelta=${minPositionDelta}`);
132246
+ vesuDeltas[0].collateralDelta = new Web3Number(minPositionDelta.toFixed(COLLATERAL_PRECISION), vesuDeltas[0].collateralDelta.decimals);
132247
+ const extendedPositionDeltas = [{
132248
+ instrument: this._config.extendedAdapter.config.extendedMarketName ?? "BTC-USD",
132249
+ delta: new Web3Number(minPositionDelta.toFixed(COLLATERAL_PRECISION), collateralDecimals)
132250
+ }];
132251
+ const vesuDepositAmount = this._computeVesuDepositAmount(vesuDeltas);
132252
+ logger2.info(`${this._tag}::_classifyDeposits vesuDepositAmount=${vesuDepositAmount}`);
132002
132253
  const routes = [];
132003
132254
  if (isExtendedToVesu) {
132004
132255
  if (dExtUpnl < 0) {
@@ -132026,13 +132277,6 @@ spurious results.`);
132026
132277
  }
132027
132278
  for (const vesuDelta of vesuDeltas) {
132028
132279
  if (!skipAvnuDepositSwap && vesuDepositAmount.toNumber() > CASE_THRESHOLD_USD) {
132029
- routes.push({
132030
- type: "AVNU_DEPOSIT_SWAP" /* AVNU_DEPOSIT_SWAP */,
132031
- priority: routes.length,
132032
- fromToken: vesuDelta.collateralToken.symbol,
132033
- fromAmount: vesuDepositAmount,
132034
- toToken: vesuDelta.debtToken.symbol
132035
- });
132036
132280
  }
132037
132281
  if (vesuDelta.collateralDelta.toNumber() > 0) {
132038
132282
  const availableBorrowCapacity = this._budget.vesuBorrowCapacity;
@@ -133009,14 +133253,6 @@ spurious results.`);
133009
133253
  );
133010
133254
  return this._executeStandardCase(caseEntry, activeRoutes);
133011
133255
  }
133012
- const setLevResult = await this._config.extendedAdapter.setLeverage(calculateExtendedLevergae().toString(), this._config.extendedAdapter.config.extendedMarketName);
133013
- if (!setLevResult) {
133014
- logger2.error(
133015
- `${this._tag}::_executeCoordinatedCase failed to set leverage`
133016
- );
133017
- results.push(this._failureResult(extendedRoute));
133018
- return results;
133019
- }
133020
133256
  const isIncrease = _ExecutionService.INCREASE_EXPOSURE_ROUTES.has(
133021
133257
  extendedRoute.type
133022
133258
  );
@@ -133037,8 +133273,9 @@ spurious results.`);
133037
133273
  onChainCalls = callArrays.flat();
133038
133274
  } catch (err2) {
133039
133275
  logger2.error(
133040
- `${this._tag}::_executeCoordinatedCase on-chain call construction failed: ${err2}`
133276
+ `${this._tag}::_executeCoordinatedCase on-chain call construction failed:`
133041
133277
  );
133278
+ console.error(err2);
133042
133279
  await this._emitEvent("FAILURE" /* FAILURE */, {
133043
133280
  routeSummary: `coordinated on-chain build for case "${caseEntry.case.id}"`,
133044
133281
  error: `${err2}`
@@ -133110,7 +133347,7 @@ spurious results.`);
133110
133347
  }
133111
133348
  const timeoutMs = this._config.extendedFillTimeoutMs ?? DEFAULT_EXTENDED_FILL_TIMEOUT_MS;
133112
133349
  const extResult = await this._executeExtendedLimitOrderWithRecovery(
133113
- btcAmount,
133350
+ Math.abs(btcAmount),
133114
133351
  executionPrice,
133115
133352
  side,
133116
133353
  {
@@ -133638,7 +133875,7 @@ spurious results.`);
133638
133875
  return this._failureResult(route);
133639
133876
  }
133640
133877
  const closeResult = await this._executeExtendedLimitOrderWithRecovery(
133641
- positionToClose.toNumber(),
133878
+ Math.abs(positionToClose.toNumber()),
133642
133879
  midPrice,
133643
133880
  "BUY" /* BUY */
133644
133881
  );
@@ -133656,7 +133893,7 @@ spurious results.`);
133656
133893
  `${this._tag}::_executeRealisePnl reopening ${positionToClose.toNumber()} on ${route.instrument}`
133657
133894
  );
133658
133895
  const reopenResult = await this._executeExtendedLimitOrderWithRecovery(
133659
- positionToClose.toNumber(),
133896
+ Math.abs(positionToClose.toNumber()),
133660
133897
  midPrice,
133661
133898
  "SELL" /* SELL */
133662
133899
  );
@@ -133710,7 +133947,7 @@ spurious results.`);
133710
133947
  return this._failureResult(route);
133711
133948
  }
133712
133949
  const result2 = await this._executeExtendedLimitOrderWithRecovery(
133713
- route.amount.toNumber(),
133950
+ Math.abs(route.amount.toNumber()),
133714
133951
  midPrice,
133715
133952
  "SELL" /* SELL */
133716
133953
  );
@@ -133758,7 +133995,7 @@ spurious results.`);
133758
133995
  return this._failureResult(route);
133759
133996
  }
133760
133997
  const result2 = await this._executeExtendedLimitOrderWithRecovery(
133761
- route.amount.toNumber(),
133998
+ Math.abs(route.amount.toNumber()),
133762
133999
  midPrice,
133763
134000
  "BUY" /* BUY */
133764
134001
  );
@@ -134381,16 +134618,16 @@ spurious results.`);
134381
134618
  ];
134382
134619
  }
134383
134620
  };
134384
- function getLooperSettings3(lstSymbol, underlyingSymbol, vaultSettings, pool1, extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) {
134621
+ function getLooperSettings3(collateralSymbol, underlyingSymbol, vaultSettings, pool1, extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) {
134385
134622
  vaultSettings.leafAdapters = [];
134386
134623
  const wbtcToken = Global.getDefaultTokens().find(
134387
- (token) => token.symbol === lstSymbol
134624
+ (token) => token.symbol === collateralSymbol
134388
134625
  );
134389
134626
  const usdcToken = Global.getDefaultTokens().find(
134390
134627
  (token) => token.symbol === underlyingSymbol
134391
134628
  );
134392
134629
  const baseAdapterConfig = {
134393
- baseToken: wbtcToken,
134630
+ baseToken: usdcToken,
134394
134631
  supportedPositions: [
134395
134632
  { asset: usdcToken, isDebt: true },
134396
134633
  { asset: wbtcToken, isDebt: false }
@@ -134490,7 +134727,7 @@ spurious results.`);
134490
134727
  vaultAddress: vaultSettings.vaultAddress,
134491
134728
  vaultAllocator: vaultSettings.vaultAllocator,
134492
134729
  manager: vaultSettings.manager,
134493
- asset: wbtcToken.address
134730
+ asset: usdcToken.address
134494
134731
  });
134495
134732
  vaultSettings.leafAdapters.push(() => vesuMultiplyAdapter.getDepositLeaf());
134496
134733
  vaultSettings.leafAdapters.push(() => vesuMultiplyAdapter.getWithdrawLeaf());
@@ -134624,6 +134861,39 @@ spurious results.`);
134624
134861
  minimumWBTCDifferenceForAvnuSwap: MINIMUM_WBTC_DIFFERENCE_FOR_AVNU_SWAP,
134625
134862
  walletAddress: "0x024b563C1C7d41B32BF4EFB9F38828508a65Be2d6e25268E9f63F22C5e9E51c5"
134626
134863
  };
134864
+ var pureUsdc = {
134865
+ vaultAddress: ContractAddr.from(
134866
+ "0x745c972db65bdee10022fd875dd328c7f40a90849135b6a0f875a40f3c632ae"
134867
+ ),
134868
+ manager: ContractAddr.from(
134869
+ "0x364e0894edefb616ec090f57f5c0274517fcd98ab276ae1f021c5e962fa1deb"
134870
+ ),
134871
+ vaultAllocator: ContractAddr.from(
134872
+ "0x6fceed28e03a96091877568893df0dd89b9bb80fec30da2b742dacbd5526179"
134873
+ ),
134874
+ redeemRequestNFT: ContractAddr.from(
134875
+ "0x501c2b87728e22c6dfcebe4c0b2b3a9fba5845606e4d59fa7bf591badcbb42"
134876
+ ),
134877
+ aumOracle: ContractAddr.from(
134878
+ "0x6ccd95f5765242695d3c75e1440b1d0b30efac8babb864ce15729977b97cb82"
134879
+ ),
134880
+ leafAdapters: [],
134881
+ adapters: [],
134882
+ targetHealthFactor: 1.4,
134883
+ minHealthFactor: 1.35,
134884
+ underlyingToken: Global.getDefaultTokens().find(
134885
+ (token) => token.symbol === "USDC"
134886
+ ),
134887
+ quoteAmountToFetchPrice: new Web3Number(
134888
+ "0.001",
134889
+ Global.getDefaultTokens().find((token) => token.symbol === "USDC").decimals
134890
+ ),
134891
+ borrowable_assets: [
134892
+ Global.getDefaultTokens().find((token) => token.symbol === "USDC")
134893
+ ],
134894
+ minimumWBTCDifferenceForAvnuSwap: MINIMUM_WBTC_DIFFERENCE_FOR_AVNU_SWAP,
134895
+ walletAddress: "0x058571C23da5FEdd4e36003FAE3fE2fA9782f2692E552f081839142B10770D0B"
134896
+ };
134627
134897
  var VesuExtendedTestStrategies = (extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) => {
134628
134898
  return [
134629
134899
  getStrategySettingsVesuExtended(
@@ -134640,14 +134910,29 @@ spurious results.`);
134640
134910
  minimumExtendedRetriesDelayForOrderStatus,
134641
134911
  minimumExtendedPriceDifferenceForSwapOpen,
134642
134912
  maximumExtendedPriceDifferenceForSwapClosing
134913
+ ),
134914
+ getStrategySettingsVesuExtended(
134915
+ "WBTC",
134916
+ "USDC",
134917
+ pureUsdc,
134918
+ false,
134919
+ false,
134920
+ extendedBackendReadUrl,
134921
+ extendedBackendWriteUrl,
134922
+ vaultIdExtended,
134923
+ minimumExtendedMovementAmount,
134924
+ minimumVesuMovementAmount,
134925
+ minimumExtendedRetriesDelayForOrderStatus,
134926
+ minimumExtendedPriceDifferenceForSwapOpen,
134927
+ maximumExtendedPriceDifferenceForSwapClosing
134643
134928
  )
134644
134929
  ];
134645
134930
  };
134646
- function getStrategySettingsVesuExtended(lstSymbol, underlyingSymbol, addresses, isPreview = false, isLST, extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) {
134931
+ function getStrategySettingsVesuExtended(collateralSymbol, underlyingSymbol, addresses, isPreview = false, isLST, extendedBackendReadUrl, extendedBackendWriteUrl, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) {
134647
134932
  return {
134648
134933
  id: `extended_${underlyingSymbol.toLowerCase()}_test`,
134649
134934
  name: `Extended Test ${underlyingSymbol}`,
134650
- description: getDescription3(lstSymbol, underlyingSymbol),
134935
+ description: getDescription3(collateralSymbol, underlyingSymbol),
134651
134936
  address: addresses.vaultAddress,
134652
134937
  launchBlock: 0,
134653
134938
  type: "Other",
@@ -134661,7 +134946,7 @@ spurious results.`);
134661
134946
  )
134662
134947
  ],
134663
134948
  additionalInfo: getLooperSettings3(
134664
- lstSymbol,
134949
+ collateralSymbol,
134665
134950
  underlyingSymbol,
134666
134951
  addresses,
134667
134952
  VesuPools.Re7USDCPrime,
@@ -134682,8 +134967,8 @@ spurious results.`);
134682
134967
  auditUrl: AUDIT_URL4,
134683
134968
  protocols: [Protocols.ENDUR, Protocols.VESU],
134684
134969
  contractDetails: getContractDetails(addresses),
134685
- faqs: getFAQs2(lstSymbol, underlyingSymbol, isLST),
134686
- investmentSteps: getInvestmentSteps(lstSymbol, underlyingSymbol),
134970
+ faqs: getFAQs2(collateralSymbol, underlyingSymbol, isLST),
134971
+ investmentSteps: getInvestmentSteps(collateralSymbol, underlyingSymbol),
134687
134972
  isPreview,
134688
134973
  apyMethodology: isLST ? "Current annualized APY in terms of base asset of the LST. There is no additional fee taken by Troves on LST APY. We charge a 10% performance fee on the additional gain which is already accounted in the APY shown." : "Current annualized APY in terms of base asset of the Yield Token. There is no additional fee taken by Troves on yield token APY. We charge a 10% performance fee on the additional gain which is already accounted in the APY shown.",
134689
134974
  security: {