* Yarn init and setup lerna * Generate watcher for Polls contract * Add custom methods for unhandled types * Fix methods to save and load values of unhandled type from local DB * Set PropColMaps for custom methods --------- Co-authored-by: Dhruv Srivastava <dhruvdhs.ds@gmail.com>
This commit is contained in:
parent
a1e0ca0d24
commit
7b857ec979
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
dist/
|
||||
out/
|
||||
.vscode
|
||||
|
||||
1
.npmrc
Normal file
1
.npmrc
Normal file
@ -0,0 +1 @@
|
||||
@cerc-io:registry=https://git.vdb.to/api/packages/cerc-io/npm/
|
||||
8
lerna.json
Normal file
8
lerna.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"useWorkspaces": true,
|
||||
"version": "0.0.0",
|
||||
"npmClient": "yarn"
|
||||
}
|
||||
15
package.json
Normal file
15
package.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "azimuth-watcher-ts",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "lerna run build --stream",
|
||||
"lint": "lerna run lint --stream -- --max-warnings=0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"lerna": "^6.6.1"
|
||||
}
|
||||
}
|
||||
2
packages/polls-watcher/.eslintignore
Normal file
2
packages/polls-watcher/.eslintignore
Normal file
@ -0,0 +1,2 @@
|
||||
# Don't lint build output.
|
||||
dist
|
||||
28
packages/polls-watcher/.eslintrc.json
Normal file
28
packages/polls-watcher/.eslintrc.json
Normal file
@ -0,0 +1,28 @@
|
||||
{
|
||||
"env": {
|
||||
"browser": true,
|
||||
"es2021": true
|
||||
},
|
||||
"extends": [
|
||||
"semistandard",
|
||||
"plugin:@typescript-eslint/recommended"
|
||||
],
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 12,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": [
|
||||
"@typescript-eslint"
|
||||
],
|
||||
"rules": {
|
||||
"indent": ["error", 2, { "SwitchCase": 1 }],
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/explicit-module-boundary-types": [
|
||||
"warn",
|
||||
{
|
||||
"allowArgumentsExplicitlyTypedAsAny": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
204
packages/polls-watcher/README.md
Normal file
204
packages/polls-watcher/README.md
Normal file
@ -0,0 +1,204 @@
|
||||
# polls-watcher
|
||||
|
||||
## Setup
|
||||
|
||||
* Run the following command to install required packages:
|
||||
|
||||
```bash
|
||||
yarn
|
||||
```
|
||||
|
||||
* Create a postgres12 database for the watcher:
|
||||
|
||||
```bash
|
||||
sudo su - postgres
|
||||
createdb polls-watcher
|
||||
```
|
||||
|
||||
* If the watcher is an `active` watcher:
|
||||
|
||||
Create database for the job queue and enable the `pgcrypto` extension on them (https://github.com/timgit/pg-boss/blob/master/docs/usage.md#intro):
|
||||
|
||||
```
|
||||
createdb polls-watcher-job-queue
|
||||
```
|
||||
|
||||
```
|
||||
postgres@tesla:~$ psql -U postgres -h localhost polls-watcher-job-queue
|
||||
Password for user postgres:
|
||||
psql (12.7 (Ubuntu 12.7-1.pgdg18.04+1))
|
||||
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
|
||||
Type "help" for help.
|
||||
|
||||
polls-watcher-job-queue=# CREATE EXTENSION pgcrypto;
|
||||
CREATE EXTENSION
|
||||
polls-watcher-job-queue=# exit
|
||||
```
|
||||
|
||||
* In the [config file](./environments/local.toml):
|
||||
|
||||
* Update the database connection settings.
|
||||
|
||||
* Update the `upstream` config and provide the `ipld-eth-server` GQL API endpoint.
|
||||
|
||||
* Update the `server` config with state checkpoint settings.
|
||||
|
||||
## Customize
|
||||
|
||||
* Indexing on an event:
|
||||
|
||||
* Edit the custom hook function `handleEvent` (triggered on an event) in [hooks.ts](./src/hooks.ts) to perform corresponding indexing using the `Indexer` object.
|
||||
|
||||
* While using the indexer storage methods for indexing, pass `diff` as true if default state is desired to be generated using the state variables being indexed.
|
||||
|
||||
* Generating state:
|
||||
|
||||
* Edit the custom hook function `createInitialState` (triggered if the watcher passes the start block, checkpoint: `true`) in [hooks.ts](./src/hooks.ts) to save an initial `State` using the `Indexer` object.
|
||||
|
||||
* Edit the custom hook function `createStateDiff` (triggered on a block) in [hooks.ts](./src/hooks.ts) to save the state in a `diff` `State` using the `Indexer` object. The default state (if exists) is updated.
|
||||
|
||||
* Edit the custom hook function `createStateCheckpoint` (triggered just before default and CLI checkpoint) in [hooks.ts](./src/hooks.ts) to save the state in a `checkpoint` `State` using the `Indexer` object.
|
||||
|
||||
### GQL Caching
|
||||
|
||||
To enable GQL requests caching:
|
||||
|
||||
* Update the `server.gqlCache` config with required settings.
|
||||
|
||||
* In the GQL [schema file](./src/schema.gql), use the `cacheControl` directive to apply cache hints at schema level.
|
||||
|
||||
* Eg. Set `inheritMaxAge` to true for non-scalar fields of a type.
|
||||
|
||||
* In the GQL [resolvers file](./src/resolvers.ts), uncomment the `setGQLCacheHints()` calls in resolvers for required queries.
|
||||
|
||||
## Run
|
||||
|
||||
* If the watcher is a `lazy` watcher:
|
||||
|
||||
* Run the server:
|
||||
|
||||
```bash
|
||||
yarn server
|
||||
```
|
||||
|
||||
GQL console: http://localhost:3009/graphql
|
||||
|
||||
* If the watcher is an `active` watcher:
|
||||
|
||||
* Run the job-runner:
|
||||
|
||||
```bash
|
||||
yarn job-runner
|
||||
```
|
||||
|
||||
* Run the server:
|
||||
|
||||
```bash
|
||||
yarn server
|
||||
```
|
||||
|
||||
GQL console: http://localhost:3009/graphql
|
||||
|
||||
* To watch a contract:
|
||||
|
||||
```bash
|
||||
yarn watch:contract --address <contract-address> --kind <contract-kind> --checkpoint <true | false> --starting-block [block-number]
|
||||
```
|
||||
|
||||
* `address`: Address or identifier of the contract to be watched.
|
||||
* `kind`: Kind of the contract.
|
||||
* `checkpoint`: Turn checkpointing on (`true` | `false`).
|
||||
* `starting-block`: Starting block for the contract (default: `1`).
|
||||
|
||||
Examples:
|
||||
|
||||
Watch a contract with its address and checkpointing on:
|
||||
|
||||
```bash
|
||||
yarn watch:contract --address 0x1F78641644feB8b64642e833cE4AFE93DD6e7833 --kind ERC20 --checkpoint true
|
||||
```
|
||||
|
||||
Watch a contract with its identifier and checkpointing on:
|
||||
|
||||
```bash
|
||||
yarn watch:contract --address MyProtocol --kind protocol --checkpoint true
|
||||
```
|
||||
|
||||
* To fill a block range:
|
||||
|
||||
```bash
|
||||
yarn fill --start-block <from-block> --end-block <to-block>
|
||||
```
|
||||
|
||||
* `start-block`: Block number to start filling from.
|
||||
* `end-block`: Block number till which to fill.
|
||||
|
||||
* To create a checkpoint for a contract:
|
||||
|
||||
```bash
|
||||
yarn checkpoint create --address <contract-address> --block-hash [block-hash]
|
||||
```
|
||||
|
||||
* `address`: Address or identifier of the contract for which to create a checkpoint.
|
||||
* `block-hash`: Hash of a block (in the pruned region) at which to create the checkpoint (default: latest canonical block hash).
|
||||
|
||||
* To reset the watcher to a previous block number:
|
||||
|
||||
* Reset watcher:
|
||||
|
||||
```bash
|
||||
yarn reset watcher --block-number <previous-block-number>
|
||||
```
|
||||
|
||||
* Reset job-queue:
|
||||
|
||||
```bash
|
||||
yarn reset job-queue
|
||||
```
|
||||
|
||||
* Reset state:
|
||||
|
||||
```bash
|
||||
yarn reset state --block-number <previous-block-number>
|
||||
```
|
||||
|
||||
* `block-number`: Block number to which to reset the watcher.
|
||||
|
||||
* To export and import the watcher state:
|
||||
|
||||
* In source watcher, export watcher state:
|
||||
|
||||
```bash
|
||||
yarn export-state --export-file [export-file-path] --block-number [snapshot-block-height]
|
||||
```
|
||||
|
||||
* `export-file`: Path of file to which to export the watcher data.
|
||||
* `block-number`: Block height at which to take snapshot for export.
|
||||
|
||||
* In target watcher, run job-runner:
|
||||
|
||||
```bash
|
||||
yarn job-runner
|
||||
```
|
||||
|
||||
* Import watcher state:
|
||||
|
||||
```bash
|
||||
yarn import-state --import-file <import-file-path>
|
||||
```
|
||||
|
||||
* `import-file`: Path of file from which to import the watcher data.
|
||||
|
||||
* Run server:
|
||||
|
||||
```bash
|
||||
yarn server
|
||||
```
|
||||
|
||||
* To inspect a CID:
|
||||
|
||||
```bash
|
||||
yarn inspect-cid --cid <cid>
|
||||
```
|
||||
|
||||
* `cid`: CID to be inspected.
|
||||
66
packages/polls-watcher/environments/local.toml
Normal file
66
packages/polls-watcher/environments/local.toml
Normal file
@ -0,0 +1,66 @@
|
||||
[server]
|
||||
host = "127.0.0.1"
|
||||
port = 3009
|
||||
kind = "lazy"
|
||||
|
||||
# Checkpointing state.
|
||||
checkpointing = true
|
||||
|
||||
# Checkpoint interval in number of blocks.
|
||||
checkpointInterval = 2000
|
||||
|
||||
# Enable state creation
|
||||
# CAUTION: Disable only if state creation is not desired or can be filled subsequently
|
||||
enableState = true
|
||||
|
||||
# Boolean to filter logs by contract.
|
||||
filterLogs = false
|
||||
|
||||
# Max block range for which to return events in eventsInRange GQL query.
|
||||
# Use -1 for skipping check on block range.
|
||||
maxEventsBlockRange = 1000
|
||||
|
||||
# GQL cache settings
|
||||
[server.gqlCache]
|
||||
enabled = true
|
||||
|
||||
# Max in-memory cache size (in bytes) (default 8 MB)
|
||||
# maxCacheSize
|
||||
|
||||
# GQL cache-control max-age settings (in seconds)
|
||||
maxAge = 15
|
||||
|
||||
[metrics]
|
||||
host = "127.0.0.1"
|
||||
port = 9000
|
||||
[metrics.gql]
|
||||
port = 9001
|
||||
|
||||
[database]
|
||||
type = "postgres"
|
||||
host = "localhost"
|
||||
port = 5432
|
||||
database = "polls-watcher"
|
||||
username = "postgres"
|
||||
password = "postgres"
|
||||
synchronize = true
|
||||
logging = false
|
||||
|
||||
[upstream]
|
||||
[upstream.ethServer]
|
||||
gqlApiEndpoint = "http://127.0.0.1:8082/graphql"
|
||||
rpcProviderEndpoint = "http://127.0.0.1:8081"
|
||||
|
||||
[upstream.cache]
|
||||
name = "requests"
|
||||
enabled = false
|
||||
deleteOnStart = false
|
||||
|
||||
[jobQueue]
|
||||
dbConnectionString = "postgres://postgres:postgres@localhost/polls-watcher-job-queue"
|
||||
maxCompletionLagInSecs = 300
|
||||
jobDelayInMilliSecs = 100
|
||||
eventsInBatch = 50
|
||||
blockDelayInMilliSecs = 2000
|
||||
prefetchBlocksInMem = true
|
||||
prefetchBlockCount = 10
|
||||
73
packages/polls-watcher/package.json
Normal file
73
packages/polls-watcher/package.json
Normal file
@ -0,0 +1,73 @@
|
||||
{
|
||||
"name": "@cerc-io/polls-watcher",
|
||||
"version": "0.1.0",
|
||||
"description": "polls-watcher",
|
||||
"private": true,
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"build": "yarn clean && tsc && yarn copy-assets",
|
||||
"clean": "rm -rf ./dist",
|
||||
"copy-assets": "copyfiles -u 1 src/**/*.gql dist/",
|
||||
"server": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/server.js",
|
||||
"server:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/server.ts",
|
||||
"job-runner": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/job-runner.js",
|
||||
"job-runner:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/job-runner.ts",
|
||||
"watch:contract": "DEBUG=vulcanize:* ts-node src/cli/watch-contract.ts",
|
||||
"fill": "DEBUG=vulcanize:* ts-node src/fill.ts",
|
||||
"reset": "DEBUG=vulcanize:* ts-node src/cli/reset.ts",
|
||||
"checkpoint": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/checkpoint.js",
|
||||
"checkpoint:dev": "DEBUG=vulcanize:* ts-node src/cli/checkpoint.ts",
|
||||
"export-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/export-state.js",
|
||||
"export-state:dev": "DEBUG=vulcanize:* ts-node src/cli/export-state.ts",
|
||||
"import-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/import-state.js",
|
||||
"import-state:dev": "DEBUG=vulcanize:* ts-node src/cli/import-state.ts",
|
||||
"inspect-cid": "DEBUG=vulcanize:* ts-node src/cli/inspect-cid.ts",
|
||||
"index-block": "DEBUG=vulcanize:* ts-node src/cli/index-block.ts"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/cerc-io/watcher-ts.git"
|
||||
},
|
||||
"author": "",
|
||||
"license": "AGPL-3.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/cerc-io/watcher-ts/issues"
|
||||
},
|
||||
"homepage": "https://github.com/cerc-io/watcher-ts#readme",
|
||||
"dependencies": {
|
||||
"@apollo/client": "^3.3.19",
|
||||
"@ethersproject/providers": "^5.4.4",
|
||||
"@cerc-io/cli": "^0.2.34",
|
||||
"@cerc-io/ipld-eth-client": "^0.2.34",
|
||||
"@cerc-io/solidity-mapper": "^0.2.34",
|
||||
"@cerc-io/util": "^0.2.34",
|
||||
"apollo-type-bigint": "^0.1.3",
|
||||
"debug": "^4.3.1",
|
||||
"ethers": "^5.4.4",
|
||||
"graphql": "^15.5.0",
|
||||
"json-bigint": "^1.0.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"typeorm": "^0.2.32",
|
||||
"yargs": "^17.0.1",
|
||||
"decimal.js": "^10.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ethersproject/abi": "^5.3.0",
|
||||
"@types/yargs": "^17.0.0",
|
||||
"@types/debug": "^4.1.5",
|
||||
"@types/json-bigint": "^1.0.1",
|
||||
"@typescript-eslint/eslint-plugin": "^5.47.1",
|
||||
"@typescript-eslint/parser": "^5.47.1",
|
||||
"eslint": "^8.35.0",
|
||||
"eslint-config-semistandard": "^15.0.1",
|
||||
"eslint-config-standard": "^16.0.3",
|
||||
"eslint-plugin-import": "^2.27.5",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^5.1.0",
|
||||
"eslint-plugin-standard": "^5.0.0",
|
||||
"ts-node": "^10.2.1",
|
||||
"typescript": "^5.0.2",
|
||||
"copyfiles": "^2.4.1"
|
||||
}
|
||||
}
|
||||
603
packages/polls-watcher/src/artifacts/Polls.json
Normal file
603
packages/polls-watcher/src/artifacts/Polls.json
Normal file
@ -0,0 +1,603 @@
|
||||
{
|
||||
"abi": [
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "pollDuration",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_proposal",
|
||||
"type": "bytes32"
|
||||
}
|
||||
],
|
||||
"name": "updateDocumentPoll",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "majority",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "getUpgradeProposals",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "proposals",
|
||||
"type": "address[]"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [],
|
||||
"name": "incrementTotalVoters",
|
||||
"outputs": [],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "getDocumentMajorities",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "majorities",
|
||||
"type": "bytes32[]"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_as",
|
||||
"type": "uint8"
|
||||
},
|
||||
{
|
||||
"name": "_proposal",
|
||||
"type": "address"
|
||||
},
|
||||
{
|
||||
"name": "_vote",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"name": "castUpgradeVote",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "majority",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_proposal",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "updateUpgradePoll",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "majority",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "totalVoters",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "uint16"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_galaxy",
|
||||
"type": "uint8"
|
||||
},
|
||||
{
|
||||
"name": "_proposal",
|
||||
"type": "bytes32"
|
||||
}
|
||||
],
|
||||
"name": "hasVotedOnDocumentPoll",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "result",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_as",
|
||||
"type": "uint8"
|
||||
},
|
||||
{
|
||||
"name": "_proposal",
|
||||
"type": "bytes32"
|
||||
},
|
||||
{
|
||||
"name": "_vote",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"name": "castDocumentVote",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "majority",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [],
|
||||
"name": "renounceOwnership",
|
||||
"outputs": [],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "bytes32"
|
||||
}
|
||||
],
|
||||
"name": "documentHasAchievedMajority",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "owner",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_proposal",
|
||||
"type": "bytes32"
|
||||
}
|
||||
],
|
||||
"name": "startDocumentPoll",
|
||||
"outputs": [],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"name": "upgradeProposals",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "bytes32"
|
||||
}
|
||||
],
|
||||
"name": "documentPolls",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "start",
|
||||
"type": "uint256"
|
||||
},
|
||||
{
|
||||
"name": "yesVotes",
|
||||
"type": "uint16"
|
||||
},
|
||||
{
|
||||
"name": "noVotes",
|
||||
"type": "uint16"
|
||||
},
|
||||
{
|
||||
"name": "duration",
|
||||
"type": "uint256"
|
||||
},
|
||||
{
|
||||
"name": "cooldown",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"name": "documentProposals",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "bytes32"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "getUpgradeProposalCount",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "count",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "getDocumentProposalCount",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "count",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "getDocumentProposals",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "proposals",
|
||||
"type": "bytes32[]"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "pollCooldown",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_pollDuration",
|
||||
"type": "uint256"
|
||||
},
|
||||
{
|
||||
"name": "_pollCooldown",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"name": "reconfigure",
|
||||
"outputs": [],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "upgradePolls",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "start",
|
||||
"type": "uint256"
|
||||
},
|
||||
{
|
||||
"name": "yesVotes",
|
||||
"type": "uint16"
|
||||
},
|
||||
{
|
||||
"name": "noVotes",
|
||||
"type": "uint16"
|
||||
},
|
||||
{
|
||||
"name": "duration",
|
||||
"type": "uint256"
|
||||
},
|
||||
{
|
||||
"name": "cooldown",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "upgradeHasAchievedMajority",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_proposal",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "startUpgradePoll",
|
||||
"outputs": [],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_newOwner",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "transferOwnership",
|
||||
"outputs": [],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"name": "documentMajorities",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "",
|
||||
"type": "bytes32"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_galaxy",
|
||||
"type": "uint8"
|
||||
},
|
||||
{
|
||||
"name": "_proposal",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "hasVotedOnUpgradePoll",
|
||||
"outputs": [
|
||||
{
|
||||
"name": "result",
|
||||
"type": "bool"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_pollDuration",
|
||||
"type": "uint256"
|
||||
},
|
||||
{
|
||||
"name": "_pollCooldown",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "constructor"
|
||||
},
|
||||
{
|
||||
"anonymous": false,
|
||||
"inputs": [
|
||||
{
|
||||
"indexed": false,
|
||||
"name": "proposal",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "UpgradePollStarted",
|
||||
"type": "event"
|
||||
},
|
||||
{
|
||||
"anonymous": false,
|
||||
"inputs": [
|
||||
{
|
||||
"indexed": false,
|
||||
"name": "proposal",
|
||||
"type": "bytes32"
|
||||
}
|
||||
],
|
||||
"name": "DocumentPollStarted",
|
||||
"type": "event"
|
||||
},
|
||||
{
|
||||
"anonymous": false,
|
||||
"inputs": [
|
||||
{
|
||||
"indexed": false,
|
||||
"name": "proposal",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "UpgradeMajority",
|
||||
"type": "event"
|
||||
},
|
||||
{
|
||||
"anonymous": false,
|
||||
"inputs": [
|
||||
{
|
||||
"indexed": false,
|
||||
"name": "proposal",
|
||||
"type": "bytes32"
|
||||
}
|
||||
],
|
||||
"name": "DocumentMajority",
|
||||
"type": "event"
|
||||
},
|
||||
{
|
||||
"anonymous": false,
|
||||
"inputs": [
|
||||
{
|
||||
"indexed": true,
|
||||
"name": "previousOwner",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "OwnershipRenounced",
|
||||
"type": "event"
|
||||
},
|
||||
{
|
||||
"anonymous": false,
|
||||
"inputs": [
|
||||
{
|
||||
"indexed": true,
|
||||
"name": "previousOwner",
|
||||
"type": "address"
|
||||
},
|
||||
{
|
||||
"indexed": true,
|
||||
"name": "newOwner",
|
||||
"type": "address"
|
||||
}
|
||||
],
|
||||
"name": "OwnershipTransferred",
|
||||
"type": "event"
|
||||
}
|
||||
]
|
||||
}
|
||||
34
packages/polls-watcher/src/cli/checkpoint-cmds/create.ts
Normal file
34
packages/polls-watcher/src/cli/checkpoint-cmds/create.ts
Normal file
@ -0,0 +1,34 @@
|
||||
//
|
||||
// Copyright 2022 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { CreateCheckpointCmd } from '@cerc-io/cli';
|
||||
|
||||
import { Database } from '../../database';
|
||||
import { Indexer } from '../../indexer';
|
||||
|
||||
export const command = 'create';
|
||||
|
||||
export const desc = 'Create checkpoint';
|
||||
|
||||
export const builder = {
|
||||
address: {
|
||||
type: 'string',
|
||||
require: true,
|
||||
demandOption: true,
|
||||
describe: 'Contract address to create the checkpoint for.'
|
||||
},
|
||||
blockHash: {
|
||||
type: 'string',
|
||||
describe: 'Blockhash at which to create the checkpoint.'
|
||||
}
|
||||
};
|
||||
|
||||
export const handler = async (argv: any): Promise<void> => {
|
||||
const createCheckpointCmd = new CreateCheckpointCmd();
|
||||
await createCheckpointCmd.init(argv, Database);
|
||||
|
||||
await createCheckpointCmd.initIndexer(Indexer);
|
||||
|
||||
await createCheckpointCmd.exec();
|
||||
};
|
||||
39
packages/polls-watcher/src/cli/checkpoint.ts
Normal file
39
packages/polls-watcher/src/cli/checkpoint.ts
Normal file
@ -0,0 +1,39 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import yargs from 'yargs';
|
||||
import 'reflect-metadata';
|
||||
import debug from 'debug';
|
||||
|
||||
import { DEFAULT_CONFIG_PATH } from '@cerc-io/util';
|
||||
|
||||
import { hideBin } from 'yargs/helpers';
|
||||
|
||||
const log = debug('vulcanize:checkpoint');
|
||||
|
||||
const main = async () => {
|
||||
return yargs(hideBin(process.argv))
|
||||
.parserConfiguration({
|
||||
'parse-numbers': false
|
||||
}).options({
|
||||
configFile: {
|
||||
alias: 'f',
|
||||
type: 'string',
|
||||
require: true,
|
||||
demandOption: true,
|
||||
describe: 'configuration file path (toml)',
|
||||
default: DEFAULT_CONFIG_PATH
|
||||
}
|
||||
})
|
||||
.commandDir('checkpoint-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ })
|
||||
.demandCommand(1)
|
||||
.help()
|
||||
.argv;
|
||||
};
|
||||
|
||||
main().then(() => {
|
||||
process.exit();
|
||||
}).catch(err => {
|
||||
log(err);
|
||||
});
|
||||
28
packages/polls-watcher/src/cli/export-state.ts
Normal file
28
packages/polls-watcher/src/cli/export-state.ts
Normal file
@ -0,0 +1,28 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import 'reflect-metadata';
|
||||
import debug from 'debug';
|
||||
|
||||
import { ExportStateCmd } from '@cerc-io/cli';
|
||||
|
||||
import { Database } from '../database';
|
||||
import { Indexer } from '../indexer';
|
||||
|
||||
const log = debug('vulcanize:export-state');
|
||||
|
||||
const main = async (): Promise<void> => {
|
||||
const exportStateCmd = new ExportStateCmd();
|
||||
await exportStateCmd.init(Database);
|
||||
|
||||
await exportStateCmd.initIndexer(Indexer);
|
||||
|
||||
await exportStateCmd.exec();
|
||||
};
|
||||
|
||||
main().catch(err => {
|
||||
log(err);
|
||||
}).finally(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
29
packages/polls-watcher/src/cli/import-state.ts
Normal file
29
packages/polls-watcher/src/cli/import-state.ts
Normal file
@ -0,0 +1,29 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import 'reflect-metadata';
|
||||
import debug from 'debug';
|
||||
|
||||
import { ImportStateCmd } from '@cerc-io/cli';
|
||||
|
||||
import { Database } from '../database';
|
||||
import { Indexer } from '../indexer';
|
||||
import { State } from '../entity/State';
|
||||
|
||||
const log = debug('vulcanize:import-state');
|
||||
|
||||
export const main = async (): Promise<any> => {
|
||||
const importStateCmd = new ImportStateCmd();
|
||||
await importStateCmd.init(Database);
|
||||
|
||||
await importStateCmd.initIndexer(Indexer);
|
||||
|
||||
await importStateCmd.exec(State);
|
||||
};
|
||||
|
||||
main().catch(err => {
|
||||
log(err);
|
||||
}).finally(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
28
packages/polls-watcher/src/cli/index-block.ts
Normal file
28
packages/polls-watcher/src/cli/index-block.ts
Normal file
@ -0,0 +1,28 @@
|
||||
//
|
||||
// Copyright 2022 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import 'reflect-metadata';
|
||||
import debug from 'debug';
|
||||
|
||||
import { IndexBlockCmd } from '@cerc-io/cli';
|
||||
|
||||
import { Database } from '../database';
|
||||
import { Indexer } from '../indexer';
|
||||
|
||||
const log = debug('vulcanize:index-block');
|
||||
|
||||
const main = async (): Promise<void> => {
|
||||
const indexBlockCmd = new IndexBlockCmd();
|
||||
await indexBlockCmd.init(Database);
|
||||
|
||||
await indexBlockCmd.initIndexer(Indexer);
|
||||
|
||||
await indexBlockCmd.exec();
|
||||
};
|
||||
|
||||
main().catch(err => {
|
||||
log(err);
|
||||
}).finally(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
28
packages/polls-watcher/src/cli/inspect-cid.ts
Normal file
28
packages/polls-watcher/src/cli/inspect-cid.ts
Normal file
@ -0,0 +1,28 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import 'reflect-metadata';
|
||||
import debug from 'debug';
|
||||
|
||||
import { InspectCIDCmd } from '@cerc-io/cli';
|
||||
|
||||
import { Database } from '../database';
|
||||
import { Indexer } from '../indexer';
|
||||
|
||||
const log = debug('vulcanize:inspect-cid');
|
||||
|
||||
const main = async (): Promise<void> => {
|
||||
const inspectCIDCmd = new InspectCIDCmd();
|
||||
await inspectCIDCmd.init(Database);
|
||||
|
||||
await inspectCIDCmd.initIndexer(Indexer);
|
||||
|
||||
await inspectCIDCmd.exec();
|
||||
};
|
||||
|
||||
main().catch(err => {
|
||||
log(err);
|
||||
}).finally(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
22
packages/polls-watcher/src/cli/reset-cmds/job-queue.ts
Normal file
22
packages/polls-watcher/src/cli/reset-cmds/job-queue.ts
Normal file
@ -0,0 +1,22 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import debug from 'debug';
|
||||
|
||||
import { getConfig, resetJobs, Config } from '@cerc-io/util';
|
||||
|
||||
const log = debug('vulcanize:reset-job-queue');
|
||||
|
||||
export const command = 'job-queue';
|
||||
|
||||
export const desc = 'Reset job queue';
|
||||
|
||||
export const builder = {};
|
||||
|
||||
export const handler = async (argv: any): Promise<void> => {
|
||||
const config: Config = await getConfig(argv.configFile);
|
||||
await resetJobs(config);
|
||||
|
||||
log('Job queue reset successfully');
|
||||
};
|
||||
24
packages/polls-watcher/src/cli/reset-cmds/state.ts
Normal file
24
packages/polls-watcher/src/cli/reset-cmds/state.ts
Normal file
@ -0,0 +1,24 @@
|
||||
//
|
||||
// Copyright 2022 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { ResetStateCmd } from '@cerc-io/cli';
|
||||
|
||||
import { Database } from '../../database';
|
||||
|
||||
export const command = 'state';
|
||||
|
||||
export const desc = 'Reset State to a given block number';
|
||||
|
||||
export const builder = {
|
||||
blockNumber: {
|
||||
type: 'number'
|
||||
}
|
||||
};
|
||||
|
||||
export const handler = async (argv: any): Promise<void> => {
|
||||
const resetStateCmd = new ResetStateCmd();
|
||||
await resetStateCmd.init(argv, Database);
|
||||
|
||||
await resetStateCmd.exec();
|
||||
};
|
||||
27
packages/polls-watcher/src/cli/reset-cmds/watcher.ts
Normal file
27
packages/polls-watcher/src/cli/reset-cmds/watcher.ts
Normal file
@ -0,0 +1,27 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { ResetWatcherCmd } from '@cerc-io/cli';
|
||||
|
||||
import { Database } from '../../database';
|
||||
import { Indexer } from '../../indexer';
|
||||
|
||||
export const command = 'watcher';
|
||||
|
||||
export const desc = 'Reset watcher to a block number';
|
||||
|
||||
export const builder = {
|
||||
blockNumber: {
|
||||
type: 'number'
|
||||
}
|
||||
};
|
||||
|
||||
export const handler = async (argv: any): Promise<void> => {
|
||||
const resetWatcherCmd = new ResetWatcherCmd();
|
||||
await resetWatcherCmd.init(argv, Database);
|
||||
|
||||
await resetWatcherCmd.initIndexer(Indexer);
|
||||
|
||||
await resetWatcherCmd.exec();
|
||||
};
|
||||
24
packages/polls-watcher/src/cli/reset.ts
Normal file
24
packages/polls-watcher/src/cli/reset.ts
Normal file
@ -0,0 +1,24 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import 'reflect-metadata';
|
||||
import debug from 'debug';
|
||||
|
||||
import { getResetYargs } from '@cerc-io/util';
|
||||
|
||||
const log = debug('vulcanize:reset');
|
||||
|
||||
const main = async () => {
|
||||
return getResetYargs()
|
||||
.commandDir('reset-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ })
|
||||
.demandCommand(1)
|
||||
.help()
|
||||
.argv;
|
||||
};
|
||||
|
||||
main().then(() => {
|
||||
process.exit();
|
||||
}).catch(err => {
|
||||
log(err);
|
||||
});
|
||||
28
packages/polls-watcher/src/cli/watch-contract.ts
Normal file
28
packages/polls-watcher/src/cli/watch-contract.ts
Normal file
@ -0,0 +1,28 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import 'reflect-metadata';
|
||||
import debug from 'debug';
|
||||
|
||||
import { WatchContractCmd } from '@cerc-io/cli';
|
||||
|
||||
import { Database } from '../database';
|
||||
import { Indexer } from '../indexer';
|
||||
|
||||
const log = debug('vulcanize:watch-contract');
|
||||
|
||||
const main = async (): Promise<void> => {
|
||||
const watchContractCmd = new WatchContractCmd();
|
||||
await watchContractCmd.init(Database);
|
||||
|
||||
await watchContractCmd.initIndexer(Indexer);
|
||||
|
||||
await watchContractCmd.exec();
|
||||
};
|
||||
|
||||
main().catch(err => {
|
||||
log(err);
|
||||
}).finally(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
91
packages/polls-watcher/src/client.ts
Normal file
91
packages/polls-watcher/src/client.ts
Normal file
@ -0,0 +1,91 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { gql } from '@apollo/client/core';
|
||||
import { GraphQLClient, GraphQLConfig } from '@cerc-io/ipld-eth-client';
|
||||
|
||||
import { queries, mutations, subscriptions } from './gql';
|
||||
|
||||
export class Client {
|
||||
_config: GraphQLConfig;
|
||||
_client: GraphQLClient;
|
||||
|
||||
constructor (config: GraphQLConfig) {
|
||||
this._config = config;
|
||||
|
||||
this._client = new GraphQLClient(config);
|
||||
}
|
||||
|
||||
async getGetUpgradeProposalCount (blockHash: string, contractAddress: string): Promise<any> {
|
||||
const { getUpgradeProposalCount } = await this._client.query(
|
||||
gql(queries.getUpgradeProposalCount),
|
||||
{ blockHash, contractAddress }
|
||||
);
|
||||
|
||||
return getUpgradeProposalCount;
|
||||
}
|
||||
|
||||
async getGetDocumentProposalCount (blockHash: string, contractAddress: string): Promise<any> {
|
||||
const { getDocumentProposalCount } = await this._client.query(
|
||||
gql(queries.getDocumentProposalCount),
|
||||
{ blockHash, contractAddress }
|
||||
);
|
||||
|
||||
return getDocumentProposalCount;
|
||||
}
|
||||
|
||||
async getHasVotedOnUpgradePoll (blockHash: string, contractAddress: string, _galaxy: number, _proposal: string): Promise<any> {
|
||||
const { hasVotedOnUpgradePoll } = await this._client.query(
|
||||
gql(queries.hasVotedOnUpgradePoll),
|
||||
{ blockHash, contractAddress, _galaxy, _proposal }
|
||||
);
|
||||
|
||||
return hasVotedOnUpgradePoll;
|
||||
}
|
||||
|
||||
async getHasVotedOnDocumentPoll (blockHash: string, contractAddress: string, _galaxy: number, _proposal: string): Promise<any> {
|
||||
const { hasVotedOnDocumentPoll } = await this._client.query(
|
||||
gql(queries.hasVotedOnDocumentPoll),
|
||||
{ blockHash, contractAddress, _galaxy, _proposal }
|
||||
);
|
||||
|
||||
return hasVotedOnDocumentPoll;
|
||||
}
|
||||
|
||||
async getEvents (blockHash: string, contractAddress: string, name: string): Promise<any> {
|
||||
const { events } = await this._client.query(
|
||||
gql(queries.events),
|
||||
{ blockHash, contractAddress, name }
|
||||
);
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise<any> {
|
||||
const { eventsInRange } = await this._client.query(
|
||||
gql(queries.eventsInRange),
|
||||
{ fromBlockNumber, toBlockNumber }
|
||||
);
|
||||
|
||||
return eventsInRange;
|
||||
}
|
||||
|
||||
async watchContract (contractAddress: string, startingBlock?: number): Promise<any> {
|
||||
const { watchContract } = await this._client.mutate(
|
||||
gql(mutations.watchContract),
|
||||
{ contractAddress, startingBlock }
|
||||
);
|
||||
|
||||
return watchContract;
|
||||
}
|
||||
|
||||
async watchEvents (onNext: (value: any) => void): Promise<ZenObservable.Subscription> {
|
||||
return this._client.subscribe(
|
||||
gql(subscriptions.onEvent),
|
||||
({ data }) => {
|
||||
onNext(data.onEvent);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
379
packages/polls-watcher/src/database.ts
Normal file
379
packages/polls-watcher/src/database.ts
Normal file
@ -0,0 +1,379 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import assert from 'assert';
|
||||
import { Connection, ConnectionOptions, DeepPartial, FindConditions, QueryRunner, FindManyOptions, EntityTarget } from 'typeorm';
|
||||
import path from 'path';
|
||||
|
||||
import {
|
||||
Database as BaseDatabase,
|
||||
DatabaseInterface,
|
||||
QueryOptions,
|
||||
StateKind,
|
||||
Where
|
||||
} from '@cerc-io/util';
|
||||
|
||||
import { Contract } from './entity/Contract';
|
||||
import { Event } from './entity/Event';
|
||||
import { SyncStatus } from './entity/SyncStatus';
|
||||
import { StateSyncStatus } from './entity/StateSyncStatus';
|
||||
import { BlockProgress } from './entity/BlockProgress';
|
||||
import { State } from './entity/State';
|
||||
import { GetUpgradeProposals } from './entity/GetUpgradeProposals';
|
||||
import { GetUpgradeProposalCount } from './entity/GetUpgradeProposalCount';
|
||||
import { GetDocumentProposals } from './entity/GetDocumentProposals';
|
||||
import { GetDocumentProposalCount } from './entity/GetDocumentProposalCount';
|
||||
import { HasVotedOnUpgradePoll } from './entity/HasVotedOnUpgradePoll';
|
||||
import { HasVotedOnDocumentPoll } from './entity/HasVotedOnDocumentPoll';
|
||||
import { GetDocumentMajorities } from './entity/GetDocumentMajorities';
|
||||
|
||||
export const ENTITIES = [GetUpgradeProposals, GetUpgradeProposalCount, GetDocumentMajorities, GetDocumentProposals, GetDocumentProposalCount, HasVotedOnUpgradePoll, HasVotedOnDocumentPoll];
|
||||
|
||||
export class Database implements DatabaseInterface {
|
||||
_config: ConnectionOptions;
|
||||
_conn!: Connection;
|
||||
_baseDatabase: BaseDatabase;
|
||||
_propColMaps: { [key: string]: Map<string, string>; };
|
||||
|
||||
constructor (config: ConnectionOptions) {
|
||||
assert(config);
|
||||
|
||||
this._config = {
|
||||
...config,
|
||||
entities: [path.join(__dirname, 'entity/*')]
|
||||
};
|
||||
|
||||
this._baseDatabase = new BaseDatabase(this._config);
|
||||
this._propColMaps = {};
|
||||
}
|
||||
|
||||
get baseDatabase (): BaseDatabase {
|
||||
return this._baseDatabase;
|
||||
}
|
||||
|
||||
async init (): Promise<void> {
|
||||
this._conn = await this._baseDatabase.init();
|
||||
this._setPropColMaps();
|
||||
}
|
||||
|
||||
async close (): Promise<void> {
|
||||
return this._baseDatabase.close();
|
||||
}
|
||||
|
||||
async getGetUpgradeProposals ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<GetUpgradeProposals | undefined> {
|
||||
return this._conn.getRepository(GetUpgradeProposals)
|
||||
.findOne({
|
||||
blockHash,
|
||||
contractAddress
|
||||
});
|
||||
}
|
||||
|
||||
async getGetUpgradeProposalCount ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<GetUpgradeProposalCount | undefined> {
|
||||
return this._conn.getRepository(GetUpgradeProposalCount)
|
||||
.findOne({
|
||||
blockHash,
|
||||
contractAddress
|
||||
});
|
||||
}
|
||||
|
||||
async getGetDocumentProposals ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<GetDocumentProposals | undefined> {
|
||||
return this._conn.getRepository(GetDocumentProposals)
|
||||
.findOne({
|
||||
blockHash,
|
||||
contractAddress
|
||||
});
|
||||
}
|
||||
|
||||
async getGetDocumentMajorities ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<GetDocumentMajorities | undefined> {
|
||||
return this._conn.getRepository(GetDocumentMajorities)
|
||||
.findOne({
|
||||
blockHash,
|
||||
contractAddress
|
||||
});
|
||||
}
|
||||
|
||||
async getGetDocumentProposalCount ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<GetDocumentProposalCount | undefined> {
|
||||
return this._conn.getRepository(GetDocumentProposalCount)
|
||||
.findOne({
|
||||
blockHash,
|
||||
contractAddress
|
||||
});
|
||||
}
|
||||
|
||||
async getHasVotedOnUpgradePoll ({ blockHash, contractAddress, _galaxy, _proposal }: { blockHash: string, contractAddress: string, _galaxy: number, _proposal: string }): Promise<HasVotedOnUpgradePoll | undefined> {
|
||||
return this._conn.getRepository(HasVotedOnUpgradePoll)
|
||||
.findOne({
|
||||
blockHash,
|
||||
contractAddress,
|
||||
_galaxy,
|
||||
_proposal
|
||||
});
|
||||
}
|
||||
|
||||
async getHasVotedOnDocumentPoll ({ blockHash, contractAddress, _galaxy, _proposal }: { blockHash: string, contractAddress: string, _galaxy: number, _proposal: string }): Promise<HasVotedOnDocumentPoll | undefined> {
|
||||
return this._conn.getRepository(HasVotedOnDocumentPoll)
|
||||
.findOne({
|
||||
blockHash,
|
||||
contractAddress,
|
||||
_galaxy,
|
||||
_proposal
|
||||
});
|
||||
}
|
||||
|
||||
async saveGetUpgradeProposals ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<GetUpgradeProposals>): Promise<GetUpgradeProposals> {
|
||||
const repo = this._conn.getRepository(GetUpgradeProposals);
|
||||
const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof });
|
||||
return repo.save(entity);
|
||||
}
|
||||
|
||||
async saveGetUpgradeProposalCount ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<GetUpgradeProposalCount>): Promise<GetUpgradeProposalCount> {
|
||||
const repo = this._conn.getRepository(GetUpgradeProposalCount);
|
||||
const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof });
|
||||
return repo.save(entity);
|
||||
}
|
||||
|
||||
async saveGetDocumentProposals ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<GetDocumentProposals>): Promise<GetDocumentProposals> {
|
||||
const repo = this._conn.getRepository(GetDocumentProposals);
|
||||
const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof });
|
||||
return repo.save(entity);
|
||||
}
|
||||
|
||||
async saveGetDocumentMajorities ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<GetDocumentMajorities>): Promise<GetDocumentMajorities> {
|
||||
const repo = this._conn.getRepository(GetDocumentMajorities);
|
||||
const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof });
|
||||
return repo.save(entity);
|
||||
}
|
||||
|
||||
async saveGetDocumentProposalCount ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<GetDocumentProposalCount>): Promise<GetDocumentProposalCount> {
|
||||
const repo = this._conn.getRepository(GetDocumentProposalCount);
|
||||
const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof });
|
||||
return repo.save(entity);
|
||||
}
|
||||
|
||||
async saveHasVotedOnUpgradePoll ({ blockHash, blockNumber, contractAddress, _galaxy, _proposal, value, proof }: DeepPartial<HasVotedOnUpgradePoll>): Promise<HasVotedOnUpgradePoll> {
|
||||
const repo = this._conn.getRepository(HasVotedOnUpgradePoll);
|
||||
const entity = repo.create({ blockHash, blockNumber, contractAddress, _galaxy, _proposal, value, proof });
|
||||
return repo.save(entity);
|
||||
}
|
||||
|
||||
async saveHasVotedOnDocumentPoll ({ blockHash, blockNumber, contractAddress, _galaxy, _proposal, value, proof }: DeepPartial<HasVotedOnDocumentPoll>): Promise<HasVotedOnDocumentPoll> {
|
||||
const repo = this._conn.getRepository(HasVotedOnDocumentPoll);
|
||||
const entity = repo.create({ blockHash, blockNumber, contractAddress, _galaxy, _proposal, value, proof });
|
||||
return repo.save(entity);
|
||||
}
|
||||
|
||||
getNewState (): State {
|
||||
return new State();
|
||||
}
|
||||
|
||||
async getStates (where: FindConditions<State>): Promise<State[]> {
|
||||
const repo = this._conn.getRepository(State);
|
||||
|
||||
return this._baseDatabase.getStates(repo, where);
|
||||
}
|
||||
|
||||
async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise<State | undefined> {
|
||||
const repo = this._conn.getRepository(State);
|
||||
|
||||
return this._baseDatabase.getLatestState(repo, contractAddress, kind, blockNumber);
|
||||
}
|
||||
|
||||
async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise<State | undefined> {
|
||||
const repo = this._conn.getRepository(State);
|
||||
|
||||
return this._baseDatabase.getPrevState(repo, blockHash, contractAddress, kind);
|
||||
}
|
||||
|
||||
// Fetch all diff States after the specified block number.
|
||||
async getDiffStatesInRange (contractAddress: string, startblock: number, endBlock: number): Promise<State[]> {
|
||||
const repo = this._conn.getRepository(State);
|
||||
|
||||
return this._baseDatabase.getDiffStatesInRange(repo, contractAddress, startblock, endBlock);
|
||||
}
|
||||
|
||||
async saveOrUpdateState (dbTx: QueryRunner, state: State): Promise<State> {
|
||||
const repo = dbTx.manager.getRepository(State);
|
||||
|
||||
return this._baseDatabase.saveOrUpdateState(repo, state);
|
||||
}
|
||||
|
||||
async removeStates (dbTx: QueryRunner, blockNumber: number, kind: string): Promise<void> {
|
||||
const repo = dbTx.manager.getRepository(State);
|
||||
|
||||
await this._baseDatabase.removeStates(repo, blockNumber, kind);
|
||||
}
|
||||
|
||||
async removeStatesAfterBlock (dbTx: QueryRunner, blockNumber: number): Promise<void> {
|
||||
const repo = dbTx.manager.getRepository(State);
|
||||
|
||||
await this._baseDatabase.removeStatesAfterBlock(repo, blockNumber);
|
||||
}
|
||||
|
||||
async getStateSyncStatus (): Promise<StateSyncStatus | undefined> {
|
||||
const repo = this._conn.getRepository(StateSyncStatus);
|
||||
|
||||
return this._baseDatabase.getStateSyncStatus(repo);
|
||||
}
|
||||
|
||||
async updateStateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise<StateSyncStatus> {
|
||||
const repo = queryRunner.manager.getRepository(StateSyncStatus);
|
||||
|
||||
return this._baseDatabase.updateStateSyncStatusIndexedBlock(repo, blockNumber, force);
|
||||
}
|
||||
|
||||
async updateStateSyncStatusCheckpointBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise<StateSyncStatus> {
|
||||
const repo = queryRunner.manager.getRepository(StateSyncStatus);
|
||||
|
||||
return this._baseDatabase.updateStateSyncStatusCheckpointBlock(repo, blockNumber, force);
|
||||
}
|
||||
|
||||
async getContracts (): Promise<Contract[]> {
|
||||
const repo = this._conn.getRepository(Contract);
|
||||
|
||||
return this._baseDatabase.getContracts(repo);
|
||||
}
|
||||
|
||||
async createTransactionRunner (): Promise<QueryRunner> {
|
||||
return this._baseDatabase.createTransactionRunner();
|
||||
}
|
||||
|
||||
async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> {
|
||||
const repo = this._conn.getRepository(BlockProgress);
|
||||
|
||||
return this._baseDatabase.getProcessedBlockCountForRange(repo, fromBlockNumber, toBlockNumber);
|
||||
}
|
||||
|
||||
async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise<Array<Event>> {
|
||||
const repo = this._conn.getRepository(Event);
|
||||
|
||||
return this._baseDatabase.getEventsInRange(repo, fromBlockNumber, toBlockNumber);
|
||||
}
|
||||
|
||||
async saveEventEntity (queryRunner: QueryRunner, entity: Event): Promise<Event> {
|
||||
const repo = queryRunner.manager.getRepository(Event);
|
||||
return this._baseDatabase.saveEventEntity(repo, entity);
|
||||
}
|
||||
|
||||
async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise<Event[]> {
|
||||
const repo = this._conn.getRepository(Event);
|
||||
|
||||
return this._baseDatabase.getBlockEvents(repo, blockHash, where, queryOptions);
|
||||
}
|
||||
|
||||
async saveBlockWithEvents (queryRunner: QueryRunner, block: DeepPartial<BlockProgress>, events: DeepPartial<Event>[]): Promise<BlockProgress> {
|
||||
const blockRepo = queryRunner.manager.getRepository(BlockProgress);
|
||||
const eventRepo = queryRunner.manager.getRepository(Event);
|
||||
|
||||
return this._baseDatabase.saveBlockWithEvents(blockRepo, eventRepo, block, events);
|
||||
}
|
||||
|
||||
async saveEvents (queryRunner: QueryRunner, events: Event[]): Promise<void> {
|
||||
const eventRepo = queryRunner.manager.getRepository(Event);
|
||||
|
||||
return this._baseDatabase.saveEvents(eventRepo, events);
|
||||
}
|
||||
|
||||
async saveBlockProgress (queryRunner: QueryRunner, block: DeepPartial<BlockProgress>): Promise<BlockProgress> {
|
||||
const repo = queryRunner.manager.getRepository(BlockProgress);
|
||||
|
||||
return this._baseDatabase.saveBlockProgress(repo, block);
|
||||
}
|
||||
|
||||
async saveContract (queryRunner: QueryRunner, address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise<Contract> {
|
||||
const repo = queryRunner.manager.getRepository(Contract);
|
||||
|
||||
return this._baseDatabase.saveContract(repo, address, kind, checkpoint, startingBlock);
|
||||
}
|
||||
|
||||
async updateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise<SyncStatus> {
|
||||
const repo = queryRunner.manager.getRepository(SyncStatus);
|
||||
|
||||
return this._baseDatabase.updateSyncStatusIndexedBlock(repo, blockHash, blockNumber, force);
|
||||
}
|
||||
|
||||
async updateSyncStatusCanonicalBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise<SyncStatus> {
|
||||
const repo = queryRunner.manager.getRepository(SyncStatus);
|
||||
|
||||
return this._baseDatabase.updateSyncStatusCanonicalBlock(repo, blockHash, blockNumber, force);
|
||||
}
|
||||
|
||||
async updateSyncStatusChainHead (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise<SyncStatus> {
|
||||
const repo = queryRunner.manager.getRepository(SyncStatus);
|
||||
|
||||
return this._baseDatabase.updateSyncStatusChainHead(repo, blockHash, blockNumber, force);
|
||||
}
|
||||
|
||||
async getSyncStatus (queryRunner: QueryRunner): Promise<SyncStatus | undefined> {
|
||||
const repo = queryRunner.manager.getRepository(SyncStatus);
|
||||
|
||||
return this._baseDatabase.getSyncStatus(repo);
|
||||
}
|
||||
|
||||
async getEvent (id: string): Promise<Event | undefined> {
|
||||
const repo = this._conn.getRepository(Event);
|
||||
|
||||
return this._baseDatabase.getEvent(repo, id);
|
||||
}
|
||||
|
||||
async getBlocksAtHeight (height: number, isPruned: boolean): Promise<BlockProgress[]> {
|
||||
const repo = this._conn.getRepository(BlockProgress);
|
||||
|
||||
return this._baseDatabase.getBlocksAtHeight(repo, height, isPruned);
|
||||
}
|
||||
|
||||
async markBlocksAsPruned (queryRunner: QueryRunner, blocks: BlockProgress[]): Promise<void> {
|
||||
const repo = queryRunner.manager.getRepository(BlockProgress);
|
||||
|
||||
return this._baseDatabase.markBlocksAsPruned(repo, blocks);
|
||||
}
|
||||
|
||||
async getBlockProgress (blockHash: string): Promise<BlockProgress | undefined> {
|
||||
const repo = this._conn.getRepository(BlockProgress);
|
||||
return this._baseDatabase.getBlockProgress(repo, blockHash);
|
||||
}
|
||||
|
||||
async getBlockProgressEntities (where: FindConditions<BlockProgress>, options: FindManyOptions<BlockProgress>): Promise<BlockProgress[]> {
|
||||
const repo = this._conn.getRepository(BlockProgress);
|
||||
|
||||
return this._baseDatabase.getBlockProgressEntities(repo, where, options);
|
||||
}
|
||||
|
||||
async getEntitiesForBlock (blockHash: string, tableName: string): Promise<any[]> {
|
||||
return this._baseDatabase.getEntitiesForBlock(blockHash, tableName);
|
||||
}
|
||||
|
||||
async updateBlockProgress (queryRunner: QueryRunner, block: BlockProgress, lastProcessedEventIndex: number): Promise<BlockProgress> {
|
||||
const repo = queryRunner.manager.getRepository(BlockProgress);
|
||||
|
||||
return this._baseDatabase.updateBlockProgress(repo, block, lastProcessedEventIndex);
|
||||
}
|
||||
|
||||
async removeEntities<Entity> (queryRunner: QueryRunner, entity: new () => Entity, findConditions?: FindManyOptions<Entity> | FindConditions<Entity>): Promise<void> {
|
||||
return this._baseDatabase.removeEntities(queryRunner, entity, findConditions);
|
||||
}
|
||||
|
||||
async deleteEntitiesByConditions<Entity> (queryRunner: QueryRunner, entity: EntityTarget<Entity>, findConditions: FindConditions<Entity>): Promise<void> {
|
||||
await this._baseDatabase.deleteEntitiesByConditions(queryRunner, entity, findConditions);
|
||||
}
|
||||
|
||||
async getAncestorAtDepth (blockHash: string, depth: number): Promise<string> {
|
||||
return this._baseDatabase.getAncestorAtDepth(blockHash, depth);
|
||||
}
|
||||
|
||||
_getPropertyColumnMapForEntity (entityName: string): Map<string, string> {
|
||||
return this._conn.getMetadata(entityName).ownColumns.reduce((acc, curr) => {
|
||||
return acc.set(curr.propertyName, curr.databaseName);
|
||||
}, new Map<string, string>());
|
||||
}
|
||||
|
||||
_setPropColMaps (): void {
|
||||
this._propColMaps.GetUpgradeProposals = this._getPropertyColumnMapForEntity('GetUpgradeProposals');
|
||||
this._propColMaps.GetDocumentProposals = this._getPropertyColumnMapForEntity('GetDocumentProposals');
|
||||
this._propColMaps.GetDocumentMajorities = this._getPropertyColumnMapForEntity('GetDocumentMajorities');
|
||||
this._propColMaps.GetUpgradeProposalCount = this._getPropertyColumnMapForEntity('GetUpgradeProposalCount');
|
||||
this._propColMaps.GetDocumentProposalCount = this._getPropertyColumnMapForEntity('GetDocumentProposalCount');
|
||||
this._propColMaps.HasVotedOnUpgradePoll = this._getPropertyColumnMapForEntity('HasVotedOnUpgradePoll');
|
||||
this._propColMaps.HasVotedOnDocumentPoll = this._getPropertyColumnMapForEntity('HasVotedOnDocumentPoll');
|
||||
}
|
||||
}
|
||||
48
packages/polls-watcher/src/entity/BlockProgress.ts
Normal file
48
packages/polls-watcher/src/entity/BlockProgress.ts
Normal file
@ -0,0 +1,48 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn } from 'typeorm';
|
||||
import { BlockProgressInterface } from '@cerc-io/util';
|
||||
|
||||
@Entity()
|
||||
@Index(['blockHash'], { unique: true })
|
||||
@Index(['blockNumber'])
|
||||
@Index(['parentHash'])
|
||||
export class BlockProgress implements BlockProgressInterface {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar')
|
||||
cid!: string;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
blockHash!: string;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
parentHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
blockNumber!: number;
|
||||
|
||||
@Column('integer')
|
||||
blockTimestamp!: number;
|
||||
|
||||
@Column('integer')
|
||||
numEvents!: number;
|
||||
|
||||
@Column('integer')
|
||||
numProcessedEvents!: number;
|
||||
|
||||
@Column('integer')
|
||||
lastProcessedEventIndex!: number;
|
||||
|
||||
@Column('boolean')
|
||||
isComplete!: boolean;
|
||||
|
||||
@Column('boolean', { default: false })
|
||||
isPruned!: boolean;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt!: Date;
|
||||
}
|
||||
24
packages/polls-watcher/src/entity/Contract.ts
Normal file
24
packages/polls-watcher/src/entity/Contract.ts
Normal file
@ -0,0 +1,24 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm';
|
||||
|
||||
@Entity()
|
||||
@Index(['address'], { unique: true })
|
||||
export class Contract {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
address!: string;
|
||||
|
||||
@Column('varchar')
|
||||
kind!: string;
|
||||
|
||||
@Column('boolean')
|
||||
checkpoint!: boolean;
|
||||
|
||||
@Column('integer')
|
||||
startingBlock!: number;
|
||||
}
|
||||
38
packages/polls-watcher/src/entity/Event.ts
Normal file
38
packages/polls-watcher/src/entity/Event.ts
Normal file
@ -0,0 +1,38 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm';
|
||||
import { BlockProgress } from './BlockProgress';
|
||||
|
||||
@Entity()
|
||||
@Index(['block', 'contract'])
|
||||
@Index(['block', 'contract', 'eventName'])
|
||||
export class Event {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' })
|
||||
block!: BlockProgress;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
txHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
index!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
contract!: string;
|
||||
|
||||
@Column('varchar', { length: 256 })
|
||||
eventName!: string;
|
||||
|
||||
@Column('text')
|
||||
eventInfo!: string;
|
||||
|
||||
@Column('text')
|
||||
extraInfo!: string;
|
||||
|
||||
@Column('text')
|
||||
proof!: string;
|
||||
}
|
||||
27
packages/polls-watcher/src/entity/GetDocumentMajorities.ts
Normal file
27
packages/polls-watcher/src/entity/GetDocumentMajorities.ts
Normal file
@ -0,0 +1,27 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm';
|
||||
|
||||
@Entity()
|
||||
@Index(['blockHash', 'contractAddress'], { unique: true })
|
||||
export class GetDocumentMajorities {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
blockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
blockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
contractAddress!: string;
|
||||
|
||||
@Column('simple-array', { nullable: false })
|
||||
value!: string[];
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
proof!: string;
|
||||
}
|
||||
@ -0,0 +1,28 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm';
|
||||
import { bigintTransformer } from '@cerc-io/util';
|
||||
|
||||
@Entity()
|
||||
@Index(['blockHash', 'contractAddress'], { unique: true })
|
||||
export class GetDocumentProposalCount {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
blockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
blockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
contractAddress!: string;
|
||||
|
||||
@Column('numeric', { transformer: bigintTransformer })
|
||||
value!: bigint;
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
proof!: string;
|
||||
}
|
||||
27
packages/polls-watcher/src/entity/GetDocumentProposals.ts
Normal file
27
packages/polls-watcher/src/entity/GetDocumentProposals.ts
Normal file
@ -0,0 +1,27 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm';
|
||||
|
||||
@Entity()
|
||||
@Index(['blockHash', 'contractAddress'], { unique: true })
|
||||
export class GetDocumentProposals {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
blockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
blockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
contractAddress!: string;
|
||||
|
||||
@Column('simple-array', { nullable: false })
|
||||
value!: string[];
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
proof!: string;
|
||||
}
|
||||
28
packages/polls-watcher/src/entity/GetUpgradeProposalCount.ts
Normal file
28
packages/polls-watcher/src/entity/GetUpgradeProposalCount.ts
Normal file
@ -0,0 +1,28 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm';
|
||||
import { bigintTransformer } from '@cerc-io/util';
|
||||
|
||||
@Entity()
|
||||
@Index(['blockHash', 'contractAddress'], { unique: true })
|
||||
export class GetUpgradeProposalCount {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
blockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
blockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
contractAddress!: string;
|
||||
|
||||
@Column('numeric', { transformer: bigintTransformer })
|
||||
value!: bigint;
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
proof!: string;
|
||||
}
|
||||
27
packages/polls-watcher/src/entity/GetUpgradeProposals.ts
Normal file
27
packages/polls-watcher/src/entity/GetUpgradeProposals.ts
Normal file
@ -0,0 +1,27 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm';
|
||||
|
||||
@Entity()
|
||||
@Index(['blockHash', 'contractAddress'], { unique: true })
|
||||
export class GetUpgradeProposals {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
blockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
blockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
contractAddress!: string;
|
||||
|
||||
@Column('simple-array', { nullable: false })
|
||||
value!: string[];
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
proof!: string;
|
||||
}
|
||||
33
packages/polls-watcher/src/entity/HasVotedOnDocumentPoll.ts
Normal file
33
packages/polls-watcher/src/entity/HasVotedOnDocumentPoll.ts
Normal file
@ -0,0 +1,33 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm';
|
||||
|
||||
@Entity()
|
||||
@Index(['blockHash', 'contractAddress', '_galaxy', '_proposal'], { unique: true })
|
||||
export class HasVotedOnDocumentPoll {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
blockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
blockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
contractAddress!: string;
|
||||
|
||||
@Column('integer')
|
||||
_galaxy!: number;
|
||||
|
||||
@Column('varchar')
|
||||
_proposal!: string;
|
||||
|
||||
@Column('boolean')
|
||||
value!: boolean;
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
proof!: string;
|
||||
}
|
||||
33
packages/polls-watcher/src/entity/HasVotedOnUpgradePoll.ts
Normal file
33
packages/polls-watcher/src/entity/HasVotedOnUpgradePoll.ts
Normal file
@ -0,0 +1,33 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm';
|
||||
|
||||
@Entity()
|
||||
@Index(['blockHash', 'contractAddress', '_galaxy', '_proposal'], { unique: true })
|
||||
export class HasVotedOnUpgradePoll {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
blockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
blockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
contractAddress!: string;
|
||||
|
||||
@Column('integer')
|
||||
_galaxy!: number;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
_proposal!: string;
|
||||
|
||||
@Column('boolean')
|
||||
value!: boolean;
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
proof!: string;
|
||||
}
|
||||
31
packages/polls-watcher/src/entity/State.ts
Normal file
31
packages/polls-watcher/src/entity/State.ts
Normal file
@ -0,0 +1,31 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm';
|
||||
import { StateKind } from '@cerc-io/util';
|
||||
import { BlockProgress } from './BlockProgress';
|
||||
|
||||
@Entity()
|
||||
@Index(['cid'], { unique: true })
|
||||
@Index(['block', 'contractAddress'])
|
||||
@Index(['block', 'contractAddress', 'kind'], { unique: true })
|
||||
export class State {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' })
|
||||
block!: BlockProgress;
|
||||
|
||||
@Column('varchar', { length: 42 })
|
||||
contractAddress!: string;
|
||||
|
||||
@Column('varchar')
|
||||
cid!: string;
|
||||
|
||||
@Column({ type: 'enum', enum: StateKind })
|
||||
kind!: StateKind;
|
||||
|
||||
@Column('bytea')
|
||||
data!: Buffer;
|
||||
}
|
||||
17
packages/polls-watcher/src/entity/StateSyncStatus.ts
Normal file
17
packages/polls-watcher/src/entity/StateSyncStatus.ts
Normal file
@ -0,0 +1,17 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||
|
||||
@Entity()
|
||||
export class StateSyncStatus {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('integer')
|
||||
latestIndexedBlockNumber!: number;
|
||||
|
||||
@Column('integer', { nullable: true })
|
||||
latestCheckpointBlockNumber!: number;
|
||||
}
|
||||
36
packages/polls-watcher/src/entity/SyncStatus.ts
Normal file
36
packages/polls-watcher/src/entity/SyncStatus.ts
Normal file
@ -0,0 +1,36 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||
import { SyncStatusInterface } from '@cerc-io/util';
|
||||
|
||||
@Entity()
|
||||
export class SyncStatus implements SyncStatusInterface {
|
||||
@PrimaryGeneratedColumn()
|
||||
id!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
chainHeadBlockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
chainHeadBlockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
latestIndexedBlockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
latestIndexedBlockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
latestCanonicalBlockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
latestCanonicalBlockNumber!: number;
|
||||
|
||||
@Column('varchar', { length: 66 })
|
||||
initialIndexedBlockHash!: string;
|
||||
|
||||
@Column('integer')
|
||||
initialIndexedBlockNumber!: number;
|
||||
}
|
||||
33
packages/polls-watcher/src/fill.ts
Normal file
33
packages/polls-watcher/src/fill.ts
Normal file
@ -0,0 +1,33 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import 'reflect-metadata';
|
||||
import debug from 'debug';
|
||||
|
||||
import { FillCmd } from '@cerc-io/cli';
|
||||
|
||||
import { Database } from './database';
|
||||
import { Indexer } from './indexer';
|
||||
|
||||
const log = debug('vulcanize:fill');
|
||||
|
||||
export const main = async (): Promise<any> => {
|
||||
const fillCmd = new FillCmd();
|
||||
await fillCmd.init(Database);
|
||||
|
||||
await fillCmd.initIndexer(Indexer);
|
||||
|
||||
await fillCmd.exec();
|
||||
};
|
||||
|
||||
main().catch(err => {
|
||||
log(err);
|
||||
}).finally(() => {
|
||||
process.exit();
|
||||
});
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
log(`Exiting process ${process.pid} with code 0`);
|
||||
process.exit(0);
|
||||
});
|
||||
3
packages/polls-watcher/src/gql/index.ts
Normal file
3
packages/polls-watcher/src/gql/index.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export * as mutations from './mutations';
|
||||
export * as queries from './queries';
|
||||
export * as subscriptions from './subscriptions';
|
||||
4
packages/polls-watcher/src/gql/mutations/index.ts
Normal file
4
packages/polls-watcher/src/gql/mutations/index.ts
Normal file
@ -0,0 +1,4 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export const watchContract = fs.readFileSync(path.join(__dirname, 'watchContract.gql'), 'utf8');
|
||||
@ -0,0 +1,3 @@
|
||||
mutation watchContract($address: String!, $kind: String!, $checkpoint: Boolean!, $startingBlock: Int){
|
||||
watchContract(address: $address, kind: $kind, checkpoint: $checkpoint, startingBlock: $startingBlock)
|
||||
}
|
||||
43
packages/polls-watcher/src/gql/queries/events.gql
Normal file
43
packages/polls-watcher/src/gql/queries/events.gql
Normal file
@ -0,0 +1,43 @@
|
||||
query events($blockHash: String!, $contractAddress: String!, $name: String){
|
||||
events(blockHash: $blockHash, contractAddress: $contractAddress, name: $name){
|
||||
block{
|
||||
cid
|
||||
hash
|
||||
number
|
||||
timestamp
|
||||
parentHash
|
||||
}
|
||||
tx{
|
||||
hash
|
||||
index
|
||||
from
|
||||
to
|
||||
}
|
||||
contract
|
||||
eventIndex
|
||||
event{
|
||||
... on UpgradePollStartedEvent {
|
||||
proposal
|
||||
}
|
||||
... on DocumentPollStartedEvent {
|
||||
proposal
|
||||
}
|
||||
... on UpgradeMajorityEvent {
|
||||
proposal
|
||||
}
|
||||
... on DocumentMajorityEvent {
|
||||
proposal
|
||||
}
|
||||
... on OwnershipRenouncedEvent {
|
||||
previousOwner
|
||||
}
|
||||
... on OwnershipTransferredEvent {
|
||||
previousOwner
|
||||
newOwner
|
||||
}
|
||||
}
|
||||
proof{
|
||||
data
|
||||
}
|
||||
}
|
||||
}
|
||||
43
packages/polls-watcher/src/gql/queries/eventsInRange.gql
Normal file
43
packages/polls-watcher/src/gql/queries/eventsInRange.gql
Normal file
@ -0,0 +1,43 @@
|
||||
query eventsInRange($fromBlockNumber: Int!, $toBlockNumber: Int!){
|
||||
eventsInRange(fromBlockNumber: $fromBlockNumber, toBlockNumber: $toBlockNumber){
|
||||
block{
|
||||
cid
|
||||
hash
|
||||
number
|
||||
timestamp
|
||||
parentHash
|
||||
}
|
||||
tx{
|
||||
hash
|
||||
index
|
||||
from
|
||||
to
|
||||
}
|
||||
contract
|
||||
eventIndex
|
||||
event{
|
||||
... on UpgradePollStartedEvent {
|
||||
proposal
|
||||
}
|
||||
... on DocumentPollStartedEvent {
|
||||
proposal
|
||||
}
|
||||
... on UpgradeMajorityEvent {
|
||||
proposal
|
||||
}
|
||||
... on DocumentMajorityEvent {
|
||||
proposal
|
||||
}
|
||||
... on OwnershipRenouncedEvent {
|
||||
previousOwner
|
||||
}
|
||||
... on OwnershipTransferredEvent {
|
||||
previousOwner
|
||||
newOwner
|
||||
}
|
||||
}
|
||||
proof{
|
||||
data
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
query getDocumentProposalCount($blockHash: String!, $contractAddress: String!){
|
||||
getDocumentProposalCount(blockHash: $blockHash, contractAddress: $contractAddress){
|
||||
value
|
||||
proof{
|
||||
data
|
||||
}
|
||||
}
|
||||
}
|
||||
15
packages/polls-watcher/src/gql/queries/getState.gql
Normal file
15
packages/polls-watcher/src/gql/queries/getState.gql
Normal file
@ -0,0 +1,15 @@
|
||||
query getState($blockHash: String!, $contractAddress: String!, $kind: String){
|
||||
getState(blockHash: $blockHash, contractAddress: $contractAddress, kind: $kind){
|
||||
block{
|
||||
cid
|
||||
hash
|
||||
number
|
||||
timestamp
|
||||
parentHash
|
||||
}
|
||||
contractAddress
|
||||
cid
|
||||
kind
|
||||
data
|
||||
}
|
||||
}
|
||||
15
packages/polls-watcher/src/gql/queries/getStateByCID.gql
Normal file
15
packages/polls-watcher/src/gql/queries/getStateByCID.gql
Normal file
@ -0,0 +1,15 @@
|
||||
query getStateByCID($cid: String!){
|
||||
getStateByCID(cid: $cid){
|
||||
block{
|
||||
cid
|
||||
hash
|
||||
number
|
||||
timestamp
|
||||
parentHash
|
||||
}
|
||||
contractAddress
|
||||
cid
|
||||
kind
|
||||
data
|
||||
}
|
||||
}
|
||||
8
packages/polls-watcher/src/gql/queries/getSyncStatus.gql
Normal file
8
packages/polls-watcher/src/gql/queries/getSyncStatus.gql
Normal file
@ -0,0 +1,8 @@
|
||||
query getSyncStatus{
|
||||
getSyncStatus{
|
||||
latestIndexedBlockHash
|
||||
latestIndexedBlockNumber
|
||||
latestCanonicalBlockHash
|
||||
latestCanonicalBlockNumber
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
query getUpgradeProposalCount($blockHash: String!, $contractAddress: String!){
|
||||
getUpgradeProposalCount(blockHash: $blockHash, contractAddress: $contractAddress){
|
||||
value
|
||||
proof{
|
||||
data
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
query hasVotedOnDocumentPoll($blockHash: String!, $contractAddress: String!, $_galaxy: Int!, $_proposal: String!){
|
||||
hasVotedOnDocumentPoll(blockHash: $blockHash, contractAddress: $contractAddress, _galaxy: $_galaxy, _proposal: $_proposal){
|
||||
value
|
||||
proof{
|
||||
data
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
query hasVotedOnUpgradePoll($blockHash: String!, $contractAddress: String!, $_galaxy: Int!, $_proposal: String!){
|
||||
hasVotedOnUpgradePoll(blockHash: $blockHash, contractAddress: $contractAddress, _galaxy: $_galaxy, _proposal: $_proposal){
|
||||
value
|
||||
proof{
|
||||
data
|
||||
}
|
||||
}
|
||||
}
|
||||
12
packages/polls-watcher/src/gql/queries/index.ts
Normal file
12
packages/polls-watcher/src/gql/queries/index.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export const events = fs.readFileSync(path.join(__dirname, 'events.gql'), 'utf8');
|
||||
export const eventsInRange = fs.readFileSync(path.join(__dirname, 'eventsInRange.gql'), 'utf8');
|
||||
export const getUpgradeProposalCount = fs.readFileSync(path.join(__dirname, 'getUpgradeProposalCount.gql'), 'utf8');
|
||||
export const getDocumentProposalCount = fs.readFileSync(path.join(__dirname, 'getDocumentProposalCount.gql'), 'utf8');
|
||||
export const hasVotedOnUpgradePoll = fs.readFileSync(path.join(__dirname, 'hasVotedOnUpgradePoll.gql'), 'utf8');
|
||||
export const hasVotedOnDocumentPoll = fs.readFileSync(path.join(__dirname, 'hasVotedOnDocumentPoll.gql'), 'utf8');
|
||||
export const getSyncStatus = fs.readFileSync(path.join(__dirname, 'getSyncStatus.gql'), 'utf8');
|
||||
export const getStateByCID = fs.readFileSync(path.join(__dirname, 'getStateByCID.gql'), 'utf8');
|
||||
export const getState = fs.readFileSync(path.join(__dirname, 'getState.gql'), 'utf8');
|
||||
4
packages/polls-watcher/src/gql/subscriptions/index.ts
Normal file
4
packages/polls-watcher/src/gql/subscriptions/index.ts
Normal file
@ -0,0 +1,4 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export const onEvent = fs.readFileSync(path.join(__dirname, 'onEvent.gql'), 'utf8');
|
||||
43
packages/polls-watcher/src/gql/subscriptions/onEvent.gql
Normal file
43
packages/polls-watcher/src/gql/subscriptions/onEvent.gql
Normal file
@ -0,0 +1,43 @@
|
||||
subscription onEvent{
|
||||
onEvent{
|
||||
block{
|
||||
cid
|
||||
hash
|
||||
number
|
||||
timestamp
|
||||
parentHash
|
||||
}
|
||||
tx{
|
||||
hash
|
||||
index
|
||||
from
|
||||
to
|
||||
}
|
||||
contract
|
||||
eventIndex
|
||||
event{
|
||||
... on UpgradePollStartedEvent {
|
||||
proposal
|
||||
}
|
||||
... on DocumentPollStartedEvent {
|
||||
proposal
|
||||
}
|
||||
... on UpgradeMajorityEvent {
|
||||
proposal
|
||||
}
|
||||
... on DocumentMajorityEvent {
|
||||
proposal
|
||||
}
|
||||
... on OwnershipRenouncedEvent {
|
||||
previousOwner
|
||||
}
|
||||
... on OwnershipTransferredEvent {
|
||||
previousOwner
|
||||
newOwner
|
||||
}
|
||||
}
|
||||
proof{
|
||||
data
|
||||
}
|
||||
}
|
||||
}
|
||||
80
packages/polls-watcher/src/hooks.ts
Normal file
80
packages/polls-watcher/src/hooks.ts
Normal file
@ -0,0 +1,80 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import assert from 'assert';
|
||||
|
||||
import { updateStateForMappingType, updateStateForElementaryType, ResultEvent } from '@cerc-io/util';
|
||||
|
||||
import { Indexer } from './indexer';
|
||||
|
||||
/**
|
||||
* Hook function to store an initial state.
|
||||
* @param indexer Indexer instance.
|
||||
* @param blockHash Hash of the concerned block.
|
||||
* @param contractAddress Address of the concerned contract.
|
||||
* @returns Data block to be stored.
|
||||
*/
|
||||
export async function createInitialState (indexer: Indexer, contractAddress: string, blockHash: string): Promise<any> {
|
||||
assert(indexer);
|
||||
assert(blockHash);
|
||||
assert(contractAddress);
|
||||
|
||||
// Store an empty State.
|
||||
const stateData: any = {
|
||||
state: {}
|
||||
};
|
||||
|
||||
// Use updateStateForElementaryType to update initial state with an elementary property.
|
||||
// Eg. const stateData = updateStateForElementaryType(stateData, '_totalBalance', result.value.toString());
|
||||
|
||||
// Use updateStateForMappingType to update initial state with a nested property.
|
||||
// Eg. const stateData = updateStateForMappingType(stateData, '_allowances', [owner, spender], allowance.value.toString());
|
||||
|
||||
// Return initial state data to be saved.
|
||||
return stateData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook function to create state diff.
|
||||
* @param indexer Indexer instance that contains methods to fetch the contract variable values.
|
||||
* @param blockHash Block hash of the concerned block.
|
||||
*/
|
||||
export async function createStateDiff (indexer: Indexer, blockHash: string): Promise<void> {
|
||||
assert(indexer);
|
||||
assert(blockHash);
|
||||
|
||||
// Use indexer.createDiff() method to save custom state diff(s).
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook function to create state checkpoint
|
||||
* @param indexer Indexer instance.
|
||||
* @param contractAddress Address of the concerned contract.
|
||||
* @param blockHash Block hash of the concerned block.
|
||||
* @returns Whether to disable default checkpoint. If false, the state from this hook is updated with that from default checkpoint.
|
||||
*/
|
||||
export async function createStateCheckpoint (indexer: Indexer, contractAddress: string, blockHash: string): Promise<boolean> {
|
||||
assert(indexer);
|
||||
assert(blockHash);
|
||||
assert(contractAddress);
|
||||
|
||||
// Use indexer.createStateCheckpoint() method to create a custom checkpoint.
|
||||
|
||||
// Return false to update the state created by this hook by auto-generated checkpoint state.
|
||||
// Return true to disable update of the state created by this hook by auto-generated checkpoint state.
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event hook function.
|
||||
* @param indexer Indexer instance that contains methods to fetch and update the contract values in the database.
|
||||
* @param eventData ResultEvent object containing event information.
|
||||
*/
|
||||
export async function handleEvent (indexer: Indexer, eventData: ResultEvent): Promise<void> {
|
||||
assert(indexer);
|
||||
assert(eventData);
|
||||
|
||||
// Use indexer methods to index data.
|
||||
// Pass `diff` parameter to indexer methods as true to save an auto-generated state from the indexed data.
|
||||
}
|
||||
640
packages/polls-watcher/src/indexer.ts
Normal file
640
packages/polls-watcher/src/indexer.ts
Normal file
@ -0,0 +1,640 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import assert from 'assert';
|
||||
import debug from 'debug';
|
||||
import { DeepPartial, FindConditions, FindManyOptions, ObjectLiteral } from 'typeorm';
|
||||
import JSONbig from 'json-bigint';
|
||||
import { ethers } from 'ethers';
|
||||
|
||||
import { JsonFragment } from '@ethersproject/abi';
|
||||
import { BaseProvider } from '@ethersproject/providers';
|
||||
import { EthClient } from '@cerc-io/ipld-eth-client';
|
||||
import { MappingKey, StorageLayout } from '@cerc-io/solidity-mapper';
|
||||
import {
|
||||
Indexer as BaseIndexer,
|
||||
IndexerInterface,
|
||||
ValueResult,
|
||||
ServerConfig,
|
||||
JobQueue,
|
||||
Where,
|
||||
QueryOptions,
|
||||
updateStateForElementaryType,
|
||||
updateStateForMappingType,
|
||||
StateKind,
|
||||
StateStatus,
|
||||
ResultEvent,
|
||||
getResultEvent,
|
||||
DatabaseInterface,
|
||||
Clients
|
||||
} from '@cerc-io/util';
|
||||
|
||||
import PollsArtifacts from './artifacts/Polls.json';
|
||||
import { Database, ENTITIES } from './database';
|
||||
import { createInitialState, handleEvent, createStateDiff, createStateCheckpoint } from './hooks';
|
||||
import { Contract } from './entity/Contract';
|
||||
import { Event } from './entity/Event';
|
||||
import { SyncStatus } from './entity/SyncStatus';
|
||||
import { StateSyncStatus } from './entity/StateSyncStatus';
|
||||
import { BlockProgress } from './entity/BlockProgress';
|
||||
import { State } from './entity/State';
|
||||
|
||||
const log = debug('vulcanize:indexer');
|
||||
const JSONbigNative = JSONbig({ useNativeBigInt: true });
|
||||
|
||||
const KIND_POLLS = 'Polls';
|
||||
|
||||
export class Indexer implements IndexerInterface {
|
||||
_db: Database;
|
||||
_ethClient: EthClient;
|
||||
_ethProvider: BaseProvider;
|
||||
_baseIndexer: BaseIndexer;
|
||||
_serverConfig: ServerConfig;
|
||||
|
||||
_abiMap: Map<string, JsonFragment[]>;
|
||||
_storageLayoutMap: Map<string, StorageLayout>;
|
||||
_contractMap: Map<string, ethers.utils.Interface>;
|
||||
|
||||
constructor (serverConfig: ServerConfig, db: DatabaseInterface, clients: Clients, ethProvider: BaseProvider, jobQueue: JobQueue) {
|
||||
assert(db);
|
||||
assert(clients.ethClient);
|
||||
|
||||
this._db = db as Database;
|
||||
this._ethClient = clients.ethClient;
|
||||
this._ethProvider = ethProvider;
|
||||
this._serverConfig = serverConfig;
|
||||
this._baseIndexer = new BaseIndexer(this._serverConfig, this._db, this._ethClient, this._ethProvider, jobQueue);
|
||||
|
||||
this._abiMap = new Map();
|
||||
this._storageLayoutMap = new Map();
|
||||
this._contractMap = new Map();
|
||||
|
||||
const { abi: PollsABI } = PollsArtifacts;
|
||||
|
||||
assert(PollsABI);
|
||||
this._abiMap.set(KIND_POLLS, PollsABI);
|
||||
this._contractMap.set(KIND_POLLS, new ethers.utils.Interface(PollsABI));
|
||||
}
|
||||
|
||||
get serverConfig (): ServerConfig {
|
||||
return this._serverConfig;
|
||||
}
|
||||
|
||||
get storageLayoutMap (): Map<string, StorageLayout> {
|
||||
return this._storageLayoutMap;
|
||||
}
|
||||
|
||||
async init (): Promise<void> {
|
||||
await this._baseIndexer.fetchContracts();
|
||||
await this._baseIndexer.fetchStateStatus();
|
||||
}
|
||||
|
||||
getResultEvent (event: Event): ResultEvent {
|
||||
return getResultEvent(event);
|
||||
}
|
||||
|
||||
async getUpgradeProposals (blockHash: string, contractAddress: string): Promise<ValueResult> {
|
||||
const entity = await this._db.getGetUpgradeProposals({ blockHash, contractAddress });
|
||||
if (entity) {
|
||||
log('getUpgradeProposals: db hit.');
|
||||
|
||||
return {
|
||||
value: entity.value,
|
||||
proof: JSON.parse(entity.proof)
|
||||
};
|
||||
}
|
||||
|
||||
log('getUpgradeProposals: db miss, fetching from upstream server');
|
||||
|
||||
const { block: { number } } = await this._ethClient.getBlockByHash(blockHash);
|
||||
const blockNumber = ethers.BigNumber.from(number).toNumber();
|
||||
|
||||
const abi = this._abiMap.get(KIND_POLLS);
|
||||
assert(abi);
|
||||
|
||||
const contract = new ethers.Contract(contractAddress, abi, this._ethProvider);
|
||||
const value = await contract.getUpgradeProposals({ blockTag: blockHash });
|
||||
|
||||
const result: ValueResult = { value };
|
||||
await this._db.saveGetUpgradeProposals({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) });
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getUpgradeProposalCount (blockHash: string, contractAddress: string): Promise<ValueResult> {
|
||||
const entity = await this._db.getGetUpgradeProposalCount({ blockHash, contractAddress });
|
||||
if (entity) {
|
||||
log('getUpgradeProposalCount: db hit.');
|
||||
|
||||
return {
|
||||
value: entity.value,
|
||||
proof: JSON.parse(entity.proof)
|
||||
};
|
||||
}
|
||||
|
||||
log('getUpgradeProposalCount: db miss, fetching from upstream server');
|
||||
|
||||
const { block: { number } } = await this._ethClient.getBlockByHash(blockHash);
|
||||
const blockNumber = ethers.BigNumber.from(number).toNumber();
|
||||
|
||||
const abi = this._abiMap.get(KIND_POLLS);
|
||||
assert(abi);
|
||||
|
||||
const contract = new ethers.Contract(contractAddress, abi, this._ethProvider);
|
||||
let value = await contract.getUpgradeProposalCount({ blockTag: blockHash });
|
||||
value = value.toString();
|
||||
value = BigInt(value);
|
||||
|
||||
const result: ValueResult = { value };
|
||||
|
||||
await this._db.saveGetUpgradeProposalCount({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) });
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getDocumentProposalCount (blockHash: string, contractAddress: string): Promise<ValueResult> {
|
||||
const entity = await this._db.getGetDocumentProposalCount({ blockHash, contractAddress });
|
||||
if (entity) {
|
||||
log('getDocumentProposalCount: db hit.');
|
||||
|
||||
return {
|
||||
value: entity.value,
|
||||
proof: JSON.parse(entity.proof)
|
||||
};
|
||||
}
|
||||
|
||||
log('getDocumentProposalCount: db miss, fetching from upstream server');
|
||||
|
||||
const { block: { number } } = await this._ethClient.getBlockByHash(blockHash);
|
||||
const blockNumber = ethers.BigNumber.from(number).toNumber();
|
||||
|
||||
const abi = this._abiMap.get(KIND_POLLS);
|
||||
assert(abi);
|
||||
|
||||
const contract = new ethers.Contract(contractAddress, abi, this._ethProvider);
|
||||
let value = await contract.getDocumentProposalCount({ blockTag: blockHash });
|
||||
value = value.toString();
|
||||
value = BigInt(value);
|
||||
|
||||
const result: ValueResult = { value };
|
||||
|
||||
await this._db.saveGetDocumentProposalCount({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) });
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getDocumentMajorities (blockHash: string, contractAddress: string): Promise<ValueResult> {
|
||||
const entity = await this._db.getGetDocumentMajorities({ blockHash, contractAddress });
|
||||
if (entity) {
|
||||
log('getDocumentMajorities: db hit.');
|
||||
|
||||
return {
|
||||
value: entity.value,
|
||||
proof: JSON.parse(entity.proof)
|
||||
};
|
||||
}
|
||||
|
||||
log('getDocumentMajorities: db miss, fetching from upstream server');
|
||||
|
||||
const { block: { number } } = await this._ethClient.getBlockByHash(blockHash);
|
||||
const blockNumber = ethers.BigNumber.from(number).toNumber();
|
||||
|
||||
const abi = this._abiMap.get(KIND_POLLS);
|
||||
assert(abi);
|
||||
|
||||
const contract = new ethers.Contract(contractAddress, abi, this._ethProvider);
|
||||
const value = await contract.getDocumentMajorities({ blockTag: blockHash });
|
||||
|
||||
const result: ValueResult = { value };
|
||||
|
||||
await this._db.saveGetDocumentMajorities({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) });
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getDocumentProposals (blockHash: string, contractAddress: string): Promise<ValueResult> {
|
||||
const entity = await this._db.getGetDocumentProposals({ blockHash, contractAddress });
|
||||
if (entity) {
|
||||
log('getDocumentProposals: db hit.');
|
||||
|
||||
return {
|
||||
value: entity.value,
|
||||
proof: JSON.parse(entity.proof)
|
||||
};
|
||||
}
|
||||
|
||||
log('getDocumentProposals: db miss, fetching from upstream server');
|
||||
|
||||
const { block: { number } } = await this._ethClient.getBlockByHash(blockHash);
|
||||
const blockNumber = ethers.BigNumber.from(number).toNumber();
|
||||
|
||||
const abi = this._abiMap.get(KIND_POLLS);
|
||||
assert(abi);
|
||||
|
||||
const contract = new ethers.Contract(contractAddress, abi, this._ethProvider);
|
||||
const value = await contract.getDocumentProposals({ blockTag: blockHash });
|
||||
|
||||
const result: ValueResult = { value };
|
||||
|
||||
await this._db.saveGetDocumentProposals({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) });
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async hasVotedOnUpgradePoll (blockHash: string, contractAddress: string, _galaxy: number, _proposal: string): Promise<ValueResult> {
|
||||
const entity = await this._db.getHasVotedOnUpgradePoll({ blockHash, contractAddress, _galaxy, _proposal });
|
||||
if (entity) {
|
||||
log('hasVotedOnUpgradePoll: db hit.');
|
||||
|
||||
return {
|
||||
value: entity.value,
|
||||
proof: JSON.parse(entity.proof)
|
||||
};
|
||||
}
|
||||
|
||||
log('hasVotedOnUpgradePoll: db miss, fetching from upstream server');
|
||||
|
||||
const { block: { number } } = await this._ethClient.getBlockByHash(blockHash);
|
||||
const blockNumber = ethers.BigNumber.from(number).toNumber();
|
||||
|
||||
const abi = this._abiMap.get(KIND_POLLS);
|
||||
assert(abi);
|
||||
|
||||
const contract = new ethers.Contract(contractAddress, abi, this._ethProvider);
|
||||
const value = await contract.hasVotedOnUpgradePoll(_galaxy, _proposal, { blockTag: blockHash });
|
||||
|
||||
const result: ValueResult = { value };
|
||||
|
||||
await this._db.saveHasVotedOnUpgradePoll({ blockHash, blockNumber, contractAddress, _galaxy, _proposal, value: result.value, proof: JSONbigNative.stringify(result.proof) });
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async hasVotedOnDocumentPoll (blockHash: string, contractAddress: string, _galaxy: number, _proposal: string): Promise<ValueResult> {
|
||||
const entity = await this._db.getHasVotedOnDocumentPoll({ blockHash, contractAddress, _galaxy, _proposal });
|
||||
if (entity) {
|
||||
log('hasVotedOnDocumentPoll: db hit.');
|
||||
|
||||
return {
|
||||
value: entity.value,
|
||||
proof: JSON.parse(entity.proof)
|
||||
};
|
||||
}
|
||||
|
||||
log('hasVotedOnDocumentPoll: db miss, fetching from upstream server');
|
||||
|
||||
const { block: { number } } = await this._ethClient.getBlockByHash(blockHash);
|
||||
const blockNumber = ethers.BigNumber.from(number).toNumber();
|
||||
|
||||
const abi = this._abiMap.get(KIND_POLLS);
|
||||
assert(abi);
|
||||
|
||||
const contract = new ethers.Contract(contractAddress, abi, this._ethProvider);
|
||||
const value = await contract.hasVotedOnDocumentPoll(_galaxy, _proposal, { blockTag: blockHash });
|
||||
|
||||
const result: ValueResult = { value };
|
||||
|
||||
await this._db.saveHasVotedOnDocumentPoll({ blockHash, blockNumber, contractAddress, _galaxy, _proposal, value: result.value, proof: JSONbigNative.stringify(result.proof) });
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getStorageValue (storageLayout: StorageLayout, blockHash: string, contractAddress: string, variable: string, ...mappingKeys: MappingKey[]): Promise<ValueResult> {
|
||||
return this._baseIndexer.getStorageValue(
|
||||
storageLayout,
|
||||
blockHash,
|
||||
contractAddress,
|
||||
variable,
|
||||
...mappingKeys
|
||||
);
|
||||
}
|
||||
|
||||
async getEntitiesForBlock (blockHash: string, tableName: string): Promise<any[]> {
|
||||
return this._db.getEntitiesForBlock(blockHash, tableName);
|
||||
}
|
||||
|
||||
async processInitialState (contractAddress: string, blockHash: string): Promise<any> {
|
||||
// Call initial state hook.
|
||||
return createInitialState(this, contractAddress, blockHash);
|
||||
}
|
||||
|
||||
async processStateCheckpoint (contractAddress: string, blockHash: string): Promise<boolean> {
|
||||
// Call checkpoint hook.
|
||||
return createStateCheckpoint(this, contractAddress, blockHash);
|
||||
}
|
||||
|
||||
async processCanonicalBlock (blockHash: string, blockNumber: number): Promise<void> {
|
||||
console.time('time:indexer#processCanonicalBlock-finalize_auto_diffs');
|
||||
// Finalize staged diff blocks if any.
|
||||
await this._baseIndexer.finalizeDiffStaged(blockHash);
|
||||
console.timeEnd('time:indexer#processCanonicalBlock-finalize_auto_diffs');
|
||||
|
||||
// Call custom stateDiff hook.
|
||||
await createStateDiff(this, blockHash);
|
||||
}
|
||||
|
||||
async processCheckpoint (blockHash: string): Promise<void> {
|
||||
// Return if checkpointInterval is <= 0.
|
||||
const checkpointInterval = this._serverConfig.checkpointInterval;
|
||||
if (checkpointInterval <= 0) return;
|
||||
|
||||
console.time('time:indexer#processCheckpoint-checkpoint');
|
||||
await this._baseIndexer.processCheckpoint(this, blockHash, checkpointInterval);
|
||||
console.timeEnd('time:indexer#processCheckpoint-checkpoint');
|
||||
}
|
||||
|
||||
async processCLICheckpoint (contractAddress: string, blockHash?: string): Promise<string | undefined> {
|
||||
return this._baseIndexer.processCLICheckpoint(this, contractAddress, blockHash);
|
||||
}
|
||||
|
||||
async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise<State | undefined> {
|
||||
return this._db.getPrevState(blockHash, contractAddress, kind);
|
||||
}
|
||||
|
||||
async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise<State | undefined> {
|
||||
return this._db.getLatestState(contractAddress, kind, blockNumber);
|
||||
}
|
||||
|
||||
async getStatesByHash (blockHash: string): Promise<State[]> {
|
||||
return this._baseIndexer.getStatesByHash(blockHash);
|
||||
}
|
||||
|
||||
async getStateByCID (cid: string): Promise<State | undefined> {
|
||||
return this._baseIndexer.getStateByCID(cid);
|
||||
}
|
||||
|
||||
async getStates (where: FindConditions<State>): Promise<State[]> {
|
||||
return this._db.getStates(where);
|
||||
}
|
||||
|
||||
getStateData (state: State): any {
|
||||
return this._baseIndexer.getStateData(state);
|
||||
}
|
||||
|
||||
// Method used to create auto diffs (diff_staged).
|
||||
async createDiffStaged (contractAddress: string, blockHash: string, data: any): Promise<void> {
|
||||
console.time('time:indexer#createDiffStaged-auto_diff');
|
||||
await this._baseIndexer.createDiffStaged(contractAddress, blockHash, data);
|
||||
console.timeEnd('time:indexer#createDiffStaged-auto_diff');
|
||||
}
|
||||
|
||||
// Method to be used by createStateDiff hook.
|
||||
async createDiff (contractAddress: string, blockHash: string, data: any): Promise<void> {
|
||||
const block = await this.getBlockProgress(blockHash);
|
||||
assert(block);
|
||||
|
||||
await this._baseIndexer.createDiff(contractAddress, block, data);
|
||||
}
|
||||
|
||||
// Method to be used by createStateCheckpoint hook.
|
||||
async createStateCheckpoint (contractAddress: string, blockHash: string, data: any): Promise<void> {
|
||||
const block = await this.getBlockProgress(blockHash);
|
||||
assert(block);
|
||||
|
||||
return this._baseIndexer.createStateCheckpoint(contractAddress, block, data);
|
||||
}
|
||||
|
||||
// Method to be used by export-state CLI.
|
||||
async createCheckpoint (contractAddress: string, blockHash: string): Promise<string | undefined> {
|
||||
const block = await this.getBlockProgress(blockHash);
|
||||
assert(block);
|
||||
|
||||
return this._baseIndexer.createCheckpoint(this, contractAddress, block);
|
||||
}
|
||||
|
||||
async saveOrUpdateState (state: State): Promise<State> {
|
||||
return this._baseIndexer.saveOrUpdateState(state);
|
||||
}
|
||||
|
||||
async removeStates (blockNumber: number, kind: StateKind): Promise<void> {
|
||||
await this._baseIndexer.removeStates(blockNumber, kind);
|
||||
}
|
||||
|
||||
async triggerIndexingOnEvent (event: Event): Promise<void> {
|
||||
const resultEvent = this.getResultEvent(event);
|
||||
|
||||
// Call custom hook function for indexing on event.
|
||||
await handleEvent(this, resultEvent);
|
||||
}
|
||||
|
||||
async processEvent (event: Event): Promise<void> {
|
||||
// Trigger indexing of data based on the event.
|
||||
await this.triggerIndexingOnEvent(event);
|
||||
}
|
||||
|
||||
async processBlock (blockProgress: BlockProgress): Promise<void> {
|
||||
console.time('time:indexer#processBlock-init_state');
|
||||
// Call a function to create initial state for contracts.
|
||||
await this._baseIndexer.createInit(this, blockProgress.blockHash, blockProgress.blockNumber);
|
||||
console.timeEnd('time:indexer#processBlock-init_state');
|
||||
}
|
||||
|
||||
parseEventNameAndArgs (kind: string, logObj: any): any {
|
||||
const { topics, data } = logObj;
|
||||
|
||||
const contract = this._contractMap.get(kind);
|
||||
assert(contract);
|
||||
|
||||
const logDescription = contract.parseLog({ data, topics });
|
||||
|
||||
const { eventName, eventInfo, eventSignature } = this._baseIndexer.parseEvent(logDescription);
|
||||
|
||||
return {
|
||||
eventName,
|
||||
eventInfo,
|
||||
eventSignature
|
||||
};
|
||||
}
|
||||
|
||||
async getStateSyncStatus (): Promise<StateSyncStatus | undefined> {
|
||||
return this._db.getStateSyncStatus();
|
||||
}
|
||||
|
||||
async updateStateSyncStatusIndexedBlock (blockNumber: number, force?: boolean): Promise<StateSyncStatus> {
|
||||
const dbTx = await this._db.createTransactionRunner();
|
||||
let res;
|
||||
|
||||
try {
|
||||
res = await this._db.updateStateSyncStatusIndexedBlock(dbTx, blockNumber, force);
|
||||
await dbTx.commitTransaction();
|
||||
} catch (error) {
|
||||
await dbTx.rollbackTransaction();
|
||||
throw error;
|
||||
} finally {
|
||||
await dbTx.release();
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
async updateStateSyncStatusCheckpointBlock (blockNumber: number, force?: boolean): Promise<StateSyncStatus> {
|
||||
const dbTx = await this._db.createTransactionRunner();
|
||||
let res;
|
||||
|
||||
try {
|
||||
res = await this._db.updateStateSyncStatusCheckpointBlock(dbTx, blockNumber, force);
|
||||
await dbTx.commitTransaction();
|
||||
} catch (error) {
|
||||
await dbTx.rollbackTransaction();
|
||||
throw error;
|
||||
} finally {
|
||||
await dbTx.release();
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
async getLatestCanonicalBlock (): Promise<BlockProgress> {
|
||||
const syncStatus = await this.getSyncStatus();
|
||||
assert(syncStatus);
|
||||
|
||||
const latestCanonicalBlock = await this.getBlockProgress(syncStatus.latestCanonicalBlockHash);
|
||||
assert(latestCanonicalBlock);
|
||||
|
||||
return latestCanonicalBlock;
|
||||
}
|
||||
|
||||
async getLatestStateIndexedBlock (): Promise<BlockProgress> {
|
||||
return this._baseIndexer.getLatestStateIndexedBlock();
|
||||
}
|
||||
|
||||
async watchContract (address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise<void> {
|
||||
return this._baseIndexer.watchContract(address, kind, checkpoint, startingBlock);
|
||||
}
|
||||
|
||||
updateStateStatusMap (address: string, stateStatus: StateStatus): void {
|
||||
this._baseIndexer.updateStateStatusMap(address, stateStatus);
|
||||
}
|
||||
|
||||
cacheContract (contract: Contract): void {
|
||||
return this._baseIndexer.cacheContract(contract);
|
||||
}
|
||||
|
||||
async saveEventEntity (dbEvent: Event): Promise<Event> {
|
||||
return this._baseIndexer.saveEventEntity(dbEvent);
|
||||
}
|
||||
|
||||
async getEventsByFilter (blockHash: string, contract?: string, name?: string): Promise<Array<Event>> {
|
||||
return this._baseIndexer.getEventsByFilter(blockHash, contract, name);
|
||||
}
|
||||
|
||||
isWatchedContract (address : string): Contract | undefined {
|
||||
return this._baseIndexer.isWatchedContract(address);
|
||||
}
|
||||
|
||||
getContractsByKind (kind: string): Contract[] {
|
||||
return this._baseIndexer.getContractsByKind(kind);
|
||||
}
|
||||
|
||||
async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> {
|
||||
return this._baseIndexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber);
|
||||
}
|
||||
|
||||
async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise<Array<Event>> {
|
||||
return this._baseIndexer.getEventsInRange(fromBlockNumber, toBlockNumber, this._serverConfig.maxEventsBlockRange);
|
||||
}
|
||||
|
||||
async getSyncStatus (): Promise<SyncStatus | undefined> {
|
||||
return this._baseIndexer.getSyncStatus();
|
||||
}
|
||||
|
||||
async getBlocks (blockFilter: { blockHash?: string, blockNumber?: number }): Promise<any> {
|
||||
return this._baseIndexer.getBlocks(blockFilter);
|
||||
}
|
||||
|
||||
async updateSyncStatusIndexedBlock (blockHash: string, blockNumber: number, force = false): Promise<SyncStatus> {
|
||||
return this._baseIndexer.updateSyncStatusIndexedBlock(blockHash, blockNumber, force);
|
||||
}
|
||||
|
||||
async updateSyncStatusChainHead (blockHash: string, blockNumber: number, force = false): Promise<SyncStatus> {
|
||||
return this._baseIndexer.updateSyncStatusChainHead(blockHash, blockNumber, force);
|
||||
}
|
||||
|
||||
async updateSyncStatusCanonicalBlock (blockHash: string, blockNumber: number, force = false): Promise<SyncStatus> {
|
||||
const syncStatus = this._baseIndexer.updateSyncStatusCanonicalBlock(blockHash, blockNumber, force);
|
||||
|
||||
return syncStatus;
|
||||
}
|
||||
|
||||
async getEvent (id: string): Promise<Event | undefined> {
|
||||
return this._baseIndexer.getEvent(id);
|
||||
}
|
||||
|
||||
async getBlockProgress (blockHash: string): Promise<BlockProgress | undefined> {
|
||||
return this._baseIndexer.getBlockProgress(blockHash);
|
||||
}
|
||||
|
||||
async getBlockProgressEntities (where: FindConditions<BlockProgress>, options: FindManyOptions<BlockProgress>): Promise<BlockProgress[]> {
|
||||
return this._baseIndexer.getBlockProgressEntities(where, options);
|
||||
}
|
||||
|
||||
async getBlocksAtHeight (height: number, isPruned: boolean): Promise<BlockProgress[]> {
|
||||
return this._baseIndexer.getBlocksAtHeight(height, isPruned);
|
||||
}
|
||||
|
||||
async saveBlockAndFetchEvents (block: DeepPartial<BlockProgress>): Promise<[BlockProgress, DeepPartial<Event>[]]> {
|
||||
return this._saveBlockAndFetchEvents(block);
|
||||
}
|
||||
|
||||
async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise<Array<Event>> {
|
||||
return this._baseIndexer.getBlockEvents(blockHash, where, queryOptions);
|
||||
}
|
||||
|
||||
async removeUnknownEvents (block: BlockProgress): Promise<void> {
|
||||
return this._baseIndexer.removeUnknownEvents(Event, block);
|
||||
}
|
||||
|
||||
async markBlocksAsPruned (blocks: BlockProgress[]): Promise<void> {
|
||||
await this._baseIndexer.markBlocksAsPruned(blocks);
|
||||
}
|
||||
|
||||
async updateBlockProgress (block: BlockProgress, lastProcessedEventIndex: number): Promise<BlockProgress> {
|
||||
return this._baseIndexer.updateBlockProgress(block, lastProcessedEventIndex);
|
||||
}
|
||||
|
||||
async getAncestorAtDepth (blockHash: string, depth: number): Promise<string> {
|
||||
return this._baseIndexer.getAncestorAtDepth(blockHash, depth);
|
||||
}
|
||||
|
||||
async resetWatcherToBlock (blockNumber: number): Promise<void> {
|
||||
const entities = [...ENTITIES];
|
||||
await this._baseIndexer.resetWatcherToBlock(blockNumber, entities);
|
||||
}
|
||||
|
||||
async _saveBlockAndFetchEvents ({
|
||||
cid: blockCid,
|
||||
blockHash,
|
||||
blockNumber,
|
||||
blockTimestamp,
|
||||
parentHash
|
||||
}: DeepPartial<BlockProgress>): Promise<[BlockProgress, DeepPartial<Event>[]]> {
|
||||
assert(blockHash);
|
||||
assert(blockNumber);
|
||||
|
||||
const dbEvents = await this._baseIndexer.fetchEvents(blockHash, blockNumber, this.parseEventNameAndArgs.bind(this));
|
||||
|
||||
const dbTx = await this._db.createTransactionRunner();
|
||||
try {
|
||||
const block = {
|
||||
cid: blockCid,
|
||||
blockHash,
|
||||
blockNumber,
|
||||
blockTimestamp,
|
||||
parentHash
|
||||
};
|
||||
|
||||
console.time(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`);
|
||||
const blockProgress = await this._db.saveBlockWithEvents(dbTx, block, dbEvents);
|
||||
await dbTx.commitTransaction();
|
||||
console.timeEnd(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`);
|
||||
|
||||
return [blockProgress, []];
|
||||
} catch (error) {
|
||||
await dbTx.rollbackTransaction();
|
||||
throw error;
|
||||
} finally {
|
||||
await dbTx.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
37
packages/polls-watcher/src/job-runner.ts
Normal file
37
packages/polls-watcher/src/job-runner.ts
Normal file
@ -0,0 +1,37 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import debug from 'debug';
|
||||
|
||||
import { JobRunnerCmd } from '@cerc-io/cli';
|
||||
import { JobRunner } from '@cerc-io/util';
|
||||
|
||||
import { Indexer } from './indexer';
|
||||
import { Database } from './database';
|
||||
|
||||
const log = debug('vulcanize:job-runner');
|
||||
|
||||
export const main = async (): Promise<any> => {
|
||||
const jobRunnerCmd = new JobRunnerCmd();
|
||||
await jobRunnerCmd.init(Database);
|
||||
|
||||
await jobRunnerCmd.initIndexer(Indexer);
|
||||
|
||||
await jobRunnerCmd.exec(async (jobRunner: JobRunner): Promise<void> => {
|
||||
await jobRunner.subscribeBlockProcessingQueue();
|
||||
await jobRunner.subscribeEventProcessingQueue();
|
||||
await jobRunner.subscribeBlockCheckpointQueue();
|
||||
await jobRunner.subscribeHooksQueue();
|
||||
});
|
||||
};
|
||||
|
||||
main().then(() => {
|
||||
log('Starting job runner...');
|
||||
}).catch(err => {
|
||||
log(err);
|
||||
});
|
||||
|
||||
process.on('uncaughtException', err => {
|
||||
log('uncaughtException', err);
|
||||
});
|
||||
241
packages/polls-watcher/src/resolvers.ts
Normal file
241
packages/polls-watcher/src/resolvers.ts
Normal file
@ -0,0 +1,241 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import assert from 'assert';
|
||||
import BigInt from 'apollo-type-bigint';
|
||||
import debug from 'debug';
|
||||
import Decimal from 'decimal.js';
|
||||
import { GraphQLResolveInfo, GraphQLScalarType } from 'graphql';
|
||||
|
||||
import {
|
||||
ValueResult,
|
||||
BlockHeight,
|
||||
gqlTotalQueryCount,
|
||||
gqlQueryCount,
|
||||
jsonBigIntStringReplacer,
|
||||
getResultState,
|
||||
setGQLCacheHints,
|
||||
IndexerInterface,
|
||||
EventWatcher
|
||||
} from '@cerc-io/util';
|
||||
|
||||
import { Indexer } from './indexer';
|
||||
|
||||
const log = debug('vulcanize:resolver');
|
||||
|
||||
export const createResolvers = async (indexerArg: IndexerInterface, eventWatcher: EventWatcher): Promise<any> => {
|
||||
const indexer = indexerArg as Indexer;
|
||||
|
||||
const gqlCacheConfig = indexer.serverConfig.gqlCache;
|
||||
|
||||
return {
|
||||
BigInt: new BigInt('bigInt'),
|
||||
|
||||
BigDecimal: new GraphQLScalarType({
|
||||
name: 'BigDecimal',
|
||||
description: 'BigDecimal custom scalar type',
|
||||
parseValue (value) {
|
||||
// value from the client
|
||||
return new Decimal(value);
|
||||
},
|
||||
serialize (value: Decimal) {
|
||||
// value sent to the client
|
||||
return value.toFixed();
|
||||
}
|
||||
}),
|
||||
|
||||
Event: {
|
||||
__resolveType: (obj: any) => {
|
||||
assert(obj.__typename);
|
||||
|
||||
return obj.__typename;
|
||||
}
|
||||
},
|
||||
|
||||
Subscription: {
|
||||
onEvent: {
|
||||
subscribe: () => eventWatcher.getEventIterator()
|
||||
}
|
||||
},
|
||||
|
||||
Mutation: {
|
||||
watchContract: async (_: any, { address, kind, checkpoint, startingBlock = 1 }: { address: string, kind: string, checkpoint: boolean, startingBlock: number }): Promise<boolean> => {
|
||||
log('watchContract', address, kind, checkpoint, startingBlock);
|
||||
await indexer.watchContract(address, kind, checkpoint, startingBlock);
|
||||
|
||||
return true;
|
||||
}
|
||||
},
|
||||
|
||||
Query: {
|
||||
getUpgradeProposals: (
|
||||
_: any,
|
||||
{ blockHash, contractAddress }: { blockHash: string, contractAddress: string },
|
||||
__: any,
|
||||
info: GraphQLResolveInfo
|
||||
): Promise<ValueResult> => {
|
||||
log('getUpgradeProposals', blockHash, contractAddress);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('getUpgradeProposals').inc(1);
|
||||
|
||||
// Set cache-control hints
|
||||
// setGQLCacheHints(info, {}, gqlCacheConfig);
|
||||
|
||||
return indexer.getUpgradeProposals(blockHash, contractAddress);
|
||||
},
|
||||
|
||||
getUpgradeProposalCount: (
|
||||
_: any,
|
||||
{ blockHash, contractAddress }: { blockHash: string, contractAddress: string },
|
||||
__: any,
|
||||
info: GraphQLResolveInfo
|
||||
): Promise<ValueResult> => {
|
||||
log('getUpgradeProposalCount', blockHash, contractAddress);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('getUpgradeProposalCount').inc(1);
|
||||
|
||||
// Set cache-control hints
|
||||
// setGQLCacheHints(info, {}, gqlCacheConfig);
|
||||
|
||||
return indexer.getUpgradeProposalCount(blockHash, contractAddress);
|
||||
},
|
||||
|
||||
getDocumentProposalCount: (
|
||||
_: any,
|
||||
{ blockHash, contractAddress }: { blockHash: string, contractAddress: string },
|
||||
__: any,
|
||||
info: GraphQLResolveInfo
|
||||
): Promise<ValueResult> => {
|
||||
log('getDocumentProposalCount', blockHash, contractAddress);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('getDocumentProposalCount').inc(1);
|
||||
|
||||
// Set cache-control hints
|
||||
// setGQLCacheHints(info, {}, gqlCacheConfig);
|
||||
|
||||
return indexer.getDocumentProposalCount(blockHash, contractAddress);
|
||||
},
|
||||
|
||||
getDocumentProposals: (
|
||||
_: any,
|
||||
{ blockHash, contractAddress }: { blockHash: string, contractAddress: string },
|
||||
__: any,
|
||||
info: GraphQLResolveInfo
|
||||
): Promise<ValueResult> => {
|
||||
log('getDocumentProposals', blockHash, contractAddress);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('getDocumentProposals').inc(1);
|
||||
|
||||
// Set cache-control hints
|
||||
// setGQLCacheHints(info, {}, gqlCacheConfig);
|
||||
|
||||
return indexer.getDocumentProposals(blockHash, contractAddress);
|
||||
},
|
||||
|
||||
getDocumentMajorities: (
|
||||
_: any,
|
||||
{ blockHash, contractAddress }: { blockHash: string, contractAddress: string },
|
||||
__: any,
|
||||
info: GraphQLResolveInfo
|
||||
): Promise<ValueResult> => {
|
||||
log('getDocumentMajorities', blockHash, contractAddress);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('getDocumentMajorities').inc(1);
|
||||
|
||||
// Set cache-control hints
|
||||
// setGQLCacheHints(info, {}, gqlCacheConfig);
|
||||
|
||||
return indexer.getDocumentMajorities(blockHash, contractAddress);
|
||||
},
|
||||
|
||||
hasVotedOnUpgradePoll: (
|
||||
_: any,
|
||||
{ blockHash, contractAddress, _galaxy, _proposal }: { blockHash: string, contractAddress: string, _galaxy: number, _proposal: string },
|
||||
__: any,
|
||||
info: GraphQLResolveInfo
|
||||
): Promise<ValueResult> => {
|
||||
log('hasVotedOnUpgradePoll', blockHash, contractAddress, _galaxy, _proposal);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('hasVotedOnUpgradePoll').inc(1);
|
||||
|
||||
// Set cache-control hints
|
||||
// setGQLCacheHints(info, {}, gqlCacheConfig);
|
||||
|
||||
return indexer.hasVotedOnUpgradePoll(blockHash, contractAddress, _galaxy, _proposal);
|
||||
},
|
||||
|
||||
hasVotedOnDocumentPoll: (
|
||||
_: any,
|
||||
{ blockHash, contractAddress, _galaxy, _proposal }: { blockHash: string, contractAddress: string, _galaxy: number, _proposal: string },
|
||||
__: any,
|
||||
info: GraphQLResolveInfo
|
||||
): Promise<ValueResult> => {
|
||||
log('hasVotedOnDocumentPoll', blockHash, contractAddress, _galaxy, _proposal);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('hasVotedOnDocumentPoll').inc(1);
|
||||
|
||||
// Set cache-control hints
|
||||
// setGQLCacheHints(info, {}, gqlCacheConfig);
|
||||
|
||||
return indexer.hasVotedOnDocumentPoll(blockHash, contractAddress, _galaxy, _proposal);
|
||||
},
|
||||
|
||||
events: async (_: any, { blockHash, contractAddress, name }: { blockHash: string, contractAddress: string, name?: string }) => {
|
||||
log('events', blockHash, contractAddress, name);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('events').inc(1);
|
||||
|
||||
const block = await indexer.getBlockProgress(blockHash);
|
||||
if (!block || !block.isComplete) {
|
||||
throw new Error(`Block hash ${blockHash} number ${block?.blockNumber} not processed yet`);
|
||||
}
|
||||
|
||||
const events = await indexer.getEventsByFilter(blockHash, contractAddress, name);
|
||||
return events.map(event => indexer.getResultEvent(event));
|
||||
},
|
||||
|
||||
eventsInRange: async (_: any, { fromBlockNumber, toBlockNumber }: { fromBlockNumber: number, toBlockNumber: number }) => {
|
||||
log('eventsInRange', fromBlockNumber, toBlockNumber);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('eventsInRange').inc(1);
|
||||
|
||||
const { expected, actual } = await indexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber);
|
||||
if (expected !== actual) {
|
||||
throw new Error(`Range not available, expected ${expected}, got ${actual} blocks in range`);
|
||||
}
|
||||
|
||||
const events = await indexer.getEventsInRange(fromBlockNumber, toBlockNumber);
|
||||
return events.map(event => indexer.getResultEvent(event));
|
||||
},
|
||||
|
||||
getStateByCID: async (_: any, { cid }: { cid: string }) => {
|
||||
log('getStateByCID', cid);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('getStateByCID').inc(1);
|
||||
|
||||
const state = await indexer.getStateByCID(cid);
|
||||
|
||||
return state && state.block.isComplete ? getResultState(state) : undefined;
|
||||
},
|
||||
|
||||
getState: async (_: any, { blockHash, contractAddress, kind }: { blockHash: string, contractAddress: string, kind: string }) => {
|
||||
log('getState', blockHash, contractAddress, kind);
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('getState').inc(1);
|
||||
|
||||
const state = await indexer.getPrevState(blockHash, contractAddress, kind);
|
||||
|
||||
return state && state.block.isComplete ? getResultState(state) : undefined;
|
||||
},
|
||||
|
||||
getSyncStatus: async () => {
|
||||
log('getSyncStatus');
|
||||
gqlTotalQueryCount.inc(1);
|
||||
gqlQueryCount.labels('getSyncStatus').inc(1);
|
||||
|
||||
return indexer.getSyncStatus();
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
130
packages/polls-watcher/src/schema.gql
Normal file
130
packages/polls-watcher/src/schema.gql
Normal file
@ -0,0 +1,130 @@
|
||||
directive @cacheControl(maxAge: Int, inheritMaxAge: Boolean, scope: CacheControlScope) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION
|
||||
|
||||
enum CacheControlScope {
|
||||
PUBLIC
|
||||
PRIVATE
|
||||
}
|
||||
|
||||
scalar BigInt
|
||||
|
||||
scalar BigDecimal
|
||||
|
||||
scalar Bytes
|
||||
|
||||
type Proof {
|
||||
data: String!
|
||||
}
|
||||
|
||||
type ResultBoolean {
|
||||
value: Boolean!
|
||||
proof: Proof
|
||||
}
|
||||
|
||||
type ResultString {
|
||||
value: String!
|
||||
proof: Proof
|
||||
}
|
||||
|
||||
type ResultStringArray {
|
||||
value: [String!]
|
||||
proof: Proof
|
||||
}
|
||||
|
||||
type ResultInt {
|
||||
value: Int!
|
||||
proof: Proof
|
||||
}
|
||||
|
||||
type ResultBigInt {
|
||||
value: BigInt!
|
||||
proof: Proof
|
||||
}
|
||||
|
||||
type _Block_ {
|
||||
cid: String!
|
||||
hash: String!
|
||||
number: Int!
|
||||
timestamp: Int!
|
||||
parentHash: String!
|
||||
}
|
||||
|
||||
type _Transaction_ {
|
||||
hash: String!
|
||||
index: Int!
|
||||
from: String!
|
||||
to: String!
|
||||
}
|
||||
|
||||
type ResultEvent {
|
||||
block: _Block_!
|
||||
tx: _Transaction_!
|
||||
contract: String!
|
||||
eventIndex: Int!
|
||||
event: Event!
|
||||
proof: Proof
|
||||
}
|
||||
|
||||
union Event = UpgradePollStartedEvent | DocumentPollStartedEvent | UpgradeMajorityEvent | DocumentMajorityEvent | OwnershipRenouncedEvent | OwnershipTransferredEvent
|
||||
|
||||
type UpgradePollStartedEvent {
|
||||
proposal: String!
|
||||
}
|
||||
|
||||
type DocumentPollStartedEvent {
|
||||
proposal: String!
|
||||
}
|
||||
|
||||
type UpgradeMajorityEvent {
|
||||
proposal: String!
|
||||
}
|
||||
|
||||
type DocumentMajorityEvent {
|
||||
proposal: String!
|
||||
}
|
||||
|
||||
type OwnershipRenouncedEvent {
|
||||
previousOwner: String!
|
||||
}
|
||||
|
||||
type OwnershipTransferredEvent {
|
||||
previousOwner: String!
|
||||
newOwner: String!
|
||||
}
|
||||
|
||||
type SyncStatus {
|
||||
latestIndexedBlockHash: String!
|
||||
latestIndexedBlockNumber: Int!
|
||||
latestCanonicalBlockHash: String!
|
||||
latestCanonicalBlockNumber: Int!
|
||||
}
|
||||
|
||||
type ResultState {
|
||||
block: _Block_!
|
||||
contractAddress: String!
|
||||
cid: String!
|
||||
kind: String!
|
||||
data: String!
|
||||
}
|
||||
|
||||
type Query {
|
||||
events(blockHash: String!, contractAddress: String!, name: String): [ResultEvent!]
|
||||
eventsInRange(fromBlockNumber: Int!, toBlockNumber: Int!): [ResultEvent!]
|
||||
getUpgradeProposalCount(blockHash: String!, contractAddress: String!): ResultBigInt!
|
||||
getDocumentMajorities(blockHash: String!, contractAddress: String!): ResultStringArray!
|
||||
getDocumentProposals(blockHash: String!, contractAddress: String!): ResultStringArray!
|
||||
getDocumentProposalCount(blockHash: String!, contractAddress: String!): ResultBigInt!
|
||||
getUpgradeProposals(blockHash: String!, contractAddress: String!): ResultStringArray
|
||||
hasVotedOnUpgradePoll(blockHash: String!, contractAddress: String!, _galaxy: Int!, _proposal: String!): ResultBoolean!
|
||||
hasVotedOnDocumentPoll(blockHash: String!, contractAddress: String!, _galaxy: Int!, _proposal: String!): ResultBoolean!
|
||||
getSyncStatus: SyncStatus
|
||||
getStateByCID(cid: String!): ResultState
|
||||
getState(blockHash: String!, contractAddress: String!, kind: String): ResultState
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
watchContract(address: String!, kind: String!, checkpoint: Boolean!, startingBlock: Int): Boolean!
|
||||
}
|
||||
|
||||
type Subscription {
|
||||
onEvent: ResultEvent!
|
||||
}
|
||||
33
packages/polls-watcher/src/server.ts
Normal file
33
packages/polls-watcher/src/server.ts
Normal file
@ -0,0 +1,33 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import 'reflect-metadata';
|
||||
import debug from 'debug';
|
||||
|
||||
import { ServerCmd } from '@cerc-io/cli';
|
||||
|
||||
import { createResolvers } from './resolvers';
|
||||
import { Indexer } from './indexer';
|
||||
import { Database } from './database';
|
||||
|
||||
const log = debug('vulcanize:server');
|
||||
|
||||
export const main = async (): Promise<any> => {
|
||||
const serverCmd = new ServerCmd();
|
||||
await serverCmd.init(Database);
|
||||
|
||||
await serverCmd.initIndexer(Indexer);
|
||||
|
||||
const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.gql')).toString();
|
||||
|
||||
return serverCmd.exec(createResolvers, typeDefs);
|
||||
};
|
||||
|
||||
main().then(() => {
|
||||
log('Starting server...');
|
||||
}).catch(err => {
|
||||
log(err);
|
||||
});
|
||||
3
packages/polls-watcher/src/types.ts
Normal file
3
packages/polls-watcher/src/types.ts
Normal file
@ -0,0 +1,3 @@
|
||||
//
|
||||
// Copyright 2021 Vulcanize, Inc.
|
||||
//
|
||||
74
packages/polls-watcher/tsconfig.json
Normal file
74
packages/polls-watcher/tsconfig.json
Normal file
@ -0,0 +1,74 @@
|
||||
{
|
||||
"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": ["es2019"], /* 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 /* Enabling the option allows importing JSON, and validating the types in that JSON file. */
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user