├── .env.copy ├── .gitignore ├── .prettierrc ├── scripts ├── deploy-test-token.js └── deploy.js ├── package.json ├── hardhat.config.js ├── README.md ├── LICENSE └── contracts ├── test └── Token.sol └── UniswapV2Twap.sol /.env.copy: -------------------------------------------------------------------------------- 1 | ALCHEMY_API_KEY= 2 | ETHERSCAN_API_KEY= 3 | PAIR= -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env 3 | coverage 4 | coverage.json 5 | typechain 6 | 7 | #Hardhat files 8 | cache 9 | artifacts 10 | 11 | package-lock.json 12 | .secret -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "overrides": [ 3 | { 4 | "files": "*.sol", 5 | "options": { 6 | "printWidth": 80, 7 | "tabWidth": 4, 8 | "explicitTypes": "never" 9 | } 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /scripts/deploy-test-token.js: -------------------------------------------------------------------------------- 1 | const hre = require("hardhat"); 2 | 3 | async function main() { 4 | try { 5 | const Token = await hre.ethers.getContractFactory("Token"); 6 | const token = await Token.deploy(); 7 | 8 | await token.deployed(); 9 | 10 | console.log("Contract deployed to:", token.address); 11 | } catch (error) { 12 | console.error(error); 13 | process.exit(1); 14 | } 15 | } 16 | 17 | main(); 18 | -------------------------------------------------------------------------------- /scripts/deploy.js: -------------------------------------------------------------------------------- 1 | const hre = require("hardhat"); 2 | 3 | async function main() { 4 | try { 5 | const UniswapV2Twap = await hre.ethers.getContractFactory("UniswapV2Twap"); 6 | const twap = await UniswapV2Twap.deploy(process.env.PAIR); 7 | 8 | await twap.deployed(); 9 | 10 | console.log("Contract deployed to:", twap.address); 11 | } catch (error) { 12 | console.error(error); 13 | process.exit(1); 14 | } 15 | } 16 | 17 | main(); 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hardhat-project", 3 | "devDependencies": { 4 | "@nomiclabs/hardhat-ethers": "^2.0.5", 5 | "@nomiclabs/hardhat-etherscan": "^3.0.3", 6 | "@nomiclabs/hardhat-waffle": "^2.0.3", 7 | "chai": "^4.3.6", 8 | "ethereum-waffle": "^3.4.0", 9 | "ethers": "^5.6.0", 10 | "hardhat": "^2.9.1" 11 | }, 12 | "dependencies": { 13 | "@uniswap/v2-core": "^1.0.1", 14 | "@uniswap/v2-periphery": "^1.1.0-beta.0", 15 | "prettier": "^2.5.1", 16 | "prettier-plugin-solidity": "^1.0.0-beta.19" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /hardhat.config.js: -------------------------------------------------------------------------------- 1 | require("@nomiclabs/hardhat-waffle"); 2 | require("@nomiclabs/hardhat-etherscan"); 3 | const fs = require("fs"); 4 | 5 | let PRIVATE_KEY = ""; 6 | try { 7 | PRIVATE_KEY = fs.readFileSync(".secret").toString(); 8 | } catch (error) {} 9 | 10 | module.exports = { 11 | solidity: { 12 | version: "0.6.6", 13 | settings: { 14 | optimizer: { 15 | enabled: true, 16 | runs: 200, 17 | }, 18 | }, 19 | }, 20 | networks: { 21 | ropsten: { 22 | url: `https://eth-ropsten.alchemyapi.io/v2/${process.env.ALCHEMY_API_KEY}`, 23 | accounts: PRIVATE_KEY ? [PRIVATE_KEY] : [], 24 | }, 25 | }, 26 | etherscan: { 27 | apiKey: process.env.ETHERSCAN_API_KEY, 28 | }, 29 | }; 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Uniswap V2 TWAP 2 | 3 | ```shell 4 | npm i 5 | 6 | # copy and edit .env 7 | cp .env.copy .env 8 | 9 | # create and paste private key 10 | touch .secret 11 | 12 | npx hardhat compile 13 | npx hardhat clean 14 | 15 | env $(cat .env) npx hardhat run scripts/deploy.js --network ropsten 16 | 17 | CONTRACT_ADDR= 18 | env $(cat .env) npx hardhat verify --network ropsten $CONTRACT_ADDR "Constructor argument 1" 19 | ``` 20 | 21 | ### Ropsten 22 | 23 | router 24 | 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D 25 | 26 | factory 27 | 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f 28 | 29 | token 30 | 0x453850ce1b1dCaA2A4448658495FdbF02b6919F9 31 | 32 | pair 33 | 0x3467940F46F4D7E75DaBF25C8d99498E15EF1d51 34 | 35 | twap 36 | 0xb995C7E94bC6Ec71e0629E7E361168E7Cf77437E 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Taz 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /contracts/test/Token.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.6; 3 | 4 | contract Token { 5 | event Transfer(address indexed from, address indexed to, uint value); 6 | event Approval(address indexed owner, address indexed spender, uint value); 7 | 8 | uint public totalSupply; 9 | mapping(address => uint) public balanceOf; 10 | mapping(address => mapping(address => uint)) public allowance; 11 | string public name = "Test"; 12 | string public symbol = "TEST"; 13 | uint8 public decimals = 18; 14 | 15 | function transfer(address recipient, uint amount) external returns (bool) { 16 | balanceOf[msg.sender] -= amount; 17 | balanceOf[recipient] += amount; 18 | emit Transfer(msg.sender, recipient, amount); 19 | return true; 20 | } 21 | 22 | function approve(address spender, uint amount) external returns (bool) { 23 | allowance[msg.sender][spender] = amount; 24 | emit Approval(msg.sender, spender, amount); 25 | return true; 26 | } 27 | 28 | function transferFrom( 29 | address sender, 30 | address recipient, 31 | uint amount 32 | ) external returns (bool) { 33 | allowance[sender][msg.sender] -= amount; 34 | balanceOf[sender] -= amount; 35 | balanceOf[recipient] += amount; 36 | emit Transfer(sender, recipient, amount); 37 | return true; 38 | } 39 | 40 | function mint(uint amount) external { 41 | balanceOf[msg.sender] += amount; 42 | totalSupply += amount; 43 | emit Transfer(address(0), msg.sender, amount); 44 | } 45 | 46 | function burn(uint amount) external { 47 | balanceOf[msg.sender] -= amount; 48 | totalSupply -= amount; 49 | emit Transfer(msg.sender, address(0), amount); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /contracts/UniswapV2Twap.sol: -------------------------------------------------------------------------------- 1 | //SPDX-License-Identifier: MIT 2 | pragma solidity 0.6.6; 3 | // NOTE: using solidity 0.6.6 to match imports 4 | 5 | import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; 6 | import "@uniswap/lib/contracts/libraries/FixedPoint.sol"; 7 | import "@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol"; 8 | import "@uniswap/v2-periphery/contracts/libraries/UniswapV2Library.sol"; 9 | 10 | contract UniswapV2Twap { 11 | using FixedPoint for *; 12 | 13 | uint public constant PERIOD = 10; 14 | 15 | IUniswapV2Pair public immutable pair; 16 | address public immutable token0; 17 | address public immutable token1; 18 | 19 | uint public price0CumulativeLast; 20 | uint public price1CumulativeLast; 21 | uint32 public blockTimestampLast; 22 | 23 | // NOTE: binary fixed point numbers 24 | // range: [0, 2**112 - 1] 25 | // resolution: 1 / 2**112 26 | FixedPoint.uq112x112 public price0Average; 27 | FixedPoint.uq112x112 public price1Average; 28 | 29 | // NOTE: public visibility 30 | // NOTE: IUniswapV2Pair 31 | constructor(IUniswapV2Pair _pair) public { 32 | pair = _pair; 33 | token0 = _pair.token0(); 34 | token1 = _pair.token1(); 35 | price0CumulativeLast = _pair.price0CumulativeLast(); 36 | price1CumulativeLast = _pair.price1CumulativeLast(); 37 | (, , blockTimestampLast) = _pair.getReserves(); 38 | } 39 | 40 | function update() external { 41 | ( 42 | uint price0Cumulative, 43 | uint price1Cumulative, 44 | uint32 blockTimestamp 45 | ) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); 46 | uint32 timeElapsed = blockTimestamp - blockTimestampLast; 47 | 48 | require(timeElapsed >= PERIOD, "time elapsed < min period"); 49 | 50 | // NOTE: overflow is desired 51 | /* 52 | |----b-------------------------a---------| 53 | 0 2**256 - 1 54 | 55 | b - a is preserved even if b overflows 56 | */ 57 | // NOTE: uint -> uint224 cuts off the bits above uint224 58 | // max uint 59 | // 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 60 | // max uint244 61 | // 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff 62 | price0Average = FixedPoint.uq112x112( 63 | uint224((price0Cumulative - price0CumulativeLast) / timeElapsed) 64 | ); 65 | price1Average = FixedPoint.uq112x112( 66 | uint224((price1Cumulative - price1CumulativeLast) / timeElapsed) 67 | ); 68 | 69 | price0CumulativeLast = price0Cumulative; 70 | price1CumulativeLast = price1Cumulative; 71 | blockTimestampLast = blockTimestamp; 72 | } 73 | 74 | function consult(address token, uint amountIn) 75 | external 76 | view 77 | returns (uint amountOut) 78 | { 79 | require(token == token0 || token == token1, "invalid token"); 80 | 81 | if (token == token0) { 82 | // NOTE: using FixedPoint for * 83 | // NOTE: mul returns uq144x112 84 | // NOTE: decode144 decodes uq144x112 to uint144 85 | amountOut = price0Average.mul(amountIn).decode144(); 86 | } else { 87 | amountOut = price1Average.mul(amountIn).decode144(); 88 | } 89 | } 90 | } 91 | --------------------------------------------------------------------------------