Pool.sol 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. // SPDX-License-Identifier: BUSL-1.1
  2. pragma solidity 0.7.6;
  3. pragma abicoder v2;
  4. // imports
  5. import "@openzeppelin/contracts/access/Ownable.sol";
  6. import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
  7. import "./LPTokenERC20.sol";
  8. import "./interfaces/IMirrorgateFeeLibrary.sol";
  9. // libraries
  10. import "@openzeppelin/contracts/math/SafeMath.sol";
  11. /// Pool contracts on other chains and managed by the Stargate protocol.
  12. contract Pool is LPTokenERC20, ReentrancyGuard {
  13. using SafeMath for uint256;
  14. //---------------------------------------------------------------------------
  15. // CONSTANTS
  16. bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
  17. uint256 public constant BP_DENOMINATOR = 10000;
  18. //---------------------------------------------------------------------------
  19. // STRUCTS
  20. struct ChainPath {
  21. bool ready; // indicate if the counter chainPath has been created.
  22. uint16 dstChainId;
  23. uint256 dstPoolId;
  24. uint256 weight;
  25. uint256 balance;
  26. uint256 lkb;
  27. uint256 credits;
  28. uint256 idealBalance;
  29. }
  30. struct SwapObj {
  31. uint256 amount;
  32. uint256 eqFee;
  33. uint256 eqReward;
  34. uint256 lpFee;
  35. uint256 protocolFee;
  36. uint256 lkbRemove;
  37. }
  38. struct CreditObj {
  39. uint256 credits;
  40. uint256 idealBalance;
  41. }
  42. //---------------------------------------------------------------------------
  43. // VARIABLES
  44. // chainPath
  45. ChainPath[] public chainPaths; // list of connected chains with shared pools
  46. mapping(uint16 => mapping(uint256 => uint256)) public chainPathIndexLookup; // lookup for chainPath by chainId => poolId =>index
  47. // metadata
  48. uint256 public immutable poolId; // shared id between chains to represent same pool
  49. uint256 public sharedDecimals; // the shared decimals (lowest common decimals between chains)
  50. uint256 public localDecimals; // the decimals for the token
  51. uint256 public immutable convertRate; // the decimals for the token
  52. address public immutable token; // the token for the pool
  53. address public immutable router; // the token for the pool
  54. bool public stopSwap; // flag to stop swapping in extreme cases
  55. // Fee and Liquidity
  56. uint256 public totalLiquidity; // the total amount of tokens added on this side of the chain (fees + deposits - withdrawals)
  57. uint256 public totalWeight; // total weight for pool percentages
  58. uint256 public mintFeeBP; // fee basis points for the mint/deposit
  59. uint256 public protocolFeeBalance; // fee balance created from dao fee
  60. uint256 public mintFeeBalance; // fee balance created from mint fee
  61. uint256 public eqFeePool; // pool rewards in Shared Decimal format. indicate the total budget for reverse swap incentive
  62. address public feeLibrary; // address for retrieving fee params for swaps
  63. // Delta related
  64. uint256 public deltaCredit; // credits accumulated from txn
  65. bool public batched; // flag to indicate if we want batch processing.
  66. bool public defaultSwapMode; // flag for the default mode for swap
  67. bool public defaultLPMode; // flag for the default mode for lp
  68. uint256 public swapDeltaBP; // basis points of poolCredits to activate Delta in swap
  69. uint256 public lpDeltaBP; // basis points of poolCredits to activate Delta in liquidity events
  70. //---------------------------------------------------------------------------
  71. // EVENTS
  72. event Mint(address to, uint256 amountLP, uint256 amountSD, uint256 mintFeeAmountSD);
  73. event Burn(address from, uint256 amountLP, uint256 amountSD);
  74. event RedeemLocalCallback(address _to, uint256 _amountSD, uint256 _amountToMintSD);
  75. event Swap(
  76. uint16 chainId,
  77. uint256 dstPoolId,
  78. address from,
  79. uint256 amountSD,
  80. uint256 eqReward,
  81. uint256 eqFee,
  82. uint256 protocolFee,
  83. uint256 lpFee
  84. );
  85. event SendCredits(uint16 dstChainId, uint256 dstPoolId, uint256 credits, uint256 idealBalance);
  86. event RedeemRemote(uint16 chainId, uint256 dstPoolId, address from, uint256 amountLP, uint256 amountSD);
  87. event RedeemLocal(address from, uint256 amountLP, uint256 amountSD, uint16 chainId, uint256 dstPoolId, bytes to);
  88. event InstantRedeemLocal(address from, uint256 amountLP, uint256 amountSD, address to);
  89. event CreditChainPath(uint16 chainId, uint256 srcPoolId, uint256 amountSD, uint256 idealBalance);
  90. event SwapRemote(address to, uint256 amountSD, uint256 protocolFee, uint256 dstFee);
  91. event WithdrawRemote(uint16 srcChainId, uint256 srcPoolId, uint256 swapAmount, uint256 mintAmount);
  92. event ChainPathUpdate(uint16 dstChainId, uint256 dstPoolId, uint256 weight);
  93. event FeesUpdated(uint256 mintFeeBP);
  94. event FeeLibraryUpdated(address feeLibraryAddr);
  95. event StopSwapUpdated(bool swapStop);
  96. event WithdrawProtocolFeeBalance(address to, uint256 amountSD);
  97. event WithdrawMintFeeBalance(address to, uint256 amountSD);
  98. event DeltaParamUpdated(bool batched, uint256 swapDeltaBP, uint256 lpDeltaBP, bool defaultSwapMode, bool defaultLPMode);
  99. //---------------------------------------------------------------------------
  100. // MODIFIERS
  101. modifier onlyRouter() {
  102. require(msg.sender == router, "Mirrorgate: only the router can call this method");
  103. _;
  104. }
  105. constructor(
  106. uint256 _poolId,
  107. address _router,
  108. address _token,
  109. uint256 _sharedDecimals,
  110. uint256 _localDecimals,
  111. address _feeLibrary,
  112. string memory _name,
  113. string memory _symbol
  114. ) LPTokenERC20(_name, _symbol) {
  115. require(_token != address(0x0), "Mirrorgate: _token cannot be 0x0");
  116. require(_router != address(0x0), "Mirrorgate: _router cannot be 0x0");
  117. poolId = _poolId;
  118. router = _router;
  119. token = _token;
  120. sharedDecimals = _sharedDecimals;
  121. decimals = uint8(_sharedDecimals);
  122. localDecimals = _localDecimals;
  123. convertRate = 10**(uint256(localDecimals).sub(sharedDecimals));
  124. totalWeight = 0;
  125. feeLibrary = _feeLibrary;
  126. //delta algo related
  127. batched = false;
  128. defaultSwapMode = true;
  129. defaultLPMode = true;
  130. }
  131. function getChainPathsLength() public view returns (uint256) {
  132. return chainPaths.length;
  133. }
  134. //---------------------------------------------------------------------------
  135. // LOCAL CHAIN FUNCTIONS
  136. function mint(address _to, uint256 _amountLD) external nonReentrant onlyRouter returns (uint256) {
  137. return _mintLocal(_to, _amountLD, true, true);
  138. }
  139. // Local Remote
  140. // ------- ---------
  141. // swap -> swapRemote
  142. function swap(
  143. uint16 _dstChainId,
  144. uint256 _dstPoolId,
  145. address _from,
  146. uint256 _amountLD,
  147. uint256 _minAmountLD,
  148. bool newLiquidity
  149. ) external nonReentrant onlyRouter returns (SwapObj memory) {
  150. require(!stopSwap, "Mirrorgate: swap func stopped");
  151. ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
  152. require(cp.ready == true, "Mirrorgate: counter chainPath is not ready");
  153. uint256 amountSD = amountLDtoSD(_amountLD);
  154. uint256 minAmountSD = amountLDtoSD(_minAmountLD);
  155. // request fee params from library
  156. SwapObj memory s = IMirrorgateFeeLibrary(feeLibrary).getFees(poolId, _dstPoolId, _dstChainId, _from, amountSD);
  157. // equilibrium fee and reward. note eqFee/eqReward are separated from swap liquidity
  158. eqFeePool = eqFeePool.sub(s.eqReward);
  159. // update the new amount the user gets minus the fees
  160. s.amount = amountSD.sub(s.eqFee).sub(s.protocolFee).sub(s.lpFee);
  161. // users will also get the eqReward
  162. require(s.amount.add(s.eqReward) >= minAmountSD, "Mirrorgate: slippage too high");
  163. // behaviours
  164. // - protocolFee: booked, stayed and withdrawn at remote.
  165. // - eqFee: booked, stayed and withdrawn at remote.
  166. // - lpFee: booked and stayed at remote, can be withdrawn anywhere
  167. s.lkbRemove = amountSD.sub(s.lpFee).add(s.eqReward);
  168. // check for transfer solvency.
  169. require(cp.balance >= s.lkbRemove, "Mirrorgate: dst balance too low");
  170. cp.balance = cp.balance.sub(s.lkbRemove);
  171. if (newLiquidity) {
  172. deltaCredit = deltaCredit.add(amountSD).add(s.eqReward);
  173. } else if (s.eqReward > 0) {
  174. deltaCredit = deltaCredit.add(s.eqReward);
  175. }
  176. // distribute credits on condition.
  177. if (!batched || deltaCredit >= totalLiquidity.mul(swapDeltaBP).div(BP_DENOMINATOR)) {
  178. _delta(defaultSwapMode);
  179. }
  180. emit Swap(_dstChainId, _dstPoolId, _from, s.amount, s.eqReward, s.eqFee, s.protocolFee, s.lpFee);
  181. return s;
  182. }
  183. // Local Remote
  184. // ------- ---------
  185. // sendCredits -> creditChainPath
  186. function sendCredits(uint16 _dstChainId, uint256 _dstPoolId) external nonReentrant onlyRouter returns (CreditObj memory c) {
  187. ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
  188. require(cp.ready == true, "Mirrorgate: counter chainPath is not ready");
  189. cp.lkb = cp.lkb.add(cp.credits);
  190. c.idealBalance = totalLiquidity.mul(cp.weight).div(totalWeight);
  191. c.credits = cp.credits;
  192. cp.credits = 0;
  193. emit SendCredits(_dstChainId, _dstPoolId, c.credits, c.idealBalance);
  194. }
  195. // Local Remote
  196. // ------- ---------
  197. // redeemRemote -> swapRemote
  198. function redeemRemote(
  199. uint16 _dstChainId,
  200. uint256 _dstPoolId,
  201. address _from,
  202. uint256 _amountLP
  203. ) external nonReentrant onlyRouter {
  204. require(_from != address(0x0), "Mirrorgate: _from cannot be 0x0");
  205. uint256 amountSD = _burnLocal(_from, _amountLP);
  206. //run Delta
  207. if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
  208. _delta(defaultLPMode);
  209. }
  210. uint256 amountLD = amountSDtoLD(amountSD);
  211. emit RedeemRemote(_dstChainId, _dstPoolId, _from, _amountLP, amountLD);
  212. }
  213. function instantRedeemLocal(
  214. address _from,
  215. uint256 _amountLP,
  216. address _to
  217. ) external nonReentrant onlyRouter returns (uint256 amountSD) {
  218. require(_from != address(0x0), "Mirrorgate: _from cannot be 0x0");
  219. uint256 _deltaCredit = deltaCredit; // sload optimization.
  220. uint256 _capAmountLP = _amountSDtoLP(_deltaCredit);
  221. if (_amountLP > _capAmountLP) _amountLP = _capAmountLP;
  222. amountSD = _burnLocal(_from, _amountLP);
  223. deltaCredit = _deltaCredit.sub(amountSD);
  224. uint256 amountLD = amountSDtoLD(amountSD);
  225. _safeTransfer(token, _to, amountLD);
  226. emit InstantRedeemLocal(_from, _amountLP, amountSD, _to);
  227. }
  228. // Local Remote
  229. // ------- ---------
  230. // redeemLocal -> redeemLocalCheckOnRemote
  231. // redeemLocalCallback <-
  232. function redeemLocal(
  233. address _from,
  234. uint256 _amountLP,
  235. uint16 _dstChainId,
  236. uint256 _dstPoolId,
  237. bytes calldata _to
  238. ) external nonReentrant onlyRouter returns (uint256 amountSD) {
  239. require(_from != address(0x0), "Mirrorgate: _from cannot be 0x0");
  240. // safeguard.
  241. require(chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]].ready == true, "Mirrorgate: counter chainPath is not ready");
  242. amountSD = _burnLocal(_from, _amountLP);
  243. // run Delta
  244. if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
  245. _delta(false);
  246. }
  247. emit RedeemLocal(_from, _amountLP, amountSD, _dstChainId, _dstPoolId, _to);
  248. }
  249. //---------------------------------------------------------------------------
  250. // REMOTE CHAIN FUNCTIONS
  251. // Local Remote
  252. // ------- ---------
  253. // sendCredits -> creditChainPath
  254. function creditChainPath(
  255. uint16 _dstChainId,
  256. uint256 _dstPoolId,
  257. CreditObj memory _c
  258. ) external nonReentrant onlyRouter {
  259. ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
  260. cp.balance = cp.balance.add(_c.credits);
  261. if (cp.idealBalance != _c.idealBalance) {
  262. cp.idealBalance = _c.idealBalance;
  263. }
  264. emit CreditChainPath(_dstChainId, _dstPoolId, _c.credits, _c.idealBalance);
  265. }
  266. // Local Remote
  267. // ------- ---------
  268. // swap -> swapRemote
  269. function swapRemote(
  270. uint16 _srcChainId,
  271. uint256 _srcPoolId,
  272. address _to,
  273. SwapObj memory _s
  274. ) external nonReentrant onlyRouter returns (uint256 amountLD) {
  275. // booking lpFee
  276. totalLiquidity = totalLiquidity.add(_s.lpFee);
  277. // booking eqFee
  278. eqFeePool = eqFeePool.add(_s.eqFee);
  279. // booking stargateFee
  280. protocolFeeBalance = protocolFeeBalance.add(_s.protocolFee);
  281. // update LKB
  282. uint256 chainPathIndex = chainPathIndexLookup[_srcChainId][_srcPoolId];
  283. chainPaths[chainPathIndex].lkb = chainPaths[chainPathIndex].lkb.sub(_s.lkbRemove);
  284. // user receives the amount + the srcReward
  285. amountLD = amountSDtoLD(_s.amount.add(_s.eqReward));
  286. _safeTransfer(token, _to, amountLD);
  287. emit SwapRemote(_to, _s.amount.add(_s.eqReward), _s.protocolFee, _s.eqFee);
  288. }
  289. // Local Remote
  290. // ------- ---------
  291. // redeemLocal -> redeemLocalCheckOnRemote
  292. // redeemLocalCallback <-
  293. function redeemLocalCallback(
  294. uint16 _srcChainId,
  295. uint256 _srcPoolId,
  296. address _to,
  297. uint256 _amountSD,
  298. uint256 _amountToMintSD
  299. ) external nonReentrant onlyRouter {
  300. if (_amountToMintSD > 0) {
  301. _mintLocal(_to, amountSDtoLD(_amountToMintSD), false, false);
  302. }
  303. ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
  304. cp.lkb = cp.lkb.sub(_amountSD);
  305. uint256 amountLD = amountSDtoLD(_amountSD);
  306. _safeTransfer(token, _to, amountLD);
  307. emit RedeemLocalCallback(_to, _amountSD, _amountToMintSD);
  308. }
  309. // Local Remote
  310. // ------- ---------
  311. // redeemLocal(amount) -> redeemLocalCheckOnRemote
  312. // redeemLocalCallback <-
  313. function redeemLocalCheckOnRemote(
  314. uint16 _srcChainId,
  315. uint256 _srcPoolId,
  316. uint256 _amountSD
  317. ) external nonReentrant onlyRouter returns (uint256 swapAmount, uint256 mintAmount) {
  318. ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
  319. if (_amountSD > cp.balance) {
  320. mintAmount = _amountSD - cp.balance;
  321. swapAmount = cp.balance;
  322. cp.balance = 0;
  323. } else {
  324. cp.balance = cp.balance.sub(_amountSD);
  325. swapAmount = _amountSD;
  326. mintAmount = 0;
  327. }
  328. emit WithdrawRemote(_srcChainId, _srcPoolId, swapAmount, mintAmount);
  329. }
  330. //---------------------------------------------------------------------------
  331. // DAO Calls
  332. function createChainPath(
  333. uint16 _dstChainId,
  334. uint256 _dstPoolId,
  335. uint256 _weight
  336. ) external onlyRouter {
  337. for (uint256 i = 0; i < chainPaths.length; ++i) {
  338. ChainPath memory cp = chainPaths[i];
  339. bool exists = cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId;
  340. require(!exists, "Mirrorgate: cant createChainPath of existing dstChainId and _dstPoolId");
  341. }
  342. totalWeight = totalWeight.add(_weight);
  343. chainPathIndexLookup[_dstChainId][_dstPoolId] = chainPaths.length;
  344. chainPaths.push(ChainPath(false, _dstChainId, _dstPoolId, _weight, 0, 0, 0, 0));
  345. emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
  346. }
  347. function setWeightForChainPath(
  348. uint16 _dstChainId,
  349. uint256 _dstPoolId,
  350. uint16 _weight
  351. ) external onlyRouter {
  352. ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
  353. totalWeight = totalWeight.sub(cp.weight).add(_weight);
  354. cp.weight = _weight;
  355. emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
  356. }
  357. function setFee(uint256 _mintFeeBP) external onlyRouter {
  358. require(_mintFeeBP <= BP_DENOMINATOR, "Bridge: cum fees > 100%");
  359. mintFeeBP = _mintFeeBP;
  360. emit FeesUpdated(mintFeeBP);
  361. }
  362. function setFeeLibrary(address _feeLibraryAddr) external onlyRouter {
  363. require(_feeLibraryAddr != address(0x0), "Mirrorgate: fee library cant be 0x0");
  364. feeLibrary = _feeLibraryAddr;
  365. emit FeeLibraryUpdated(_feeLibraryAddr);
  366. }
  367. function setSwapStop(bool _swapStop) external onlyRouter {
  368. stopSwap = _swapStop;
  369. emit StopSwapUpdated(_swapStop);
  370. }
  371. function setDeltaParam(
  372. bool _batched,
  373. uint256 _swapDeltaBP,
  374. uint256 _lpDeltaBP,
  375. bool _defaultSwapMode,
  376. bool _defaultLPMode
  377. ) external onlyRouter {
  378. require(_swapDeltaBP <= BP_DENOMINATOR && _lpDeltaBP <= BP_DENOMINATOR, "Mirrorgate: wrong Delta param");
  379. batched = _batched;
  380. swapDeltaBP = _swapDeltaBP;
  381. lpDeltaBP = _lpDeltaBP;
  382. defaultSwapMode = _defaultSwapMode;
  383. defaultLPMode = _defaultLPMode;
  384. emit DeltaParamUpdated(_batched, _swapDeltaBP, _lpDeltaBP, _defaultSwapMode, _defaultLPMode);
  385. }
  386. function callDelta(bool _fullMode) external onlyRouter {
  387. _delta(_fullMode);
  388. }
  389. function activateChainPath(uint16 _dstChainId, uint256 _dstPoolId) external onlyRouter {
  390. ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
  391. require(cp.ready == false, "Mirrorgate: chainPath is already active");
  392. // this func will only be called once
  393. cp.ready = true;
  394. }
  395. function withdrawProtocolFeeBalance(address _to) external onlyRouter {
  396. if (protocolFeeBalance > 0) {
  397. uint256 amountOfLD = amountSDtoLD(protocolFeeBalance);
  398. protocolFeeBalance = 0;
  399. _safeTransfer(token, _to, amountOfLD);
  400. emit WithdrawProtocolFeeBalance(_to, amountOfLD);
  401. }
  402. }
  403. function withdrawMintFeeBalance(address _to) external onlyRouter {
  404. if (mintFeeBalance > 0) {
  405. uint256 amountOfLD = amountSDtoLD(mintFeeBalance);
  406. mintFeeBalance = 0;
  407. _safeTransfer(token, _to, amountOfLD);
  408. emit WithdrawMintFeeBalance(_to, amountOfLD);
  409. }
  410. }
  411. //---------------------------------------------------------------------------
  412. // INTERNAL
  413. // Conversion Helpers
  414. //---------------------------------------------------------------------------
  415. function amountLPtoLD(uint256 _amountLP) external view returns (uint256) {
  416. return amountSDtoLD(_amountLPtoSD(_amountLP));
  417. }
  418. function _amountLPtoSD(uint256 _amountLP) internal view returns (uint256) {
  419. require(totalSupply > 0, "Mirrorgate: cant convert LPtoSD when totalSupply == 0");
  420. return _amountLP.mul(totalLiquidity).div(totalSupply);
  421. }
  422. function _amountSDtoLP(uint256 _amountSD) internal view returns (uint256) {
  423. require(totalLiquidity > 0, "Mirrorgate: cant convert SDtoLP when totalLiq == 0");
  424. return _amountSD.mul(totalSupply).div(totalLiquidity);
  425. }
  426. function amountSDtoLD(uint256 _amount) internal view returns (uint256) {
  427. return _amount.mul(convertRate);
  428. }
  429. function amountLDtoSD(uint256 _amount) internal view returns (uint256) {
  430. return _amount.div(convertRate);
  431. }
  432. function getAndCheckCP(uint16 _dstChainId, uint256 _dstPoolId) internal view returns (ChainPath storage) {
  433. require(chainPaths.length > 0, "Mirrorgate: no chainpaths exist");
  434. ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
  435. require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Mirrorgate: local chainPath does not exist");
  436. return cp;
  437. }
  438. function getChainPath(uint16 _dstChainId, uint256 _dstPoolId) external view returns (ChainPath memory) {
  439. ChainPath memory cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
  440. require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Mirrorgate: local chainPath does not exist");
  441. return cp;
  442. }
  443. function _burnLocal(address _from, uint256 _amountLP) internal returns (uint256) {
  444. require(totalSupply > 0, "Mirrorgate: cant burn when totalSupply == 0");
  445. uint256 amountOfLPTokens = balanceOf[_from];
  446. require(amountOfLPTokens >= _amountLP, "Mirrorgate: not enough LP tokens to burn");
  447. uint256 amountSD = _amountLP.mul(totalLiquidity).div(totalSupply);
  448. //subtract totalLiquidity accordingly
  449. totalLiquidity = totalLiquidity.sub(amountSD);
  450. _burn(_from, _amountLP);
  451. emit Burn(_from, _amountLP, amountSD);
  452. return amountSD;
  453. }
  454. function _delta(bool fullMode) internal {
  455. if (deltaCredit > 0 && totalWeight > 0) {
  456. uint256 cpLength = chainPaths.length;
  457. uint256[] memory deficit = new uint256[](cpLength);
  458. uint256 totalDeficit = 0;
  459. // algorithm steps 6-9: calculate the total and the amounts required to get to balance state
  460. for (uint256 i = 0; i < cpLength; ++i) {
  461. ChainPath storage cp = chainPaths[i];
  462. // (liquidity * (weight/totalWeight)) - (lkb+credits)
  463. uint256 balLiq = totalLiquidity.mul(cp.weight).div(totalWeight);
  464. uint256 currLiq = cp.lkb.add(cp.credits);
  465. if (balLiq > currLiq) {
  466. // save gas since we know balLiq > currLiq and we know deficit[i] > 0
  467. deficit[i] = balLiq - currLiq;
  468. totalDeficit = totalDeficit.add(deficit[i]);
  469. }
  470. }
  471. // indicates how much delta credit is distributed
  472. uint256 spent;
  473. // handle credits with 2 tranches. the [ < totalDeficit] [excessCredit]
  474. // run full Delta, allocate all credits
  475. if (totalDeficit == 0) {
  476. // only fullMode delta will allocate excess credits
  477. if (fullMode && deltaCredit > 0) {
  478. // credit ChainPath by weights
  479. for (uint256 i = 0; i < cpLength; ++i) {
  480. ChainPath storage cp = chainPaths[i];
  481. // credits = credits + toBalanceChange + remaining allocation based on weight
  482. uint256 amtToCredit = deltaCredit.mul(cp.weight).div(totalWeight);
  483. spent = spent.add(amtToCredit);
  484. cp.credits = cp.credits.add(amtToCredit);
  485. }
  486. } // else do nth
  487. } else if (totalDeficit <= deltaCredit) {
  488. if (fullMode) {
  489. // algorithm step 13: calculate amount to disperse to bring to balance state or as close as possible
  490. uint256 excessCredit = deltaCredit - totalDeficit;
  491. // algorithm steps 14-16: calculate credits
  492. for (uint256 i = 0; i < cpLength; ++i) {
  493. if (deficit[i] > 0) {
  494. ChainPath storage cp = chainPaths[i];
  495. // credits = credits + deficit + remaining allocation based on weight
  496. uint256 amtToCredit = deficit[i].add(excessCredit.mul(cp.weight).div(totalWeight));
  497. spent = spent.add(amtToCredit);
  498. cp.credits = cp.credits.add(amtToCredit);
  499. }
  500. }
  501. } else {
  502. // totalDeficit <= deltaCredit but not running fullMode
  503. // credit chainPaths as is if any deficit, not using all deltaCredit
  504. for (uint256 i = 0; i < cpLength; ++i) {
  505. if (deficit[i] > 0) {
  506. ChainPath storage cp = chainPaths[i];
  507. uint256 amtToCredit = deficit[i];
  508. spent = spent.add(amtToCredit);
  509. cp.credits = cp.credits.add(amtToCredit);
  510. }
  511. }
  512. }
  513. } else {
  514. // totalDeficit > deltaCredit, fullMode or not, normalize the deficit by deltaCredit
  515. for (uint256 i = 0; i < cpLength; ++i) {
  516. if (deficit[i] > 0) {
  517. ChainPath storage cp = chainPaths[i];
  518. uint256 proportionalDeficit = deficit[i].mul(deltaCredit).div(totalDeficit);
  519. spent = spent.add(proportionalDeficit);
  520. cp.credits = cp.credits.add(proportionalDeficit);
  521. }
  522. }
  523. }
  524. // deduct the amount of credit sent
  525. deltaCredit = deltaCredit.sub(spent);
  526. }
  527. }
  528. function _mintLocal(
  529. address _to,
  530. uint256 _amountLD,
  531. bool _feesEnabled,
  532. bool _creditDelta
  533. ) internal returns (uint256 amountSD) {
  534. require(totalWeight > 0, "Mirrorgate: No ChainPaths exist");
  535. amountSD = amountLDtoSD(_amountLD);
  536. uint256 mintFeeSD = 0;
  537. if (_feesEnabled) {
  538. mintFeeSD = amountSD.mul(mintFeeBP).div(BP_DENOMINATOR);
  539. amountSD = amountSD.sub(mintFeeSD);
  540. mintFeeBalance = mintFeeBalance.add(mintFeeSD);
  541. }
  542. if (_creditDelta) {
  543. deltaCredit = deltaCredit.add(amountSD);
  544. }
  545. uint256 amountLPTokens = amountSD;
  546. if (totalSupply != 0) {
  547. amountLPTokens = amountSD.mul(totalSupply).div(totalLiquidity);
  548. }
  549. totalLiquidity = totalLiquidity.add(amountSD);
  550. _mint(_to, amountLPTokens);
  551. emit Mint(_to, amountLPTokens, amountSD, mintFeeSD);
  552. // add to credits and call delta. short circuit to save gas
  553. if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
  554. _delta(defaultLPMode);
  555. }
  556. }
  557. function _safeTransfer(
  558. address _token,
  559. address _to,
  560. uint256 _value
  561. ) private {
  562. (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(SELECTOR, _to, _value));
  563. require(success && (data.length == 0 || abi.decode(data, (bool))), "Mirrorgate: TRANSFER_FAILED");
  564. }
  565. }