1. /**
    2. *Submitted for verification at Etherscan.io on 2020-12-18
    3. */
    4. /**
    5. * https://tornado.cash
    6. *
    7. * d888888P dP a88888b. dP
    8. * 88 88 d8' `88 88
    9. * 88 .d8888b. 88d888b. 88d888b. .d8888b. .d888b88 .d8888b. 88 .d8888b. .d8888b. 88d888b.
    10. * 88 88' `88 88' `88 88' `88 88' `88 88' `88 88' `88 88 88' `88 Y8ooooo. 88' `88
    11. * 88 88. .88 88 88 88 88. .88 88. .88 88. .88 dP Y8. .88 88. .88 88 88 88
    12. * dP `88888P' dP dP dP `88888P8 `88888P8 `88888P' 88 Y88888P' `88888P8 `88888P' dP dP
    13. * ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
    14. */
    15. // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
    16. pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
    17. /**
    18. * @dev Interface of the ERC20 standard as defined in the EIP.
    19. */
    20. interface IERC20 {
    21. /**
    22. * @dev Returns the amount of tokens in existence.
    23. */
    24. function totalSupply() external view returns (uint256);
    25. /**
    26. * @dev Returns the amount of tokens owned by `account`.
    27. */
    28. function balanceOf(address account) external view returns (uint256);
    29. /**
    30. * @dev Moves `amount` tokens from the caller's account to `recipient`.
    31. *
    32. * Returns a boolean value indicating whether the operation succeeded.
    33. *
    34. * Emits a {Transfer} event.
    35. */
    36. function transfer(address recipient, uint256 amount) external returns (bool);
    37. /**
    38. * @dev Returns the remaining number of tokens that `spender` will be
    39. * allowed to spend on behalf of `owner` through {transferFrom}. This is
    40. * zero by default.
    41. *
    42. * This value changes when {approve} or {transferFrom} are called.
    43. */
    44. function allowance(address owner, address spender) external view returns (uint256);
    45. /**
    46. * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
    47. *
    48. * Returns a boolean value indicating whether the operation succeeded.
    49. *
    50. * IMPORTANT: Beware that changing an allowance with this method brings the risk
    51. * that someone may use both the old and the new allowance by unfortunate
    52. * transaction ordering. One possible solution to mitigate this race
    53. * condition is to first reduce the spender's allowance to 0 and set the
    54. * desired value afterwards:
    55. * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
    56. *
    57. * Emits an {Approval} event.
    58. */
    59. function approve(address spender, uint256 amount) external returns (bool);
    60. /**
    61. * @dev Moves `amount` tokens from `sender` to `recipient` using the
    62. * allowance mechanism. `amount` is then deducted from the caller's
    63. * allowance.
    64. *
    65. * Returns a boolean value indicating whether the operation succeeded.
    66. *
    67. * Emits a {Transfer} event.
    68. */
    69. function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    70. /**
    71. * @dev Emitted when `value` tokens are moved from one account (`from`) to
    72. * another (`to`).
    73. *
    74. * Note that `value` may be zero.
    75. */
    76. event Transfer(address indexed from, address indexed to, uint256 value);
    77. /**
    78. * @dev Emitted when the allowance of a `spender` for an `owner` is set by
    79. * a call to {approve}. `value` is the new allowance.
    80. */
    81. event Approval(address indexed owner, address indexed spender, uint256 value);
    82. }
    83. // File: @openzeppelin/contracts/math/SafeMath.sol
    84. pragma solidity ^0.6.0;
    85. /**
    86. * @dev Wrappers over Solidity's arithmetic operations with added overflow
    87. * checks.
    88. *
    89. * Arithmetic operations in Solidity wrap on overflow. This can easily result
    90. * in bugs, because programmers usually assume that an overflow raises an
    91. * error, which is the standard behavior in high level programming languages.
    92. * `SafeMath` restores this intuition by reverting the transaction when an
    93. * operation overflows.
    94. *
    95. * Using this library instead of the unchecked operations eliminates an entire
    96. * class of bugs, so it's recommended to use it always.
    97. */
    98. library SafeMath {
    99. /**
    100. * @dev Returns the addition of two unsigned integers, reverting on
    101. * overflow.
    102. *
    103. * Counterpart to Solidity's `+` operator.
    104. *
    105. * Requirements:
    106. *
    107. * - Addition cannot overflow.
    108. */
    109. function add(uint256 a, uint256 b) internal pure returns (uint256) {
    110. uint256 c = a + b;
    111. require(c >= a, "SafeMath: addition overflow");
    112. return c;
    113. }
    114. /**
    115. * @dev Returns the subtraction of two unsigned integers, reverting on
    116. * overflow (when the result is negative).
    117. *
    118. * Counterpart to Solidity's `-` operator.
    119. *
    120. * Requirements:
    121. *
    122. * - Subtraction cannot overflow.
    123. */
    124. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
    125. return sub(a, b, "SafeMath: subtraction overflow");
    126. }
    127. /**
    128. * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
    129. * overflow (when the result is negative).
    130. *
    131. * Counterpart to Solidity's `-` operator.
    132. *
    133. * Requirements:
    134. *
    135. * - Subtraction cannot overflow.
    136. */
    137. function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
    138. require(b <= a, errorMessage);
    139. uint256 c = a - b;
    140. return c;
    141. }
    142. /**
    143. * @dev Returns the multiplication of two unsigned integers, reverting on
    144. * overflow.
    145. *
    146. * Counterpart to Solidity's `*` operator.
    147. *
    148. * Requirements:
    149. *
    150. * - Multiplication cannot overflow.
    151. */
    152. function mul(uint256 a, uint256 b) internal pure returns (uint256) {
    153. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
    154. // benefit is lost if 'b' is also tested.
    155. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
    156. if (a == 0) {
    157. return 0;
    158. }
    159. uint256 c = a * b;
    160. require(c / a == b, "SafeMath: multiplication overflow");
    161. return c;
    162. }
    163. /**
    164. * @dev Returns the integer division of two unsigned integers. Reverts on
    165. * division by zero. The result is rounded towards zero.
    166. *
    167. * Counterpart to Solidity's `/` operator. Note: this function uses a
    168. * `revert` opcode (which leaves remaining gas untouched) while Solidity
    169. * uses an invalid opcode to revert (consuming all remaining gas).
    170. *
    171. * Requirements:
    172. *
    173. * - The divisor cannot be zero.
    174. */
    175. function div(uint256 a, uint256 b) internal pure returns (uint256) {
    176. return div(a, b, "SafeMath: division by zero");
    177. }
    178. /**
    179. * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
    180. * division by zero. The result is rounded towards zero.
    181. *
    182. * Counterpart to Solidity's `/` operator. Note: this function uses a
    183. * `revert` opcode (which leaves remaining gas untouched) while Solidity
    184. * uses an invalid opcode to revert (consuming all remaining gas).
    185. *
    186. * Requirements:
    187. *
    188. * - The divisor cannot be zero.
    189. */
    190. function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
    191. require(b > 0, errorMessage);
    192. uint256 c = a / b;
    193. // assert(a == b * c + a % b); // There is no case in which this doesn't hold
    194. return c;
    195. }
    196. /**
    197. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
    198. * Reverts when dividing by zero.
    199. *
    200. * Counterpart to Solidity's `%` operator. This function uses a `revert`
    201. * opcode (which leaves remaining gas untouched) while Solidity uses an
    202. * invalid opcode to revert (consuming all remaining gas).
    203. *
    204. * Requirements:
    205. *
    206. * - The divisor cannot be zero.
    207. */
    208. function mod(uint256 a, uint256 b) internal pure returns (uint256) {
    209. return mod(a, b, "SafeMath: modulo by zero");
    210. }
    211. /**
    212. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
    213. * Reverts with custom message when dividing by zero.
    214. *
    215. * Counterpart to Solidity's `%` operator. This function uses a `revert`
    216. * opcode (which leaves remaining gas untouched) while Solidity uses an
    217. * invalid opcode to revert (consuming all remaining gas).
    218. *
    219. * Requirements:
    220. *
    221. * - The divisor cannot be zero.
    222. */
    223. function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
    224. require(b != 0, errorMessage);
    225. return a % b;
    226. }
    227. }
    228. // File: @openzeppelin/contracts/utils/Address.sol
    229. pragma solidity ^0.6.2;
    230. /**
    231. * @dev Collection of functions related to the address type
    232. */
    233. library Address {
    234. /**
    235. * @dev Returns true if `account` is a contract.
    236. *
    237. * [IMPORTANT]
    238. * ====
    239. * It is unsafe to assume that an address for which this function returns
    240. * false is an externally-owned account (EOA) and not a contract.
    241. *
    242. * Among others, `isContract` will return false for the following
    243. * types of addresses:
    244. *
    245. * - an externally-owned account
    246. * - a contract in construction
    247. * - an address where a contract will be created
    248. * - an address where a contract lived, but was destroyed
    249. * ====
    250. */
    251. function isContract(address account) internal view returns (bool) {
    252. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
    253. // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
    254. // for accounts without code, i.e. `keccak256('')`
    255. bytes32 codehash;
    256. bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
    257. // solhint-disable-next-line no-inline-assembly
    258. assembly { codehash := extcodehash(account) }
    259. return (codehash != accountHash && codehash != 0x0);
    260. }
    261. /**
    262. * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
    263. * `recipient`, forwarding all available gas and reverting on errors.
    264. *
    265. * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
    266. * of certain opcodes, possibly making contracts go over the 2300 gas limit
    267. * imposed by `transfer`, making them unable to receive funds via
    268. * `transfer`. {sendValue} removes this limitation.
    269. *
    270. * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
    271. *
    272. * IMPORTANT: because control is transferred to `recipient`, care must be
    273. * taken to not create reentrancy vulnerabilities. Consider using
    274. * {ReentrancyGuard} or the
    275. * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
    276. */
    277. function sendValue(address payable recipient, uint256 amount) internal {
    278. require(address(this).balance >= amount, "Address: insufficient balance");
    279. // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
    280. (bool success, ) = recipient.call{ value: amount }("");
    281. require(success, "Address: unable to send value, recipient may have reverted");
    282. }
    283. /**
    284. * @dev Performs a Solidity function call using a low level `call`. A
    285. * plain`call` is an unsafe replacement for a function call: use this
    286. * function instead.
    287. *
    288. * If `target` reverts with a revert reason, it is bubbled up by this
    289. * function (like regular Solidity function calls).
    290. *
    291. * Returns the raw returned data. To convert to the expected return value,
    292. * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
    293. *
    294. * Requirements:
    295. *
    296. * - `target` must be a contract.
    297. * - calling `target` with `data` must not revert.
    298. *
    299. * _Available since v3.1._
    300. */
    301. function functionCall(address target, bytes memory data) internal returns (bytes memory) {
    302. return functionCall(target, data, "Address: low-level call failed");
    303. }
    304. /**
    305. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
    306. * `errorMessage` as a fallback revert reason when `target` reverts.
    307. *
    308. * _Available since v3.1._
    309. */
    310. function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
    311. return _functionCallWithValue(target, data, 0, errorMessage);
    312. }
    313. /**
    314. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
    315. * but also transferring `value` wei to `target`.
    316. *
    317. * Requirements:
    318. *
    319. * - the calling contract must have an ETH balance of at least `value`.
    320. * - the called Solidity function must be `payable`.
    321. *
    322. * _Available since v3.1._
    323. */
    324. function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
    325. return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    326. }
    327. /**
    328. * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
    329. * with `errorMessage` as a fallback revert reason when `target` reverts.
    330. *
    331. * _Available since v3.1._
    332. */
    333. function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
    334. require(address(this).balance >= value, "Address: insufficient balance for call");
    335. return _functionCallWithValue(target, data, value, errorMessage);
    336. }
    337. function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
    338. require(isContract(target), "Address: call to non-contract");
    339. // solhint-disable-next-line avoid-low-level-calls
    340. (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
    341. if (success) {
    342. return returndata;
    343. } else {
    344. // Look for revert reason and bubble it up if present
    345. if (returndata.length > 0) {
    346. // The easiest way to bubble the revert reason is using memory via assembly
    347. // solhint-disable-next-line no-inline-assembly
    348. assembly {
    349. let returndata_size := mload(returndata)
    350. revert(add(32, returndata), returndata_size)
    351. }
    352. } else {
    353. revert(errorMessage);
    354. }
    355. }
    356. }
    357. }
    358. // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
    359. pragma solidity ^0.6.0;
    360. /**
    361. * @title SafeERC20
    362. * @dev Wrappers around ERC20 operations that throw on failure (when the token
    363. * contract returns false). Tokens that return no value (and instead revert or
    364. * throw on failure) are also supported, non-reverting calls are assumed to be
    365. * successful.
    366. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
    367. * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
    368. */
    369. library SafeERC20 {
    370. using SafeMath for uint256;
    371. using Address for address;
    372. function safeTransfer(IERC20 token, address to, uint256 value) internal {
    373. _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    374. }
    375. function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
    376. _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    377. }
    378. /**
    379. * @dev Deprecated. This function has issues similar to the ones found in
    380. * {IERC20-approve}, and its usage is discouraged.
    381. *
    382. * Whenever possible, use {safeIncreaseAllowance} and
    383. * {safeDecreaseAllowance} instead.
    384. */
    385. function safeApprove(IERC20 token, address spender, uint256 value) internal {
    386. // safeApprove should only be called when setting an initial allowance,
    387. // or when resetting it to zero. To increase and decrease it, use
    388. // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
    389. // solhint-disable-next-line max-line-length
    390. require((value == 0) || (token.allowance(address(this), spender) == 0),
    391. "SafeERC20: approve from non-zero to non-zero allowance"
    392. );
    393. _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    394. }
    395. function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
    396. uint256 newAllowance = token.allowance(address(this), spender).add(value);
    397. _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    398. }
    399. function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
    400. uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
    401. _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    402. }
    403. /**
    404. * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
    405. * on the return value: the return value is optional (but if data is returned, it must not be false).
    406. * @param token The token targeted by the call.
    407. * @param data The call data (encoded using abi.encode or one of its variants).
    408. */
    409. function _callOptionalReturn(IERC20 token, bytes memory data) private {
    410. // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
    411. // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
    412. // the target address contains contract code and also asserts for success in the low-level call.
    413. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
    414. if (returndata.length > 0) { // Return data is optional
    415. // solhint-disable-next-line max-line-length
    416. require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    417. }
    418. }
    419. }
    420. // File: torn-token/contracts/ENS.sol
    421. pragma solidity ^0.6.0;
    422. interface ENS {
    423. function resolver(bytes32 node) external view returns (Resolver);
    424. }
    425. interface Resolver {
    426. function addr(bytes32 node) external view returns (address);
    427. }
    428. contract EnsResolve {
    429. function resolve(bytes32 node) public view virtual returns (address) {
    430. ENS Registry = ENS(
    431. getChainId() == 1 ? 0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e : 0x8595bFb0D940DfEDC98943FA8a907091203f25EE
    432. );
    433. return Registry.resolver(node).addr(node);
    434. }
    435. function bulkResolve(bytes32[] memory domains) public view returns (address[] memory result) {
    436. result = new address[](domains.length);
    437. for (uint256 i = 0; i < domains.length; i++) {
    438. result[i] = resolve(domains[i]);
    439. }
    440. }
    441. function getChainId() internal pure returns (uint256) {
    442. uint256 chainId;
    443. assembly {
    444. chainId := chainid()
    445. }
    446. return chainId;
    447. }
    448. }
    449. // File: contracts/utils/FloatMath.sol
    450. // SPDX-License-Identifier: BSD-4-Clause
    451. /*
    452. * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
    453. * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>
    454. */
    455. // pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
    456. pragma solidity ^0.6.0;
    457. /**
    458. * Smart contract library of mathematical functions operating with signed
    459. * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
    460. * basically a simple fraction whose numerator is signed 128-bit integer and
    461. * denominator is 2^64. As long as denominator is always the same, there is no
    462. * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
    463. * represented by int128 type holding only the numerator.
    464. */
    465. library FloatMath {
    466. /*
    467. * Minimum value signed 64.64-bit fixed point number may have.
    468. */
    469. int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
    470. /*
    471. * Maximum value signed 64.64-bit fixed point number may have.
    472. */
    473. int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
    474. /**
    475. * Convert signed 256-bit integer number into signed 64.64-bit fixed point
    476. * number. Revert on overflow.
    477. *
    478. * @param x signed 256-bit integer number
    479. * @return signed 64.64-bit fixed point number
    480. */
    481. function fromInt (int256 x) internal pure returns (int128) {
    482. require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
    483. return int128 (x << 64);
    484. }
    485. /**
    486. * Convert signed 64.64 fixed point number into signed 64-bit integer number
    487. * rounding down.
    488. *
    489. * @param x signed 64.64-bit fixed point number
    490. * @return signed 64-bit integer number
    491. */
    492. function toInt (int128 x) internal pure returns (int64) {
    493. return int64 (x >> 64);
    494. }
    495. /**
    496. * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
    497. * number. Revert on overflow.
    498. *
    499. * @param x unsigned 256-bit integer number
    500. * @return signed 64.64-bit fixed point number
    501. */
    502. function fromUInt (uint256 x) internal pure returns (int128) {
    503. require (x <= 0x7FFFFFFFFFFFFFFF);
    504. return int128 (x << 64);
    505. }
    506. /**
    507. * Convert signed 64.64 fixed point number into unsigned 64-bit integer
    508. * number rounding down. Revert on underflow.
    509. *
    510. * @param x signed 64.64-bit fixed point number
    511. * @return unsigned 64-bit integer number
    512. */
    513. function toUInt (int128 x) internal pure returns (uint64) {
    514. require (x >= 0);
    515. return uint64 (x >> 64);
    516. }
    517. /**
    518. * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
    519. * number rounding down. Revert on overflow.
    520. *
    521. * @param x signed 128.128-bin fixed point number
    522. * @return signed 64.64-bit fixed point number
    523. */
    524. function from128x128 (int256 x) internal pure returns (int128) {
    525. int256 result = x >> 64;
    526. require (result >= MIN_64x64 && result <= MAX_64x64);
    527. return int128 (result);
    528. }
    529. /**
    530. * Convert signed 64.64 fixed point number into signed 128.128 fixed point
    531. * number.
    532. *
    533. * @param x signed 64.64-bit fixed point number
    534. * @return signed 128.128 fixed point number
    535. */
    536. function to128x128 (int128 x) internal pure returns (int256) {
    537. return int256 (x) << 64;
    538. }
    539. /**
    540. * Calculate x + y. Revert on overflow.
    541. *
    542. * @param x signed 64.64-bit fixed point number
    543. * @param y signed 64.64-bit fixed point number
    544. * @return signed 64.64-bit fixed point number
    545. */
    546. function add (int128 x, int128 y) internal pure returns (int128) {
    547. int256 result = int256(x) + y;
    548. require (result >= MIN_64x64 && result <= MAX_64x64);
    549. return int128 (result);
    550. }
    551. /**
    552. * Calculate x - y. Revert on overflow.
    553. *
    554. * @param x signed 64.64-bit fixed point number
    555. * @param y signed 64.64-bit fixed point number
    556. * @return signed 64.64-bit fixed point number
    557. */
    558. function sub (int128 x, int128 y) internal pure returns (int128) {
    559. int256 result = int256(x) - y;
    560. require (result >= MIN_64x64 && result <= MAX_64x64);
    561. return int128 (result);
    562. }
    563. /**
    564. * Calculate x * y rounding down. Revert on overflow.
    565. *
    566. * @param x signed 64.64-bit fixed point number
    567. * @param y signed 64.64-bit fixed point number
    568. * @return signed 64.64-bit fixed point number
    569. */
    570. function mul (int128 x, int128 y) internal pure returns (int128) {
    571. int256 result = int256(x) * y >> 64;
    572. require (result >= MIN_64x64 && result <= MAX_64x64);
    573. return int128 (result);
    574. }
    575. /**
    576. * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
    577. * number and y is signed 256-bit integer number. Revert on overflow.
    578. *
    579. * @param x signed 64.64 fixed point number
    580. * @param y signed 256-bit integer number
    581. * @return signed 256-bit integer number
    582. */
    583. function muli (int128 x, int256 y) internal pure returns (int256) {
    584. if (x == MIN_64x64) {
    585. require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
    586. y <= 0x1000000000000000000000000000000000000000000000000);
    587. return -y << 63;
    588. } else {
    589. bool negativeResult = false;
    590. if (x < 0) {
    591. x = -x;
    592. negativeResult = true;
    593. }
    594. if (y < 0) {
    595. y = -y; // We rely on overflow behavior here
    596. negativeResult = !negativeResult;
    597. }
    598. uint256 absoluteResult = mulu (x, uint256 (y));
    599. if (negativeResult) {
    600. require (absoluteResult <=
    601. 0x8000000000000000000000000000000000000000000000000000000000000000);
    602. return -int256 (absoluteResult); // We rely on overflow behavior here
    603. } else {
    604. require (absoluteResult <=
    605. 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
    606. return int256 (absoluteResult);
    607. }
    608. }
    609. }
    610. /**
    611. * Calculate x * y rounding down, where x is signed 64.64 fixed point number
    612. * and y is unsigned 256-bit integer number. Revert on overflow.
    613. *
    614. * @param x signed 64.64 fixed point number
    615. * @param y unsigned 256-bit integer number
    616. * @return unsigned 256-bit integer number
    617. */
    618. function mulu (int128 x, uint256 y) internal pure returns (uint256) {
    619. if (y == 0) return 0;
    620. require (x >= 0);
    621. uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
    622. uint256 hi = uint256 (x) * (y >> 128);
    623. require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
    624. hi <<= 64;
    625. require (hi <=
    626. 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
    627. return hi + lo;
    628. }
    629. /**
    630. * Calculate x / y rounding towards zero. Revert on overflow or when y is
    631. * zero.
    632. *
    633. * @param x signed 64.64-bit fixed point number
    634. * @param y signed 64.64-bit fixed point number
    635. * @return signed 64.64-bit fixed point number
    636. */
    637. function div (int128 x, int128 y) internal pure returns (int128) {
    638. require (y != 0);
    639. int256 result = (int256 (x) << 64) / y;
    640. require (result >= MIN_64x64 && result <= MAX_64x64);
    641. return int128 (result);
    642. }
    643. /**
    644. * Calculate x / y rounding towards zero, where x and y are signed 256-bit
    645. * integer numbers. Revert on overflow or when y is zero.
    646. *
    647. * @param x signed 256-bit integer number
    648. * @param y signed 256-bit integer number
    649. * @return signed 64.64-bit fixed point number
    650. */
    651. function divi (int256 x, int256 y) internal pure returns (int128) {
    652. require (y != 0);
    653. bool negativeResult = false;
    654. if (x < 0) {
    655. x = -x; // We rely on overflow behavior here
    656. negativeResult = true;
    657. }
    658. if (y < 0) {
    659. y = -y; // We rely on overflow behavior here
    660. negativeResult = !negativeResult;
    661. }
    662. uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
    663. if (negativeResult) {
    664. require (absoluteResult <= 0x80000000000000000000000000000000);
    665. return -int128 (absoluteResult); // We rely on overflow behavior here
    666. } else {
    667. require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
    668. return int128 (absoluteResult); // We rely on overflow behavior here
    669. }
    670. }
    671. /**
    672. * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
    673. * integer numbers. Revert on overflow or when y is zero.
    674. *
    675. * @param x unsigned 256-bit integer number
    676. * @param y unsigned 256-bit integer number
    677. * @return signed 64.64-bit fixed point number
    678. */
    679. function divu (uint256 x, uint256 y) internal pure returns (int128) {
    680. require (y != 0);
    681. uint128 result = divuu (x, y);
    682. require (result <= uint128 (MAX_64x64));
    683. return int128 (result);
    684. }
    685. /**
    686. * Calculate -x. Revert on overflow.
    687. *
    688. * @param x signed 64.64-bit fixed point number
    689. * @return signed 64.64-bit fixed point number
    690. */
    691. function neg (int128 x) internal pure returns (int128) {
    692. require (x != MIN_64x64);
    693. return -x;
    694. }
    695. /**
    696. * Calculate |x|. Revert on overflow.
    697. *
    698. * @param x signed 64.64-bit fixed point number
    699. * @return signed 64.64-bit fixed point number
    700. */
    701. function abs (int128 x) internal pure returns (int128) {
    702. require (x != MIN_64x64);
    703. return x < 0 ? -x : x;
    704. }
    705. /**
    706. * Calculate 1 / x rounding towards zero. Revert on overflow or when x is
    707. * zero.
    708. *
    709. * @param x signed 64.64-bit fixed point number
    710. * @return signed 64.64-bit fixed point number
    711. */
    712. function inv (int128 x) internal pure returns (int128) {
    713. require (x != 0);
    714. int256 result = int256 (0x100000000000000000000000000000000) / x;
    715. require (result >= MIN_64x64 && result <= MAX_64x64);
    716. return int128 (result);
    717. }
    718. /**
    719. * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
    720. *
    721. * @param x signed 64.64-bit fixed point number
    722. * @param y signed 64.64-bit fixed point number
    723. * @return signed 64.64-bit fixed point number
    724. */
    725. function avg (int128 x, int128 y) internal pure returns (int128) {
    726. return int128 ((int256 (x) + int256 (y)) >> 1);
    727. }
    728. /**
    729. * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
    730. * Revert on overflow or in case x * y is negative.
    731. *
    732. * @param x signed 64.64-bit fixed point number
    733. * @param y signed 64.64-bit fixed point number
    734. * @return signed 64.64-bit fixed point number
    735. */
    736. function gavg (int128 x, int128 y) internal pure returns (int128) {
    737. int256 m = int256 (x) * int256 (y);
    738. require (m >= 0);
    739. require (m <
    740. 0x4000000000000000000000000000000000000000000000000000000000000000);
    741. return int128 (sqrtu (uint256 (m)));
    742. }
    743. /**
    744. * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
    745. * and y is unsigned 256-bit integer number. Revert on overflow.
    746. *
    747. * @param x signed 64.64-bit fixed point number
    748. * @param y uint256 value
    749. * @return signed 64.64-bit fixed point number
    750. */
    751. function pow (int128 x, uint256 y) internal pure returns (int128) {
    752. uint256 absoluteResult;
    753. bool negativeResult = false;
    754. if (x >= 0) {
    755. absoluteResult = powu (uint256 (x) << 63, y);
    756. } else {
    757. // We rely on overflow behavior here
    758. absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
    759. negativeResult = y & 1 > 0;
    760. }
    761. absoluteResult >>= 63;
    762. if (negativeResult) {
    763. require (absoluteResult <= 0x80000000000000000000000000000000);
    764. return -int128 (absoluteResult); // We rely on overflow behavior here
    765. } else {
    766. require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
    767. return int128 (absoluteResult); // We rely on overflow behavior here
    768. }
    769. }
    770. /**
    771. * Calculate sqrt (x) rounding down. Revert if x < 0.
    772. *
    773. * @param x signed 64.64-bit fixed point number
    774. * @return signed 64.64-bit fixed point number
    775. */
    776. function sqrt (int128 x) internal pure returns (int128) {
    777. require (x >= 0);
    778. return int128 (sqrtu (uint256 (x) << 64));
    779. }
    780. /**
    781. * Calculate binary logarithm of x. Revert if x <= 0.
    782. *
    783. * @param x signed 64.64-bit fixed point number
    784. * @return signed 64.64-bit fixed point number
    785. */
    786. function log_2 (int128 x) internal pure returns (int128) {
    787. require (x > 0);
    788. int256 msb = 0;
    789. int256 xc = x;
    790. if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
    791. if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
    792. if (xc >= 0x10000) { xc >>= 16; msb += 16; }
    793. if (xc >= 0x100) { xc >>= 8; msb += 8; }
    794. if (xc >= 0x10) { xc >>= 4; msb += 4; }
    795. if (xc >= 0x4) { xc >>= 2; msb += 2; }
    796. if (xc >= 0x2) msb += 1; // No need to shift xc anymore
    797. int256 result = msb - 64 << 64;
    798. uint256 ux = uint256 (x) << uint256 (127 - msb);
    799. for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
    800. ux *= ux;
    801. uint256 b = ux >> 255;
    802. ux >>= 127 + b;
    803. result += bit * int256 (b);
    804. }
    805. return int128 (result);
    806. }
    807. /**
    808. * Calculate natural logarithm of x. Revert if x <= 0.
    809. *
    810. * @param x signed 64.64-bit fixed point number
    811. * @return signed 64.64-bit fixed point number
    812. */
    813. function ln (int128 x) internal pure returns (int128) {
    814. require (x > 0);
    815. return int128 (
    816. uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
    817. }
    818. /**
    819. * Calculate binary exponent of x. Revert on overflow.
    820. *
    821. * @param x signed 64.64-bit fixed point number
    822. * @return signed 64.64-bit fixed point number
    823. */
    824. function exp_2 (int128 x) internal pure returns (int128) {
    825. require (x < 0x400000000000000000); // Overflow
    826. if (x < -0x400000000000000000) return 0; // Underflow
    827. uint256 result = 0x80000000000000000000000000000000;
    828. if (x & 0x8000000000000000 > 0)
    829. result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
    830. if (x & 0x4000000000000000 > 0)
    831. result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
    832. if (x & 0x2000000000000000 > 0)
    833. result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
    834. if (x & 0x1000000000000000 > 0)
    835. result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
    836. if (x & 0x800000000000000 > 0)
    837. result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
    838. if (x & 0x400000000000000 > 0)
    839. result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
    840. if (x & 0x200000000000000 > 0)
    841. result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
    842. if (x & 0x100000000000000 > 0)
    843. result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
    844. if (x & 0x80000000000000 > 0)
    845. result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
    846. if (x & 0x40000000000000 > 0)
    847. result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
    848. if (x & 0x20000000000000 > 0)
    849. result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
    850. if (x & 0x10000000000000 > 0)
    851. result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
    852. if (x & 0x8000000000000 > 0)
    853. result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
    854. if (x & 0x4000000000000 > 0)
    855. result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
    856. if (x & 0x2000000000000 > 0)
    857. result = result * 0x1000162E525EE054754457D5995292026 >> 128;
    858. if (x & 0x1000000000000 > 0)
    859. result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
    860. if (x & 0x800000000000 > 0)
    861. result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
    862. if (x & 0x400000000000 > 0)
    863. result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
    864. if (x & 0x200000000000 > 0)
    865. result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
    866. if (x & 0x100000000000 > 0)
    867. result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
    868. if (x & 0x80000000000 > 0)
    869. result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
    870. if (x & 0x40000000000 > 0)
    871. result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
    872. if (x & 0x20000000000 > 0)
    873. result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
    874. if (x & 0x10000000000 > 0)
    875. result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
    876. if (x & 0x8000000000 > 0)
    877. result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
    878. if (x & 0x4000000000 > 0)
    879. result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
    880. if (x & 0x2000000000 > 0)
    881. result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
    882. if (x & 0x1000000000 > 0)
    883. result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
    884. if (x & 0x800000000 > 0)
    885. result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
    886. if (x & 0x400000000 > 0)
    887. result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
    888. if (x & 0x200000000 > 0)
    889. result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
    890. if (x & 0x100000000 > 0)
    891. result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
    892. if (x & 0x80000000 > 0)
    893. result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
    894. if (x & 0x40000000 > 0)
    895. result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
    896. if (x & 0x20000000 > 0)
    897. result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
    898. if (x & 0x10000000 > 0)
    899. result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
    900. if (x & 0x8000000 > 0)
    901. result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
    902. if (x & 0x4000000 > 0)
    903. result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
    904. if (x & 0x2000000 > 0)
    905. result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
    906. if (x & 0x1000000 > 0)
    907. result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
    908. if (x & 0x800000 > 0)
    909. result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
    910. if (x & 0x400000 > 0)
    911. result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
    912. if (x & 0x200000 > 0)
    913. result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
    914. if (x & 0x100000 > 0)
    915. result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
    916. if (x & 0x80000 > 0)
    917. result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
    918. if (x & 0x40000 > 0)
    919. result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
    920. if (x & 0x20000 > 0)
    921. result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
    922. if (x & 0x10000 > 0)
    923. result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
    924. if (x & 0x8000 > 0)
    925. result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
    926. if (x & 0x4000 > 0)
    927. result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
    928. if (x & 0x2000 > 0)
    929. result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
    930. if (x & 0x1000 > 0)
    931. result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
    932. if (x & 0x800 > 0)
    933. result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
    934. if (x & 0x400 > 0)
    935. result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
    936. if (x & 0x200 > 0)
    937. result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
    938. if (x & 0x100 > 0)
    939. result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
    940. if (x & 0x80 > 0)
    941. result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
    942. if (x & 0x40 > 0)
    943. result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
    944. if (x & 0x20 > 0)
    945. result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
    946. if (x & 0x10 > 0)
    947. result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
    948. if (x & 0x8 > 0)
    949. result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
    950. if (x & 0x4 > 0)
    951. result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
    952. if (x & 0x2 > 0)
    953. result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
    954. if (x & 0x1 > 0)
    955. result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
    956. result >>= uint256 (63 - (x >> 64));
    957. require (result <= uint256 (MAX_64x64));
    958. return int128 (result);
    959. }
    960. /**
    961. * Calculate natural exponent of x. Revert on overflow.
    962. *
    963. * @param x signed 64.64-bit fixed point number
    964. * @return signed 64.64-bit fixed point number
    965. */
    966. function exp (int128 x) internal pure returns (int128) {
    967. require (x < 0x400000000000000000); // Overflow
    968. if (x < -0x400000000000000000) return 0; // Underflow
    969. return exp_2 (
    970. int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
    971. }
    972. /**
    973. * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
    974. * integer numbers. Revert on overflow or when y is zero.
    975. *
    976. * @param x unsigned 256-bit integer number
    977. * @param y unsigned 256-bit integer number
    978. * @return unsigned 64.64-bit fixed point number
    979. */
    980. function divuu (uint256 x, uint256 y) private pure returns (uint128) {
    981. require (y != 0);
    982. uint256 result;
    983. if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
    984. result = (x << 64) / y;
    985. else {
    986. uint256 msb = 192;
    987. uint256 xc = x >> 192;
    988. if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
    989. if (xc >= 0x10000) { xc >>= 16; msb += 16; }
    990. if (xc >= 0x100) { xc >>= 8; msb += 8; }
    991. if (xc >= 0x10) { xc >>= 4; msb += 4; }
    992. if (xc >= 0x4) { xc >>= 2; msb += 2; }
    993. if (xc >= 0x2) msb += 1; // No need to shift xc anymore
    994. result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
    995. require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
    996. uint256 hi = result * (y >> 128);
    997. uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
    998. uint256 xh = x >> 192;
    999. uint256 xl = x << 64;
    1000. if (xl < lo) xh -= 1;
    1001. xl -= lo; // We rely on overflow behavior here
    1002. lo = hi << 128;
    1003. if (xl < lo) xh -= 1;
    1004. xl -= lo; // We rely on overflow behavior here
    1005. assert (xh == hi >> 128);
    1006. result += xl / y;
    1007. }
    1008. require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
    1009. return uint128 (result);
    1010. }
    1011. /**
    1012. * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
    1013. * number and y is unsigned 256-bit integer number. Revert on overflow.
    1014. *
    1015. * @param x unsigned 129.127-bit fixed point number
    1016. * @param y uint256 value
    1017. * @return unsigned 129.127-bit fixed point number
    1018. */
    1019. function powu (uint256 x, uint256 y) private pure returns (uint256) {
    1020. if (y == 0) return 0x80000000000000000000000000000000;
    1021. else if (x == 0) return 0;
    1022. else {
    1023. int256 msb = 0;
    1024. uint256 xc = x;
    1025. if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
    1026. if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
    1027. if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
    1028. if (xc >= 0x10000) { xc >>= 16; msb += 16; }
    1029. if (xc >= 0x100) { xc >>= 8; msb += 8; }
    1030. if (xc >= 0x10) { xc >>= 4; msb += 4; }
    1031. if (xc >= 0x4) { xc >>= 2; msb += 2; }
    1032. if (xc >= 0x2) msb += 1; // No need to shift xc anymore
    1033. int256 xe = msb - 127;
    1034. if (xe > 0) x >>= uint256 (xe);
    1035. else x <<= uint256 (-xe);
    1036. uint256 result = 0x80000000000000000000000000000000;
    1037. int256 re = 0;
    1038. while (y > 0) {
    1039. if (y & 1 > 0) {
    1040. result = result * x;
    1041. y -= 1;
    1042. re += xe;
    1043. if (result >=
    1044. 0x8000000000000000000000000000000000000000000000000000000000000000) {
    1045. result >>= 128;
    1046. re += 1;
    1047. } else result >>= 127;
    1048. if (re < -127) return 0; // Underflow
    1049. require (re < 128); // Overflow
    1050. } else {
    1051. x = x * x;
    1052. y >>= 1;
    1053. xe <<= 1;
    1054. if (x >=
    1055. 0x8000000000000000000000000000000000000000000000000000000000000000) {
    1056. x >>= 128;
    1057. xe += 1;
    1058. } else x >>= 127;
    1059. if (xe < -127) return 0; // Underflow
    1060. require (xe < 128); // Overflow
    1061. }
    1062. }
    1063. if (re > 0) result <<= uint256 (re);
    1064. else if (re < 0) result >>= uint256 (-re);
    1065. return result;
    1066. }
    1067. }
    1068. /**
    1069. * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
    1070. * number.
    1071. *
    1072. * @param x unsigned 256-bit integer number
    1073. * @return unsigned 128-bit integer number
    1074. */
    1075. function sqrtu (uint256 x) private pure returns (uint128) {
    1076. if (x == 0) return 0;
    1077. else {
    1078. uint256 xx = x;
    1079. uint256 r = 1;
    1080. if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
    1081. if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
    1082. if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
    1083. if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
    1084. if (xx >= 0x100) { xx >>= 8; r <<= 4; }
    1085. if (xx >= 0x10) { xx >>= 4; r <<= 2; }
    1086. if (xx >= 0x8) { r <<= 1; }
    1087. r = (r + x / r) >> 1;
    1088. r = (r + x / r) >> 1;
    1089. r = (r + x / r) >> 1;
    1090. r = (r + x / r) >> 1;
    1091. r = (r + x / r) >> 1;
    1092. r = (r + x / r) >> 1;
    1093. r = (r + x / r) >> 1; // Seven iterations should be enough
    1094. uint256 r1 = x / r;
    1095. return uint128 (r < r1 ? r : r1);
    1096. }
    1097. }
    1098. }
    1099. // File: contracts/RewardSwap.sol
    1100. pragma solidity ^0.6.0;
    1101. /**
    1102. Let's imagine we have 1M TORN tokens for anonymity mining to distribute during 1 year (~31536000 seconds).
    1103. The contract should constantly add liquidity to a pool of claimed rewards to TORN (REWD/TORN). At any time user can exchange REWD->TORN using
    1104. this pool. The rate depends on current available TORN liquidity - the more TORN are withdrawn the worse the swap rate is.
    1105. The contract starts with some virtual balance liquidity and adds some TORN tokens every second to the balance. Users will decrease
    1106. this balance by swaps.
    1107. Exchange rate can be calculated as following:
    1108. BalanceAfter = BalanceBefore * e^(-rewardAmount/poolWeight)
    1109. tokens = BalanceBefore - BalanceAfter
    1110. */
    1111. contract RewardSwap is EnsResolve {
    1112. using SafeMath for uint256;
    1113. uint256 public constant DURATION = 365 days;
    1114. IERC20 public immutable torn;
    1115. address public immutable miner;
    1116. uint256 public immutable startTimestamp;
    1117. uint256 public immutable initialLiquidity;
    1118. uint256 public immutable liquidity;
    1119. uint256 public tokensSold;
    1120. uint256 public poolWeight;
    1121. event Swap(address indexed recipient, uint256 pTORN, uint256 TORN);
    1122. event PoolWeightUpdated(uint256 newWeight);
    1123. modifier onlyMiner() {
    1124. require(msg.sender == miner, "Only Miner contract can call");
    1125. _;
    1126. }
    1127. constructor(
    1128. bytes32 _torn,
    1129. bytes32 _miner,
    1130. uint256 _miningCap,
    1131. uint256 _initialLiquidity,
    1132. uint256 _poolWeight
    1133. ) public {
    1134. require(_initialLiquidity <= _miningCap, "Initial liquidity should be lower than mining cap");
    1135. torn = IERC20(resolve(_torn));
    1136. miner = resolve(_miner);
    1137. initialLiquidity = _initialLiquidity;
    1138. liquidity = _miningCap.sub(_initialLiquidity);
    1139. poolWeight = _poolWeight;
    1140. startTimestamp = getTimestamp();
    1141. }
    1142. function swap(address _recipient, uint256 _amount) external onlyMiner returns (uint256) {
    1143. uint256 tokens = getExpectedReturn(_amount);
    1144. tokensSold += tokens;
    1145. require(torn.transfer(_recipient, tokens), "transfer failed");
    1146. emit Swap(_recipient, _amount, tokens);
    1147. return tokens;
    1148. }
    1149. /**
    1150. @dev
    1151. */
    1152. function getExpectedReturn(uint256 _amount) public view returns (uint256) {
    1153. uint256 oldBalance = tornVirtualBalance();
    1154. int128 pow = FloatMath.neg(FloatMath.divu(_amount, poolWeight));
    1155. int128 exp = FloatMath.exp(pow);
    1156. uint256 newBalance = FloatMath.mulu(exp, oldBalance);
    1157. return oldBalance.sub(newBalance);
    1158. }
    1159. function tornVirtualBalance() public view returns (uint256) {
    1160. uint256 passedTime = getTimestamp().sub(startTimestamp);
    1161. if (passedTime < DURATION) {
    1162. return initialLiquidity.add(liquidity.mul(passedTime).div(DURATION)).sub(tokensSold);
    1163. } else {
    1164. return torn.balanceOf(address(this));
    1165. }
    1166. }
    1167. function setPoolWeight(uint256 _newWeight) external onlyMiner {
    1168. poolWeight = _newWeight;
    1169. emit PoolWeightUpdated(_newWeight);
    1170. }
    1171. function getTimestamp() public view virtual returns (uint256) {
    1172. return block.timestamp;
    1173. }
    1174. }