classic-ui-dev/services/registry/index.js

250 lines
7.2 KiB
JavaScript
Raw Normal View History

2022-11-21 06:07:23 -05:00
import Web3 from 'web3'
2022-04-21 23:05:56 -04:00
import namehash from 'eth-ens-namehash'
import { BigNumber as BN } from 'bignumber.js'
2022-11-21 06:07:23 -05:00
import { toChecksumAddress, isAddress } from 'web3-utils'
2022-04-21 23:05:56 -04:00
import networkConfig from '@/networkConfig'
2022-11-23 07:05:23 -05:00
import { REGISTRY_DEPLOYED_BLOCK } from '@/constants'
2022-11-21 06:07:23 -05:00
import { sleep, flattenNArray } from '@/utils'
2022-04-21 23:05:56 -04:00
import AggregatorABI from '@/abis/Aggregator.abi.json'
import RelayerRegistryABI from '@/abis/RelayerRegistry.abi.json'
const MIN_STAKE_BALANCE = '0x22B1C8C1227A00000' // 40 TORN
const subdomains = Object.values(networkConfig).map(({ ensSubdomainKey }) => ensSubdomainKey)
class RelayerRegister {
constructor(provider) {
this.provider = provider
2022-06-14 06:02:45 -04:00
this.$indexedDB = window.$nuxt.$indexedDB(1)
2022-04-21 23:05:56 -04:00
const { registryContract, aggregatorContract } = networkConfig.netId1
this.aggregator = new this.provider.Contract(AggregatorABI, aggregatorContract)
this.relayerRegistry = new this.provider.Contract(RelayerRegistryABI, registryContract)
}
2022-11-23 07:05:23 -05:00
fetchEvents = ({ fromBlock, toBlock }, shouldRetry = false) => {
return new Promise((resolve, reject) => {
if (fromBlock <= toBlock) {
2022-11-21 06:07:23 -05:00
try {
const registeredEventsPart = this.relayerRegistry.getPastEvents('RelayerRegistered', {
fromBlock,
toBlock
})
resolve(registeredEventsPart)
} catch (error) {
2022-11-23 07:05:23 -05:00
if (shouldRetry) {
2023-03-22 16:50:13 -04:00
sleep(500)
2022-11-21 06:07:23 -05:00
2022-11-23 07:05:23 -05:00
const events = this.fetchEvents({ fromBlock, toBlock })
2022-11-21 06:07:23 -05:00
2022-11-23 07:05:23 -05:00
resolve(events)
} else {
reject(new Error(error))
2022-11-21 06:07:23 -05:00
}
2022-04-21 23:05:56 -04:00
}
2022-11-23 07:05:23 -05:00
} else {
resolve([])
}
})
2022-11-21 06:07:23 -05:00
}
batchFetchEvents = async ({ fromBlock, toBlock }) => {
const blockRange = 10000
const blockDifference = toBlock - fromBlock
const chunkCount = Math.ceil(blockDifference / blockRange)
const blockDenom = Math.ceil(blockDifference / chunkCount)
2022-11-23 07:05:23 -05:00
const promises = new Array(chunkCount).fill('').map(
(_, i) =>
new Promise((resolve) => {
2023-03-22 16:50:13 -04:00
sleep(20 * i)
2022-11-23 07:05:23 -05:00
const batch = this.fetchEvents(
{
fromBlock: i * blockDenom + fromBlock,
toBlock: (i + 1) * blockDenom + fromBlock
},
true
)
resolve(batch)
})
2022-11-21 06:07:23 -05:00
)
const batchEvents = flattenNArray(await Promise.all(promises))
const events = batchEvents.map((e) => ({ ...e.returnValues }))
return events
2022-04-21 23:05:56 -04:00
}
saveEvents = async ({ events, lastSyncBlock, storeName }) => {
try {
if (this.$indexedDB.isBlocked) {
return
}
await this.$indexedDB.putItem({
data: {
blockNumber: lastSyncBlock,
name: storeName
},
2022-06-14 06:02:45 -04:00
storeName: 'lastEvents'
2022-04-21 23:05:56 -04:00
})
if (events.length) {
this.$indexedDB.createMultipleTransactions({ data: events, storeName })
}
} catch (err) {
console.error(`saveEvents has error: ${err.message}`)
}
}
getCachedData = async () => {
let blockFrom = REGISTRY_DEPLOYED_BLOCK[1]
try {
const blockTo = await this.provider.getBlockNumber()
const cachedEvents = await this.$indexedDB.getAll({
storeName: 'register_events'
})
const lastBlock = await this.$indexedDB.getFromIndex({
indexName: 'name',
key: 'register_events',
2022-06-14 06:02:45 -04:00
storeName: 'lastEvents'
2022-04-21 23:05:56 -04:00
})
if (lastBlock) {
blockFrom = blockTo >= lastBlock.blockNumber ? lastBlock.blockNumber + 1 : blockTo
}
return { blockFrom, blockTo, cachedEvents }
} catch {
return { blockFrom, blockTo: 'latest', cachedEvents: [] }
}
}
2022-11-21 06:07:23 -05:00
getENSAddress = async (ensName) => {
const { url } = Object.values(networkConfig.netId1.rpcUrls)[0]
2022-11-23 07:05:23 -05:00
const provider = new Web3(url)
2022-11-21 06:07:23 -05:00
const ensAddress = await provider.eth.ens.getAddress(ensName)
return ensAddress
}
2022-04-21 23:05:56 -04:00
fetchRelayers = async () => {
2022-11-21 06:07:23 -05:00
const blockRange = 10000
2022-04-21 23:05:56 -04:00
// eslint-disable-next-line prefer-const
2022-11-21 06:07:23 -05:00
let { blockTo, cachedEvents } = await this.getCachedData()
2022-04-21 23:05:56 -04:00
let allRelayers = cachedEvents
2022-11-21 06:07:23 -05:00
const currentBlockNumber = await this.provider.getBlockNumber()
const fromBlock = cachedEvents.length === 0 ? REGISTRY_DEPLOYED_BLOCK[1] : blockTo
const blockDifference = currentBlockNumber - fromBlock
2022-04-21 23:05:56 -04:00
2022-11-21 06:07:23 -05:00
try {
let toBlock
let registerRelayerEvents
2022-11-23 07:05:23 -05:00
let lastSyncBlock = blockTo
2022-11-21 06:07:23 -05:00
if (cachedEvents.length > 0 || blockDifference === 0) {
return cachedEvents
} else if (blockDifference >= blockRange) {
toBlock = currentBlockNumber
registerRelayerEvents = await this.batchFetchEvents({ fromBlock, toBlock })
2022-11-23 07:05:23 -05:00
lastSyncBlock = toBlock
2022-11-21 06:07:23 -05:00
} else {
toBlock = fromBlock + blockRange
2022-11-23 07:05:23 -05:00
registerRelayerEvents = await this.fetchEvents({ fromBlock, toBlock }, true)
lastSyncBlock = toBlock
2022-04-21 23:05:56 -04:00
}
2022-11-21 06:07:23 -05:00
const relayerEvents = cachedEvents.concat(registerRelayerEvents || [])
const events = []
2022-04-21 23:05:56 -04:00
2022-11-21 06:07:23 -05:00
for (let x = 0; x < relayerEvents.length; x++) {
const { ensName, relayerAddress } = relayerEvents[x]
let ensAddress
if (!isAddress(relayerAddress)) {
ensAddress = await this.getENSAddress(ensName)
ensAddress = toChecksumAddress(ensAddress)
} else {
ensAddress = relayerAddress
2022-04-21 23:05:56 -04:00
}
2022-11-21 06:07:23 -05:00
events.push({ ensName, relayerAddress: ensAddress })
2022-04-21 23:05:56 -04:00
}
2022-11-21 06:07:23 -05:00
await this.saveEvents({ storeName: 'register_events', lastSyncBlock, events })
2022-04-21 23:05:56 -04:00
2022-11-21 06:07:23 -05:00
allRelayers = allRelayers.concat(events)
2022-11-23 07:05:23 -05:00
} catch (err) {
console.log(err)
2022-11-21 06:07:23 -05:00
}
2022-04-21 23:05:56 -04:00
return allRelayers
}
filterRelayer = (acc, curr, ensSubdomainKey, relayer) => {
const subdomainIndex = subdomains.indexOf(ensSubdomainKey)
const mainnetSubdomain = curr.records[0]
const hostname = curr.records[subdomainIndex]
const isHostWithProtocol = hostname.includes('http')
const isOwner = relayer.relayerAddress === curr.owner
const hasMinBalance = new BN(curr.balance).gte(MIN_STAKE_BALANCE)
if (
hostname &&
isOwner &&
mainnetSubdomain &&
curr.isRegistered &&
hasMinBalance &&
!isHostWithProtocol
) {
acc.push({
hostname,
ensName: relayer.ensName,
stakeBalance: curr.balance,
relayerAddress: relayer.relayerAddress
})
} else {
console.error(`${relayer.ensName} invalid: `, {
isOwner,
hasTXT: Boolean(hostname),
isHasMinBalance: hasMinBalance,
isRegistered: curr.isRegistered,
isHostWithoutProtocol: !isHostWithProtocol,
isMainnetSubdomain: Boolean(mainnetSubdomain)
})
}
return acc
}
getValidRelayers = async (relayers, ensSubdomainKey) => {
const relayerNameHashes = relayers.map((r) => namehash.hash(r.ensName))
const relayersData = await this.aggregator.methods.relayersData(relayerNameHashes, subdomains).call()
const validRelayers = relayersData.reduce(
(acc, curr, index) => this.filterRelayer(acc, curr, ensSubdomainKey, relayers[index]),
[]
)
return validRelayers
}
getRelayers = async (ensSubdomainKey) => {
const relayers = await this.fetchRelayers()
const validRelayers = await this.getValidRelayers(relayers, ensSubdomainKey)
return validRelayers
}
}
export const relayerRegisterService = (provider) => new RelayerRegister(provider.eth)