@dolomite-exchange/dolomite-margin 0.2.6 → 0.2.7

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 (200) hide show
  1. package/build/contracts/Account.json +11 -11
  2. package/build/contracts/Actions.json +11 -11
  3. package/build/contracts/Address.json +1 -1
  4. package/build/contracts/Admin.json +23 -23
  5. package/build/contracts/AdminImpl.json +35 -307
  6. package/build/contracts/AdvancedMath.json +7 -7
  7. package/build/contracts/AmmRebalancerProxy.json +577 -621
  8. package/build/contracts/AmmRebalancerProxyV1.json +78 -32
  9. package/build/contracts/Babylonian.json +1 -1
  10. package/build/contracts/Bits.json +9 -9
  11. package/build/contracts/Cache.json +13 -13
  12. package/build/contracts/ChainlinkPriceOracleV1.json +16 -16
  13. package/build/contracts/Context.json +1 -1
  14. package/build/contracts/CustomTestToken.json +9 -9
  15. package/build/contracts/Decimal.json +9 -9
  16. package/build/contracts/DelayedMultiSig.json +9 -9
  17. package/build/contracts/DolomiteAmmERC20.json +11 -11
  18. package/build/contracts/DolomiteAmmFactory.json +14 -52
  19. package/build/contracts/DolomiteAmmLibrary.json +24 -24
  20. package/build/contracts/DolomiteAmmPair.json +27 -27
  21. package/build/contracts/DolomiteAmmRouterProxy.json +30 -363
  22. package/build/contracts/DolomiteMargin.json +21 -67
  23. package/build/contracts/DoubleExponentInterestSetter.json +15 -21
  24. package/build/contracts/EnumerableSet.json +7 -7
  25. package/build/contracts/ErroringOmiseToken.json +9 -9
  26. package/build/contracts/ErroringToken.json +10 -10
  27. package/build/contracts/Events.json +17 -17
  28. package/build/contracts/ExcessivelySafeCall.json +35 -35
  29. package/build/contracts/Exchange.json +15 -15
  30. package/build/contracts/Expiry.json +36 -36
  31. package/build/contracts/Getters.json +33 -33
  32. package/build/contracts/IAutoTrader.json +9 -9
  33. package/build/contracts/ICallee.json +7 -7
  34. package/build/contracts/IChainlinkAggregator.json +5 -5
  35. package/build/contracts/IDolomiteAmmERC20.json +5 -5
  36. package/build/contracts/IDolomiteAmmFactory.json +9 -9
  37. package/build/contracts/IDolomiteAmmPair.json +9 -9
  38. package/build/contracts/IDolomiteMargin.json +23 -23
  39. package/build/contracts/IERC20.json +1 -1
  40. package/build/contracts/IERC20Detailed.json +5 -5
  41. package/build/contracts/IExchangeWrapper.json +5 -5
  42. package/build/contracts/IExpiry.json +9 -9
  43. package/build/contracts/IInterestSetter.json +7 -7
  44. package/build/contracts/ILiquidationCallback.json +7 -7
  45. package/build/contracts/IMakerOracle.json +5 -5
  46. package/build/contracts/IOasisDex.json +5 -5
  47. package/build/contracts/IPriceOracle.json +7 -7
  48. package/build/contracts/IRecyclable.json +9 -9
  49. package/build/contracts/ITransferProxy.json +5 -5
  50. package/build/contracts/IUniswapV2Callee.json +5 -5
  51. package/build/contracts/IUniswapV2Factory.json +5 -5
  52. package/build/contracts/IUniswapV2Pair.json +5 -5
  53. package/build/contracts/IUniswapV2Router.json +5 -5
  54. package/build/contracts/IWETH.json +5 -5
  55. package/build/contracts/Interest.json +15 -15
  56. package/build/contracts/LiquidateOrVaporizeImpl.json +32 -83
  57. package/build/contracts/LiquidatorProxyHelper.json +23 -23
  58. package/build/contracts/LiquidatorProxyV1.json +30 -36
  59. package/build/contracts/LiquidatorProxyV1WithAmm.json +49 -105
  60. package/build/contracts/Math.json +1 -1
  61. package/build/contracts/Migrations.json +8 -14
  62. package/build/contracts/Monetary.json +7 -7
  63. package/build/contracts/MultiCall.json +8 -14
  64. package/build/contracts/MultiSig.json +7 -7
  65. package/build/contracts/OmiseToken.json +8 -8
  66. package/build/contracts/OnlyDolomiteMargin.json +11 -11
  67. package/build/contracts/Operation.json +15 -15
  68. package/build/contracts/OperationImpl.json +39 -47
  69. package/build/contracts/Ownable.json +1 -1
  70. package/build/contracts/PartiallyDelayedMultiSig.json +9 -9
  71. package/build/contracts/PayableProxy.json +17 -23
  72. package/build/contracts/Permission.json +11 -11
  73. package/build/contracts/PolynomialInterestSetter.json +13 -13
  74. package/build/contracts/RecyclableTokenProxy.json +25 -25
  75. package/build/contracts/ReentrancyGuard.json +1 -1
  76. package/build/contracts/Require.json +7 -7
  77. package/build/contracts/SafeERC20.json +1 -1
  78. package/build/contracts/SafeETH.json +7 -7
  79. package/build/contracts/SafeLiquidationCallback.json +17 -17
  80. package/build/contracts/SafeMath.json +1 -1
  81. package/build/contracts/SignedOperationProxy.json +21 -104
  82. package/build/contracts/SimpleFeeOwner.json +18 -63
  83. package/build/contracts/State.json +9 -9
  84. package/build/contracts/Storage.json +37 -37
  85. package/build/contracts/TestAmmRebalancerProxy.json +32 -58
  86. package/build/contracts/TestAutoTrader.json +22 -22
  87. package/build/contracts/TestBtcUsdChainlinkAggregator.json +10 -10
  88. package/build/contracts/TestCallee.json +19 -19
  89. package/build/contracts/TestChainlinkPriceOracleV1.json +10 -94
  90. package/build/contracts/TestCounter.json +7 -7
  91. package/build/contracts/TestDaiUsdChainlinkAggregator.json +11 -11
  92. package/build/contracts/TestDolomiteMargin.json +22 -22
  93. package/build/contracts/TestDoubleExponentInterestSetter.json +10 -10
  94. package/build/contracts/TestEthUsdChainlinkAggregator.json +11 -11
  95. package/build/contracts/TestExchangeWrapper.json +28 -28
  96. package/build/contracts/TestInterestSetter.json +13 -13
  97. package/build/contracts/TestLib.json +22 -22
  98. package/build/contracts/TestLinkUsdChainlinkAggregator.json +11 -11
  99. package/build/contracts/TestLiquidateCallback.json +719 -719
  100. package/build/contracts/TestLiquidationCallback.json +13 -13
  101. package/build/contracts/TestLrcEthChainlinkAggregator.json +11 -11
  102. package/build/contracts/TestMakerOracle.json +10 -10
  103. package/build/contracts/TestMaticUsdChainlinkAggregator.json +10 -10
  104. package/build/contracts/TestOasisDex.json +12 -12
  105. package/build/contracts/TestOperationImpl.json +14 -14
  106. package/build/contracts/TestPolynomialInterestSetter.json +10 -10
  107. package/build/contracts/TestPriceAggregator.json +9 -9
  108. package/build/contracts/TestPriceOracle.json +13 -13
  109. package/build/contracts/TestRecyclableToken.json +9 -9
  110. package/build/contracts/TestSimpleCallee.json +15 -15
  111. package/build/contracts/TestToken.json +9 -9
  112. package/build/contracts/TestTrader.json +17 -17
  113. package/build/contracts/TestUniswapAmmRebalancerProxy.json +16 -16
  114. package/build/contracts/TestUsdcUsdChainlinkAggregator.json +11 -11
  115. package/build/contracts/TestWETH.json +9 -9
  116. package/build/contracts/Time.json +9 -9
  117. package/build/contracts/Token.json +9 -9
  118. package/build/contracts/TokenA.json +10 -10
  119. package/build/contracts/TokenB.json +10 -10
  120. package/build/contracts/TokenC.json +10 -10
  121. package/build/contracts/TokenD.json +10 -10
  122. package/build/contracts/TokenE.json +10 -10
  123. package/build/contracts/TokenF.json +10 -10
  124. package/build/contracts/TransferProxy.json +22 -28
  125. package/build/contracts/TypedSignature.json +9 -9
  126. package/build/contracts/Types.json +9 -9
  127. package/build/contracts/UQ112x112.json +7 -7
  128. package/build/contracts/UniswapV2ERC20.json +7 -7
  129. package/build/contracts/UniswapV2Factory.json +12 -12
  130. package/build/contracts/UniswapV2Library.json +20 -20
  131. package/build/contracts/UniswapV2Pair.json +17 -17
  132. package/build/contracts/UniswapV2Router02.json +16 -16
  133. package/build/contracts/WETH9.json +1 -1
  134. package/contracts/external/amm/DolomiteAmmERC20.sol +135 -0
  135. package/contracts/external/amm/DolomiteAmmFactory.sol +122 -0
  136. package/contracts/external/amm/DolomiteAmmPair.sol +573 -0
  137. package/contracts/external/amm/SimpleFeeOwner.sol +107 -0
  138. package/contracts/external/helpers/LiquidatorProxyHelper.sol +252 -0
  139. package/contracts/external/helpers/OnlyDolomiteMargin.sol +63 -0
  140. package/contracts/external/interestsetters/DoubleExponentInterestSetter.sol +212 -0
  141. package/contracts/external/interestsetters/PolynomialInterestSetter.sol +205 -0
  142. package/contracts/external/interfaces/IChainlinkAggregator.sol +33 -0
  143. package/contracts/external/interfaces/IDolomiteAmmERC20.sol +52 -0
  144. package/contracts/external/interfaces/IDolomiteAmmFactory.sol +42 -0
  145. package/contracts/external/interfaces/IDolomiteAmmPair.sol +116 -0
  146. package/contracts/external/interfaces/IExpiry.sol +70 -0
  147. package/contracts/external/interfaces/IMakerOracle.sol +52 -0
  148. package/contracts/external/interfaces/IOasisDex.sol +326 -0
  149. package/contracts/external/interfaces/ITransferProxy.sol +53 -0
  150. package/contracts/external/interfaces/IUniswapV2Router.sol +134 -0
  151. package/contracts/external/lib/AdvancedMath.sol +23 -0
  152. package/contracts/external/lib/DolomiteAmmLibrary.sol +323 -0
  153. package/contracts/external/lib/TypedSignature.sol +120 -0
  154. package/contracts/external/lib/UQ112x112.sol +22 -0
  155. package/contracts/external/multisig/DelayedMultiSig.sol +206 -0
  156. package/contracts/external/multisig/MultiSig.sol +571 -0
  157. package/contracts/external/multisig/PartiallyDelayedMultiSig.sol +174 -0
  158. package/contracts/external/oracles/ChainlinkPriceOracleV1.sol +197 -0
  159. package/contracts/external/oracles/TestChainlinkPriceOracleV1.sol +98 -0
  160. package/contracts/external/proxies/AmmRebalancerProxyV1.sol +465 -0
  161. package/contracts/external/proxies/DolomiteAmmRouterProxy.sol +877 -0
  162. package/contracts/external/proxies/LiquidatorProxyV1.sol +507 -0
  163. package/contracts/external/proxies/LiquidatorProxyV1WithAmm.sol +574 -0
  164. package/contracts/external/proxies/PayableProxy.sol +146 -0
  165. package/contracts/external/proxies/RecyclableTokenProxy.sol +463 -0
  166. package/contracts/external/proxies/SignedOperationProxy.sol +553 -0
  167. package/contracts/external/proxies/TransferProxy.sol +207 -0
  168. package/contracts/external/traders/Expiry.sol +532 -0
  169. package/contracts/external/uniswap-v2/UniswapV2ERC20.sol +118 -0
  170. package/contracts/external/uniswap-v2/UniswapV2Factory.sol +67 -0
  171. package/contracts/external/uniswap-v2/UniswapV2Pair.sol +283 -0
  172. package/contracts/external/uniswap-v2/UniswapV2Router02.sol +566 -0
  173. package/contracts/external/uniswap-v2/interfaces/IUniswapV2Callee.sol +13 -0
  174. package/contracts/external/uniswap-v2/interfaces/IUniswapV2Factory.sol +18 -0
  175. package/contracts/external/uniswap-v2/interfaces/IUniswapV2Pair.sol +67 -0
  176. package/contracts/external/uniswap-v2/interfaces/IWETH.sol +7 -0
  177. package/contracts/external/uniswap-v2/libraries/SafeETH.sol +29 -0
  178. package/contracts/external/uniswap-v2/libraries/UniswapV2Library.sol +117 -0
  179. package/contracts/external/utils/MultiCall.sol +95 -0
  180. package/contracts/protocol/impl/artifacts/OperationImpl.json +80 -0
  181. package/contracts/protocol/impl/artifacts/OperationImpl_metadata.json +193 -0
  182. package/dist/build/published_contracts/AdminImpl.json +2 -2
  183. package/dist/build/published_contracts/AmmRebalancerProxyV1.json +5 -0
  184. package/dist/build/published_contracts/ChainlinkPriceOracleV1.json +1 -1
  185. package/dist/build/published_contracts/DolomiteAmmFactory.json +1 -1
  186. package/dist/build/published_contracts/DolomiteAmmRouterProxy.json +1 -1
  187. package/dist/build/published_contracts/DoubleExponentInterestSetter.json +2 -2
  188. package/dist/build/published_contracts/Expiry.json +1 -1
  189. package/dist/build/published_contracts/LiquidatorProxyV1.json +1 -1
  190. package/dist/build/published_contracts/LiquidatorProxyV1WithAmm.json +1 -1
  191. package/dist/build/published_contracts/MultiCall.json +1 -1
  192. package/dist/build/published_contracts/PayableProxy.json +2 -2
  193. package/dist/build/published_contracts/SignedOperationProxy.json +2 -2
  194. package/dist/build/published_contracts/SimpleFeeOwner.json +1 -1
  195. package/dist/build/published_contracts/TestUniswapAmmRebalancerProxy.json +140 -0
  196. package/dist/build/published_contracts/TransferProxy.json +1 -1
  197. package/dist/src/lib/Contracts.d.ts +3 -1
  198. package/dist/src/lib/Contracts.js +7 -3
  199. package/dist/src/lib/Contracts.js.map +1 -1
  200. package/package.json +2 -1
@@ -0,0 +1,507 @@
1
+ /*
2
+
3
+ Copyright 2019 dYdX Trading Inc.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ */
18
+
19
+ pragma solidity ^0.5.7;
20
+ pragma experimental ABIEncoderV2;
21
+
22
+ import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
23
+ import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
24
+
25
+ import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
26
+ import { Account } from "../../protocol/lib/Account.sol";
27
+ import { Actions } from "../../protocol/lib/Actions.sol";
28
+ import { Decimal } from "../../protocol/lib/Decimal.sol";
29
+ import { Interest } from "../../protocol/lib/Interest.sol";
30
+ import { Math } from "../../protocol/lib/Math.sol";
31
+ import { Monetary } from "../../protocol/lib/Monetary.sol";
32
+ import { Require } from "../../protocol/lib/Require.sol";
33
+ import { Types } from "../../protocol/lib/Types.sol";
34
+ import { LiquidatorProxyHelper } from "../helpers/LiquidatorProxyHelper.sol";
35
+ import { OnlyDolomiteMargin } from "../helpers/OnlyDolomiteMargin.sol";
36
+
37
+
38
+ /**
39
+ * @title LiquidatorProxyV1
40
+ * @author dYdX
41
+ *
42
+ * Contract for liquidating other accounts in DolomiteMargin.
43
+ */
44
+ contract LiquidatorProxyV1 is OnlyDolomiteMargin, ReentrancyGuard, LiquidatorProxyHelper {
45
+ using Math for uint256;
46
+ using SafeMath for uint256;
47
+ using Types for Types.Par;
48
+ using Types for Types.Wei;
49
+
50
+ // ============ Constants ============
51
+
52
+ bytes32 constant FILE = "LiquidatorProxyV1";
53
+
54
+ // ============ Structs ============
55
+
56
+ struct Constants {
57
+ IDolomiteMargin dolomiteMargin;
58
+ Account.Info solidAccount;
59
+ Account.Info liquidAccount;
60
+ Decimal.D256 minLiquidatorRatio;
61
+ MarketInfo[] markets;
62
+ uint256[] liquidMarkets;
63
+ }
64
+
65
+ struct LiquidatorProxyCache {
66
+ // mutable
67
+ uint256 toLiquidate;
68
+ Types.Wei heldWei;
69
+ Types.Wei owedWei;
70
+ uint256 supplyValue;
71
+ uint256 borrowValue;
72
+
73
+ // immutable
74
+ Decimal.D256 spread;
75
+ uint256 heldMarket;
76
+ uint256 owedMarket;
77
+ uint256 heldPrice;
78
+ uint256 owedPrice;
79
+ uint256 owedPriceAdj;
80
+ }
81
+
82
+ // ============ Constructor ============
83
+
84
+ constructor (
85
+ address dolomiteMargin
86
+ )
87
+ public
88
+ OnlyDolomiteMargin(dolomiteMargin)
89
+ {} /* solium-disable-line no-empty-blocks */
90
+
91
+ // ============ Public Functions ============
92
+
93
+ /**
94
+ * Liquidate liquidAccount using solidAccount. This contract and the msg.sender to this contract
95
+ * must both be operators for the solidAccount.
96
+ *
97
+ * @param solidAccount The account that will do the liquidating
98
+ * @param liquidAccount The account that will be liquidated
99
+ * @param minLiquidatorRatio The minimum collateralization ratio to leave the solidAccount at
100
+ * @param owedPreferences Ordered list of markets to repay first
101
+ * @param heldPreferences Ordered list of markets to receive payout for first
102
+ */
103
+ function liquidate(
104
+ Account.Info memory solidAccount,
105
+ Account.Info memory liquidAccount,
106
+ Decimal.D256 memory minLiquidatorRatio,
107
+ uint256 minValueLiquidated,
108
+ uint256[] memory owedPreferences,
109
+ uint256[] memory heldPreferences
110
+ )
111
+ public
112
+ nonReentrant
113
+ {
114
+ // put all values that will not change into a single struct
115
+ Constants memory constants;
116
+ constants.dolomiteMargin = DOLOMITE_MARGIN;
117
+ constants.solidAccount = solidAccount;
118
+ constants.liquidAccount = liquidAccount;
119
+ constants.minLiquidatorRatio = minLiquidatorRatio;
120
+ constants.liquidMarkets = constants.dolomiteMargin.getAccountMarketsWithNonZeroBalances(liquidAccount);
121
+ constants.markets = getMarketInfos(
122
+ constants.dolomiteMargin,
123
+ constants.dolomiteMargin.getAccountMarketsWithNonZeroBalances(solidAccount),
124
+ constants.liquidMarkets
125
+ );
126
+
127
+ // validate the msg.sender and that the liquidAccount can be liquidated
128
+ checkRequirements(constants);
129
+
130
+ // keep a running tally of how much value will be attempted to be liquidated
131
+ uint256 totalValueLiquidated = 0;
132
+
133
+ // for each owedMarket
134
+ for (uint256 owedIndex = 0; owedIndex < owedPreferences.length; owedIndex++) {
135
+ uint256 owedMarket = owedPreferences[owedIndex];
136
+
137
+ // for each heldMarket
138
+ for (uint256 heldIndex = 0; heldIndex < heldPreferences.length; heldIndex++) {
139
+ uint256 heldMarket = heldPreferences[heldIndex];
140
+
141
+ // cannot use the same market
142
+ if (heldMarket == owedMarket) {
143
+ continue;
144
+ }
145
+
146
+ // cannot liquidate non-negative markets
147
+ if (!constants.dolomiteMargin.getAccountPar(liquidAccount, owedMarket).isNegative()) {
148
+ break;
149
+ }
150
+
151
+ // cannot use non-positive markets as collateral
152
+ if (!constants.dolomiteMargin.getAccountPar(liquidAccount, heldMarket).isPositive()) {
153
+ continue;
154
+ }
155
+
156
+ // get all relevant values
157
+ LiquidatorProxyCache memory cache = initializeCache(constants, heldMarket, owedMarket);
158
+
159
+ // get the liquidation amount (before liquidator decreases in collateralization)
160
+ calculateSafeLiquidationAmount(cache);
161
+
162
+ // get the max liquidation amount (before liquidator reaches minLiquidatorRatio)
163
+ calculateMaxLiquidationAmount(constants, cache);
164
+
165
+ // if nothing to liquidate, do nothing
166
+ if (cache.toLiquidate == 0) {
167
+ continue;
168
+ }
169
+
170
+ // execute the liquidations
171
+ constants.dolomiteMargin.operate(
172
+ constructAccountsArray(constants),
173
+ constructActionsArray(cache)
174
+ );
175
+
176
+ // increment the total value liquidated
177
+ totalValueLiquidated = totalValueLiquidated.add(cache.toLiquidate.mul(cache.owedPrice));
178
+ }
179
+ }
180
+
181
+ // revert if liquidator account does not have a lot of overhead to liquidate these pairs
182
+ Require.that(
183
+ totalValueLiquidated >= minValueLiquidated,
184
+ FILE,
185
+ "Not enough liquidatable value",
186
+ totalValueLiquidated,
187
+ minValueLiquidated
188
+ );
189
+ }
190
+
191
+ // ============ Calculation Functions ============
192
+
193
+ /**
194
+ * Calculate the owedAmount that can be liquidated until the liquidator account will be left
195
+ * with BOTH a non-negative balance of heldMarket AND a non-positive balance of owedMarket.
196
+ * This is the amount that can be liquidated until the collateralization of the liquidator
197
+ * account will begin to decrease.
198
+ */
199
+ function calculateSafeLiquidationAmount(
200
+ LiquidatorProxyCache memory cache
201
+ )
202
+ private
203
+ pure
204
+ {
205
+ bool negOwed = !cache.owedWei.isPositive();
206
+ bool posHeld = !cache.heldWei.isNegative();
207
+
208
+ // owedWei is already negative and heldWei is already positive
209
+ if (negOwed && posHeld) {
210
+ return;
211
+ }
212
+
213
+ // true if it takes longer for the liquidator owed balance to become negative than it takes
214
+ // the liquidator held balance to become positive.
215
+ bool owedGoesToZeroLast;
216
+ if (negOwed) {
217
+ owedGoesToZeroLast = false;
218
+ } else if (posHeld) {
219
+ owedGoesToZeroLast = true;
220
+ } else {
221
+ // owed is still positive and held is still negative
222
+ owedGoesToZeroLast = cache.owedWei.value.mul(cache.owedPriceAdj) > cache.heldWei.value.mul(cache.heldPrice);
223
+ }
224
+
225
+ if (owedGoesToZeroLast) {
226
+ // calculate the change in heldWei to get owedWei to zero
227
+ Types.Wei memory heldWeiDelta = Types.Wei({
228
+ sign: cache.owedWei.sign,
229
+ value: cache.owedWei.value.getPartial(cache.owedPriceAdj, cache.heldPrice)
230
+ });
231
+ setCacheWeiValues(
232
+ cache,
233
+ cache.heldWei.add(heldWeiDelta),
234
+ Types.zeroWei()
235
+ );
236
+ } else {
237
+ // calculate the change in owedWei to get heldWei to zero
238
+ Types.Wei memory owedWeiDelta = Types.Wei({
239
+ sign: cache.heldWei.sign,
240
+ value: cache.heldWei.value.getPartial(cache.heldPrice, cache.owedPriceAdj)
241
+ });
242
+ setCacheWeiValues(
243
+ cache,
244
+ Types.zeroWei(),
245
+ cache.owedWei.add(owedWeiDelta)
246
+ );
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Calculate the additional owedAmount that can be liquidated until the collateralization of the
252
+ * liquidator account reaches the minLiquidatorRatio. By this point, the cache will be set such
253
+ * that the amount of owedMarket is non-positive and the amount of heldMarket is non-negative.
254
+ */
255
+ function calculateMaxLiquidationAmount(
256
+ Constants memory constants,
257
+ LiquidatorProxyCache memory cache
258
+ )
259
+ private
260
+ pure
261
+ {
262
+ assert(!cache.heldWei.isNegative());
263
+ assert(!cache.owedWei.isPositive());
264
+
265
+ // if the liquidator account is already not above the collateralization requirement, return
266
+ bool liquidatorAboveCollateralization = isCollateralized(
267
+ cache.supplyValue,
268
+ cache.borrowValue,
269
+ constants.minLiquidatorRatio
270
+ );
271
+ if (!liquidatorAboveCollateralization) {
272
+ cache.toLiquidate = 0;
273
+ return;
274
+ }
275
+
276
+ // find the value difference between the current margin and the margin at minLiquidatorRatio
277
+ uint256 requiredOverhead = Decimal.mul(cache.borrowValue, constants.minLiquidatorRatio);
278
+ uint256 requiredSupplyValue = cache.borrowValue.add(requiredOverhead);
279
+ uint256 remainingValueBuffer = cache.supplyValue.sub(requiredSupplyValue);
280
+
281
+ // get the absolute difference between the minLiquidatorRatio and the liquidation spread
282
+ Decimal.D256 memory spreadMarginDiff = Decimal.D256({
283
+ value: constants.minLiquidatorRatio.value.sub(cache.spread.value)
284
+ });
285
+
286
+ // get the additional value of owedToken I can borrow to liquidate this position
287
+ uint256 owedValueToTakeOn = Decimal.div(remainingValueBuffer, spreadMarginDiff);
288
+
289
+ // get the additional amount of owedWei to liquidate
290
+ uint256 owedWeiToLiquidate = owedValueToTakeOn.div(cache.owedPrice);
291
+
292
+ // store the additional amount in the cache
293
+ cache.toLiquidate = cache.toLiquidate.add(owedWeiToLiquidate);
294
+ }
295
+
296
+ // ============ Helper Functions ============
297
+
298
+ /**
299
+ * Make some basic checks before attempting to liquidate an account.
300
+ * - Require that the msg.sender has the permission to use the liquidator account
301
+ * - Require that the liquid account is liquidatable
302
+ */
303
+ function checkRequirements(
304
+ Constants memory constants
305
+ )
306
+ private
307
+ view
308
+ {
309
+ // check credentials for msg.sender
310
+ Require.that(
311
+ constants.solidAccount.owner == msg.sender
312
+ || constants.dolomiteMargin.getIsLocalOperator(constants.solidAccount.owner, msg.sender),
313
+ FILE,
314
+ "Sender not operator",
315
+ constants.solidAccount.owner
316
+ );
317
+
318
+ // require that the liquidAccount is liquidatable
319
+ (
320
+ Monetary.Value memory liquidSupplyValue,
321
+ Monetary.Value memory liquidBorrowValue
322
+ ) = getAdjustedAccountValues(
323
+ constants.dolomiteMargin,
324
+ constants.markets,
325
+ constants.liquidAccount,
326
+ constants.liquidMarkets
327
+ );
328
+ Require.that(
329
+ liquidSupplyValue.value != 0,
330
+ FILE,
331
+ "Liquid account no supply"
332
+ );
333
+ Require.that(
334
+ constants.dolomiteMargin.getAccountStatus(constants.liquidAccount) == Account.Status.Liquid ||
335
+ !isCollateralized(
336
+ liquidSupplyValue.value,
337
+ liquidBorrowValue.value,
338
+ constants.dolomiteMargin.getMarginRatio()
339
+ ),
340
+ FILE,
341
+ "Liquid account not liquidatable",
342
+ liquidSupplyValue.value,
343
+ liquidBorrowValue.value
344
+ );
345
+ }
346
+
347
+ /**
348
+ * Changes the cache values to reflect changing the heldWei and owedWei of the liquidator
349
+ * account. Changes toLiquidate, heldWei, owedWei, supplyValue, and borrowValue.
350
+ */
351
+ function setCacheWeiValues(
352
+ LiquidatorProxyCache memory cache,
353
+ Types.Wei memory newHeldWei,
354
+ Types.Wei memory newOwedWei
355
+ )
356
+ private
357
+ pure
358
+ {
359
+ // roll-back the old held value
360
+ uint256 oldHeldValue = cache.heldWei.value.mul(cache.heldPrice);
361
+ if (cache.heldWei.sign) {
362
+ cache.supplyValue = cache.supplyValue.sub(oldHeldValue, "cache.heldWei.sign");
363
+ } else {
364
+ cache.borrowValue = cache.borrowValue.sub(oldHeldValue, "!cache.heldWei.sign");
365
+ }
366
+
367
+ // add the new held value
368
+ uint256 newHeldValue = newHeldWei.value.mul(cache.heldPrice);
369
+ if (newHeldWei.sign) {
370
+ cache.supplyValue = cache.supplyValue.add(newHeldValue);
371
+ } else {
372
+ cache.borrowValue = cache.borrowValue.add(newHeldValue);
373
+ }
374
+
375
+ // roll-back the old owed value
376
+ uint256 oldOwedValue = cache.owedWei.value.mul(cache.owedPrice);
377
+ if (cache.owedWei.sign) {
378
+ cache.supplyValue = cache.supplyValue.sub(oldOwedValue, "cache.owedWei.sign");
379
+ } else {
380
+ cache.borrowValue = cache.borrowValue.sub(oldOwedValue, "!cache.owedWei.sign");
381
+ }
382
+
383
+ // add the new owed value
384
+ uint256 newOwedValue = newOwedWei.value.mul(cache.owedPrice);
385
+ if (newOwedWei.sign) {
386
+ cache.supplyValue = cache.supplyValue.add(newOwedValue);
387
+ } else {
388
+ cache.borrowValue = cache.borrowValue.add(newOwedValue);
389
+ }
390
+
391
+ // update toLiquidate, heldWei, and owedWei
392
+ Types.Wei memory delta = cache.owedWei.sub(newOwedWei);
393
+ assert(!delta.isNegative());
394
+ cache.toLiquidate = cache.toLiquidate.add(delta.value);
395
+ cache.heldWei = newHeldWei;
396
+ cache.owedWei = newOwedWei;
397
+ }
398
+
399
+ /**
400
+ * Returns true if the supplyValue over-collateralizes the borrowValue by the ratio.
401
+ */
402
+ function isCollateralized(
403
+ uint256 supplyValue,
404
+ uint256 borrowValue,
405
+ Decimal.D256 memory ratio
406
+ )
407
+ private
408
+ pure
409
+ returns(bool)
410
+ {
411
+ uint256 requiredMargin = Decimal.mul(borrowValue, ratio);
412
+ return supplyValue >= borrowValue.add(requiredMargin);
413
+ }
414
+
415
+ // ============ Getter Functions ============
416
+
417
+ /**
418
+ * Pre-populates cache values for some pair of markets.
419
+ */
420
+ function initializeCache(
421
+ Constants memory constants,
422
+ uint256 heldMarket,
423
+ uint256 owedMarket
424
+ )
425
+ private
426
+ view
427
+ returns (LiquidatorProxyCache memory)
428
+ {
429
+ (
430
+ Monetary.Value memory supplyValue,
431
+ Monetary.Value memory borrowValue
432
+ ) = getAccountValues(
433
+ constants.dolomiteMargin,
434
+ constants.markets,
435
+ constants.solidAccount,
436
+ constants.dolomiteMargin.getAccountMarketsWithNonZeroBalances(constants.solidAccount)
437
+ );
438
+
439
+ MarketInfo memory heldMarketInfo = binarySearch(constants.markets, heldMarket);
440
+ MarketInfo memory owedMarketInfo = binarySearch(constants.markets, owedMarket);
441
+
442
+ uint256 heldPrice = heldMarketInfo.price.value;
443
+ uint256 owedPrice = owedMarketInfo.price.value;
444
+ Decimal.D256 memory spread = constants.dolomiteMargin.getLiquidationSpreadForPair(heldMarket, owedMarket);
445
+
446
+ return LiquidatorProxyCache({
447
+ heldWei: Interest.parToWei(
448
+ constants.dolomiteMargin.getAccountPar(constants.solidAccount, heldMarket),
449
+ heldMarketInfo.index
450
+ ),
451
+ owedWei: Interest.parToWei(
452
+ constants.dolomiteMargin.getAccountPar(constants.solidAccount, owedMarket),
453
+ owedMarketInfo.index
454
+ ),
455
+ toLiquidate: 0,
456
+ supplyValue: supplyValue.value,
457
+ borrowValue: borrowValue.value,
458
+ heldMarket: heldMarket,
459
+ owedMarket: owedMarket,
460
+ spread: spread,
461
+ heldPrice: heldPrice,
462
+ owedPrice: owedPrice,
463
+ owedPriceAdj: Decimal.mul(owedPrice, Decimal.onePlus(spread))
464
+ });
465
+ }
466
+
467
+ // ============ Operation-Construction Functions ============
468
+
469
+ function constructAccountsArray(
470
+ Constants memory constants
471
+ )
472
+ private
473
+ pure
474
+ returns (Account.Info[] memory)
475
+ {
476
+ Account.Info[] memory accounts = new Account.Info[](2);
477
+ accounts[0] = constants.solidAccount;
478
+ accounts[1] = constants.liquidAccount;
479
+ return accounts;
480
+ }
481
+
482
+ function constructActionsArray(
483
+ LiquidatorProxyCache memory cache
484
+ )
485
+ private
486
+ pure
487
+ returns (Actions.ActionArgs[] memory)
488
+ {
489
+ Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
490
+ actions[0] = Actions.ActionArgs({
491
+ actionType: Actions.ActionType.Liquidate,
492
+ accountId: 0,
493
+ amount: Types.AssetAmount({
494
+ sign: true,
495
+ denomination: Types.AssetDenomination.Wei,
496
+ ref: Types.AssetReference.Delta,
497
+ value: cache.toLiquidate
498
+ }),
499
+ primaryMarketId: cache.owedMarket,
500
+ secondaryMarketId: cache.heldMarket,
501
+ otherAddress: address(0),
502
+ otherAccountId: 1,
503
+ data: new bytes(0)
504
+ });
505
+ return actions;
506
+ }
507
+ }