Skip to content

Commit

Permalink
feat: add listeners scaffolding
Browse files Browse the repository at this point in the history
  • Loading branch information
eccentricexit committed Apr 14, 2020
1 parent 8361b77 commit 330c82d
Show file tree
Hide file tree
Showing 9 changed files with 152 additions and 6 deletions.
12 changes: 12 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Web3---
FACTORY_ADDRESS=0x9fDd978101EF4F7A3AE5AEC08898258b5CDBF52B
PROVIDER_URL=https://kovan.infura.io/v3/<secret-key>
# The block time is used calculate how many blocks to scan when fetching
# logs and avoid rate limiting by web3 providers.
BLOCK_TIME_MILLISECONDS=4000

# The bot learns the addresses of TCRs to watch by fetching logs,
# emitted by the factory. We can fetch logs more quickly by
# sweeping the blockchain from the deployment block of the factory contract.
# This field is optional, if not set, 0 will be used.
FACTORY_BLOCK_NUM=16384123
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
"gtcr",
"bot"
],
"dependencies": {
"@kleros/tcr": "^1.7.1",
"ethers": "^4.0.46"
},
"devDependencies": {
"@commitlint/cli": "^8.3.5",
"@commitlint/config-conventional": "^8.3.4",
Expand Down
20 changes: 20 additions & 0 deletions src/handlers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { ethers } from 'ethers'

import requestSubmittedHandler from './request-submitted'
import requestResolvedHandler from './request-resolved'

export default async function addTCRListeners(tcr: ethers.Contract) {
// Submissions and removal requests.
tcr.on(
tcr.filters.RequestSubmitted(),
requestSubmittedHandler()
)

// Request resolved.
tcr.on(
tcr.filters.ItemStatusChange(null, null, null, null, true),
requestResolvedHandler()
)

console.info(`Done setting up listeners for ${tcr.address}`)
}
4 changes: 4 additions & 0 deletions src/handlers/request-resolved.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default () => async () => {
// TODO: Stop monitoring item.
// TODO: Withdraw pending crowdfunding rewards.
}
3 changes: 3 additions & 0 deletions src/handlers/request-submitted.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default () => async () => {
// TODO: Add to DB and start monitoring.
}
83 changes: 82 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,82 @@
// TODO
import { ethers } from 'ethers'

import _GTCRFactory from '@kleros/tcr/build/contracts/GTCRFactory.json'
import _GeneralizedTCR from '@kleros/tcr/build/contracts/GeneralizedTCR.json'

// Run env variable checks.
import './utils/env-check'
import addTCRListeners from './handlers'

const provider = new ethers.providers.JsonRpcProvider(process.env.PROVIDER_URL)
provider.pollingInterval = 60 * 1000 // Poll every minute.

const gtcrFactory = new ethers.Contract(
process.env.FACTORY_ADDRESS as string,
_GTCRFactory.abi,
provider
)

// Run bot.
;(async () => {
// Initial setup.
console.info('Booting...')
console.info()
const [currBlock, network] = await Promise.all([
provider.getBlockNumber(),
provider.getNetwork()
])

console.info(`Connected to ${network.name} of chain of ID ${network.chainId}`)
console.info(`GTCR Factory deployed at ${process.env.FACTORY_ADDRESS}`)

// Fetch all TCR addresses from factory logs, instantiate and add
// event listeners.
const deploymentBlock = Number(process.env.FACTORY_BLOCK_NUM) || 0

// Fetch logs by scanning the blockchain in batches of 4 months
// to avoid rate-limiting.
const blocksPerMinute = Math.floor(
60 / (Number(process.env.BLOCK_TIME_MILLISECONDS as string) / 1000)
)
const blocksPerRequest = blocksPerMinute * 60 * 24 * 30 * 4

// Fetch the addresses of TCRs deployed with this factory.
const logPromises = []
for (let fromBlock = deploymentBlock; ; ) {
logPromises.push(
provider.getLogs({
...gtcrFactory.filters.NewGTCR(),
fromBlock: fromBlock,
toBlock: fromBlock + blocksPerRequest
})
)

if (fromBlock + blocksPerRequest >= currBlock) break
fromBlock += blocksPerRequest
}

// Concat results and instantiate TCRs.
const tcrs = (await Promise.all(logPromises))
.reduce((acc, curr) => acc.concat(curr), [])
.map(log => gtcrFactory.interface.parseLog(log).values._address)
.map(address => new ethers.Contract(address, _GeneralizedTCR.abi, provider))

// Add listeners for events emitted by the TCRs.
await Promise.all(
tcrs.map(tcr =>
addTCRListeners(
tcr
)
)
)

// Watch for new TCRs and add listeners.
gtcrFactory.on(gtcrFactory.filters.NewGTCR(), _address =>
addTCRListeners(
new ethers.Contract(_address, _GeneralizedTCR.abi, provider),
)
)

console.info()
console.info('Done. Watching for blockchain events.')
})()
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true
"strictNullChecks": true,
"esModuleInterop": true,
},
"include": [
"src/**/*"
Expand Down
21 changes: 21 additions & 0 deletions utils/env-check.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Web3
if (!process.env.PROVIDER_URL) {
console.error(
'No web3 provider set. Please set the PROVIDER_URL environment variable'
)
process.exit(1)
}

if (!process.env.FACTORY_ADDRESS) {
console.error(
'No factory address set. Please set the FACTORY_ADDRESS environment variable'
)
process.exit(1)
}

if (!process.env.BLOCK_TIME_MILLISECONDS) {
console.error(
'Network block time not set. Please set the BLOCK_TIME_MILLISECONDS environment variable'
)
process.exit(1)
}
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -913,13 +913,13 @@ bignumber.js@^7.2.1:
resolved "https://registry.yarnpkg.com/bignumber.js/-/bignumber.js-7.2.1.tgz#80c048759d826800807c4bfd521e50edbba57a5f"
integrity sha512-S4XzBk5sMB+Rcb/LNcpzXr57VRTxgAvaAEDAl1AwRx27j00hT84O6OkteE7u8UB3NuaaygCRrEpqox4uDOrbdQ==

"bignumber.js@git+https://github.com/debris/bignumber.js.git#94d7146671b9719e00a09c29b01a691bc85048c2":
"bignumber.js@git+https://github.com/debris/bignumber.js#master":
version "2.0.7"
resolved "git+https://github.com/debris/bignumber.js.git#94d7146671b9719e00a09c29b01a691bc85048c2"
resolved "git+https://github.com/debris/bignumber.js#c7a38de919ed75e6fb6ba38051986e294b328df9"

"bignumber.js@git+https://github.com/debris/bignumber.js.git#master":
"bignumber.js@git+https://github.com/debris/bignumber.js.git#94d7146671b9719e00a09c29b01a691bc85048c2":
version "2.0.7"
resolved "git+https://github.com/debris/bignumber.js.git#c7a38de919ed75e6fb6ba38051986e294b328df9"
resolved "git+https://github.com/debris/bignumber.js.git#94d7146671b9719e00a09c29b01a691bc85048c2"

binaryextensions@^2.2.0:
version "2.2.0"
Expand Down

0 comments on commit 330c82d

Please sign in to comment.