Watch pool burn and swap events (#128)

* Remove test scripts, moved to vulcanize/uniswap-v3-core#watcher-ts.

* Move uniswap analysis docs.

* Watch pool burn and swap events.
This commit is contained in:
Ashwin Phatak 2021-07-09 12:30:50 +05:30 committed by GitHub
parent 538e4b7591
commit 7f5229bf2f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 48 additions and 400 deletions

View File

@ -203,3 +203,17 @@ Queries with ID param
}
}
```
## Scripts
* **generate:schema**
Generate schema for uniswap subgraph in graphql format. The `get-graphql-schema` tool is used to generate the schema (https://github.com/prisma-labs/get-graphql-schema). The uniswap subgraph graphql endpoint is provided in the script to generate the schema.
* **lint:schema**
Lint schema graphql files:
```bash
$ yarn lint:schema docs/analysis/schema/frontend.graphql
```

View File

@ -17,7 +17,9 @@
"server:mock": "MOCK=1 nodemon src/server.ts -f environments/local.toml",
"test": "mocha -r ts-node/register src/**/*.spec.ts",
"lint": "eslint .",
"build": "tsc"
"build": "tsc",
"generate:schema": "get-graphql-schema https://api.thegraph.com/subgraphs/name/ianlapham/uniswap-v3-alt > docs/analysis/schema/full-schema.graphql",
"lint:schema": "graphql-schema-linter"
},
"devDependencies": {
"@types/chance": "^1.1.2",
@ -33,6 +35,8 @@
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.1.0",
"eslint-plugin-standard": "^5.0.0",
"get-graphql-schema": "^2.1.2",
"graphql-schema-linter": "^2.0.1",
"mocha": "^8.4.0",
"nodemon": "^2.0.7"
}

View File

@ -179,6 +179,35 @@ export class Indexer {
amount1: amount1.toString()
};
break;
}
case 'Burn': {
eventName = logDescription.name;
const { owner, tickLower, tickUpper, amount, amount0, amount1 } = logDescription.args;
eventProps = {
owner,
tickLower,
tickUpper,
amount: amount.toString(),
amount0: amount0.toString(),
amount1: amount1.toString()
};
break;
}
case 'Swap': {
eventName = logDescription.name;
const { sender, recipient, amount0, amount1, sqrtPriceX96, liquidity, tick } = logDescription.args;
eventProps = {
sender,
recipient,
amount0: amount0.toString(),
amount1: amount1.toString(),
sqrtPriceX96: sqrtPriceX96.toString(),
liquidity: liquidity.toString(),
tick
};
break;
}
}

View File

@ -1 +0,0 @@
ETH_RPC_URL=http://127.0.0.1:8545

View File

@ -1,8 +0,0 @@
node_modules
#Hardhat files
cache
artifacts
# Environment variables
.env

View File

@ -1,88 +0,0 @@
# Uniswap
## Instructions
### Deploy contracts
```bash
# Create .env.
$ cp .env.example .env
# Set ETH_RPC_URL variable to target chain network.
# Deploy contracts to private network specified by ETH_RPC_URL
$ yarn deploy:factory
# Factory deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3
$ yarn deploy:token --name Token0 --symbol TK0
# token TK0 deployed to: 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512
$ yarn deploy:token --name Token1 --symbol TK1
# token TK1 deployed to: 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0
$ yarn create:pool --factory 0x5FbDB2315678afecb367f032d93F642f64180aa3 --token0 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512 --token1 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0 --fee 500
# Pool deployed to: 0x315244f2680ABa32F27004B67d83E53c8c88F5FE
# For local development.
# Start hardhat local network.
$ yarn hardhat node
# Deploy contracts to local network.
# Deploy contracts to private network specified by ETH_RPC_URL
$ yarn deploy:factory --network localhost
$ yarn deploy:token --network localhost --name Token0 --symbol TK0
```
## Scripts
* **generate:schema**
Generate schema for uniswap subgraph in graphql format. The `get-graphql-schema` tool is used to generate the schema (https://github.com/prisma-labs/get-graphql-schema). The uniswap subgraph graphql endpoint is provided in the script to generate the schema.
* **lint:schema**
Lint schema graphql files:
```bash
$ yarn lint:schema schema/frontend.graphql
```
* **deploy:factory**
Deploy Factory contract:
```bash
$ yarn deploy:factory
# Deploy to hardhat local network.
$ yarn deploy --network localhost
```
* **deploy:token**
Deploy Token contract:
```bash
$ yarn deploy:token --name TokenName --symbol TKS
```
* **create:pool**
Create pool with factory contract and tokens:
```bash
$ yarn create:pool --factory 0xFactoryAddress --token0 0xToken0Address --token1 0xToken1Address --fee 500
```
* **initialize:pool**
Initialize a pool with price:
```bash
$ yarn initialize:pool --pool 0xPoolAddress --sqrt-price 4295128739
```
## References
* https://github.com/Uniswap/uniswap-v3-core

View File

@ -1,10 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract ERC20Token is ERC20 {
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
_mint(msg.sender, 1000000000000000000000);
}
}

View File

@ -1,24 +0,0 @@
import 'dotenv/config';
import { HardhatUserConfig } from "hardhat/config";
import "@nomiclabs/hardhat-waffle";
import './tasks/accounts';
import './tasks/deploy-factory';
import './tasks/deploy-token';
import './tasks/create-pool';
import './tasks/initialize-pool';
import './tasks/mint-pool';
const config: HardhatUserConfig = {
solidity: "0.8.0",
networks: {
private: {
url: process.env.ETH_RPC_URL
}
},
defaultNetwork: 'private'
};
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
export default config;

View File

@ -1,35 +0,0 @@
{
"name": "@vulcanize/uniswap",
"version": "0.1.0",
"main": "index.js",
"license": "UNLICENSED",
"scripts": {
"generate:schema": "get-graphql-schema https://api.thegraph.com/subgraphs/name/ianlapham/uniswap-v3-alt > schema/full.graphql",
"lint:schema": "graphql-schema-linter",
"deploy:factory": "hardhat deploy-factory",
"deploy:token": "hardhat deploy-token",
"create:pool": "hardhat create-pool",
"initialize:pool": "hardhat initialize-pool",
"mint:pool": "hardhat mint-pool"
},
"devDependencies": {
"@nomiclabs/hardhat-ethers": "^2.0.2",
"@nomiclabs/hardhat-waffle": "^2.0.1",
"@types/chai": "^4.2.18",
"@types/mocha": "^8.2.2",
"@types/node": "^15.14.0",
"chai": "^4.3.4",
"ethereum-waffle": "^3.3.0",
"ethers": "^5.2.0",
"get-graphql-schema": "^2.1.2",
"graphql-schema-linter": "^2.0.1",
"hardhat": "^2.3.0",
"ts-node": "^10.0.0",
"typescript": "^4.3.2"
},
"dependencies": {
"@openzeppelin/contracts": "^4.2.0",
"@uniswap/v3-core": "^1.0.0",
"dotenv": "^10.0.0"
}
}

View File

@ -1,13 +0,0 @@
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import { task } from "hardhat/config";
import '@nomiclabs/hardhat-ethers';
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (args, hre) => {
const accounts: SignerWithAddress[] = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});

View File

@ -1,28 +0,0 @@
import { task, types } from "hardhat/config";
import {
abi as FACTORY_ABI,
} from '@uniswap/v3-core/artifacts/contracts/UniswapV3Factory.sol/UniswapV3Factory.json'
import { ContractTransaction } from "ethers";
import '@nomiclabs/hardhat-ethers';
task("create-pool", "Creates pool using Factory contract")
.addParam('factory', 'Address of factory contract', undefined, types.string)
.addParam('token0', 'Address of first token contract', undefined, types.string)
.addParam('token1', 'Address of second token contract', undefined, types.string)
.addParam('fee', "The pool's fee", undefined, types.int)
.setAction(async (args, hre) => {
const { factory: factoryAddress, token0, token1, fee } = args
const [signer] = await hre.ethers.getSigners();
const factory = new hre.ethers.Contract(factoryAddress, FACTORY_ABI, signer);
const transaction: ContractTransaction = await factory.createPool(token0, token1, fee)
const receipt = await transaction.wait();
if (receipt.events) {
const poolCreatedEvent = receipt.events.find(el => el.event === 'PoolCreated');
if (poolCreatedEvent && poolCreatedEvent.args) {
const { pool } = poolCreatedEvent.args;
console.log('Pool deployed to:', pool);
}
}
});

View File

@ -1,15 +0,0 @@
import { task } from "hardhat/config";
import {
abi as FACTORY_ABI,
bytecode as FACTORY_BYTECODE,
} from '@uniswap/v3-core/artifacts/contracts/UniswapV3Factory.sol/UniswapV3Factory.json';
import '@nomiclabs/hardhat-ethers';
task("deploy-factory", "Deploys Factory contract")
.setAction(async (_, hre) => {
const [signer] = await hre.ethers.getSigners();
const Factory = new hre.ethers.ContractFactory(FACTORY_ABI , FACTORY_BYTECODE, signer);
const factory = await Factory.deploy();
await factory.deployed();
console.log("Factory deployed to:", factory.address);
});

View File

@ -1,15 +0,0 @@
import { task, types } from "hardhat/config";
import '@nomiclabs/hardhat-ethers';
task("deploy-token", "Deploys new token")
.addParam('name', 'Name of the token', undefined, types.string)
.addParam('symbol', 'Symbol of the token', undefined, types.string)
.setAction(async (args, hre) => {
const { name, symbol } = args
await hre.run("compile");
const Token = await hre.ethers.getContractFactory('ERC20Token');
const token = await Token.deploy(name, symbol);
console.log(`Token ${symbol} deployed to:`, token.address)
return token;
});

View File

@ -1,26 +0,0 @@
import { task, types } from "hardhat/config";
import {
abi as POOL_ABI,
} from '@uniswap/v3-core/artifacts/contracts/UniswapV3Pool.sol/UniswapV3Pool.json'
import { ContractTransaction } from "ethers";
import '@nomiclabs/hardhat-ethers';
task("initialize-pool", "Initializes a pool")
.addParam('pool', 'Address of pool contract', undefined, types.string)
.addParam('sqrtPrice', 'Initial sqrtPriceX96', undefined, types.int)
.setAction(async (args, hre) => {
const { pool: poolAddress, sqrtPrice } = args
const [signer] = await hre.ethers.getSigners();
const pool = new hre.ethers.Contract(poolAddress, POOL_ABI, signer);
const transaction: ContractTransaction = await pool.initialize(sqrtPrice);
const receipt = await transaction.wait();
if (receipt.events) {
const poolInitializeEvent = receipt.events.find(el => el.event === 'Initialize');
if (poolInitializeEvent && poolInitializeEvent.args) {
const { sqrtPriceX96, tick } = poolInitializeEvent.args;
console.log('Pool initialized:', sqrtPriceX96.toString(), tick);
}
}
});

View File

@ -1,46 +0,0 @@
import { task, types } from "hardhat/config";
import {
abi as POOL_ABI,
} from '@uniswap/v3-core/artifacts/contracts/UniswapV3Pool.sol/UniswapV3Pool.json'
import {
abi as ERC20_ABI
} from '@uniswap/v3-core/artifacts/contracts/interfaces/IERC20Minimal.sol/IERC20Minimal.json';
import { ContractTransaction } from "ethers";
import '@nomiclabs/hardhat-ethers';
const getMinTick = (tickSpacing: number) => Math.ceil(-887272 / tickSpacing) * tickSpacing;
const getMaxTick = (tickSpacing: number) => Math.floor(887272 / tickSpacing) * tickSpacing;
const APPROVE_AMOUNT = BigInt(1000000000000000000);
task("mint-pool", "Adds liquidity for the given position to the pool")
.addParam('pool', 'Address of pool contract', undefined, types.string)
.addParam('recipient', 'Address for which the liquidity will be created', undefined, types.string)
.addParam('tickLower', 'Lower tick of the position in which to add liquidity', undefined, types.string)
.addParam('tickUpper', 'Upper tick of the position in which to add liquidity', undefined, types.string)
.addParam('amount', 'Amount of liquidity to mint', undefined, types.string)
.setAction(async (args, hre) => {
const { pool: poolAddress, recipient, tickLower, tickUpper, amount } = args
const [signer] = await hre.ethers.getSigners();
const pool = new hre.ethers.Contract(poolAddress, POOL_ABI, signer);
const token0Address = await pool.token0();
const token1Address = await pool.token1();
const tickSpacing = await pool.tickSpacing();
console.log(token0Address, token1Address, tickSpacing, getMinTick(tickSpacing), getMaxTick(tickSpacing));
const token0 = new hre.ethers.Contract(token0Address, ERC20_ABI, signer);
const token1 = new hre.ethers.Contract(token1Address, ERC20_ABI, signer);
const t0 = await token0.approve(poolAddress, APPROVE_AMOUNT);
await t0.wait();
const t1 = await token1.approve(poolAddress, APPROVE_AMOUNT);
await t1.wait();
const transaction: ContractTransaction = await pool.mint(recipient, BigInt(tickLower), BigInt(tickUpper), BigInt(amount), '0x00');
const receipt = await transaction.wait();
console.log(JSON.stringify(receipt));
});

View File

@ -1,75 +0,0 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": [ "ES2020" ], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
"downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
"resolveJsonModule": true
},
"include": ["src/**/*", "tasks/*"],
"exclude": ["src/**/*.test.ts"]
}

View File

@ -1890,11 +1890,6 @@
dependencies:
"@octokit/openapi-types" "^7.2.3"
"@openzeppelin/contracts@^4.2.0":
version "4.2.0"
resolved "https://registry.yarnpkg.com/@openzeppelin/contracts/-/contracts-4.2.0.tgz#260d921d99356e48013d9d760caaa6cea35dc642"
integrity sha512-LD4NnkKpHHSMo5z9MvFsG4g1xxZUDqV3A3Futu3nvyfs4wPwXxqOgMaxOoa2PeyGL2VNeSlbxT54enbQzGcgJQ==
"@protobufjs/aspromise@^1.1.1", "@protobufjs/aspromise@^1.1.2":
version "1.1.2"
resolved "https://registry.yarnpkg.com/@protobufjs/aspromise/-/aspromise-1.1.2.tgz#9b8b0cc663d669a7d8f6f5d0893a14d348f30fbf"
@ -2400,11 +2395,6 @@
resolved "https://registry.yarnpkg.com/@types/node/-/node-12.20.13.tgz#e743bae112bd779ac9650f907197dd2caa7f0364"
integrity sha512-1x8W5OpxPq+T85OUsHRP6BqXeosKmeXRtjoF39STcdf/UWLqUsoehstZKOi0CunhVqHG17AyZgpj20eRVooK6A==
"@types/node@^15.14.0":
version "15.14.0"
resolved "https://registry.yarnpkg.com/@types/node/-/node-15.14.0.tgz#74dbf254fb375551a9d2a71faf6b9dbc2178dc53"
integrity sha512-um/+/ip3QZmwLfIkWZSNtQIJNVAqrJ92OkLMeuZrjZMTAJniI7fh8N8OICyDhAJ2mzgk/fmYFo72jRr5HyZ1EQ==
"@types/normalize-package-data@^2.4.0":
version "2.4.0"
resolved "https://registry.yarnpkg.com/@types/normalize-package-data/-/normalize-package-data-2.4.0.tgz#e486d0d97396d79beedd0a6e33f4534ff6b4973e"
@ -2586,11 +2576,6 @@
resolved "https://registry.yarnpkg.com/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz#aa58042711d6e3275dd37dc597e5d31e8c290a44"
integrity sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==
"@uniswap/v3-core@^1.0.0":
version "1.0.0"
resolved "https://registry.yarnpkg.com/@uniswap/v3-core/-/v3-core-1.0.0.tgz#6c24adacc4c25dceee0ba3ca142b35adbd7e359d"
integrity sha512-kSC4djMGKMHj7sLMYVnn61k9nu+lHjMIxgg9CDQT+s2QYLoA56GbSK9Oxr+qJXzzygbkrmuY6cwgP6cW2JXPFA==
"@wry/context@^0.6.0":
version "0.6.0"
resolved "https://registry.yarnpkg.com/@wry/context/-/context-0.6.0.tgz#f903eceb89d238ef7e8168ed30f4511f92d83e06"