Skip to content

Instantly share code, notes, and snippets.

@k06a
Last active August 18, 2019 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k06a/3b57c88501ff676710b80703e6520858 to your computer and use it in GitHub Desktop.
Save k06a/3b57c88501ff676710b80703e6520858 to your computer and use it in GitHub Desktop.
Universal Gas Discounter
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