Advertisement
Guest User

Untitled

a guest
Jul 9th, 2021
509
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 81.33 KB | None | 0 0
  1. /**
  2. *Submitted for verification at BscScan.com on 2021-04-23
  3. */
  4.  
  5. // SPDX-License-Identifier: MIT
  6.  
  7. // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
  8.  
  9. pragma solidity >=0.5.0;
  10.  
  11. interface IUniswapV2Factory {
  12. event PairCreated(address indexed token0, address indexed token1, address pair, uint);
  13.  
  14. function feeTo() external view returns (address);
  15. function feeToSetter() external view returns (address);
  16.  
  17. function getPair(address tokenA, address tokenB) external view returns (address pair);
  18. function allPairs(uint) external view returns (address pair);
  19. function allPairsLength() external view returns (uint);
  20.  
  21. function createPair(address tokenA, address tokenB) external returns (address pair);
  22.  
  23. function setFeeTo(address) external;
  24. function setFeeToSetter(address) external;
  25. }
  26.  
  27. // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
  28.  
  29. pragma solidity >=0.5.0;
  30.  
  31. interface IUniswapV2Pair {
  32. event Approval(address indexed owner, address indexed spender, uint value);
  33. event Transfer(address indexed from, address indexed to, uint value);
  34.  
  35. function name() external pure returns (string memory);
  36. function symbol() external pure returns (string memory);
  37. function decimals() external pure returns (uint8);
  38. function totalSupply() external view returns (uint);
  39. function balanceOf(address owner) external view returns (uint);
  40. function allowance(address owner, address spender) external view returns (uint);
  41.  
  42. function approve(address spender, uint value) external returns (bool);
  43. function transfer(address to, uint value) external returns (bool);
  44. function transferFrom(address from, address to, uint value) external returns (bool);
  45.  
  46. function DOMAIN_SEPARATOR() external view returns (bytes32);
  47. function PERMIT_TYPEHASH() external pure returns (bytes32);
  48. function nonces(address owner) external view returns (uint);
  49.  
  50. function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
  51.  
  52. event Mint(address indexed sender, uint amount0, uint amount1);
  53. event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
  54. event Swap(
  55. address indexed sender,
  56. uint amount0In,
  57. uint amount1In,
  58. uint amount0Out,
  59. uint amount1Out,
  60. address indexed to
  61. );
  62. event Sync(uint112 reserve0, uint112 reserve1);
  63.  
  64. function MINIMUM_LIQUIDITY() external pure returns (uint);
  65. function factory() external view returns (address);
  66. function token0() external view returns (address);
  67. function token1() external view returns (address);
  68. function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
  69. function price0CumulativeLast() external view returns (uint);
  70. function price1CumulativeLast() external view returns (uint);
  71. function kLast() external view returns (uint);
  72.  
  73. function mint(address to) external returns (uint liquidity);
  74. function burn(address to) external returns (uint amount0, uint amount1);
  75. function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
  76. function skim(address to) external;
  77. function sync() external;
  78.  
  79. function initialize(address, address) external;
  80. }
  81.  
  82. // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
  83.  
  84. pragma solidity >=0.6.2;
  85.  
  86. interface IUniswapV2Router01 {
  87. function factory() external pure returns (address);
  88. function WETH() external pure returns (address);
  89.  
  90. function addLiquidity(
  91. address tokenA,
  92. address tokenB,
  93. uint amountADesired,
  94. uint amountBDesired,
  95. uint amountAMin,
  96. uint amountBMin,
  97. address to,
  98. uint deadline
  99. ) external returns (uint amountA, uint amountB, uint liquidity);
  100. function addLiquidityETH(
  101. address token,
  102. uint amountTokenDesired,
  103. uint amountTokenMin,
  104. uint amountETHMin,
  105. address to,
  106. uint deadline
  107. ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
  108. function removeLiquidity(
  109. address tokenA,
  110. address tokenB,
  111. uint liquidity,
  112. uint amountAMin,
  113. uint amountBMin,
  114. address to,
  115. uint deadline
  116. ) external returns (uint amountA, uint amountB);
  117. function removeLiquidityETH(
  118. address token,
  119. uint liquidity,
  120. uint amountTokenMin,
  121. uint amountETHMin,
  122. address to,
  123. uint deadline
  124. ) external returns (uint amountToken, uint amountETH);
  125. function removeLiquidityWithPermit(
  126. address tokenA,
  127. address tokenB,
  128. uint liquidity,
  129. uint amountAMin,
  130. uint amountBMin,
  131. address to,
  132. uint deadline,
  133. bool approveMax, uint8 v, bytes32 r, bytes32 s
  134. ) external returns (uint amountA, uint amountB);
  135. function removeLiquidityETHWithPermit(
  136. address token,
  137. uint liquidity,
  138. uint amountTokenMin,
  139. uint amountETHMin,
  140. address to,
  141. uint deadline,
  142. bool approveMax, uint8 v, bytes32 r, bytes32 s
  143. ) external returns (uint amountToken, uint amountETH);
  144. function swapExactTokensForTokens(
  145. uint amountIn,
  146. uint amountOutMin,
  147. address[] calldata path,
  148. address to,
  149. uint deadline
  150. ) external returns (uint[] memory amounts);
  151. function swapTokensForExactTokens(
  152. uint amountOut,
  153. uint amountInMax,
  154. address[] calldata path,
  155. address to,
  156. uint deadline
  157. ) external returns (uint[] memory amounts);
  158. function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
  159. external
  160. payable
  161. returns (uint[] memory amounts);
  162. function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
  163. external
  164. returns (uint[] memory amounts);
  165. function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
  166. external
  167. returns (uint[] memory amounts);
  168. function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
  169. external
  170. payable
  171. returns (uint[] memory amounts);
  172.  
  173. function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
  174. function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
  175. function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
  176. function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
  177. function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
  178. }
  179.  
  180. // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
  181.  
  182. pragma solidity >=0.6.2;
  183.  
  184.  
  185. interface IUniswapV2Router02 is IUniswapV2Router01 {
  186. function removeLiquidityETHSupportingFeeOnTransferTokens(
  187. address token,
  188. uint liquidity,
  189. uint amountTokenMin,
  190. uint amountETHMin,
  191. address to,
  192. uint deadline
  193. ) external returns (uint amountETH);
  194. function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
  195. address token,
  196. uint liquidity,
  197. uint amountTokenMin,
  198. uint amountETHMin,
  199. address to,
  200. uint deadline,
  201. bool approveMax, uint8 v, bytes32 r, bytes32 s
  202. ) external returns (uint amountETH);
  203.  
  204. function swapExactTokensForTokensSupportingFeeOnTransferTokens(
  205. uint amountIn,
  206. uint amountOutMin,
  207. address[] calldata path,
  208. address to,
  209. uint deadline
  210. ) external;
  211. function swapExactETHForTokensSupportingFeeOnTransferTokens(
  212. uint amountOutMin,
  213. address[] calldata path,
  214. address to,
  215. uint deadline
  216. ) external payable;
  217. function swapExactTokensForETHSupportingFeeOnTransferTokens(
  218. uint amountIn,
  219. uint amountOutMin,
  220. address[] calldata path,
  221. address to,
  222. uint deadline
  223. ) external;
  224. }
  225.  
  226.  
  227. // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
  228.  
  229. pragma solidity >=0.6.0 <0.8.0;
  230.  
  231. /**
  232. * @dev Contract module that helps prevent reentrant calls to a function.
  233. *
  234. * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
  235. * available, which can be applied to functions to make sure there are no nested
  236. * (reentrant) calls to them.
  237. *
  238. * Note that because there is a single `nonReentrant` guard, functions marked as
  239. * `nonReentrant` may not call one another. This can be worked around by making
  240. * those functions `private`, and then adding `external` `nonReentrant` entry
  241. * points to them.
  242. *
  243. * TIP: If you would like to learn more about reentrancy and alternative ways
  244. * to protect against it, check out our blog post
  245. * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
  246. */
  247. abstract contract ReentrancyGuard {
  248. // Booleans are more expensive than uint256 or any type that takes up a full
  249. // word because each write operation emits an extra SLOAD to first read the
  250. // slot's contents, replace the bits taken up by the boolean, and then write
  251. // back. This is the compiler's defense against contract upgrades and
  252. // pointer aliasing, and it cannot be disabled.
  253.  
  254. // The values being non-zero value makes deployment a bit more expensive,
  255. // but in exchange the refund on every call to nonReentrant will be lower in
  256. // amount. Since refunds are capped to a percentage of the total
  257. // transaction's gas, it is best to keep them low in cases like this one, to
  258. // increase the likelihood of the full refund coming into effect.
  259. uint256 private constant _NOT_ENTERED = 1;
  260. uint256 private constant _ENTERED = 2;
  261.  
  262. uint256 private _status;
  263.  
  264. constructor () internal {
  265. _status = _NOT_ENTERED;
  266. }
  267.  
  268. /**
  269. * @dev Prevents a contract from calling itself, directly or indirectly.
  270. * Calling a `nonReentrant` function from another `nonReentrant`
  271. * function is not supported. It is possible to prevent this from happening
  272. * by making the `nonReentrant` function external, and make it call a
  273. * `private` function that does the actual work.
  274. */
  275. modifier nonReentrant() {
  276. // On the first call to nonReentrant, _notEntered will be true
  277. require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
  278.  
  279. // Any calls to nonReentrant after this point will fail
  280. _status = _ENTERED;
  281.  
  282. _;
  283.  
  284. // By storing the original value once again, a refund is triggered (see
  285. // https://eips.ethereum.org/EIPS/eip-2200)
  286. _status = _NOT_ENTERED;
  287. }
  288. }
  289.  
  290. // File: @openzeppelin/contracts/utils/Context.sol
  291.  
  292. pragma solidity >=0.6.0 <0.8.0;
  293.  
  294. /*
  295. * @dev Provides information about the current execution context, including the
  296. * sender of the transaction and its data. While these are generally available
  297. * via msg.sender and msg.data, they should not be accessed in such a direct
  298. * manner, since when dealing with GSN meta-transactions the account sending and
  299. * paying for execution may not be the actual sender (as far as an application
  300. * is concerned).
  301. *
  302. * This contract is only required for intermediate, library-like contracts.
  303. */
  304. abstract contract Context {
  305. function _msgSender() internal view virtual returns (address payable) {
  306. return msg.sender;
  307. }
  308.  
  309. function _msgData() internal view virtual returns (bytes memory) {
  310. this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
  311. return msg.data;
  312. }
  313. }
  314.  
  315. // File: @openzeppelin/contracts/access/Ownable.sol
  316.  
  317. pragma solidity >=0.6.0 <0.8.0;
  318.  
  319. /**
  320. * @dev Contract module which provides a basic access control mechanism, where
  321. * there is an account (an owner) that can be granted exclusive access to
  322. * specific functions.
  323. *
  324. * By default, the owner account will be the one that deploys the contract. This
  325. * can later be changed with {transferOwnership}.
  326. *
  327. * This module is used through inheritance. It will make available the modifier
  328. * `onlyOwner`, which can be applied to your functions to restrict their use to
  329. * the owner.
  330. */
  331. abstract contract Ownable is Context {
  332. address private _owner;
  333.  
  334. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
  335.  
  336. /**
  337. * @dev Initializes the contract setting the deployer as the initial owner.
  338. */
  339. constructor () internal {
  340. address msgSender = _msgSender();
  341. _owner = msgSender;
  342. emit OwnershipTransferred(address(0), msgSender);
  343. }
  344.  
  345. /**
  346. * @dev Returns the address of the current owner.
  347. */
  348. function owner() public view virtual returns (address) {
  349. return _owner;
  350. }
  351.  
  352. /**
  353. * @dev Throws if called by any account other than the owner.
  354. */
  355. modifier onlyOwner() {
  356. require(owner() == _msgSender(), "Ownable: caller is not the owner");
  357. _;
  358. }
  359.  
  360. /**
  361. * @dev Leaves the contract without owner. It will not be possible to call
  362. * `onlyOwner` functions anymore. Can only be called by the current owner.
  363. *
  364. * NOTE: Renouncing ownership will leave the contract without an owner,
  365. * thereby removing any functionality that is only available to the owner.
  366. */
  367. function renounceOwnership() public virtual onlyOwner {
  368. emit OwnershipTransferred(_owner, address(0));
  369. _owner = address(0);
  370. }
  371.  
  372. /**
  373. * @dev Transfers ownership of the contract to a new account (`newOwner`).
  374. * Can only be called by the current owner.
  375. */
  376. function transferOwnership(address newOwner) public virtual onlyOwner {
  377. require(newOwner != address(0), "Ownable: new owner is the zero address");
  378. emit OwnershipTransferred(_owner, newOwner);
  379. _owner = newOwner;
  380. }
  381. }
  382.  
  383. // File: contracts/libs/IKudexReferral.sol
  384.  
  385. pragma solidity 0.6.12;
  386.  
  387. interface IKudexReferral {
  388. /**
  389. * @dev Record referral.
  390. */
  391. function recordReferral(address user, address referrer) external;
  392.  
  393. /**
  394. * @dev Record referral commission.
  395. */
  396. function recordReferralCommission(address referrer, uint256 commission) external;
  397.  
  398. /**
  399. * @dev Get the referrer address that referred the user.
  400. */
  401. function getReferrer(address user) external view returns (address);
  402. }
  403.  
  404. // File: @openzeppelin/contracts/utils/Address.sol
  405.  
  406. pragma solidity >=0.6.2 <0.8.0;
  407.  
  408. /**
  409. * @dev Collection of functions related to the address type
  410. */
  411. library Address {
  412. /**
  413. * @dev Returns true if `account` is a contract.
  414. *
  415. * [IMPORTANT]
  416. * ====
  417. * It is unsafe to assume that an address for which this function returns
  418. * false is an externally-owned account (EOA) and not a contract.
  419. *
  420. * Among others, `isContract` will return false for the following
  421. * types of addresses:
  422. *
  423. * - an externally-owned account
  424. * - a contract in construction
  425. * - an address where a contract will be created
  426. * - an address where a contract lived, but was destroyed
  427. * ====
  428. */
  429. function isContract(address account) internal view returns (bool) {
  430. // This method relies on extcodesize, which returns 0 for contracts in
  431. // construction, since the code is only stored at the end of the
  432. // constructor execution.
  433.  
  434. uint256 size;
  435. // solhint-disable-next-line no-inline-assembly
  436. assembly { size := extcodesize(account) }
  437. return size > 0;
  438. }
  439.  
  440. /**
  441. * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
  442. * `recipient`, forwarding all available gas and reverting on errors.
  443. *
  444. * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
  445. * of certain opcodes, possibly making contracts go over the 2300 gas limit
  446. * imposed by `transfer`, making them unable to receive funds via
  447. * `transfer`. {sendValue} removes this limitation.
  448. *
  449. * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
  450. *
  451. * IMPORTANT: because control is transferred to `recipient`, care must be
  452. * taken to not create reentrancy vulnerabilities. Consider using
  453. * {ReentrancyGuard} or the
  454. * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
  455. */
  456. function sendValue(address payable recipient, uint256 amount) internal {
  457. require(address(this).balance >= amount, "Address: insufficient balance");
  458.  
  459. // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
  460. (bool success, ) = recipient.call{ value: amount }("");
  461. require(success, "Address: unable to send value, recipient may have reverted");
  462. }
  463.  
  464. /**
  465. * @dev Performs a Solidity function call using a low level `call`. A
  466. * plain`call` is an unsafe replacement for a function call: use this
  467. * function instead.
  468. *
  469. * If `target` reverts with a revert reason, it is bubbled up by this
  470. * function (like regular Solidity function calls).
  471. *
  472. * Returns the raw returned data. To convert to the expected return value,
  473. * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
  474. *
  475. * Requirements:
  476. *
  477. * - `target` must be a contract.
  478. * - calling `target` with `data` must not revert.
  479. *
  480. * _Available since v3.1._
  481. */
  482. function functionCall(address target, bytes memory data) internal returns (bytes memory) {
  483. return functionCall(target, data, "Address: low-level call failed");
  484. }
  485.  
  486. /**
  487. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
  488. * `errorMessage` as a fallback revert reason when `target` reverts.
  489. *
  490. * _Available since v3.1._
  491. */
  492. function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
  493. return functionCallWithValue(target, data, 0, errorMessage);
  494. }
  495.  
  496. /**
  497. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
  498. * but also transferring `value` wei to `target`.
  499. *
  500. * Requirements:
  501. *
  502. * - the calling contract must have an ETH balance of at least `value`.
  503. * - the called Solidity function must be `payable`.
  504. *
  505. * _Available since v3.1._
  506. */
  507. function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
  508. return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
  509. }
  510.  
  511. /**
  512. * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
  513. * with `errorMessage` as a fallback revert reason when `target` reverts.
  514. *
  515. * _Available since v3.1._
  516. */
  517. function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
  518. require(address(this).balance >= value, "Address: insufficient balance for call");
  519. require(isContract(target), "Address: call to non-contract");
  520.  
  521. // solhint-disable-next-line avoid-low-level-calls
  522. (bool success, bytes memory returndata) = target.call{ value: value }(data);
  523. return _verifyCallResult(success, returndata, errorMessage);
  524. }
  525.  
  526. /**
  527. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
  528. * but performing a static call.
  529. *
  530. * _Available since v3.3._
  531. */
  532. function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
  533. return functionStaticCall(target, data, "Address: low-level static call failed");
  534. }
  535.  
  536. /**
  537. * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
  538. * but performing a static call.
  539. *
  540. * _Available since v3.3._
  541. */
  542. function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
  543. require(isContract(target), "Address: static call to non-contract");
  544.  
  545. // solhint-disable-next-line avoid-low-level-calls
  546. (bool success, bytes memory returndata) = target.staticcall(data);
  547. return _verifyCallResult(success, returndata, errorMessage);
  548. }
  549.  
  550. /**
  551. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
  552. * but performing a delegate call.
  553. *
  554. * _Available since v3.4._
  555. */
  556. function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
  557. return functionDelegateCall(target, data, "Address: low-level delegate call failed");
  558. }
  559.  
  560. /**
  561. * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
  562. * but performing a delegate call.
  563. *
  564. * _Available since v3.4._
  565. */
  566. function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
  567. require(isContract(target), "Address: delegate call to non-contract");
  568.  
  569. // solhint-disable-next-line avoid-low-level-calls
  570. (bool success, bytes memory returndata) = target.delegatecall(data);
  571. return _verifyCallResult(success, returndata, errorMessage);
  572. }
  573.  
  574. function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
  575. if (success) {
  576. return returndata;
  577. } else {
  578. // Look for revert reason and bubble it up if present
  579. if (returndata.length > 0) {
  580. // The easiest way to bubble the revert reason is using memory via assembly
  581.  
  582. // solhint-disable-next-line no-inline-assembly
  583. assembly {
  584. let returndata_size := mload(returndata)
  585. revert(add(32, returndata), returndata_size)
  586. }
  587. } else {
  588. revert(errorMessage);
  589. }
  590. }
  591. }
  592. }
  593.  
  594. // File: contracts/libs/SafeKRC20.sol
  595.  
  596. pragma solidity ^0.6.0;
  597.  
  598.  
  599.  
  600.  
  601. /**
  602. * @title SafeKRC20
  603. * @dev Wrappers around KRC20 operations that throw on failure (when the token
  604. * contract returns false). Tokens that return no value (and instead revert or
  605. * throw on failure) are also supported, non-reverting calls are assumed to be
  606. * successful.
  607. * To use this library you can add a `using SafeKRC20 for IKRC20;` statement to your contract,
  608. * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
  609. */
  610. library SafeKRC20 {
  611. using SafeMath for uint256;
  612. using Address for address;
  613.  
  614. function safeTransfer(
  615. IKRC20 token,
  616. address to,
  617. uint256 value
  618. ) internal {
  619. _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
  620. }
  621.  
  622. function safeTransferFrom(
  623. IKRC20 token,
  624. address from,
  625. address to,
  626. uint256 value
  627. ) internal {
  628. _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
  629. }
  630.  
  631. /**
  632. * @dev Deprecated. This function has issues similar to the ones found in
  633. * {IKRC20-approve}, and its usage is discouraged.
  634. *
  635. * Whenever possible, use {safeIncreaseAllowance} and
  636. * {safeDecreaseAllowance} instead.
  637. */
  638. function safeApprove(
  639. IKRC20 token,
  640. address spender,
  641. uint256 value
  642. ) internal {
  643. // safeApprove should only be called when setting an initial allowance,
  644. // or when resetting it to zero. To increase and decrease it, use
  645. // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
  646. // solhint-disable-next-line max-line-length
  647. require(
  648. (value == 0) || (token.allowance(address(this), spender) == 0),
  649. "SafeKRC20: approve from non-zero to non-zero allowance"
  650. );
  651. _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
  652. }
  653.  
  654. function safeIncreaseAllowance(
  655. IKRC20 token,
  656. address spender,
  657. uint256 value
  658. ) internal {
  659. uint256 newAllowance = token.allowance(address(this), spender).add(value);
  660. _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
  661. }
  662.  
  663. function safeDecreaseAllowance(
  664. IKRC20 token,
  665. address spender,
  666. uint256 value
  667. ) internal {
  668. uint256 newAllowance = token.allowance(address(this), spender).sub(
  669. value,
  670. "SafeKRC20: decreased allowance below zero"
  671. );
  672. _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
  673. }
  674.  
  675. /**
  676. * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
  677. * on the return value: the return value is optional (but if data is returned, it must not be false).
  678. * @param token The token targeted by the call.
  679. * @param data The call data (encoded using abi.encode or one of its variants).
  680. */
  681. function _callOptionalReturn(IKRC20 token, bytes memory data) private {
  682. // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
  683. // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
  684. // the target address contains contract code and also asserts for success in the low-level call.
  685.  
  686. bytes memory returndata = address(token).functionCall(data, "SafeKRC20: low-level call failed");
  687. if (returndata.length > 0) {
  688. // Return data is optional
  689. // solhint-disable-next-line max-line-length
  690. require(abi.decode(returndata, (bool)), "SafeKRC20: KRC20 operation did not succeed");
  691. }
  692. }
  693. }
  694.  
  695. // File: contracts/libs/IKRC20.sol
  696.  
  697. pragma solidity >=0.4.0;
  698.  
  699. interface IKRC20 {
  700. /**
  701. * @dev Returns the amount of tokens in existence.
  702. */
  703. function totalSupply() external view returns (uint256);
  704.  
  705. /**
  706. * @dev Returns the token decimals.
  707. */
  708. function decimals() external view returns (uint8);
  709.  
  710. /**
  711. * @dev Returns the token symbol.
  712. */
  713. function symbol() external view returns (string memory);
  714.  
  715. /**
  716. * @dev Returns the token name.
  717. */
  718. function name() external view returns (string memory);
  719.  
  720. /**
  721. * @dev Returns the bep token owner.
  722. */
  723. function getOwner() external view returns (address);
  724.  
  725. /**
  726. * @dev Returns the amount of tokens owned by `account`.
  727. */
  728. function balanceOf(address account) external view returns (uint256);
  729.  
  730. /**
  731. * @dev Moves `amount` tokens from the caller's account to `recipient`.
  732. *
  733. * Returns a boolean value indicating whether the operation succeeded.
  734. *
  735. * Emits a {Transfer} event.
  736. */
  737. function transfer(address recipient, uint256 amount) external returns (bool);
  738.  
  739. /**
  740. * @dev Returns the remaining number of tokens that `spender` will be
  741. * allowed to spend on behalf of `owner` through {transferFrom}. This is
  742. * zero by default.
  743. *
  744. * This value changes when {approve} or {transferFrom} are called.
  745. */
  746. function allowance(address _owner, address spender) external view returns (uint256);
  747.  
  748. /**
  749. * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
  750. *
  751. * Returns a boolean value indicating whether the operation succeeded.
  752. *
  753. * IMPORTANT: Beware that changing an allowance with this method brings the risk
  754. * that someone may use both the old and the new allowance by unfortunate
  755. * transaction ordering. One possible solution to mitigate this race
  756. * condition is to first reduce the spender's allowance to 0 and set the
  757. * desired value afterwards:
  758. * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
  759. *
  760. * Emits an {Approval} event.
  761. */
  762. function approve(address spender, uint256 amount) external returns (bool);
  763.  
  764. /**
  765. * @dev Moves `amount` tokens from `sender` to `recipient` using the
  766. * allowance mechanism. `amount` is then deducted from the caller's
  767. * allowance.
  768. *
  769. * Returns a boolean value indicating whether the operation succeeded.
  770. *
  771. * Emits a {Transfer} event.
  772. */
  773. function transferFrom(
  774. address sender,
  775. address recipient,
  776. uint256 amount
  777. ) external returns (bool);
  778.  
  779. /**
  780. * @dev Emitted when `value` tokens are moved from one account (`from`) to
  781. * another (`to`).
  782. *
  783. * Note that `value` may be zero.
  784. */
  785. event Transfer(address indexed from, address indexed to, uint256 value);
  786.  
  787. /**
  788. * @dev Emitted when the allowance of a `spender` for an `owner` is set by
  789. * a call to {approve}. `value` is the new allowance.
  790. */
  791. event Approval(address indexed owner, address indexed spender, uint256 value);
  792. }
  793.  
  794. // File: @openzeppelin/contracts/math/SafeMath.sol
  795.  
  796. pragma solidity >=0.6.0 <0.8.0;
  797.  
  798. /**
  799. * @dev Wrappers over Solidity's arithmetic operations with added overflow
  800. * checks.
  801. *
  802. * Arithmetic operations in Solidity wrap on overflow. This can easily result
  803. * in bugs, because programmers usually assume that an overflow raises an
  804. * error, which is the standard behavior in high level programming languages.
  805. * `SafeMath` restores this intuition by reverting the transaction when an
  806. * operation overflows.
  807. *
  808. * Using this library instead of the unchecked operations eliminates an entire
  809. * class of bugs, so it's recommended to use it always.
  810. */
  811. library SafeMath {
  812. /**
  813. * @dev Returns the addition of two unsigned integers, with an overflow flag.
  814. *
  815. * _Available since v3.4._
  816. */
  817. function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  818. uint256 c = a + b;
  819. if (c < a) return (false, 0);
  820. return (true, c);
  821. }
  822.  
  823. /**
  824. * @dev Returns the substraction of two unsigned integers, with an overflow flag.
  825. *
  826. * _Available since v3.4._
  827. */
  828. function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  829. if (b > a) return (false, 0);
  830. return (true, a - b);
  831. }
  832.  
  833. /**
  834. * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
  835. *
  836. * _Available since v3.4._
  837. */
  838. function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  839. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
  840. // benefit is lost if 'b' is also tested.
  841. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
  842. if (a == 0) return (true, 0);
  843. uint256 c = a * b;
  844. if (c / a != b) return (false, 0);
  845. return (true, c);
  846. }
  847.  
  848. /**
  849. * @dev Returns the division of two unsigned integers, with a division by zero flag.
  850. *
  851. * _Available since v3.4._
  852. */
  853. function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  854. if (b == 0) return (false, 0);
  855. return (true, a / b);
  856. }
  857.  
  858. /**
  859. * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
  860. *
  861. * _Available since v3.4._
  862. */
  863. function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  864. if (b == 0) return (false, 0);
  865. return (true, a % b);
  866. }
  867.  
  868. /**
  869. * @dev Returns the addition of two unsigned integers, reverting on
  870. * overflow.
  871. *
  872. * Counterpart to Solidity's `+` operator.
  873. *
  874. * Requirements:
  875. *
  876. * - Addition cannot overflow.
  877. */
  878. function add(uint256 a, uint256 b) internal pure returns (uint256) {
  879. uint256 c = a + b;
  880. require(c >= a, "SafeMath: addition overflow");
  881. return c;
  882. }
  883.  
  884. /**
  885. * @dev Returns the subtraction of two unsigned integers, reverting on
  886. * overflow (when the result is negative).
  887. *
  888. * Counterpart to Solidity's `-` operator.
  889. *
  890. * Requirements:
  891. *
  892. * - Subtraction cannot overflow.
  893. */
  894. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
  895. require(b <= a, "SafeMath: subtraction overflow");
  896. return a - b;
  897. }
  898.  
  899. /**
  900. * @dev Returns the multiplication of two unsigned integers, reverting on
  901. * overflow.
  902. *
  903. * Counterpart to Solidity's `*` operator.
  904. *
  905. * Requirements:
  906. *
  907. * - Multiplication cannot overflow.
  908. */
  909. function mul(uint256 a, uint256 b) internal pure returns (uint256) {
  910. if (a == 0) return 0;
  911. uint256 c = a * b;
  912. require(c / a == b, "SafeMath: multiplication overflow");
  913. return c;
  914. }
  915.  
  916. /**
  917. * @dev Returns the integer division of two unsigned integers, reverting on
  918. * division by zero. The result is rounded towards zero.
  919. *
  920. * Counterpart to Solidity's `/` operator. Note: this function uses a
  921. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  922. * uses an invalid opcode to revert (consuming all remaining gas).
  923. *
  924. * Requirements:
  925. *
  926. * - The divisor cannot be zero.
  927. */
  928. function div(uint256 a, uint256 b) internal pure returns (uint256) {
  929. require(b > 0, "SafeMath: division by zero");
  930. return a / b;
  931. }
  932.  
  933. /**
  934. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
  935. * reverting when dividing by zero.
  936. *
  937. * Counterpart to Solidity's `%` operator. This function uses a `revert`
  938. * opcode (which leaves remaining gas untouched) while Solidity uses an
  939. * invalid opcode to revert (consuming all remaining gas).
  940. *
  941. * Requirements:
  942. *
  943. * - The divisor cannot be zero.
  944. */
  945. function mod(uint256 a, uint256 b) internal pure returns (uint256) {
  946. require(b > 0, "SafeMath: modulo by zero");
  947. return a % b;
  948. }
  949.  
  950. /**
  951. * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
  952. * overflow (when the result is negative).
  953. *
  954. * CAUTION: This function is deprecated because it requires allocating memory for the error
  955. * message unnecessarily. For custom revert reasons use {trySub}.
  956. *
  957. * Counterpart to Solidity's `-` operator.
  958. *
  959. * Requirements:
  960. *
  961. * - Subtraction cannot overflow.
  962. */
  963. function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  964. require(b <= a, errorMessage);
  965. return a - b;
  966. }
  967.  
  968. /**
  969. * @dev Returns the integer division of two unsigned integers, reverting with custom message on
  970. * division by zero. The result is rounded towards zero.
  971. *
  972. * CAUTION: This function is deprecated because it requires allocating memory for the error
  973. * message unnecessarily. For custom revert reasons use {tryDiv}.
  974. *
  975. * Counterpart to Solidity's `/` operator. Note: this function uses a
  976. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  977. * uses an invalid opcode to revert (consuming all remaining gas).
  978. *
  979. * Requirements:
  980. *
  981. * - The divisor cannot be zero.
  982. */
  983. function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  984. require(b > 0, errorMessage);
  985. return a / b;
  986. }
  987.  
  988. /**
  989. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
  990. * reverting with custom message when dividing by zero.
  991. *
  992. * CAUTION: This function is deprecated because it requires allocating memory for the error
  993. * message unnecessarily. For custom revert reasons use {tryMod}.
  994. *
  995. * Counterpart to Solidity's `%` operator. This function uses a `revert`
  996. * opcode (which leaves remaining gas untouched) while Solidity uses an
  997. * invalid opcode to revert (consuming all remaining gas).
  998. *
  999. * Requirements:
  1000. *
  1001. * - The divisor cannot be zero.
  1002. */
  1003. function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  1004. require(b > 0, errorMessage);
  1005. return a % b;
  1006. }
  1007. }
  1008.  
  1009.  
  1010. // File: contracts/libs/KRC20.sol
  1011.  
  1012. pragma solidity >=0.4.0;
  1013.  
  1014.  
  1015.  
  1016.  
  1017.  
  1018.  
  1019. /**
  1020. * @dev Implementation of the {IKRC20} interface.
  1021. *
  1022. * This implementation is agnostic to the way tokens are created. This means
  1023. * that a supply mechanism has to be added in a derived contract using {_mint}.
  1024. * For a generic mechanism see {KRC20PresetMinterPauser}.
  1025. *
  1026. * TIP: For a detailed writeup see our guide
  1027. * https://forum.zeppelin.solutions/t/how-to-implement-KRC20-supply-mechanisms/226[How
  1028. * to implement supply mechanisms].
  1029. *
  1030. * We have followed general OpenZeppelin guidelines: functions revert instead
  1031. * of returning `false` on failure. This behavior is nonetheless conventional
  1032. * and does not conflict with the expectations of KRC20 applications.
  1033. *
  1034. * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
  1035. * This allows applications to reconstruct the allowance for all accounts just
  1036. * by listening to said events. Other implementations of the EIP may not emit
  1037. * these events, as it isn't required by the specification.
  1038. *
  1039. * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
  1040. * functions have been added to mitigate the well-known issues around setting
  1041. * allowances. See {IKRC20-approve}.
  1042. */
  1043. contract KRC20 is Context, IKRC20, Ownable {
  1044. using SafeMath for uint256;
  1045. using Address for address;
  1046.  
  1047. mapping(address => uint256) private _balances;
  1048.  
  1049. mapping(address => mapping(address => uint256)) private _allowances;
  1050.  
  1051. uint256 private _totalSupply;
  1052.  
  1053. string private _name;
  1054. string private _symbol;
  1055. uint8 private _decimals;
  1056.  
  1057. /**
  1058. * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
  1059. * a default value of 18.
  1060. *
  1061. * To select a different value for {decimals}, use {_setupDecimals}.
  1062. *
  1063. * All three of these values are immutable: they can only be set once during
  1064. * construction.
  1065. */
  1066. constructor(string memory name, string memory symbol) public {
  1067. _name = name;
  1068. _symbol = symbol;
  1069. _decimals = 18;
  1070. }
  1071.  
  1072. /**
  1073. * @dev Returns the bep token owner.
  1074. */
  1075. function getOwner() external override view returns (address) {
  1076. return owner();
  1077. }
  1078.  
  1079. /**
  1080. * @dev Returns the token name.
  1081. */
  1082. function name() public override view returns (string memory) {
  1083. return _name;
  1084. }
  1085.  
  1086. /**
  1087. * @dev Returns the token decimals.
  1088. */
  1089. function decimals() public override view returns (uint8) {
  1090. return _decimals;
  1091. }
  1092.  
  1093. /**
  1094. * @dev Returns the token symbol.
  1095. */
  1096. function symbol() public override view returns (string memory) {
  1097. return _symbol;
  1098. }
  1099.  
  1100. /**
  1101. * @dev See {KRC20-totalSupply}.
  1102. */
  1103. function totalSupply() public override view returns (uint256) {
  1104. return _totalSupply;
  1105. }
  1106.  
  1107. /**
  1108. * @dev See {KRC20-balanceOf}.
  1109. */
  1110. function balanceOf(address account) public override view returns (uint256) {
  1111. return _balances[account];
  1112. }
  1113.  
  1114. /**
  1115. * @dev See {KRC20-transfer}.
  1116. *
  1117. * Requirements:
  1118. *
  1119. * - `recipient` cannot be the zero address.
  1120. * - the caller must have a balance of at least `amount`.
  1121. */
  1122. function transfer(address recipient, uint256 amount) public override returns (bool) {
  1123. _transfer(_msgSender(), recipient, amount);
  1124. return true;
  1125. }
  1126.  
  1127. /**
  1128. * @dev See {KRC20-allowance}.
  1129. */
  1130. function allowance(address owner, address spender) public override view returns (uint256) {
  1131. return _allowances[owner][spender];
  1132. }
  1133.  
  1134. /**
  1135. * @dev See {KRC20-approve}.
  1136. *
  1137. * Requirements:
  1138. *
  1139. * - `spender` cannot be the zero address.
  1140. */
  1141. function approve(address spender, uint256 amount) public override returns (bool) {
  1142. _approve(_msgSender(), spender, amount);
  1143. return true;
  1144. }
  1145.  
  1146. /**
  1147. * @dev See {KRC20-transferFrom}.
  1148. *
  1149. * Emits an {Approval} event indicating the updated allowance. This is not
  1150. * required by the EIP. See the note at the beginning of {KRC20};
  1151. *
  1152. * Requirements:
  1153. * - `sender` and `recipient` cannot be the zero address.
  1154. * - `sender` must have a balance of at least `amount`.
  1155. * - the caller must have allowance for `sender`'s tokens of at least
  1156. * `amount`.
  1157. */
  1158. function transferFrom(
  1159. address sender,
  1160. address recipient,
  1161. uint256 amount
  1162. ) public override returns (bool) {
  1163. _transfer(sender, recipient, amount);
  1164. _approve(
  1165. sender,
  1166. _msgSender(),
  1167. _allowances[sender][_msgSender()].sub(amount, "KRC20: transfer amount exceeds allowance")
  1168. );
  1169. return true;
  1170. }
  1171.  
  1172. /**
  1173. * @dev Atomically increases the allowance granted to `spender` by the caller.
  1174. *
  1175. * This is an alternative to {approve} that can be used as a mitigation for
  1176. * problems described in {KRC20-approve}.
  1177. *
  1178. * Emits an {Approval} event indicating the updated allowance.
  1179. *
  1180. * Requirements:
  1181. *
  1182. * - `spender` cannot be the zero address.
  1183. */
  1184. function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
  1185. _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
  1186. return true;
  1187. }
  1188.  
  1189. /**
  1190. * @dev Atomically decreases the allowance granted to `spender` by the caller.
  1191. *
  1192. * This is an alternative to {approve} that can be used as a mitigation for
  1193. * problems described in {KRC20-approve}.
  1194. *
  1195. * Emits an {Approval} event indicating the updated allowance.
  1196. *
  1197. * Requirements:
  1198. *
  1199. * - `spender` cannot be the zero address.
  1200. * - `spender` must have allowance for the caller of at least
  1201. * `subtractedValue`.
  1202. */
  1203. function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
  1204. _approve(
  1205. _msgSender(),
  1206. spender,
  1207. _allowances[_msgSender()][spender].sub(subtractedValue, "KRC20: decreased allowance below zero")
  1208. );
  1209. return true;
  1210. }
  1211.  
  1212. /**
  1213. * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
  1214. * the total supply.
  1215. *
  1216. * Requirements
  1217. *
  1218. * - `msg.sender` must be the token owner
  1219. */
  1220. function mint(uint256 amount) public onlyOwner returns (bool) {
  1221. _mint(_msgSender(), amount);
  1222. return true;
  1223. }
  1224.  
  1225. /**
  1226. * @dev Moves tokens `amount` from `sender` to `recipient`.
  1227. *
  1228. * This is internal function is equivalent to {transfer}, and can be used to
  1229. * e.g. implement automatic token fees, slashing mechanisms, etc.
  1230. *
  1231. * Emits a {Transfer} event.
  1232. *
  1233. * Requirements:
  1234. *
  1235. * - `sender` cannot be the zero address.
  1236. * - `recipient` cannot be the zero address.
  1237. * - `sender` must have a balance of at least `amount`.
  1238. */
  1239. function _transfer(
  1240. address sender,
  1241. address recipient,
  1242. uint256 amount
  1243. ) internal virtual {
  1244. require(sender != address(0), "KRC20: transfer from the zero address");
  1245. require(recipient != address(0), "KRC20: transfer to the zero address");
  1246.  
  1247. _balances[sender] = _balances[sender].sub(amount, "KRC20: transfer amount exceeds balance");
  1248. _balances[recipient] = _balances[recipient].add(amount);
  1249. emit Transfer(sender, recipient, amount);
  1250. }
  1251.  
  1252. /** @dev Creates `amount` tokens and assigns them to `account`, increasing
  1253. * the total supply.
  1254. *
  1255. * Emits a {Transfer} event with `from` set to the zero address.
  1256. *
  1257. * Requirements
  1258. *
  1259. * - `to` cannot be the zero address.
  1260. */
  1261. function _mint(address account, uint256 amount) internal {
  1262. require(account != address(0), "KRC20: mint to the zero address");
  1263.  
  1264. _totalSupply = _totalSupply.add(amount);
  1265. _balances[account] = _balances[account].add(amount);
  1266. emit Transfer(address(0), account, amount);
  1267. }
  1268.  
  1269. /**
  1270. * @dev Destroys `amount` tokens from `account`, reducing the
  1271. * total supply.
  1272. *
  1273. * Emits a {Transfer} event with `to` set to the zero address.
  1274. *
  1275. * Requirements
  1276. *
  1277. * - `account` cannot be the zero address.
  1278. * - `account` must have at least `amount` tokens.
  1279. */
  1280. function _burn(address account, uint256 amount) internal {
  1281. require(account != address(0), "KRC20: burn from the zero address");
  1282.  
  1283. _balances[account] = _balances[account].sub(amount, "KRC20: burn amount exceeds balance");
  1284. _totalSupply = _totalSupply.sub(amount);
  1285. emit Transfer(account, address(0), amount);
  1286. }
  1287.  
  1288. /**
  1289. * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
  1290. *
  1291. * This is internal function is equivalent to `approve`, and can be used to
  1292. * e.g. set automatic allowances for certain subsystems, etc.
  1293. *
  1294. * Emits an {Approval} event.
  1295. *
  1296. * Requirements:
  1297. *
  1298. * - `owner` cannot be the zero address.
  1299. * - `spender` cannot be the zero address.
  1300. */
  1301. function _approve(
  1302. address owner,
  1303. address spender,
  1304. uint256 amount
  1305. ) internal {
  1306. require(owner != address(0), "KRC20: approve from the zero address");
  1307. require(spender != address(0), "KRC20: approve to the zero address");
  1308.  
  1309. _allowances[owner][spender] = amount;
  1310. emit Approval(owner, spender, amount);
  1311. }
  1312.  
  1313. /**
  1314. * @dev Destroys `amount` tokens from `account`.`amount` is then deducted
  1315. * from the caller's allowance.
  1316. *
  1317. * See {_burn} and {_approve}.
  1318. */
  1319. function _burnFrom(address account, uint256 amount) internal {
  1320. _burn(account, amount);
  1321. _approve(
  1322. account,
  1323. _msgSender(),
  1324. _allowances[account][_msgSender()].sub(amount, "KRC20: burn amount exceeds allowance")
  1325. );
  1326. }
  1327. }
  1328.  
  1329. // File: contracts/KudexToken.sol
  1330.  
  1331. pragma solidity 0.6.12;
  1332.  
  1333.  
  1334.  
  1335.  
  1336.  
  1337. // KudexToken with Governance.
  1338. contract KudexToken is KRC20 {
  1339. // Transfer tax rate in basis points. (default 5%)
  1340. uint16 public transferTaxRate = 500;
  1341. // Burn rate % of transfer tax. (default 20% x 5% = 1% of total amount).
  1342. uint16 public burnRate = 20;
  1343. // Max transfer tax rate: 10%.
  1344. uint16 public constant MAXIMUM_TRANSFER_TAX_RATE = 1000;
  1345. // Burn address
  1346. address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
  1347.  
  1348. // Max transfer amount rate in basis points. (default is 0.5% of total supply)
  1349. uint16 public maxTransferAmountRate = 50;
  1350. // Addresses that excluded from antiWhale
  1351. mapping(address => bool) private _excludedFromAntiWhale;
  1352. // Automatic swap and liquify enabled
  1353. bool public swapAndLiquifyEnabled = false;
  1354. // Min amount to liquify. (default 500 KUDs)
  1355. uint256 public minAmountToLiquify = 500 ether;
  1356. // The swap router, modifiable. Will be changed to KudexSwap's router when our own AMM release
  1357. IUniswapV2Router02 public kudexSwapRouter;
  1358. // The trading pair
  1359. address public kudexSwapPair;
  1360. // In swap and liquify
  1361. bool private _inSwapAndLiquify;
  1362.  
  1363. // The operator can only update the transfer tax rate
  1364. address private _operator;
  1365.  
  1366. // Events
  1367. event OperatorTransferred(address indexed previousOperator, address indexed newOperator);
  1368. event TransferTaxRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
  1369. event BurnRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
  1370. event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
  1371. event SwapAndLiquifyEnabledUpdated(address indexed operator, bool enabled);
  1372. event MinAmountToLiquifyUpdated(address indexed operator, uint256 previousAmount, uint256 newAmount);
  1373. event KudexSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair);
  1374. event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
  1375.  
  1376. modifier onlyOperator() {
  1377. require(_operator == msg.sender, "operator: caller is not the operator");
  1378. _;
  1379. }
  1380.  
  1381. modifier antiWhale(address sender, address recipient, uint256 amount) {
  1382. if (maxTransferAmount() > 0) {
  1383. if (
  1384. _excludedFromAntiWhale[sender] == false
  1385. && _excludedFromAntiWhale[recipient] == false
  1386. ) {
  1387. require(amount <= maxTransferAmount(), "KUDEX::antiWhale: Transfer amount exceeds the maxTransferAmount");
  1388. }
  1389. }
  1390. _;
  1391. }
  1392.  
  1393. modifier lockTheSwap {
  1394. _inSwapAndLiquify = true;
  1395. _;
  1396. _inSwapAndLiquify = false;
  1397. }
  1398.  
  1399. modifier transferTaxFree {
  1400. uint16 _transferTaxRate = transferTaxRate;
  1401. transferTaxRate = 0;
  1402. _;
  1403. transferTaxRate = _transferTaxRate;
  1404. }
  1405.  
  1406. /**
  1407. * @notice Constructs the KudexToken contract.
  1408. */
  1409. constructor() public KRC20("Kudex Token", "KUD") {
  1410. _operator = _msgSender();
  1411. emit OperatorTransferred(address(0), _operator);
  1412.  
  1413. _excludedFromAntiWhale[msg.sender] = true;
  1414. _excludedFromAntiWhale[address(0)] = true;
  1415. _excludedFromAntiWhale[address(this)] = true;
  1416. _excludedFromAntiWhale[BURN_ADDRESS] = true;
  1417. }
  1418.  
  1419. /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
  1420. function mint(address _to, uint256 _amount) public onlyOwner {
  1421. _mint(_to, _amount);
  1422. _moveDelegates(address(0), _delegates[_to], _amount);
  1423. }
  1424.  
  1425. /// @dev overrides transfer function to meet tokenomics of KUD
  1426. function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) {
  1427. // swap and liquify
  1428. if (
  1429. swapAndLiquifyEnabled == true
  1430. && _inSwapAndLiquify == false
  1431. && address(kudexSwapRouter) != address(0)
  1432. && kudexSwapPair != address(0)
  1433. && sender != kudexSwapPair
  1434. && sender != owner()
  1435. ) {
  1436. swapAndLiquify();
  1437. }
  1438.  
  1439. if (recipient == BURN_ADDRESS || transferTaxRate == 0) {
  1440. super._transfer(sender, recipient, amount);
  1441. } else {
  1442. // default tax is 5% of every transfer
  1443. uint256 taxAmount = amount.mul(transferTaxRate).div(10000);
  1444. uint256 burnAmount = taxAmount.mul(burnRate).div(100);
  1445. uint256 liquidityAmount = taxAmount.sub(burnAmount);
  1446. require(taxAmount == burnAmount + liquidityAmount, "KUD::transfer: Burn value invalid");
  1447.  
  1448. // default 95% of transfer sent to recipient
  1449. uint256 sendAmount = amount.sub(taxAmount);
  1450. require(amount == sendAmount + taxAmount, "KUD::transfer: Tax value invalid");
  1451.  
  1452. super._transfer(sender, BURN_ADDRESS, burnAmount);
  1453. super._transfer(sender, address(this), liquidityAmount);
  1454. super._transfer(sender, recipient, sendAmount);
  1455. amount = sendAmount;
  1456. }
  1457. }
  1458.  
  1459. /// @dev Swap and liquify
  1460. function swapAndLiquify() private lockTheSwap transferTaxFree {
  1461. uint256 contractTokenBalance = balanceOf(address(this));
  1462. uint256 maxTransferAmount = maxTransferAmount();
  1463. contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance;
  1464.  
  1465. if (contractTokenBalance >= minAmountToLiquify) {
  1466. // only min amount to liquify
  1467. uint256 liquifyAmount = minAmountToLiquify;
  1468.  
  1469. // split the liquify amount into halves
  1470. uint256 half = liquifyAmount.div(2);
  1471. uint256 otherHalf = liquifyAmount.sub(half);
  1472.  
  1473. // capture the contract's current ETH balance.
  1474. // this is so that we can capture exactly the amount of ETH that the
  1475. // swap creates, and not make the liquidity event include any ETH that
  1476. // has been manually sent to the contract
  1477. uint256 initialBalance = address(this).balance;
  1478.  
  1479. // swap tokens for ETH
  1480. swapTokensForEth(half);
  1481.  
  1482. // how much ETH did we just swap into?
  1483. uint256 newBalance = address(this).balance.sub(initialBalance);
  1484.  
  1485. // add liquidity
  1486. addLiquidity(otherHalf, newBalance);
  1487.  
  1488. emit SwapAndLiquify(half, newBalance, otherHalf);
  1489. }
  1490. }
  1491.  
  1492. /// @dev Swap tokens for eth
  1493. function swapTokensForEth(uint256 tokenAmount) private {
  1494. // generate the kudexSwap pair path of token -> weth
  1495. address[] memory path = new address[](2);
  1496. path[0] = address(this);
  1497. path[1] = kudexSwapRouter.WETH();
  1498.  
  1499. _approve(address(this), address(kudexSwapRouter), tokenAmount);
  1500.  
  1501. // make the swap
  1502. kudexSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
  1503. tokenAmount,
  1504. 0, // accept any amount of ETH
  1505. path,
  1506. address(this),
  1507. block.timestamp
  1508. );
  1509. }
  1510.  
  1511. /// @dev Add liquidity
  1512. function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
  1513. // approve token transfer to cover all possible scenarios
  1514. _approve(address(this), address(kudexSwapRouter), tokenAmount);
  1515.  
  1516. // add the liquidity
  1517. kudexSwapRouter.addLiquidityETH{value: ethAmount}(
  1518. address(this),
  1519. tokenAmount,
  1520. 0, // slippage is unavoidable
  1521. 0, // slippage is unavoidable
  1522. operator(),
  1523. block.timestamp
  1524. );
  1525. }
  1526.  
  1527. /**
  1528. * @dev Returns the max transfer amount.
  1529. */
  1530. function maxTransferAmount() public view returns (uint256) {
  1531. return totalSupply().mul(maxTransferAmountRate).div(10000);
  1532. }
  1533.  
  1534. /**
  1535. * @dev Returns the address is excluded from antiWhale or not.
  1536. */
  1537. function isExcludedFromAntiWhale(address _account) public view returns (bool) {
  1538. return _excludedFromAntiWhale[_account];
  1539. }
  1540.  
  1541. // To receive BNB from kudexSwapRouter when swapping
  1542. receive() external payable {}
  1543.  
  1544. /**
  1545. * @dev Update the transfer tax rate.
  1546. * Can only be called by the current operator.
  1547. */
  1548. function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOperator {
  1549. require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "KUD::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate.");
  1550. emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate);
  1551. transferTaxRate = _transferTaxRate;
  1552. }
  1553.  
  1554. /**
  1555. * @dev Update the burn rate.
  1556. * Can only be called by the current operator.
  1557. */
  1558. function updateBurnRate(uint16 _burnRate) public onlyOperator {
  1559. require(_burnRate <= 100, "KUD::updateBurnRate: Burn rate must not exceed the maximum rate.");
  1560. emit BurnRateUpdated(msg.sender, burnRate, _burnRate);
  1561. burnRate = _burnRate;
  1562. }
  1563.  
  1564. /**
  1565. * @dev Update the max transfer amount rate.
  1566. * Can only be called by the current operator.
  1567. */
  1568. function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOperator {
  1569. require(_maxTransferAmountRate <= 10000, "KUD::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate.");
  1570. emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate);
  1571. maxTransferAmountRate = _maxTransferAmountRate;
  1572. }
  1573.  
  1574. /**
  1575. * @dev Update the min amount to liquify.
  1576. * Can only be called by the current operator.
  1577. */
  1578. function updateMinAmountToLiquify(uint256 _minAmount) public onlyOperator {
  1579. emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount);
  1580. minAmountToLiquify = _minAmount;
  1581. }
  1582.  
  1583. /**
  1584. * @dev Exclude or include an address from antiWhale.
  1585. * Can only be called by the current operator.
  1586. */
  1587. function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyOperator {
  1588. _excludedFromAntiWhale[_account] = _excluded;
  1589. }
  1590.  
  1591. /**
  1592. * @dev Update the swapAndLiquifyEnabled.
  1593. * Can only be called by the current operator.
  1594. */
  1595. function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOperator {
  1596. emit SwapAndLiquifyEnabledUpdated(msg.sender, _enabled);
  1597. swapAndLiquifyEnabled = _enabled;
  1598. }
  1599.  
  1600. /**
  1601. * @dev Update the swap router.
  1602. * Can only be called by the current operator.
  1603. */
  1604. function updateKudexSwapRouter(address _router) public onlyOperator {
  1605. kudexSwapRouter = IUniswapV2Router02(_router);
  1606. kudexSwapPair = IUniswapV2Factory(kudexSwapRouter.factory()).getPair(address(this), kudexSwapRouter.WETH());
  1607. require(kudexSwapPair != address(0), "KUD::updateKudexSwapRouter: Invalid pair address.");
  1608. emit KudexSwapRouterUpdated(msg.sender, address(kudexSwapRouter), kudexSwapPair);
  1609. }
  1610.  
  1611. /**
  1612. * @dev Returns the address of the current operator.
  1613. */
  1614. function operator() public view returns (address) {
  1615. return _operator;
  1616. }
  1617.  
  1618. /**
  1619. * @dev Transfers operator of the contract to a new account (`newOperator`).
  1620. * Can only be called by the current operator.
  1621. */
  1622. function transferOperator(address newOperator) public onlyOperator {
  1623. require(newOperator != address(0), "KUD::transferOperator: new operator is the zero address");
  1624. emit OperatorTransferred(_operator, newOperator);
  1625. _operator = newOperator;
  1626. }
  1627.  
  1628. // Copied and modified from YAM code:
  1629. // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
  1630. // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
  1631. // Which is copied and modified from COMPOUND:
  1632. // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
  1633.  
  1634. /// @dev A record of each accounts delegate
  1635. mapping (address => address) internal _delegates;
  1636.  
  1637. /// @notice A checkpoint for marking number of votes from a given block
  1638. struct Checkpoint {
  1639. uint32 fromBlock;
  1640. uint256 votes;
  1641. }
  1642.  
  1643. /// @notice A record of votes checkpoints for each account, by index
  1644. mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
  1645.  
  1646. /// @notice The number of checkpoints for each account
  1647. mapping (address => uint32) public numCheckpoints;
  1648.  
  1649. /// @notice The EIP-712 typehash for the contract's domain
  1650. bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
  1651.  
  1652. /// @notice The EIP-712 typehash for the delegation struct used by the contract
  1653. bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
  1654.  
  1655. /// @notice A record of states for signing / validating signatures
  1656. mapping (address => uint) public nonces;
  1657.  
  1658. /// @notice An event thats emitted when an account changes its delegate
  1659. event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
  1660.  
  1661. /// @notice An event thats emitted when a delegate account's vote balance changes
  1662. event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
  1663.  
  1664. /**
  1665. * @notice Delegate votes from `msg.sender` to `delegatee`
  1666. * @param delegator The address to get delegatee for
  1667. */
  1668. function delegates(address delegator)
  1669. external
  1670. view
  1671. returns (address)
  1672. {
  1673. return _delegates[delegator];
  1674. }
  1675.  
  1676. /**
  1677. * @notice Delegate votes from `msg.sender` to `delegatee`
  1678. * @param delegatee The address to delegate votes to
  1679. */
  1680. function delegate(address delegatee) external {
  1681. return _delegate(msg.sender, delegatee);
  1682. }
  1683.  
  1684. /**
  1685. * @notice Delegates votes from signatory to `delegatee`
  1686. * @param delegatee The address to delegate votes to
  1687. * @param nonce The contract state required to match the signature
  1688. * @param expiry The time at which to expire the signature
  1689. * @param v The recovery byte of the signature
  1690. * @param r Half of the ECDSA signature pair
  1691. * @param s Half of the ECDSA signature pair
  1692. */
  1693. function delegateBySig(
  1694. address delegatee,
  1695. uint nonce,
  1696. uint expiry,
  1697. uint8 v,
  1698. bytes32 r,
  1699. bytes32 s
  1700. )
  1701. external
  1702. {
  1703. bytes32 domainSeparator = keccak256(
  1704. abi.encode(
  1705. DOMAIN_TYPEHASH,
  1706. keccak256(bytes(name())),
  1707. getChainId(),
  1708. address(this)
  1709. )
  1710. );
  1711.  
  1712. bytes32 structHash = keccak256(
  1713. abi.encode(
  1714. DELEGATION_TYPEHASH,
  1715. delegatee,
  1716. nonce,
  1717. expiry
  1718. )
  1719. );
  1720.  
  1721. bytes32 digest = keccak256(
  1722. abi.encodePacked(
  1723. "\x19\x01",
  1724. domainSeparator,
  1725. structHash
  1726. )
  1727. );
  1728.  
  1729. address signatory = ecrecover(digest, v, r, s);
  1730. require(signatory != address(0), "KUD::delegateBySig: invalid signature");
  1731. require(nonce == nonces[signatory]++, "KUD::delegateBySig: invalid nonce");
  1732. require(now <= expiry, "KUD::delegateBySig: signature expired");
  1733. return _delegate(signatory, delegatee);
  1734. }
  1735.  
  1736. /**
  1737. * @notice Gets the current votes balance for `account`
  1738. * @param account The address to get votes balance
  1739. * @return The number of current votes for `account`
  1740. */
  1741. function getCurrentVotes(address account)
  1742. external
  1743. view
  1744. returns (uint256)
  1745. {
  1746. uint32 nCheckpoints = numCheckpoints[account];
  1747. return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
  1748. }
  1749.  
  1750. /**
  1751. * @notice Determine the prior number of votes for an account as of a block number
  1752. * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
  1753. * @param account The address of the account to check
  1754. * @param blockNumber The block number to get the vote balance at
  1755. * @return The number of votes the account had as of the given block
  1756. */
  1757. function getPriorVotes(address account, uint blockNumber)
  1758. external
  1759. view
  1760. returns (uint256)
  1761. {
  1762. require(blockNumber < block.number, "KUD::getPriorVotes: not yet determined");
  1763.  
  1764. uint32 nCheckpoints = numCheckpoints[account];
  1765. if (nCheckpoints == 0) {
  1766. return 0;
  1767. }
  1768.  
  1769. // First check most recent balance
  1770. if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
  1771. return checkpoints[account][nCheckpoints - 1].votes;
  1772. }
  1773.  
  1774. // Next check implicit zero balance
  1775. if (checkpoints[account][0].fromBlock > blockNumber) {
  1776. return 0;
  1777. }
  1778.  
  1779. uint32 lower = 0;
  1780. uint32 upper = nCheckpoints - 1;
  1781. while (upper > lower) {
  1782. uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
  1783. Checkpoint memory cp = checkpoints[account][center];
  1784. if (cp.fromBlock == blockNumber) {
  1785. return cp.votes;
  1786. } else if (cp.fromBlock < blockNumber) {
  1787. lower = center;
  1788. } else {
  1789. upper = center - 1;
  1790. }
  1791. }
  1792. return checkpoints[account][lower].votes;
  1793. }
  1794.  
  1795. function _delegate(address delegator, address delegatee)
  1796. internal
  1797. {
  1798. address currentDelegate = _delegates[delegator];
  1799. uint256 delegatorBalance = balanceOf(delegator); // balance of underlying KUDs (not scaled);
  1800. _delegates[delegator] = delegatee;
  1801.  
  1802. emit DelegateChanged(delegator, currentDelegate, delegatee);
  1803.  
  1804. _moveDelegates(currentDelegate, delegatee, delegatorBalance);
  1805. }
  1806.  
  1807. function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
  1808. if (srcRep != dstRep && amount > 0) {
  1809. if (srcRep != address(0)) {
  1810. // decrease old representative
  1811. uint32 srcRepNum = numCheckpoints[srcRep];
  1812. uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
  1813. uint256 srcRepNew = srcRepOld.sub(amount);
  1814. _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
  1815. }
  1816.  
  1817. if (dstRep != address(0)) {
  1818. // increase new representative
  1819. uint32 dstRepNum = numCheckpoints[dstRep];
  1820. uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
  1821. uint256 dstRepNew = dstRepOld.add(amount);
  1822. _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
  1823. }
  1824. }
  1825. }
  1826.  
  1827. function _writeCheckpoint(
  1828. address delegatee,
  1829. uint32 nCheckpoints,
  1830. uint256 oldVotes,
  1831. uint256 newVotes
  1832. )
  1833. internal
  1834. {
  1835. uint32 blockNumber = safe32(block.number, "KUD::_writeCheckpoint: block number exceeds 32 bits");
  1836.  
  1837. if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
  1838. checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
  1839. } else {
  1840. checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
  1841. numCheckpoints[delegatee] = nCheckpoints + 1;
  1842. }
  1843.  
  1844. emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
  1845. }
  1846.  
  1847. function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
  1848. require(n < 2**32, errorMessage);
  1849. return uint32(n);
  1850. }
  1851.  
  1852. function getChainId() internal pure returns (uint) {
  1853. uint256 chainId;
  1854. assembly { chainId := chainid() }
  1855. return chainId;
  1856. }
  1857. }
  1858.  
  1859.  
  1860. // File: contracts/MasterChef.sol
  1861.  
  1862. pragma solidity 0.6.12;
  1863.  
  1864.  
  1865.  
  1866.  
  1867.  
  1868.  
  1869.  
  1870.  
  1871. // MasterChef is the master of Kudex. He can make Kudex and he is a fair guy.
  1872. //
  1873. // Note that it's ownable and the owner wields tremendous power. The ownership
  1874. // will be transferred to a governance smart contract once KUD is sufficiently
  1875. // distributed and the community can show to govern itself.
  1876. //
  1877. // Have fun reading it. Hopefully it's bug-free. God bless.
  1878. contract MasterChef is Ownable, ReentrancyGuard {
  1879. using SafeMath for uint256;
  1880. using SafeKRC20 for IKRC20;
  1881.  
  1882. // Info of each user.
  1883. struct UserInfo {
  1884. uint256 amount; // How many LP tokens the user has provided.
  1885. uint256 rewardDebt; // Reward debt. See explanation below.
  1886. uint256 rewardLockedUp; // Reward locked up.
  1887. uint256 nextHarvestUntil; // When can the user harvest again.
  1888. //
  1889. // We do some fancy math here. Basically, any point in time, the amount of KUDs
  1890. // entitled to a user but is pending to be distributed is:
  1891. //
  1892. // pending reward = (user.amount * pool.accKudexPerShare) - user.rewardDebt
  1893. //
  1894. // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
  1895. // 1. The pool's `accKudexPerShare` (and `lastRewardBlock`) gets updated.
  1896. // 2. User receives the pending reward sent to his/her address.
  1897. // 3. User's `amount` gets updated.
  1898. // 4. User's `rewardDebt` gets updated.
  1899. }
  1900.  
  1901. // Info of each pool.
  1902. struct PoolInfo {
  1903. IKRC20 lpToken; // Address of LP token contract.
  1904. uint256 allocPoint; // How many allocation points assigned to this pool. KUDs to distribute per block.
  1905. uint256 lastRewardBlock; // Last block number that KUDs distribution occurs.
  1906. uint256 accKudexPerShare; // Accumulated KUDs per share, times 1e12. See below.
  1907. uint16 depositFeeBP; // Deposit fee in basis points
  1908. uint256 harvestInterval; // Harvest interval in seconds
  1909. }
  1910.  
  1911. // The KUD TOKEN!
  1912. KudexToken public kudex;
  1913. // Dev address.
  1914. address public devAddress;
  1915. // Deposit Fee address
  1916. address public feeAddress;
  1917. // KUD tokens created per block.
  1918. uint256 public kudexPerBlock;
  1919. // Bonus muliplier for early kudex makers.
  1920. uint256 public constant BONUS_MULTIPLIER = 1;
  1921. // Max harvest interval: 14 days.
  1922. uint256 public constant MAXIMUM_HARVEST_INTERVAL = 14 days;
  1923.  
  1924. // Info of each pool.
  1925. PoolInfo[] public poolInfo;
  1926. // Info of each user that stakes LP tokens.
  1927. mapping(uint256 => mapping(address => UserInfo)) public userInfo;
  1928. // Total allocation points. Must be the sum of all allocation points in all pools.
  1929. uint256 public totalAllocPoint = 0;
  1930. // The block number when KUD mining starts.
  1931. uint256 public startBlock;
  1932. // Total locked up rewards
  1933. uint256 public totalLockedUpRewards;
  1934.  
  1935. // Kudex referral contract address.
  1936. IKudexReferral public kudexReferral;
  1937. // Referral commission rate in basis points.
  1938. uint16 public referralCommissionRate = 100;
  1939. // Max referral commission rate: 10%.
  1940. uint16 public constant MAXIMUM_REFERRAL_COMMISSION_RATE = 1000;
  1941.  
  1942. event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
  1943. event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
  1944. event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
  1945. event EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount);
  1946. event ReferralCommissionPaid(address indexed user, address indexed referrer, uint256 commissionAmount);
  1947. event RewardLockedUp(address indexed user, uint256 indexed pid, uint256 amountLockedUp);
  1948.  
  1949. constructor(
  1950. KudexToken _kudex,
  1951. uint256 _startBlock,
  1952. uint256 _kudexPerBlock
  1953. ) public {
  1954. kudex = _kudex;
  1955. startBlock = _startBlock;
  1956. kudexPerBlock = _kudexPerBlock;
  1957.  
  1958. devAddress = msg.sender;
  1959. feeAddress = msg.sender;
  1960. }
  1961.  
  1962. function poolLength() external view returns (uint256) {
  1963. return poolInfo.length;
  1964. }
  1965.  
  1966. // Add a new lp to the pool. Can only be called by the owner.
  1967. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
  1968. function add(uint256 _allocPoint, IKRC20 _lpToken, uint16 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate) public onlyOwner {
  1969. require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
  1970. require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "add: invalid harvest interval");
  1971. if (_withUpdate) {
  1972. massUpdatePools();
  1973. }
  1974. uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
  1975. totalAllocPoint = totalAllocPoint.add(_allocPoint);
  1976. poolInfo.push(PoolInfo({
  1977. lpToken: _lpToken,
  1978. allocPoint: _allocPoint,
  1979. lastRewardBlock: lastRewardBlock,
  1980. accKudexPerShare: 0,
  1981. depositFeeBP: _depositFeeBP,
  1982. harvestInterval: _harvestInterval
  1983. }));
  1984. }
  1985.  
  1986. // Update the given pool's KUD allocation point and deposit fee. Can only be called by the owner.
  1987. function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate) public onlyOwner {
  1988. require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
  1989. require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: invalid harvest interval");
  1990. if (_withUpdate) {
  1991. massUpdatePools();
  1992. }
  1993. totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
  1994. poolInfo[_pid].allocPoint = _allocPoint;
  1995. poolInfo[_pid].depositFeeBP = _depositFeeBP;
  1996. poolInfo[_pid].harvestInterval = _harvestInterval;
  1997. }
  1998.  
  1999. // Return reward multiplier over the given _from to _to block.
  2000. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
  2001. return _to.sub(_from).mul(BONUS_MULTIPLIER);
  2002. }
  2003.  
  2004. // View function to see pending KUDs on frontend.
  2005. function pendingKudex(uint256 _pid, address _user) external view returns (uint256) {
  2006. PoolInfo storage pool = poolInfo[_pid];
  2007. UserInfo storage user = userInfo[_pid][_user];
  2008. uint256 accKudexPerShare = pool.accKudexPerShare;
  2009. uint256 lpSupply = pool.lpToken.balanceOf(address(this));
  2010. if (block.number > pool.lastRewardBlock && lpSupply != 0) {
  2011. uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
  2012. uint256 kudexReward = multiplier.mul(kudexPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
  2013. accKudexPerShare = accKudexPerShare.add(kudexReward.mul(1e12).div(lpSupply));
  2014. }
  2015. uint256 pending = user.amount.mul(accKudexPerShare).div(1e12).sub(user.rewardDebt);
  2016. return pending.add(user.rewardLockedUp);
  2017. }
  2018.  
  2019. // View function to see if user can harvest KUDs.
  2020. function canHarvest(uint256 _pid, address _user) public view returns (bool) {
  2021. UserInfo storage user = userInfo[_pid][_user];
  2022. return block.timestamp >= user.nextHarvestUntil;
  2023. }
  2024.  
  2025. // Update reward variables for all pools. Be careful of gas spending!
  2026. function massUpdatePools() public {
  2027. uint256 length = poolInfo.length;
  2028. for (uint256 pid = 0; pid < length; ++pid) {
  2029. updatePool(pid);
  2030. }
  2031. }
  2032.  
  2033. // Update reward variables of the given pool to be up-to-date.
  2034. function updatePool(uint256 _pid) public {
  2035. PoolInfo storage pool = poolInfo[_pid];
  2036. if (block.number <= pool.lastRewardBlock) {
  2037. return;
  2038. }
  2039. uint256 lpSupply = pool.lpToken.balanceOf(address(this));
  2040. if (lpSupply == 0 || pool.allocPoint == 0) {
  2041. pool.lastRewardBlock = block.number;
  2042. return;
  2043. }
  2044. uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
  2045. uint256 kudexReward = multiplier.mul(kudexPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
  2046. kudex.mint(devAddress, kudexReward.div(10));
  2047. kudex.mint(address(this), kudexReward);
  2048. pool.accKudexPerShare = pool.accKudexPerShare.add(kudexReward.mul(1e12).div(lpSupply));
  2049. pool.lastRewardBlock = block.number;
  2050. }
  2051.  
  2052. // Deposit LP tokens to MasterChef for KUD allocation.
  2053. function deposit(uint256 _pid, uint256 _amount, address _referrer) public nonReentrant {
  2054. PoolInfo storage pool = poolInfo[_pid];
  2055. UserInfo storage user = userInfo[_pid][msg.sender];
  2056. updatePool(_pid);
  2057. if (_amount > 0 && address(kudexReferral) != address(0) && _referrer != address(0) && _referrer != msg.sender) {
  2058. kudexReferral.recordReferral(msg.sender, _referrer);
  2059. }
  2060. payOrLockupPendingKudex(_pid);
  2061. if (_amount > 0) {
  2062. pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
  2063. if (address(pool.lpToken) == address(kudex)) {
  2064. uint256 transferTax = _amount.mul(kudex.transferTaxRate()).div(10000);
  2065. _amount = _amount.sub(transferTax);
  2066. }
  2067. if (pool.depositFeeBP > 0) {
  2068. uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
  2069. pool.lpToken.safeTransfer(feeAddress, depositFee);
  2070. user.amount = user.amount.add(_amount).sub(depositFee);
  2071. } else {
  2072. user.amount = user.amount.add(_amount);
  2073. }
  2074. }
  2075. user.rewardDebt = user.amount.mul(pool.accKudexPerShare).div(1e12);
  2076. emit Deposit(msg.sender, _pid, _amount);
  2077. }
  2078.  
  2079. // Withdraw LP tokens from MasterChef.
  2080. function withdraw(uint256 _pid, uint256 _amount) public nonReentrant {
  2081. PoolInfo storage pool = poolInfo[_pid];
  2082. UserInfo storage user = userInfo[_pid][msg.sender];
  2083. require(user.amount >= _amount, "withdraw: not good");
  2084. updatePool(_pid);
  2085. payOrLockupPendingKudex(_pid);
  2086. if (_amount > 0) {
  2087. user.amount = user.amount.sub(_amount);
  2088. pool.lpToken.safeTransfer(address(msg.sender), _amount);
  2089. }
  2090. user.rewardDebt = user.amount.mul(pool.accKudexPerShare).div(1e12);
  2091. emit Withdraw(msg.sender, _pid, _amount);
  2092. }
  2093.  
  2094. // Withdraw without caring about rewards. EMERGENCY ONLY.
  2095. function emergencyWithdraw(uint256 _pid) public nonReentrant {
  2096. PoolInfo storage pool = poolInfo[_pid];
  2097. UserInfo storage user = userInfo[_pid][msg.sender];
  2098. uint256 amount = user.amount;
  2099. user.amount = 0;
  2100. user.rewardDebt = 0;
  2101. user.rewardLockedUp = 0;
  2102. user.nextHarvestUntil = 0;
  2103. pool.lpToken.safeTransfer(address(msg.sender), amount);
  2104. emit EmergencyWithdraw(msg.sender, _pid, amount);
  2105. }
  2106.  
  2107. // Pay or lockup pending KUDs.
  2108. function payOrLockupPendingKudex(uint256 _pid) internal {
  2109. PoolInfo storage pool = poolInfo[_pid];
  2110. UserInfo storage user = userInfo[_pid][msg.sender];
  2111.  
  2112. if (user.nextHarvestUntil == 0) {
  2113. user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
  2114. }
  2115.  
  2116. uint256 pending = user.amount.mul(pool.accKudexPerShare).div(1e12).sub(user.rewardDebt);
  2117. if (canHarvest(_pid, msg.sender)) {
  2118. if (pending > 0 || user.rewardLockedUp > 0) {
  2119. uint256 totalRewards = pending.add(user.rewardLockedUp);
  2120.  
  2121. // reset lockup
  2122. totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp);
  2123. user.rewardLockedUp = 0;
  2124. user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
  2125.  
  2126. // send rewards
  2127. safeKudexTransfer(msg.sender, totalRewards);
  2128. payReferralCommission(msg.sender, totalRewards);
  2129. }
  2130. } else if (pending > 0) {
  2131. user.rewardLockedUp = user.rewardLockedUp.add(pending);
  2132. totalLockedUpRewards = totalLockedUpRewards.add(pending);
  2133. emit RewardLockedUp(msg.sender, _pid, pending);
  2134. }
  2135. }
  2136.  
  2137. // Safe kudex transfer function, just in case if rounding error causes pool to not have enough KUDs.
  2138. function safeKudexTransfer(address _to, uint256 _amount) internal {
  2139. uint256 kudexBal = kudex.balanceOf(address(this));
  2140. if (_amount > kudexBal) {
  2141. kudex.transfer(_to, kudexBal);
  2142. } else {
  2143. kudex.transfer(_to, _amount);
  2144. }
  2145. }
  2146.  
  2147. // Update dev address by the previous dev.
  2148. function setDevAddress(address _devAddress) public {
  2149. require(msg.sender == devAddress, "setDevAddress: FORBIDDEN");
  2150. require(_devAddress != address(0), "setDevAddress: ZERO");
  2151. devAddress = _devAddress;
  2152. }
  2153.  
  2154. function setFeeAddress(address _feeAddress) public {
  2155. require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN");
  2156. require(_feeAddress != address(0), "setFeeAddress: ZERO");
  2157. feeAddress = _feeAddress;
  2158. }
  2159.  
  2160. // Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all.
  2161. function updateEmissionRate(uint256 _kudexPerBlock) public onlyOwner {
  2162. massUpdatePools();
  2163. emit EmissionRateUpdated(msg.sender, kudexPerBlock, _kudexPerBlock);
  2164. kudexPerBlock = _kudexPerBlock;
  2165. }
  2166.  
  2167. // Update the kudex referral contract address by the owner
  2168. function setKudexReferral(IKudexReferral _kudexReferral) public onlyOwner {
  2169. kudexReferral = _kudexReferral;
  2170. }
  2171.  
  2172. // Update referral commission rate by the owner
  2173. function setReferralCommissionRate(uint16 _referralCommissionRate) public onlyOwner {
  2174. require(_referralCommissionRate <= MAXIMUM_REFERRAL_COMMISSION_RATE, "setReferralCommissionRate: invalid referral commission rate basis points");
  2175. referralCommissionRate = _referralCommissionRate;
  2176. }
  2177.  
  2178. // Pay referral commission to the referrer who referred this user.
  2179. function payReferralCommission(address _user, uint256 _pending) internal {
  2180. if (address(kudexReferral) != address(0) && referralCommissionRate > 0) {
  2181. address referrer = kudexReferral.getReferrer(_user);
  2182. uint256 commissionAmount = _pending.mul(referralCommissionRate).div(10000);
  2183.  
  2184. if (referrer != address(0) && commissionAmount > 0) {
  2185. kudex.mint(referrer, commissionAmount);
  2186. kudexReferral.recordReferralCommission(referrer, commissionAmount);
  2187. emit ReferralCommissionPaid(_user, referrer, commissionAmount);
  2188. }
  2189. }
  2190. }
  2191. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement