@paraswap/dex-lib 2.41.4 → 2.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/.idea/aws.xml +17 -0
  2. package/.idea/codeStyles/Project.xml +19 -0
  3. package/.idea/codeStyles/codeStyleConfig.xml +5 -0
  4. package/.idea/misc.xml +6 -0
  5. package/.idea/modules.xml +8 -0
  6. package/.idea/paraswap-dex-lib.iml +9 -0
  7. package/.idea/vcs.xml +6 -0
  8. package/build/abi/algebra/AlgebraPool.abi.json +727 -0
  9. package/build/abi/curve-v1/StableSwapFRXETH.json +889 -0
  10. package/build/abi/curve-v1/StableSwapWBETH.json +1223 -0
  11. package/build/abi/polygon-migration/PolygonMigration.abi.json +364 -0
  12. package/build/abi/sushiswap-v3/QuoterV2.json +267 -0
  13. package/build/abi/sushiswap-v3/RouterProcessor3.json +289 -0
  14. package/build/abi/uniswap-v3/UniswapV3Quoter.abi.json +193 -0
  15. package/build/abi/uniswap-v3/pancakeswap-v3/PancakeswapV3QuoterV2.abi.json +285 -0
  16. package/build/abi/uniswap-v3/pancakeswap-v3/PancakeswapV3Router.abi.json +583 -0
  17. package/build/abi/wBETH.json +1527 -0
  18. package/build/abi/woo-fi/WooFeeManager.abi.json +318 -0
  19. package/build/abi/woo-fi/WooPP.abi.json +548 -0
  20. package/build/abi/woo-fi/Wooracle.abi.json +260 -0
  21. package/build/config.js +2 -2
  22. package/build/dex/aave-v3/tokens/arbitrum.json +50 -0
  23. package/build/dex/aave-v3/tokens/avalanche.json +74 -0
  24. package/build/dex/aave-v3/tokens/fantom.json +62 -0
  25. package/build/dex/aave-v3/tokens/optimism.json +50 -0
  26. package/build/dex/aave-v3/tokens/polygon.json +116 -0
  27. package/build/dex/algebra/algebra-pool.d.ts +46 -0
  28. package/build/dex/algebra/algebra-pool.js +336 -0
  29. package/build/dex/algebra/algebra-pool.js.map +1 -0
  30. package/build/dex/balancer-v2/LinearMath.d.ts +19 -0
  31. package/build/dex/balancer-v2/LinearMath.js +179 -0
  32. package/build/dex/balancer-v2/LinearMath.js.map +1 -0
  33. package/build/dex/balancer-v2/LinearPool.d.ts +47 -0
  34. package/build/dex/balancer-v2/LinearPool.js +324 -0
  35. package/build/dex/balancer-v2/LinearPool.js.map +1 -0
  36. package/build/dex/balancer-v2/PhantomStablePool.d.ts +47 -0
  37. package/build/dex/balancer-v2/PhantomStablePool.js +294 -0
  38. package/build/dex/balancer-v2/PhantomStablePool.js.map +1 -0
  39. package/build/dex/balancer-v2/StableMath.d.ts +9 -0
  40. package/build/dex/balancer-v2/StableMath.js +272 -0
  41. package/build/dex/balancer-v2/StableMath.js.map +1 -0
  42. package/build/dex/balancer-v2/balancer-v2-pool.d.ts +75 -0
  43. package/build/dex/balancer-v2/balancer-v2-pool.js +417 -0
  44. package/build/dex/balancer-v2/balancer-v2-pool.js.map +1 -0
  45. package/build/dex/curve-v1/pools/frxETHpool.d.ts +7 -0
  46. package/build/dex/curve-v1/pools/frxETHpool.js +27 -0
  47. package/build/dex/curve-v1/pools/frxETHpool.js.map +1 -0
  48. package/build/dex/curve-v1/pools/wbETHpool.d.ts +29 -0
  49. package/build/dex/curve-v1/pools/wbETHpool.js +408 -0
  50. package/build/dex/curve-v1/pools/wbETHpool.js.map +1 -0
  51. package/build/dex/index.js +2 -0
  52. package/build/dex/index.js.map +1 -1
  53. package/build/dex/lighter-v1/abi/erc20.json +222 -0
  54. package/build/dex/lighter-v1/abi/factory.json +291 -0
  55. package/build/dex/lighter-v1/abi/order_book.json +594 -0
  56. package/build/dex/lighter-v1/abi/order_book_helper.json +176 -0
  57. package/build/dex/lighter-v1/abi/router.json +488 -0
  58. package/build/dex/{my-test-dex → lighter-v1}/config.d.ts +1 -1
  59. package/build/dex/lighter-v1/config.js +17 -0
  60. package/build/dex/lighter-v1/config.js.map +1 -0
  61. package/build/dex/lighter-v1/constants.d.ts +2 -0
  62. package/build/dex/lighter-v1/constants.js +13 -0
  63. package/build/dex/lighter-v1/constants.js.map +1 -0
  64. package/build/dex/{my-test-dex/my-test-dex-pool.d.ts → lighter-v1/lighter-v1-pool.d.ts} +24 -6
  65. package/build/dex/lighter-v1/lighter-v1-pool.js +310 -0
  66. package/build/dex/lighter-v1/lighter-v1-pool.js.map +1 -0
  67. package/build/dex/{my-test-dex/my-test-dex.d.ts → lighter-v1/lighter-v1.d.ts} +18 -10
  68. package/build/dex/lighter-v1/lighter-v1.js +331 -0
  69. package/build/dex/lighter-v1/lighter-v1.js.map +1 -0
  70. package/build/dex/lighter-v1/types.d.ts +40 -0
  71. package/build/dex/{my-test-dex → lighter-v1}/types.js.map +1 -1
  72. package/build/dex/pancakeswap-v3/types.d.ts +14 -0
  73. package/build/dex/pancakeswap-v3/types.js.map +1 -0
  74. package/build/dex/polygon-migrator/config.d.ts +11 -0
  75. package/build/dex/polygon-migrator/config.js +21 -0
  76. package/build/dex/polygon-migrator/config.js.map +1 -0
  77. package/build/dex/polygon-migrator/constants.d.ts +1 -0
  78. package/build/dex/polygon-migrator/constants.js +5 -0
  79. package/build/dex/polygon-migrator/constants.js.map +1 -0
  80. package/build/dex/polygon-migrator/polygon-migrator.d.ts +48 -0
  81. package/build/dex/polygon-migrator/polygon-migrator.js +109 -0
  82. package/build/dex/polygon-migrator/polygon-migrator.js.map +1 -0
  83. package/build/dex/polygon-migrator/types.d.ts +11 -0
  84. package/build/dex/polygon-migrator/types.js +9 -0
  85. package/build/dex/polygon-migrator/types.js.map +1 -0
  86. package/build/dex/quickswap/camelot-v3.d.ts +6 -0
  87. package/build/dex/quickswap/camelot-v3.js +19 -0
  88. package/build/dex/quickswap/camelot-v3.js.map +1 -0
  89. package/build/dex/quickswap/zyberswap-v3.d.ts +6 -0
  90. package/build/dex/quickswap/zyberswap-v3.js +19 -0
  91. package/build/dex/quickswap/zyberswap-v3.js.map +1 -0
  92. package/build/dex/quickswap-v3.d.ts +21 -0
  93. package/build/dex/quickswap-v3.js +40 -0
  94. package/build/dex/quickswap-v3.js.map +1 -0
  95. package/build/dex/ramses-v2/config.d.ts +4 -0
  96. package/build/dex/ramses-v2/config.js +28 -0
  97. package/build/dex/ramses-v2/config.js.map +1 -0
  98. package/build/dex/ramses-v2/constants.d.ts +28 -0
  99. package/build/dex/ramses-v2/constants.js +35 -0
  100. package/build/dex/ramses-v2/constants.js.map +1 -0
  101. package/build/dex/ramses-v2/contract-math/BitMath.d.ts +4 -0
  102. package/build/dex/ramses-v2/contract-math/BitMath.js +93 -0
  103. package/build/dex/ramses-v2/contract-math/BitMath.js.map +1 -0
  104. package/build/dex/ramses-v2/contract-math/FixedPoint128.d.ts +3 -0
  105. package/build/dex/ramses-v2/contract-math/FixedPoint128.js +8 -0
  106. package/build/dex/ramses-v2/contract-math/FixedPoint128.js.map +1 -0
  107. package/build/dex/ramses-v2/contract-math/FixedPoint96.d.ts +4 -0
  108. package/build/dex/ramses-v2/contract-math/FixedPoint96.js +9 -0
  109. package/build/dex/ramses-v2/contract-math/FixedPoint96.js.map +1 -0
  110. package/build/dex/ramses-v2/contract-math/FullMath.d.ts +4 -0
  111. package/build/dex/ramses-v2/contract-math/FullMath.js +19 -0
  112. package/build/dex/ramses-v2/contract-math/FullMath.js.map +1 -0
  113. package/build/dex/ramses-v2/contract-math/LiquidityMath.d.ts +3 -0
  114. package/build/dex/ramses-v2/contract-math/LiquidityMath.js +22 -0
  115. package/build/dex/ramses-v2/contract-math/LiquidityMath.js.map +1 -0
  116. package/build/dex/ramses-v2/contract-math/Oracle.d.ts +10 -0
  117. package/build/dex/ramses-v2/contract-math/Oracle.js +133 -0
  118. package/build/dex/ramses-v2/contract-math/Oracle.js.map +1 -0
  119. package/build/dex/ramses-v2/contract-math/SqrtPriceMath.d.ts +10 -0
  120. package/build/dex/ramses-v2/contract-math/SqrtPriceMath.js +91 -0
  121. package/build/dex/ramses-v2/contract-math/SqrtPriceMath.js.map +1 -0
  122. package/build/dex/ramses-v2/contract-math/SwapMath.d.ts +8 -0
  123. package/build/dex/ramses-v2/contract-math/SwapMath.js +70 -0
  124. package/build/dex/ramses-v2/contract-math/SwapMath.js.map +1 -0
  125. package/build/dex/ramses-v2/contract-math/Tick.d.ts +7 -0
  126. package/build/dex/ramses-v2/contract-math/Tick.js +45 -0
  127. package/build/dex/ramses-v2/contract-math/Tick.js.map +1 -0
  128. package/build/dex/ramses-v2/contract-math/TickBitMap.d.ts +8 -0
  129. package/build/dex/ramses-v2/contract-math/TickBitMap.js +87 -0
  130. package/build/dex/ramses-v2/contract-math/TickBitMap.js.map +1 -0
  131. package/build/dex/ramses-v2/contract-math/TickMath.d.ts +8 -0
  132. package/build/dex/ramses-v2/contract-math/TickMath.js +162 -0
  133. package/build/dex/ramses-v2/contract-math/TickMath.js.map +1 -0
  134. package/build/dex/ramses-v2/contract-math/UnsafeMath.d.ts +3 -0
  135. package/build/dex/ramses-v2/contract-math/UnsafeMath.js +10 -0
  136. package/build/dex/ramses-v2/contract-math/UnsafeMath.js.map +1 -0
  137. package/build/dex/ramses-v2/contract-math/uniswap-v3-math.d.ts +18 -0
  138. package/build/dex/ramses-v2/contract-math/uniswap-v3-math.js +392 -0
  139. package/build/dex/ramses-v2/contract-math/uniswap-v3-math.js.map +1 -0
  140. package/build/dex/ramses-v2/contract-math/utils.d.ts +3 -0
  141. package/build/dex/ramses-v2/contract-math/utils.js +16 -0
  142. package/build/dex/ramses-v2/contract-math/utils.js.map +1 -0
  143. package/build/dex/ramses-v2/ramses-v2-pool.d.ts +42 -0
  144. package/build/dex/ramses-v2/ramses-v2-pool.js +307 -0
  145. package/build/dex/ramses-v2/ramses-v2-pool.js.map +1 -0
  146. package/build/dex/ramses-v2/ramses-v2.d.ts +61 -0
  147. package/build/dex/ramses-v2/ramses-v2.js +690 -0
  148. package/build/dex/ramses-v2/ramses-v2.js.map +1 -0
  149. package/build/dex/ramses-v2/types.d.ts +154 -0
  150. package/build/dex/ramses-v2/types.js +9 -0
  151. package/build/dex/ramses-v2/types.js.map +1 -0
  152. package/build/dex/ramses-v2/utils.d.ts +6 -0
  153. package/build/dex/ramses-v2/utils.js +71 -0
  154. package/build/dex/ramses-v2/utils.js.map +1 -0
  155. package/build/dex/sushiswap-v3/config.d.ts +4 -0
  156. package/build/dex/sushiswap-v3/config.js +132 -0
  157. package/build/dex/sushiswap-v3/config.js.map +1 -0
  158. package/build/dex/sushiswap-v3/constants.d.ts +4 -0
  159. package/build/dex/sushiswap-v3/constants.js +32 -0
  160. package/build/dex/sushiswap-v3/constants.js.map +1 -0
  161. package/build/dex/sushiswap-v3/sushiswap-v3-original.d.ts +56 -0
  162. package/build/dex/sushiswap-v3/sushiswap-v3-original.js +598 -0
  163. package/build/dex/sushiswap-v3/sushiswap-v3-original.js.map +1 -0
  164. package/build/dex/sushiswap-v3/sushiswap-v3-pool.d.ts +1 -0
  165. package/build/dex/sushiswap-v3/sushiswap-v3-pool.js +6 -0
  166. package/build/dex/sushiswap-v3/sushiswap-v3-pool.js.map +1 -0
  167. package/build/dex/sushiswap-v3/sushiswap-v3.d.ts +21 -0
  168. package/build/dex/sushiswap-v3/sushiswap-v3.js +58 -0
  169. package/build/dex/sushiswap-v3/sushiswap-v3.js.map +1 -0
  170. package/build/dex/sushiswap-v3/token.d.ts +6 -0
  171. package/build/dex/sushiswap-v3/token.js +23 -0
  172. package/build/dex/sushiswap-v3/token.js.map +1 -0
  173. package/build/dex/sushiswap-v3/types.d.ts +15 -0
  174. package/build/dex/sushiswap-v3/types.js +18 -0
  175. package/build/dex/sushiswap-v3/types.js.map +1 -0
  176. package/build/dex/uniswap-v3/forks/pancakeswap-v3/pancakeswap-v3.d.ts +12 -0
  177. package/build/dex/uniswap-v3/forks/pancakeswap-v3/pancakeswap-v3.js +23 -0
  178. package/build/dex/uniswap-v3/forks/pancakeswap-v3/pancakeswap-v3.js.map +1 -0
  179. package/build/dex/{hello → woo-fi}/config.d.ts +1 -1
  180. package/build/dex/woo-fi/config.js +141 -0
  181. package/build/dex/woo-fi/config.js.map +1 -0
  182. package/build/dex/woo-fi/constants.d.ts +5 -0
  183. package/build/dex/woo-fi/constants.js +20 -0
  184. package/build/dex/woo-fi/constants.js.map +1 -0
  185. package/build/dex/woo-fi/types.d.ts +48 -0
  186. package/build/dex/woo-fi/types.js +3 -0
  187. package/build/dex/{hello → woo-fi}/types.js.map +1 -1
  188. package/build/dex/woo-fi/woo-fi-decimal-math.d.ts +14 -0
  189. package/build/dex/woo-fi/woo-fi-decimal-math.js +42 -0
  190. package/build/dex/woo-fi/woo-fi-decimal-math.js.map +1 -0
  191. package/build/dex/woo-fi/woo-fi-math.d.ts +31 -0
  192. package/build/dex/woo-fi/woo-fi-math.js +300 -0
  193. package/build/dex/woo-fi/woo-fi-math.js.map +1 -0
  194. package/build/dex/woo-fi/woo-fi.d.ts +65 -0
  195. package/build/dex/woo-fi/woo-fi.js +480 -0
  196. package/build/dex/woo-fi/woo-fi.js.map +1 -0
  197. package/package.json +1 -1
  198. package/src/abi/polygon-migration/PolygonMigration.abi.json +364 -0
  199. package/src/config.ts +2 -2
  200. package/src/dex/index.ts +2 -0
  201. package/src/dex/polygon-migrator/config.ts +25 -0
  202. package/src/dex/polygon-migrator/constants.ts +2 -0
  203. package/src/dex/polygon-migrator/polygon-migrator-e2e.test.ts +102 -0
  204. package/src/dex/polygon-migrator/polygon-migrator-integration.test.ts +140 -0
  205. package/src/dex/polygon-migrator/polygon-migrator.ts +151 -0
  206. package/src/dex/polygon-migrator/types.ts +14 -0
  207. package/tests/constants-e2e.ts +10 -0
  208. package/build/dex/hello/config.js +0 -15
  209. package/build/dex/hello/config.js.map +0 -1
  210. package/build/dex/hello/hello-pool.d.ts +0 -39
  211. package/build/dex/hello/hello-pool.js +0 -64
  212. package/build/dex/hello/hello-pool.js.map +0 -1
  213. package/build/dex/hello/hello.d.ts +0 -37
  214. package/build/dex/hello/hello.js +0 -126
  215. package/build/dex/hello/hello.js.map +0 -1
  216. package/build/dex/hello/types.d.ts +0 -6
  217. package/build/dex/my-test-dex/config.js +0 -15
  218. package/build/dex/my-test-dex/config.js.map +0 -1
  219. package/build/dex/my-test-dex/my-test-dex-pool.js +0 -64
  220. package/build/dex/my-test-dex/my-test-dex-pool.js.map +0 -1
  221. package/build/dex/my-test-dex/my-test-dex.js +0 -126
  222. package/build/dex/my-test-dex/my-test-dex.js.map +0 -1
  223. package/build/dex/my-test-dex/types.d.ts +0 -6
  224. /package/build/dex/{hello → lighter-v1}/types.js +0 -0
  225. /package/build/dex/{my-test-dex → pancakeswap-v3}/types.js +0 -0
@@ -0,0 +1,294 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.PhantomStablePool = void 0;
30
+ const abi_1 = require("@ethersproject/abi");
31
+ const bignumber_1 = require("@ethersproject/bignumber");
32
+ const balancer_v2_pool_1 = require("./balancer-v2-pool");
33
+ const utils_1 = require("./utils");
34
+ const StableMath = __importStar(require("./StableMath"));
35
+ const meta_stable_pool_json_1 = __importDefault(require("../../abi/balancer-v2/meta-stable-pool.json"));
36
+ const ComposableStable_json_1 = __importDefault(require("../../abi/balancer-v2/ComposableStable.json"));
37
+ const lodash_1 = require("lodash");
38
+ var PairTypes;
39
+ (function (PairTypes) {
40
+ PairTypes[PairTypes["BptToToken"] = 0] = "BptToToken";
41
+ PairTypes[PairTypes["TokenToBpt"] = 1] = "TokenToBpt";
42
+ PairTypes[PairTypes["TokenToToken"] = 2] = "TokenToToken";
43
+ })(PairTypes || (PairTypes = {}));
44
+ /*
45
+ /**
46
+ * StablePool with preminted BPT and rate providers for each token, allowing for e.g. wrapped tokens with a known
47
+ * price ratio, such as Compound's cTokens.
48
+ * BPT is preminted on Pool initialization and registered as one of the Pool's tokens, allowing for swaps to behave as
49
+ * single-token joins or exits (by swapping a token for BPT). Regular joins and exits are disabled, since no BPT is
50
+ * minted or burned after initialization.
51
+ * Preminted BPT is sometimes called Phantom BPT, as the preminted BPT (which is deposited in the Vault as balance of
52
+ * the Pool) doesn't belong to any entity until transferred out of the Pool. The Pool's arithmetic behaves as if it
53
+ * didn't exist, and the BPT total supply is not a useful value: we rely on the 'virtual supply' (how much BPT is
54
+ * actually owned by some entity) instead.
55
+ */
56
+ class PhantomStablePool extends balancer_v2_pool_1.BasePool {
57
+ constructor(vaultAddress, vaultInterface, isComposable = false) {
58
+ super();
59
+ this.isComposable = isComposable;
60
+ // This is the maximum token amount the Vault can hold. In regular operation, the total BPT supply remains constant
61
+ // and equal to _INITIAL_BPT_SUPPLY, but most of it remains in the Pool, waiting to be exchanged for tokens. The
62
+ // actual amount of BPT in circulation is the total supply minus the amount held by the Pool, and is known as the
63
+ // 'virtual supply'.
64
+ this.MAX_TOKEN_BALANCE = bignumber_1.BigNumber.from('2').pow('112').sub('1');
65
+ this.vaultAddress = vaultAddress;
66
+ this.vaultInterface = vaultInterface;
67
+ if (isComposable)
68
+ this.poolInterface = new abi_1.Interface(ComposableStable_json_1.default);
69
+ else
70
+ this.poolInterface = new abi_1.Interface(meta_stable_pool_json_1.default);
71
+ }
72
+ /*
73
+ scaling factors should include rate:
74
+ i.e.
75
+ scalingFactors: pool.tokens.map(({ decimals, priceRate }) =>
76
+ MathSol.mulDownFixed(getTokenScalingFactor(decimals), priceRate)
77
+ )
78
+ */
79
+ onSell(amounts, poolPairData) {
80
+ return this._swapGivenIn(amounts, poolPairData.tokens, poolPairData.balances, poolPairData.indexIn, poolPairData.indexOut, poolPairData.bptIndex, poolPairData.scalingFactors, poolPairData.swapFee, poolPairData.amp, poolPairData.actualSupply);
81
+ }
82
+ // StablePool's `_onSwapGivenIn` and `_onSwapGivenOut` handlers are meant to process swaps between Pool tokens.
83
+ // Since one of the Pool's tokens is the preminted BPT, we need to a) handle swaps where that tokens is involved
84
+ // separately (as they are effectively single-token joins or exits), and b) remove BPT from the balances array when
85
+ // processing regular swaps before delegating those to StablePool's handler.
86
+ removeBPT(balances, tokenIndexIn, tokenIndexOut, bptIndex) {
87
+ if (bptIndex != -1) {
88
+ balances.splice(bptIndex, 1);
89
+ if (bptIndex < tokenIndexIn)
90
+ tokenIndexIn -= 1;
91
+ if (bptIndex < tokenIndexOut)
92
+ tokenIndexOut -= 1;
93
+ }
94
+ return {
95
+ balances,
96
+ indexIn: tokenIndexIn,
97
+ indexOut: tokenIndexOut,
98
+ };
99
+ }
100
+ _swapGivenIn(tokenAmountsIn, tokens, balances, indexIn, indexOut, bptIndex, scalingFactors, swapFeePercentage, amplificationParameter, actualSupply) {
101
+ // Phantom pools allow trading between token and pool BPT
102
+ let pairType;
103
+ if ((0, utils_1.isSameAddress)(tokens[indexIn], tokens[bptIndex])) {
104
+ pairType = PairTypes.BptToToken;
105
+ }
106
+ else if ((0, utils_1.isSameAddress)(tokens[indexOut], tokens[bptIndex])) {
107
+ pairType = PairTypes.TokenToBpt;
108
+ }
109
+ else {
110
+ pairType = PairTypes.TokenToToken;
111
+ }
112
+ // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis.
113
+ const tokenAmountsInWithFee = tokenAmountsIn.map(a => this._subtractSwapFeeAmount(a, swapFeePercentage));
114
+ const balancesUpscaled = this._upscaleArray(balances, scalingFactors);
115
+ const tokenAmountsInScaled = tokenAmountsInWithFee.map(a => this._upscale(a, scalingFactors[indexIn]));
116
+ let bptSupply;
117
+ if (actualSupply)
118
+ bptSupply = actualSupply;
119
+ // VirtualBPTSupply must be used for the maths
120
+ else
121
+ bptSupply = this.MAX_TOKEN_BALANCE.sub(balances[bptIndex]).toBigInt();
122
+ const droppedBpt = this.removeBPT(balancesUpscaled, indexIn, indexOut, bptIndex);
123
+ const amountsOut = this._onSwapGivenIn(tokenAmountsInScaled, droppedBpt.balances, droppedBpt.indexIn, droppedBpt.indexOut, amplificationParameter, bptSupply, pairType);
124
+ // amountOut tokens are exiting the Pool, so we round down.
125
+ return amountsOut.map(a => this._downscaleDown(a, scalingFactors[indexOut]));
126
+ }
127
+ /*
128
+ Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known.
129
+ All amounts are upscaled.
130
+ Swap fee is already deducted.
131
+ The return value is also considered upscaled, and should be downscaled (rounding down)
132
+ */
133
+ _onSwapGivenIn(tokenAmountsIn, balances, indexIn, indexOut, _amplificationParameter, virtualBptSupply, pairType) {
134
+ const invariant = StableMath._calculateInvariant(_amplificationParameter, balances, true);
135
+ const amountsOut = [];
136
+ if (pairType === PairTypes.TokenToBpt) {
137
+ tokenAmountsIn.forEach(amountIn => {
138
+ let amt;
139
+ try {
140
+ const amountsInBigInt = Array(balances.length).fill(0n);
141
+ amountsInBigInt[indexIn] = amountIn;
142
+ amt = StableMath._calcBptOutGivenExactTokensIn(_amplificationParameter, balances, amountsInBigInt, virtualBptSupply, invariant);
143
+ }
144
+ catch (err) {
145
+ amt = 0n;
146
+ }
147
+ amountsOut.push(amt);
148
+ });
149
+ }
150
+ else if (pairType === PairTypes.BptToToken) {
151
+ tokenAmountsIn.forEach(amountIn => {
152
+ let amt;
153
+ try {
154
+ amt = StableMath._calcTokenOutGivenExactBptIn(_amplificationParameter, balances, indexOut, amountIn, virtualBptSupply, invariant);
155
+ }
156
+ catch (err) {
157
+ amt = 0n;
158
+ }
159
+ amountsOut.push(amt);
160
+ });
161
+ }
162
+ else {
163
+ tokenAmountsIn.forEach(amountIn => {
164
+ let amt;
165
+ try {
166
+ amt = StableMath._calcOutGivenIn(_amplificationParameter, balances, indexIn, indexOut, amountIn, invariant);
167
+ }
168
+ catch (err) {
169
+ amt = 0n;
170
+ }
171
+ amountsOut.push(amt);
172
+ });
173
+ }
174
+ return amountsOut;
175
+ }
176
+ /*
177
+ Helper function to parse pool data into params for onSell function.
178
+ */
179
+ parsePoolPairData(pool, poolState, tokenIn, tokenOut) {
180
+ let indexIn = 0, indexOut = 0, bptIndex = 0;
181
+ const balances = [];
182
+ const scalingFactors = [];
183
+ const tokens = poolState.orderedTokens.map((tokenAddress, i) => {
184
+ const t = pool.tokensMap[tokenAddress.toLowerCase()];
185
+ if (t.address.toLowerCase() === tokenIn.toLowerCase())
186
+ indexIn = i;
187
+ if (t.address.toLowerCase() === tokenOut.toLowerCase())
188
+ indexOut = i;
189
+ if (t.address.toLowerCase() === pool.address.toLowerCase())
190
+ bptIndex = i;
191
+ balances.push(poolState.tokens[t.address.toLowerCase()].balance);
192
+ scalingFactors.push(poolState.tokens[t.address.toLowerCase()].scalingFactor || 0n);
193
+ return t.address;
194
+ });
195
+ const poolPairData = {
196
+ tokens,
197
+ balances,
198
+ indexIn,
199
+ indexOut,
200
+ scalingFactors,
201
+ bptIndex,
202
+ swapFee: poolState.swapFee,
203
+ amp: poolState.amp ? poolState.amp : 0n,
204
+ actualSupply: poolState.actualSupply,
205
+ };
206
+ return poolPairData;
207
+ }
208
+ /*
209
+ Helper function to construct onchain multicall data for PhantomStablePool.
210
+ Main difference to standard StablePool is scaling factors which includes rate.
211
+ This also applies to MetaStablePool.
212
+ */
213
+ getOnChainCalls(pool) {
214
+ const calls = [
215
+ {
216
+ target: this.vaultAddress,
217
+ callData: this.vaultInterface.encodeFunctionData('getPoolTokens', [
218
+ pool.id,
219
+ ]),
220
+ },
221
+ {
222
+ target: pool.address,
223
+ callData: this.poolInterface.encodeFunctionData('getSwapFeePercentage'),
224
+ },
225
+ {
226
+ target: pool.address,
227
+ callData: this.poolInterface.encodeFunctionData('getScalingFactors'),
228
+ },
229
+ {
230
+ target: pool.address,
231
+ callData: this.poolInterface.encodeFunctionData('getAmplificationParameter'),
232
+ },
233
+ ];
234
+ /**
235
+ * Returns the effective BPT supply.
236
+ * In other pools, this would be the same as `totalSupply`, but there are two key differences here:
237
+ * - this pool pre-mints BPT and holds it in the Vault as a token, and as such we need to subtract the Vault's
238
+ * balance to get the total "circulating supply". This is called the 'virtualSupply'.
239
+ * - the Pool owes debt to the Protocol in the form of unminted BPT, which will be minted immediately before the
240
+ * next join or exit. We need to take these into account since, even if they don't yet exist, they will
241
+ * effectively be included in any Pool operation that involves BPT.
242
+ * In the vast majority of cases, this function should be used instead of `totalSupply()`.
243
+ */
244
+ if (this.isComposable)
245
+ calls.push({
246
+ target: pool.address,
247
+ callData: this.poolInterface.encodeFunctionData('getActualSupply'),
248
+ });
249
+ return calls;
250
+ }
251
+ /*
252
+ Helper function to decodes multicall data for a PhantomStable Pool.
253
+ Main difference to standard StablePool is scaling factors which includes rate.
254
+ This also applies to MetaStablePool.
255
+ data must contain returnData
256
+ startIndex is where to start in returnData. Allows this decode function to be called along with other pool types.
257
+ */
258
+ decodeOnChainCalls(pool, data, startIndex) {
259
+ const pools = {};
260
+ const poolTokens = (0, utils_1.decodeThrowError)(this.vaultInterface, 'getPoolTokens', data[startIndex++], pool.address);
261
+ const swapFee = (0, utils_1.decodeThrowError)(this.poolInterface, 'getSwapFeePercentage', data[startIndex++], pool.address)[0];
262
+ const scalingFactors = (0, utils_1.decodeThrowError)(this.poolInterface, 'getScalingFactors', data[startIndex++], pool.address)[0];
263
+ const amp = (0, utils_1.decodeThrowError)(this.poolInterface, 'getAmplificationParameter', data[startIndex++], pool.address);
264
+ const tokens = poolTokens.tokens.map((address, idx) => ({
265
+ address: address.toLowerCase(),
266
+ balance: BigInt(poolTokens.balances[idx].toString()),
267
+ scalingFactor: BigInt(scalingFactors[idx].toString()),
268
+ }));
269
+ const poolState = {
270
+ swapFee: BigInt(swapFee.toString()),
271
+ tokens: (0, lodash_1.keyBy)(tokens, 'address'),
272
+ orderedTokens: poolTokens.tokens,
273
+ };
274
+ if (amp) {
275
+ poolState.amp = BigInt(amp.value.toString());
276
+ }
277
+ if (this.isComposable) {
278
+ const totalSupply = (0, utils_1.decodeThrowError)(this.poolInterface, 'getActualSupply', data[startIndex++], pool.address);
279
+ poolState.actualSupply = BigInt(totalSupply.toString());
280
+ }
281
+ pools[pool.address] = poolState;
282
+ return [pools, startIndex];
283
+ }
284
+ /*
285
+ For stable pools there is no Swap limit. As an approx - use almost the total balance of token out as we can add any amount of tokenIn and expect some back.
286
+ */
287
+ getSwapMaxAmount(poolPairData, side) {
288
+ return ((this._upscale(poolPairData.balances[poolPairData.indexOut], poolPairData.scalingFactors[poolPairData.indexOut]) *
289
+ 99n) /
290
+ 100n);
291
+ }
292
+ }
293
+ exports.PhantomStablePool = PhantomStablePool;
294
+ //# sourceMappingURL=PhantomStablePool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PhantomStablePool.js","sourceRoot":"","sources":["../../../src/dex/balancer-v2/PhantomStablePool.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,4CAA+C;AAC/C,wDAAqD;AACrD,yDAA8C;AAC9C,mCAA0D;AAC1D,yDAA2C;AAG3C,wGAA4E;AAC5E,wGAAkF;AAClF,mCAA+B;AAE/B,IAAK,SAIJ;AAJD,WAAK,SAAS;IACZ,qDAAU,CAAA;IACV,qDAAU,CAAA;IACV,yDAAY,CAAA;AACd,CAAC,EAJI,SAAS,KAAT,SAAS,QAIb;AAcD;;;;;;;;;;;GAWG;A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EACvC,IAAc;QAEd,OAAO,CACL,CAAC,IAAI,CAAC,QAAQ,CACZ,YAAY,CAAC,QAAQ,CAAC,YAAY,CAAC,QAAQ,CAAC,EAC5C,YAAY,CAAC,cAAc,CAAC,YAAY,CAAC,QAAQ,CAAC,CACnD;YACC,GAAG,CAAC;YACN,IAAI,CACL,CAAC;IACJ,CAAC;CACF;AAjYD,8CAiYC"}
@@ -0,0 +1,9 @@
1
+ export declare function _calculateInvariant(amp: bigint, balances: bigint[], roundUp: boolean): bigint;
2
+ export declare function _calcOutGivenIn(amp: bigint, balances: bigint[], tokenIndexIn: number, tokenIndexOut: number, amountIn: bigint, invariant?: bigint): bigint;
3
+ export declare function _calcInGivenOut(amp: bigint, balances: bigint[], tokenIndexIn: number, tokenIndexOut: number, amountOut: bigint, fee: bigint, invariant?: bigint): bigint;
4
+ export declare function _calcBptOutGivenExactTokensIn(amp: bigint, balances: bigint[], amountsIn: bigint[], bptTotalSupply: bigint, invariant?: bigint): bigint;
5
+ export declare function _calcBptInGivenExactTokensOut(amp: bigint, balances: bigint[], amountsOut: bigint[], bptTotalSupply: bigint, swapFeePercentage: bigint, invariant?: bigint): bigint;
6
+ export declare function _calcTokenOutGivenExactBptIn(amp: bigint, balances: bigint[], tokenIndex: number, bptAmountIn: bigint, bptTotalSupply: bigint, invariant?: bigint): bigint;
7
+ export declare function _calcTokensOutGivenExactBptIn(balances: bigint[], bptAmountIn: bigint, bptTotalSupply: bigint): bigint[];
8
+ export declare function subtractFee(amount: bigint, fee: bigint): bigint;
9
+ export declare function addFee(amount: bigint, fee: bigint): bigint;
@@ -0,0 +1,272 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addFee = exports.subtractFee = exports._calcTokensOutGivenExactBptIn = exports._calcTokenOutGivenExactBptIn = exports._calcBptInGivenExactTokensOut = exports._calcBptOutGivenExactTokensIn = exports._calcInGivenOut = exports._calcOutGivenIn = exports._calculateInvariant = void 0;
4
+ const bigint_constants_1 = require("../../bigint-constants");
5
+ const balancer_v2_math_1 = require("./balancer-v2-math");
6
+ const AMP_PRECISION = bigint_constants_1.BI_POWS[3];
7
+ function _calculateInvariant(amp, balances, roundUp) {
8
+ /**********************************************************************************************
9
+ // invariant //
10
+ // D = invariant D^(n+1) //
11
+ // A = amplification coefficient A n^n S + D = A D n^n + ----------- //
12
+ // S = sum of balances n^n P //
13
+ // P = product of balances //
14
+ // n = number of tokens //
15
+ *********x************************************************************************************/
16
+ // We support rounding up or down.
17
+ let sum = 0n;
18
+ const numTokens = balances.length;
19
+ for (let i = 0; i < numTokens; i++) {
20
+ sum = sum + balances[i];
21
+ }
22
+ if (sum == 0n) {
23
+ return 0n;
24
+ }
25
+ let prevInvariant = 0n;
26
+ let invariant = sum;
27
+ const ampTimesTotal = amp * BigInt(numTokens);
28
+ for (let i = 0; i < 255; i++) {
29
+ let P_D = balances[0] * BigInt(numTokens);
30
+ for (let j = 1; j < numTokens; j++) {
31
+ P_D = balancer_v2_math_1.MathSol.div(balancer_v2_math_1.MathSol.mul(balancer_v2_math_1.MathSol.mul(P_D, balances[j]), BigInt(numTokens)), invariant, roundUp);
32
+ }
33
+ prevInvariant = invariant;
34
+ invariant = balancer_v2_math_1.MathSol.div(balancer_v2_math_1.MathSol.mul(balancer_v2_math_1.MathSol.mul(BigInt(numTokens), invariant), invariant) +
35
+ balancer_v2_math_1.MathSol.div(balancer_v2_math_1.MathSol.mul(balancer_v2_math_1.MathSol.mul(ampTimesTotal, sum), P_D), AMP_PRECISION, roundUp), balancer_v2_math_1.MathSol.mul(BigInt(numTokens + 1), invariant) +
36
+ // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1
37
+ balancer_v2_math_1.MathSol.div(balancer_v2_math_1.MathSol.mul(ampTimesTotal - AMP_PRECISION, P_D), AMP_PRECISION, !roundUp), roundUp);
38
+ if (invariant > prevInvariant) {
39
+ if (invariant - prevInvariant <= 1) {
40
+ return invariant;
41
+ }
42
+ }
43
+ else if (prevInvariant - invariant <= 1) {
44
+ return invariant;
45
+ }
46
+ }
47
+ throw new Error('Errors.STABLE_INVARIANT_DIDNT_CONVERGE');
48
+ }
49
+ exports._calculateInvariant = _calculateInvariant;
50
+ // PairType = 'token->token'
51
+ // SwapType = 'swapExactIn'
52
+ function _calcOutGivenIn(amp, balances, tokenIndexIn, tokenIndexOut, amountIn, invariant) {
53
+ balances = [...balances];
54
+ // Given that we need to have a greater final balance out, the invariant needs to be rounded up
55
+ if (!invariant)
56
+ invariant = _calculateInvariant(amp, balances, true);
57
+ const initBalance = balances[tokenIndexIn];
58
+ balances[tokenIndexIn] = initBalance + amountIn;
59
+ const finalBalanceOut = _getTokenBalanceGivenInvariantAndAllOtherBalances(amp, balances, invariant, tokenIndexOut);
60
+ return balances[tokenIndexOut] - finalBalanceOut - 1n;
61
+ }
62
+ exports._calcOutGivenIn = _calcOutGivenIn;
63
+ function _calcInGivenOut(amp, balances, tokenIndexIn, tokenIndexOut, amountOut, fee, invariant) {
64
+ balances = [...balances];
65
+ if (!invariant)
66
+ invariant = _calculateInvariant(amp, balances, true);
67
+ balances[tokenIndexOut] = balancer_v2_math_1.MathSol.sub(balances[tokenIndexOut], amountOut);
68
+ const finalBalanceIn = _getTokenBalanceGivenInvariantAndAllOtherBalances(amp, balances, invariant, tokenIndexIn);
69
+ let amountIn = balancer_v2_math_1.MathSol.add(balancer_v2_math_1.MathSol.sub(finalBalanceIn, balances[tokenIndexIn]), 1n);
70
+ amountIn = addFee(amountIn, fee);
71
+ return amountIn;
72
+ }
73
+ exports._calcInGivenOut = _calcInGivenOut;
74
+ function _calcBptOutGivenExactTokensIn(amp, balances, amountsIn, bptTotalSupply, invariant) {
75
+ if (!invariant)
76
+ invariant = _calculateInvariant(amp, balances, true);
77
+ // BPT out, so we round down overall.
78
+ // First loop calculates the sum of all token balances, which will be used to calculate
79
+ // the current weights of each token, relative to this sum
80
+ let sumBalances = 0n;
81
+ for (let i = 0; i < balances.length; i++) {
82
+ sumBalances = sumBalances + balances[i];
83
+ }
84
+ // Calculate the weighted balance ratio without considering fees
85
+ const balanceRatiosWithFee = new Array(amountsIn.length);
86
+ // The weighted sum of token balance ratios with fee
87
+ let invariantRatioWithFees = 0n;
88
+ for (let i = 0; i < balances.length; i++) {
89
+ const currentWeight = balancer_v2_math_1.MathSol.divDownFixed(balances[i], sumBalances);
90
+ balanceRatiosWithFee[i] = balancer_v2_math_1.MathSol.divDownFixed(balances[i] + amountsIn[i], balances[i]);
91
+ invariantRatioWithFees =
92
+ invariantRatioWithFees +
93
+ balancer_v2_math_1.MathSol.mulDownFixed(balanceRatiosWithFee[i], currentWeight);
94
+ }
95
+ // Second loop calculates new amounts in, taking into account the fee on the percentage excess
96
+ const newBalances = new Array(balances.length);
97
+ for (let i = 0; i < balances.length; i++) {
98
+ let amountInWithoutFee;
99
+ // Check if the balance ratio is greater than the ideal ratio to charge fees or not
100
+ if (balanceRatiosWithFee[i] > invariantRatioWithFees) {
101
+ const nonTaxableAmount = balancer_v2_math_1.MathSol.mulDownFixed(balances[i], invariantRatioWithFees - balancer_v2_math_1.MathSol.ONE);
102
+ const taxableAmount = amountsIn[i] - nonTaxableAmount;
103
+ // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
104
+ // amountInWithoutFee =
105
+ // nonTaxableAmount +
106
+ // MathSol.mulDownFixed(
107
+ // taxableAmount,
108
+ // MathSol.ONE - swapFeePercentage
109
+ // );
110
+ amountInWithoutFee = nonTaxableAmount + taxableAmount;
111
+ }
112
+ else {
113
+ amountInWithoutFee = amountsIn[i];
114
+ }
115
+ newBalances[i] = balances[i] + amountInWithoutFee;
116
+ }
117
+ // Get current and new invariants, taking swap fees into account
118
+ const currentInvariant = _calculateInvariant(amp, balances, true);
119
+ const newInvariant = _calculateInvariant(amp, newBalances, false);
120
+ const invariantRatio = balancer_v2_math_1.MathSol.divDownFixed(newInvariant, currentInvariant);
121
+ // If the invariant didn't increase for any reason, we simply don't mint BPT
122
+ if (invariantRatio > balancer_v2_math_1.MathSol.ONE) {
123
+ return balancer_v2_math_1.MathSol.mulDownFixed(bptTotalSupply, invariantRatio - balancer_v2_math_1.MathSol.ONE);
124
+ }
125
+ else {
126
+ return 0n;
127
+ }
128
+ }
129
+ exports._calcBptOutGivenExactTokensIn = _calcBptOutGivenExactTokensIn;
130
+ /*
131
+ Flow of calculations:
132
+ amountsTokenOut -> amountsOutProportional ->
133
+ amountOutPercentageExcess -> amountOutBeforeFee -> newInvariant -> amountBPTIn
134
+ */
135
+ function _calcBptInGivenExactTokensOut(amp, balances, amountsOut, bptTotalSupply, swapFeePercentage, invariant) {
136
+ if (!invariant)
137
+ invariant = _calculateInvariant(amp, balances, true);
138
+ // BPT in, so we round up overall.
139
+ // First loop calculates the sum of all token balances, which will be used to calculate
140
+ // the current weights of each token relative to this sum
141
+ let sumBalances = 0n;
142
+ for (let i = 0; i < balances.length; i++) {
143
+ sumBalances = sumBalances + balances[i];
144
+ }
145
+ // Calculate the weighted balance ratio without considering fees
146
+ const balanceRatiosWithoutFee = new Array(amountsOut.length);
147
+ let invariantRatioWithoutFees = 0n;
148
+ for (let i = 0; i < balances.length; i++) {
149
+ const currentWeight = balancer_v2_math_1.MathSol.divUpFixed(balances[i], sumBalances);
150
+ balanceRatiosWithoutFee[i] = balancer_v2_math_1.MathSol.divUpFixed(balances[i] - amountsOut[i], balances[i]);
151
+ invariantRatioWithoutFees =
152
+ invariantRatioWithoutFees +
153
+ balancer_v2_math_1.MathSol.mulUpFixed(balanceRatiosWithoutFee[i], currentWeight);
154
+ }
155
+ // Second loop calculates new amounts in, taking into account the fee on the percentage excess
156
+ const newBalances = new Array(balances.length);
157
+ for (let i = 0; i < balances.length; i++) {
158
+ // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to
159
+ // 'token out'. This results in slightly larger price impact.
160
+ let amountOutWithFee;
161
+ if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) {
162
+ const nonTaxableAmount = balancer_v2_math_1.MathSol.mulDownFixed(balances[i], balancer_v2_math_1.MathSol.complementFixed(invariantRatioWithoutFees));
163
+ const taxableAmount = amountsOut[i] - nonTaxableAmount;
164
+ // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
165
+ amountOutWithFee =
166
+ nonTaxableAmount +
167
+ balancer_v2_math_1.MathSol.divUpFixed(taxableAmount, balancer_v2_math_1.MathSol.ONE - swapFeePercentage);
168
+ }
169
+ else {
170
+ amountOutWithFee = amountsOut[i];
171
+ }
172
+ newBalances[i] = balances[i] - amountOutWithFee;
173
+ }
174
+ // Get current and new invariants, taking into account swap fees
175
+ const currentInvariant = _calculateInvariant(amp, balances, true);
176
+ const newInvariant = _calculateInvariant(amp, newBalances, false);
177
+ const invariantRatio = balancer_v2_math_1.MathSol.divDownFixed(newInvariant, currentInvariant);
178
+ // return amountBPTIn
179
+ return balancer_v2_math_1.MathSol.mulUpFixed(bptTotalSupply, balancer_v2_math_1.MathSol.complementFixed(invariantRatio));
180
+ }
181
+ exports._calcBptInGivenExactTokensOut = _calcBptInGivenExactTokensOut;
182
+ function _calcTokenOutGivenExactBptIn(amp, balances, tokenIndex, bptAmountIn, bptTotalSupply, invariant) {
183
+ if (!invariant)
184
+ invariant = _calculateInvariant(amp, balances, true);
185
+ // Token out, so we round down overall.
186
+ // Get the current and new invariants. Since we need a bigger new invariant, we round the current one up.
187
+ const currentInvariant = _calculateInvariant(amp, balances, true);
188
+ const newInvariant = balancer_v2_math_1.MathSol.mulUpFixed(balancer_v2_math_1.MathSol.divUpFixed(bptTotalSupply - bptAmountIn, bptTotalSupply), currentInvariant);
189
+ // Calculate amount out without fee
190
+ const newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances(amp, balances, newInvariant, tokenIndex);
191
+ const amountOutWithoutFee = balances[tokenIndex] - newBalanceTokenIndex;
192
+ // First calculate the sum of all token balances, which will be used to calculate
193
+ // the current weight of each token
194
+ let sumBalances = 0n;
195
+ for (let i = 0; i < balances.length; i++) {
196
+ sumBalances = sumBalances + balances[i];
197
+ }
198
+ // We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result
199
+ // in swap fees.
200
+ const currentWeight = balancer_v2_math_1.MathSol.divDownFixed(balances[tokenIndex], sumBalances);
201
+ const taxablePercentage = balancer_v2_math_1.MathSol.complementFixed(currentWeight);
202
+ // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it
203
+ // to 'token out'. This results in slightly larger price impact. Fees are rounded up.
204
+ const taxableAmount = balancer_v2_math_1.MathSol.mulUpFixed(amountOutWithoutFee, taxablePercentage);
205
+ const nonTaxableAmount = amountOutWithoutFee - taxableAmount;
206
+ // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
207
+ return nonTaxableAmount + taxableAmount;
208
+ }
209
+ exports._calcTokenOutGivenExactBptIn = _calcTokenOutGivenExactBptIn;
210
+ function _calcTokensOutGivenExactBptIn(balances, bptAmountIn, bptTotalSupply) {
211
+ /**********************************************************************************************
212
+ // exactBPTInForTokensOut //
213
+ // (per token) //
214
+ // aO = tokenAmountOut / bptIn \ //
215
+ // b = tokenBalance a0 = b * | --------------------- | //
216
+ // bptIn = bptAmountIn \ bptTotalSupply / //
217
+ // bpt = bptTotalSupply //
218
+ **********************************************************************************************/
219
+ // Since we're computing an amount out, we round down overall. This means rounding down on both the
220
+ // multiplication and division.
221
+ const bptRatio = balancer_v2_math_1.MathSol.divDownFixed(bptAmountIn, bptTotalSupply);
222
+ const amountsOut = new Array(balances.length);
223
+ for (let i = 0; i < balances.length; i++) {
224
+ amountsOut[i] = balancer_v2_math_1.MathSol.mulDownFixed(balances[i], bptRatio);
225
+ }
226
+ return amountsOut;
227
+ }
228
+ exports._calcTokensOutGivenExactBptIn = _calcTokensOutGivenExactBptIn;
229
+ function _getTokenBalanceGivenInvariantAndAllOtherBalances(amp, balances, invariant, tokenIndex) {
230
+ // Rounds result up overall
231
+ const ampTimesTotal = amp * BigInt(balances.length);
232
+ let sum = balances[0];
233
+ let P_D = balances[0] * BigInt(balances.length);
234
+ for (let j = 1; j < balances.length; j++) {
235
+ P_D = balancer_v2_math_1.MathSol.divDown(balancer_v2_math_1.MathSol.mul(balancer_v2_math_1.MathSol.mul(P_D, balances[j]), BigInt(balances.length)), invariant);
236
+ sum = sum + balances[j];
237
+ }
238
+ // No need to use safe math, based on the loop above `sum` is greater than or equal to `balances[tokenIndex]`
239
+ sum = sum - balances[tokenIndex];
240
+ const inv2 = balancer_v2_math_1.MathSol.mul(invariant, invariant);
241
+ // We remove the balance fromm c by multiplying it
242
+ const c = balancer_v2_math_1.MathSol.mul(balancer_v2_math_1.MathSol.mul(balancer_v2_math_1.MathSol.divUp(inv2, balancer_v2_math_1.MathSol.mul(ampTimesTotal, P_D)), AMP_PRECISION), balances[tokenIndex]);
243
+ const b = sum + balancer_v2_math_1.MathSol.mul(balancer_v2_math_1.MathSol.divDown(invariant, ampTimesTotal), AMP_PRECISION);
244
+ // We iterate to find the balance
245
+ let prevTokenBalance = 0n;
246
+ // We multiply the first iteration outside the loop with the invariant to set the value of the
247
+ // initial approximation.
248
+ let tokenBalance = balancer_v2_math_1.MathSol.divUp(inv2 + c, invariant + b);
249
+ for (let i = 0; i < 255; i++) {
250
+ prevTokenBalance = tokenBalance;
251
+ tokenBalance = balancer_v2_math_1.MathSol.divUp(balancer_v2_math_1.MathSol.mul(tokenBalance, tokenBalance) + c, balancer_v2_math_1.MathSol.mul(tokenBalance, 2n) + b - invariant);
252
+ if (tokenBalance > prevTokenBalance) {
253
+ if (tokenBalance - prevTokenBalance <= 1) {
254
+ return tokenBalance;
255
+ }
256
+ }
257
+ else if (prevTokenBalance - tokenBalance <= 1) {
258
+ return tokenBalance;
259
+ }
260
+ }
261
+ throw new Error('Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE');
262
+ }
263
+ function subtractFee(amount, fee) {
264
+ const feeAmount = balancer_v2_math_1.MathSol.mulUpFixed(amount, fee);
265
+ return amount - feeAmount;
266
+ }
267
+ exports.subtractFee = subtractFee;
268
+ function addFee(amount, fee) {
269
+ return balancer_v2_math_1.MathSol.divUpFixed(amount, balancer_v2_math_1.MathSol.complementFixed(fee));
270
+ }
271
+ exports.addFee = addFee;
272
+ //# sourceMappingURL=StableMath.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"StableMath.js","sourceRoot":"","sources":["../../../src/dex/balancer-v2/StableMath.ts"],"names":[],"mappings":";;;AAAA,6DAAiD;AACjD,yDAA6C;AAE7C,MAAM,aAAa,GAAG,0BAAO,CAAC,CAAC,CAAC,CAAC;AAEjC,SAAgB,mBAAmB,CACjC,GAAW,EACX,QAAkB,EAClB,OAAgB;IAEhB;;;;;;;uGAOmG;IAEnG,kCAAkC;IAElC,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,MAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC;IAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,EAAE,CAAC,EAAE,EAAE;QAClC,GAAG,GAAG,GAAG,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;KACzB;IACD,IAAI,GAAG,IAAI,EAAE,EAAE;QACb,OAAO,EAAE,CAAC;KACX;IAED,IAAI,aAAa,GAAG,EAAE,CAAC;IACvB,IAAI,SAAS,GAAG,GAAG,CAAC;IACpB,MAAM,aAAa,GAAG,GAAG,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;IAE9C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;QAC5B,IAAI,GAAG,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;QAC1C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,EAAE,CAAC,EAAE,EAAE;YAClC,GAAG,GAAG,0BAAO,CAAC,GAAG,CACf,0BAAO,CAAC,GAAG,CAAC,0BAAO,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ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