Skip to content

Commit

Permalink
chore(api): delete unused legacy code and adapt codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
Tommytrg committed Dec 23, 2024
1 parent 9e3a856 commit 0237b56
Show file tree
Hide file tree
Showing 22 changed files with 65 additions and 2,185 deletions.
4 changes: 0 additions & 4 deletions packages/api/src/dataFeedsRouter.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
{
"contracts": {
"legacy": {
"abi": "./src/abi/PriceFeedRouter.json",
"pollingPeriod": 120000
},
"2.0": {
"abi": "./src/abi/WitnetPriceFeeds.json",
"address": "0x1111AbA2164AcdC6D291b08DfB374280035E1111",
Expand Down
15 changes: 5 additions & 10 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
} from '../types'
import { Web3Middleware } from './web3Middleware/index'
import { normalizeNetworkConfig } from './utils/index'
import { fetchFeedsLegacy, fetchDataFeedsRouterConfig } from './readDataFeeds'
import { fetchDataFeedsRouterConfig } from './readDataFeeds'
import { SvgCache } from './svgCache'
import { NetworkRouter } from './web3Middleware/NetworkRouter'
import { Configuration } from './web3Middleware/Configuration'
Expand Down Expand Up @@ -71,23 +71,18 @@ class DataFeedsExplorer {
await this.initializeConfiguration(this.svgCache)
this.routers = await this.initializeNetworkRouters()

const legacyFeeds: Array<FeedInfo> = fetchFeedsLegacy(
this.configurationFile,
)
const v2Feeds: Array<FeedInfo> = await fetchFeedsV2(this.routers)

this.repositories = {
feedRepository: new FeedRepository(this.feedsState),
resultRequestRepository: new ResultRequestRepository(db),
}
this.repositories.feedRepository.setLegacyFeeds(legacyFeeds)
this.repositories.feedRepository.setV2Feeds(v2Feeds)

const web3Middleware = new Web3Middleware(
this.configuration,
{ repositories: this.repositories, Web3: Web3 },
legacyFeeds,
)
const web3Middleware = new Web3Middleware(this.configuration, {
repositories: this.repositories,
Web3: Web3,
})

web3Middleware.listen()

Expand Down
93 changes: 1 addition & 92 deletions packages/api/src/readDataFeeds.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import axios from 'axios'
import path from 'path'
import fs from 'fs'
import { RouterDataFeedsConfig, FeedInfo, FeedInfoConfig } from '../types'
import { normalizeConfig } from './utils'
import { RouterDataFeedsConfig } from '../types'

const CONFIG_URL = process.env.TEST_BRANCH
? `https://raw.github.com/witnet/data-feeds-explorer/${process.env.TEST_BRANCH}/packages/api/src/dataFeedsRouter.json`
Expand Down Expand Up @@ -32,91 +29,3 @@ export async function fetchDataFeedsRouterConfig(): Promise<RouterDataFeedsConfi
return null
})
}
/**
* FIXME(#197): fetchFeedsLegacy could be refactored to include the ABI to avoid
* have multiple functions to build the object. So we should review how we are fetching,
* validating and normalizing the configuration file We can even review the normalized object
* structure to check if it has sense right now or only because it was the previous configuration
* format
*/
export function fetchFeedsLegacy(
config: RouterDataFeedsConfig,
): Array<FeedInfo> {
const dataFeeds: Array<Omit<FeedInfoConfig, 'abi' | 'routerAbi'>> =
normalizeConfig(config)

// Throw and error if config file is not valid
// validateDataFeeds(dataFeeds)
return dataFeeds.map((dataFeed) => ({
...dataFeed,
routerAbi: JSON.parse(
fs.readFileSync(
path.resolve(
process.env.DATA_FEED_ROUTER_ABI_PATH || config.contracts.legacy.abi,
),
'utf-8',
),
),
abi: JSON.parse(
fs.readFileSync(
path.resolve(
// TODO: should this abi be in the config file?
process.env.DATA_FEED_ABI_PATH || './src/abi/PriceFeed.json',
),
'utf-8',
),
),
}))
}

// // Throw an error if a field is missing in the data feed config file
// function validateDataFeeds (
// dataFeeds: Array<Omit<FeedInfoConfig, 'abi' | 'routerAbi'>>
// ) {
// const expectedFields = [
// 'feedFullName',
// 'id',
// 'address',
// 'contractId',
// 'network',
// 'networkName',
// 'chain',
// 'name',
// 'label',
// 'pollingPeriod',
// 'color',
// 'blockExplorer',
// 'deviation',
// 'heartbeat',
// 'finality',
// 'isRouted'
// ]

// const optionalFields = ['deviation', 'heartbeat', 'isRouted']

// dataFeeds.forEach((feedInfoConfig, index) => {
// expectedFields.forEach(field => {
// // Validate nested keys in a field
// field.split('.').reduce((acc, val) => {
// // Throw error if the key is not found or has a falsy value
// if (!(val in acc) || !acc[val]) {
// if (optionalFields.includes(val)) {
// return acc[val]
// } else {
// throw new Error(
// `Missing field ${field} in index ${index} in data feed config file`
// )
// }
// } else {
// // Throw error if not validated new fields are added in the config file
// if (Object.keys(feedInfoConfig).length !== expectedFields.length) {
// throw new Error(
// `There are more fields in the feed config than expected`
// )
// }
// return acc[val]
// }
// }, feedInfoConfig)
// })
// })
// }
23 changes: 0 additions & 23 deletions packages/api/src/repository/Feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,24 +59,6 @@ export class FeedRepository {
}
}

updateFeedAddress(
feedFullName: string,
{ address, contractId }: { address: string; contractId: string },
): FeedInfo {
const hasSameFeedFullName = (feed: FeedInfo) =>
feed.feedFullName === feedFullName

const legacyFeeds = this.feedsState.getLegacyFeeds()
const index = legacyFeeds.findIndex(hasSameFeedFullName)
const updatedFeed = { ...legacyFeeds[index], address, contractId }
legacyFeeds[index] = updatedFeed
this.feedsState.setLegacyFeeds(legacyFeeds)

this.initialize()

return updatedFeed
}

refreshV2NetworkFeeds(network: string, feedInfos: Array<FeedInfo>) {
const v2Feeds = this.feedsState.getV2Feeds()

Expand All @@ -89,11 +71,6 @@ export class FeedRepository {
this.initialize()
}

setLegacyFeeds(legacyFeeds: Array<FeedInfo>) {
this.feedsState.setLegacyFeeds(legacyFeeds)
this.initialize()
}

setV2Feeds(v2Feeds: Array<FeedInfo>) {
this.feedsState.setV2Feeds(v2Feeds)
this.initialize()
Expand Down
12 changes: 1 addition & 11 deletions packages/api/src/repository/feedState.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,21 @@
import { FeedInfo } from '../../types'

export class FeedsState {
private legacyFeeds: Array<FeedInfo>
private v2Feeds: Array<FeedInfo>

constructor() {
this.legacyFeeds = []
this.v2Feeds = []
}

setV2Feeds(v2Feeds: Array<FeedInfo>) {
this.v2Feeds = v2Feeds
}

setLegacyFeeds(legacyFeeds: Array<FeedInfo>) {
this.legacyFeeds = legacyFeeds
}

getV2Feeds(): Array<FeedInfo> {
return this.v2Feeds
}

getLegacyFeeds(): Array<FeedInfo> {
return this.legacyFeeds
}

listFeeds(): Array<FeedInfo> {
return [...this.legacyFeeds, ...this.v2Feeds]
return [...this.v2Feeds]
}
}
118 changes: 2 additions & 116 deletions packages/api/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,5 @@
import {
ExtendedFeedConfig,
FeedInfosWithoutAbis,
FeedParamsConfig,
FeedParsedParams,
NetworkConfigMap,
RouterDataFeedsConfig,
NetworksConfig,
Chain,
FeedConfig,
} from '../../types'
// parse network name to fit schema
export function parseNetworkName(value) {
return value.toLowerCase().split('.').join('-')
}
export function parseChainName(value) {
return value.toLowerCase().split('.')[0]
}
// parse data feed name to fit schema
export function parseDataName(value) {
return value.split('-')[1].toLowerCase()
}
export function parseDataDecimals(value) {
return value.split('-')[2]
}
import { RouterDataFeedsConfig, NetworksConfig } from '../../types'

// parse data feed full name to fit schema
export function createFeedFullName(network, name, decimals) {
return `${network}_${name.split('/').join('-')}_${decimals}`.toLowerCase()
Expand Down Expand Up @@ -73,97 +50,6 @@ export function normalizeNetworkConfig(
]
}

// normalize config to fit schema

export function normalizeConfig(
config: RouterDataFeedsConfig,
): FeedInfosWithoutAbis {
// Chain list
const chains: Array<{ networks: NetworkConfigMap }> = Object.values(
config.chains,
)
// Network Config list deleting key label
const networksConfigMap = chains.flatMap((network: Chain) => {
return Object.values(network.networks)
.map((chainConfig: FeedConfig, index) => ({
...chainConfig,
chain: network.name,
hide: !!network.hide || chainConfig.hide,
network: Object.keys(network.networks)[index],
}))
.filter((network) => !network.version || network.version === 'legacy')
})

// Parse Feed adding common config
const feeds: FeedInfosWithoutAbis = networksConfigMap.reduce(
(acc: FeedInfosWithoutAbis, config: ExtendedFeedConfig) => {
const feedsArrayConfig: Array<FeedParamsConfig> = config.feeds
? Object.values(config.feeds)
: []
// Extracts feeds deleting key label
const feedsArray: Array<FeedParsedParams> = feedsArrayConfig.map(
(feed, index) => {
return {
...feed,
key: Object.keys(config.feeds)[index],
} as FeedParsedParams
},
)

feedsArray.forEach((feed) => {
const chain = config.chain
const network = parseNetworkName(config.network)
const name = parseDataName(feed.key)
const decimals = parseDataDecimals(feed.key)
if (!config.hide) {
acc.push({
feedFullName: createFeedFullName(network, name, decimals),
isRouted: !!feed.isRouted,
id: feed.key,
address: '0x0000000000000000000000000000000000000000',
contractId: '0x0000000000000000000000000000000000000000',
routerAddress: config.address,
network,
networkName: config.name,
chain,
name,
label: feed.label,
pollingPeriod: config.pollingPeriod,
color: config.color,
blockExplorer: config.blockExplorer,
deviation: feed.deviationPercentage?.toString() || null,
heartbeat: feed.maxSecsBetweenUpdates
? `${feed.maxSecsBetweenUpdates}000`
: null,
finality: '900000',
})
}
})

return acc
},
[],
)

return feeds
}

export function isZeroAddress(address: string) {
return address === '0x0000000000000000000000000000000000000000' || !address
}

export function isZeroHash(hash: string) {
return (
hash ===
'0x0000000000000000000000000000000000000000000000000000000000000000' ||
!hash
)
}

export function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}

export function removeRepeatedElements<T>(items: Array<T>): Array<T> {
return [...new Set(items)]
}
27 changes: 0 additions & 27 deletions packages/api/src/web3Middleware/Configuration.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
FeedParamsConfig,
LegacyRouterDataFeedsConfig,
Network,
NetworksConfig,
RouterDataFeedsConfig,
Expand Down Expand Up @@ -66,32 +65,6 @@ export class Configuration {
)
}

public getLegacyConfigurationFile(): LegacyRouterDataFeedsConfig {
const abi = this.configurationFile.contracts.legacy.abi
const chains = Object.entries(this.configurationFile.chains).reduce(
(acc, [chainKey, chain]) => {
const networks = Object.entries(chain.networks).reduce(
(accNetworks, [networkKey, network]) => {
// add the network entry if it's legacy
return !network.version || network.version === 'legacy'
? { ...accNetworks, [networkKey]: network }
: accNetworks
},
{},
)
return Object.keys(networks).length > 0
? { ...acc, [chainKey]: { ...chain, networks } }
: acc
},
{},
)

return {
chains,
abi,
}
}

public getFeedConfiguration(
priceFeedName: string,
network: Network,
Expand Down
Loading

0 comments on commit 0237b56

Please sign in to comment.