Last active
August 18, 2019 08:57
-
-
Save k06a/3b57c88501ff676710b80703e6520858 to your computer and use it in GitHub Desktop.
Universal Gas Discounter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IUniswap { | |
function getEthToTokenInputPrice(uint256 eth_sold) external view returns(uint256); | |
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns(uint256); | |
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns(uint256); | |
} | |
interface IGasToken { | |
function free(uint256 value) external returns (bool success); | |
function freeUpTo(uint256 value) public returns (uint256 freed); | |
function freeFromUpTo(address from, uint256 value) public returns (uint256 freed); | |
} | |
contract GasDiscounter { | |
IUniswap constant private _exchange = IUniswap(0x929507CD3D90Ab11eC4822E9eB5A48eb3a178F19); | |
IGasToken constant private _gasToken = IGasToken(0x0000000000b3F879cb30FE243b4Dfee438691c04); | |
modifier gasDiscount(uint256 value, bool shouldReturnToSender) { | |
uint256 initialGasLeft = gasleft(); | |
_; | |
_getGasDiscount(value, shouldReturnToSender, initialGasLeft - gasleft()); | |
} | |
function _getGasDiscount(uint256 value, bool shouldReturnToSender, uint256 gasSpent) private { | |
uint256 tokens = (gasSpent + 50000 + 14154) / (2*24000 - 6870); | |
uint256 cost = 0; | |
if (tokens > 0) { | |
if (_exchange.getEthToTokenOutputPrice(tokens) < tx.gasprice * 17000 * tokens) { | |
tokens -= _gasToken.freeUpTo(tokens); | |
if (tokens > 0) { | |
tokens -= _gasToken.freeFromUpTo(msg.sender, tokens); | |
if (tokens > 0) { | |
uint256 possibleTokens = _exchange.getEthToTokenInputPrice(value); | |
uint256 buyTokens = tokens < possibleTokens ? tokens : possibleTokens; | |
cost = _exchange.getEthToTokenOutputPrice(buyTokens); | |
_exchange.ethToTokenSwapInput.value(cost)(buyTokens, now); | |
require(_gasToken.free(tokens)); | |
} | |
} | |
} | |
} | |
if (shouldReturnToSender && cost < value) { | |
msg.sender.transfer(value - cost); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment