Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: reduce number of calls to chainId #560

Merged
merged 5 commits into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion integration/nevermined/Artifacts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ describe('Artifacts', () => {
assert.isDefined(nvm)
assert.isDefined(nvm.keeper)
assert.isDefined(nvm.keeper.didRegistry)
assert.oneOf((await nvm.keeper.getNetworkName()).toLowerCase(), networkName)
assert.oneOf(await nvm.keeper.getNetworkName(), networkName)
assert.oneOf(await nvm.keeper.getNetworkId(), networkId)
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe('Claim aborted agreements End-to-End', () => {
nevermined = await Nevermined.getInstance(config)
;[, publisher, collector1, , other] = await nevermined.accounts.list()

const networkName = (await nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nevermined.keeper.getNetworkName()
const erc721ABI = await ContractHandler.getABI(
'NFT721Upgradeable',
config.artifactsFolder,
Expand Down
2 changes: 1 addition & 1 deletion integration/nevermined/NFT1155.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ describe('NFT1155 End-to-End', () => {

describe('As user I can deploy Nevermined ERC-1155 NFT contract instances', () => {
it('Using the ABI', async () => {
const networkName = (await nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nevermined.keeper.getNetworkName()
const erc1155ABI = await ContractHandler.getABI(
'NFT1155Upgradeable',
config.artifactsFolder,
Expand Down
4 changes: 2 additions & 2 deletions integration/nevermined/NFT1155Api.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ function makeTest(isCustom) {
)

if (isCustom) {
const networkName = (await nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nevermined.keeper.getNetworkName()
const erc1155ABI = await ContractHandler.getABI(
'NFT1155Upgradeable',
config.artifactsFolder,
Expand Down Expand Up @@ -468,7 +468,7 @@ function makeTest(isCustom) {

describe('Node should not be able to transfer the nft without the operator role', () => {
it('should create the subscription NFT without granting Nevermined the operator role', async () => {
const networkName = (await nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nevermined.keeper.getNetworkName()
const erc1155ABI = await ContractHandler.getABI(
'NFT1155Upgradeable',
config.artifactsFolder,
Expand Down
2 changes: 1 addition & 1 deletion integration/nevermined/NFT721.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ describe('Nfts721 operations', async () => {
// Accounts
;[deployer, artist, collector] = await nevermined.accounts.list()

const networkName = (await nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nevermined.keeper.getNetworkName()
const erc721ABI = await ContractHandler.getABI(
'NFT721Upgradeable',
config.artifactsFolder,
Expand Down
2 changes: 1 addition & 1 deletion integration/nevermined/NFT721Api.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe('NFTs721 Api End-to-End', () => {
nevermined = await Nevermined.getInstance(config)
;[, artist, collector1, , gallery] = await nevermined.accounts.list()

const networkName = (await nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nevermined.keeper.getNetworkName()
const erc721ABI = await ContractHandler.getABI(
'NFT721Upgradeable',
config.artifactsFolder,
Expand Down
4 changes: 2 additions & 2 deletions integration/nevermined/NFT721Templates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ describe('NFT721Templates E2E', () => {
nevermined = await Nevermined.getInstance(config)
;[owner, artist, collector1, collector2, gallery] = await nevermined.accounts.list()

const networkName = (await nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nevermined.keeper.getNetworkName()
const erc721ABI = await ContractHandler.getABI(
'NFT721Upgradeable',
config.artifactsFolder,
Expand Down Expand Up @@ -609,7 +609,7 @@ describe('NFT721Templates E2E', () => {
collector2.getId(),
)

const networkName = (await nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nevermined.keeper.getNetworkName()
const erc721ABI = await ContractHandler.getABI(
'NFT721Upgradeable',
config.artifactsFolder,
Expand Down
2 changes: 1 addition & 1 deletion integration/nevermined/NFTsWithMultipleServices.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe('E2E Flow for NFTs with multiple services', () => {

neverminedNodeAddress = await nevermined.services.node.getProviderAddress()

const networkName = (await nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nevermined.keeper.getNetworkName()
const erc721ABI = await ContractHandler.getABI(
'NFT721Upgradeable',
config.artifactsFolder,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"test": "mocha --opts test/mocha.opts ./test/**/*.test.ts",
"test:watch": "mocha -w --watch-extensions js,ts,json",
"test:cover": "nyc --report-dir coverage/unit mocha --opts test/mocha.opts ./test/**/*.test.ts",
"integration": "mocha --opts integration/mocha.opts ",
"integration": "mocha --opts integration/mocha.opts ./integration/nevermined/*.test.ts",
"integration:subgraph": "mocha --opts integration/mocha.opts ./integration/**/*.test.subgraph.ts",
"integration:production": "export NETWORK_NAME=production; yarn integration",
"integration:staging": "export NETWORK_NAME=staging; yarn integration",
Expand Down Expand Up @@ -66,7 +66,7 @@
"cross-fetch": "^4.0.0",
"crypto-browserify": "^3.12.0",
"deprecated-decorator": "^0.1.6",
"ethers": "^6.6.4",
"ethers": "^6.6.5",
"graphql": "^16.7.1",
"https-browserify": "^1.0.0",
"jose": "^4.5.1",
Expand Down
10 changes: 5 additions & 5 deletions src/Instantiable.abstract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export interface InstantiableConfig {
circuitsFolder?: string
}

export function generateIntantiableConfigFromConfig(
export async function generateIntantiableConfigFromConfig(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo in the function name, generateInstantiableConfigFromConfig

config: NeverminedOptions,
): Partial<InstantiableConfig> {
): Promise<Partial<InstantiableConfig>> {
const logLevel =
typeof config.verbose !== 'number'
? config.verbose
Expand All @@ -24,7 +24,7 @@ export function generateIntantiableConfigFromConfig(
: (config.verbose as LogLevel)
return {
config,
web3: Web3Provider.getWeb3(config),
web3: await Web3Provider.getWeb3(config),
logger: new Logger(logLevel),
artifactsFolder: config.artifactsFolder,
circuitsFolder: config.circuitsFolder,
Expand All @@ -41,8 +41,8 @@ export abstract class Instantiable {

public get web3() {
if (!this._instantiableConfig?.web3) {
this.logger.warn('ethers.Provider instance is not defined. Using default instance.')
return Web3Provider.getWeb3()
this.logger.error('Web3 Provider not initialized')
throw new Error('Web3 Provider not initialized')
}
return this._instantiableConfig.web3
}
Expand Down
16 changes: 8 additions & 8 deletions src/keeper/ContractHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ export class ContractHandler extends Instantiable {
artifactsFolder: string,
address?: string,
): Promise<ethers.BaseContract> {
const networkId = await this.nevermined.keeper.getNetworkId()
const where = (await this.nevermined.keeper.getNetworkName()).toLowerCase()
const chainId = await this.nevermined.keeper.getNetworkId()
const where = await this.nevermined.keeper.getNetworkName()
try {
this.logger.debug(`ContractHandler :: get :: ${artifactsFolder} and address ${address}`)
return (
ContractHandler.getContract(what, networkId, address) ||
(await this.load(what, where, networkId, artifactsFolder, address))
ContractHandler.getContract(what, chainId, address) ||
(await this.load(what, where, chainId, artifactsFolder, address))
)
} catch (err) {
if (!optional) {
Expand Down Expand Up @@ -98,7 +98,7 @@ export class ContractHandler extends Instantiable {
}

public async getVersion(contractName: string, artifactsFolder: string): Promise<string> {
const where = (await this.nevermined.keeper.getNetworkName()).toLowerCase()
const where = await this.nevermined.keeper.getNetworkName()
let artifact
this.logger.debug(
`ContractHandler :: getVersion :: Trying to read ${artifactsFolder}/${contractName}.${where}.json`,
Expand Down Expand Up @@ -257,9 +257,9 @@ export class ContractHandler extends Instantiable {

public async getFeeData(gasPrice?: bigint, maxFeePerGas?: bigint, maxPriorityFeePerGas?: bigint) {
// Custom gas fee for polygon networks
const networkId = await this.nevermined.keeper.getNetworkId()
if (networkId === 137 || networkId === 80001) {
return this.getFeeDataPolygon(networkId)
const chainId = await this.nevermined.keeper.getNetworkId()
if (chainId === 137 || chainId === 80001) {
return this.getFeeDataPolygon(chainId)
}

const feeData = await this.web3.getFeeData()
Expand Down
89 changes: 59 additions & 30 deletions src/keeper/Keeper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,13 @@ export class Keeper extends Instantiable {
eventHandler: new EventHandler(),
}
// version
this.version = this.didRegistry.version.replace('v', '')
const chainId = Number((await this.web3.getNetwork()).chainId)
this.network = {
chainId,
version: this.didRegistry.version.replace('v', ''),
name: await KeeperUtils.getNetworkName(chainId),
loading: false,
}
}

/**
Expand Down Expand Up @@ -328,16 +334,25 @@ export class Keeper extends Instantiable {
eventHandler: EventHandler
}

/**
* Version of the artifacts in use
*/
public version: string

/**
* Network id loaded from web3
*/
protected network: {
id?: number
/**
* chainId of the network
*/
chainId?: number
/**
* Name of the network
*/
name?: string
/**
* Version of the artifacts in use
*/
version?: string
/**
* True if keeper is still connecting
*/
loading: boolean
} = {
loading: true,
Expand All @@ -363,47 +378,61 @@ export class Keeper extends Instantiable {
return Object.values(this.templates).find((template) => template.contractName === name)
}

/**
* Returns a Access template by name.
* @param name - Template name.
* @returns Agreement template instance.
*/
public getAccessTemplateByName(name: string): GenericAccess {
return this.templateList.find((template) => template.contractName === name)
}

/**
* Returns a template by address.
* @param address - Template address.
* @returns Agreement template instance.
*/
public getTemplateByAddress(address: string) {
return Object.values(this.templates).find((template) => template.address === address)
}

/**
* Returns the network by name.
* @returns Network name.
*/
public async getNetworkName(): Promise<string> {
return KeeperUtils.getNetworkName(await this.getNetworkId())
if (!this.network.name) {
this.network.name = await KeeperUtils.getNetworkName(await this.getNetworkId())
}
return this.network.name
}

/**
* Returns the id of the network.
* @returns Network ID.
*/
public async getNetworkId(): Promise<number> {
if (this.network.loading) {
if (!this.network.chainId) {
this.network.loading = false
this.network.id = Number((await this.web3.getNetwork()).chainId)
this.network.chainId = Number((await this.web3.getNetwork()).chainId)
}

while (!this.network.id) {
while (!this.network.chainId) {
await new Promise((resolve) => setTimeout(resolve, 1))
}

return this.network.id
return this.network.chainId
}

/**
* Returns the network version.
* @returns Network version.
*/
public getNetworkVersion(): string {
if (!this.network.version) {
this.network.version = this.didRegistry.version.replace('v', '')
}
return this.network.version
}

/**
* Returns a Access template by name.
* @param name - Template name.
* @returns Agreement template instance.
*/
public getAccessTemplateByName(name: string): GenericAccess {
return this.templateList.find((template) => template.contractName === name)
}

/**
* Returns a template by address.
* @param address - Template address.
* @returns Agreement template instance.
*/
public getTemplateByAddress(address: string) {
return Object.values(this.templates).find((template) => template.address === address)
}

public getAllInstances() {
Expand Down
17 changes: 14 additions & 3 deletions src/keeper/Web3Provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,26 @@ export class Web3Provider {
*
* @returns web3 instance
*/
public static getWeb3(
public static async getWeb3(
config: Partial<NeverminedOptions> = {},
): ethers.JsonRpcProvider | ethers.BrowserProvider {
): Promise<ethers.JsonRpcProvider | ethers.BrowserProvider> {
if (config.web3Provider) {
return new ethers.BrowserProvider(config.web3Provider)
}

// disabling the cache since this will lead to duplicated nonces on test networks
// See https://docs.ethers.org/v6/api/providers/abstract-provider/#AbstractProviderOptions
return new ethers.JsonRpcProvider(config.web3ProviderUri, undefined, { cacheTimeout: -1 })
let provider = new ethers.JsonRpcProvider(config.web3ProviderUri, undefined, {
cacheTimeout: -1,
})

// Adding the static network prevents ethers from calling eth_chainId with every call
const network = await provider.getNetwork()
provider = new ethers.JsonRpcProvider(config.web3ProviderUri, undefined, {
cacheTimeout: -1,
staticNetwork: network,
})

return provider
}
}
2 changes: 1 addition & 1 deletion src/keeper/contracts/Nft1155Contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class Nft1155Contract extends NFTContractsBase {
await nft.init(config)

if (address) {
const networkName = (await nft.nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nft.nevermined.keeper.getNetworkName()

const solidityABI = await ContractHandler.getABI(contractName, artifactsFolder, networkName)
await new ContractHandler(config).checkExists(address)
Expand Down
2 changes: 1 addition & 1 deletion src/keeper/contracts/Nft721Contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class Nft721Contract extends NFTContractsBase {
): Promise<Nft721Contract> {
const nft: Nft721Contract = new Nft721Contract(contractName)
nft.setInstanceConfig(config)
const networkName = (await nft.nevermined.keeper.getNetworkName()).toLowerCase()
const networkName = await nft.nevermined.keeper.getNetworkName()

// We don't have a subgraph for NFT721 so we can only use ContractEvent
const eventEmitter = new EventHandler()
Expand Down
18 changes: 9 additions & 9 deletions src/keeper/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,23 @@ import { KeeperError } from '../errors'
export async function getNetworkName(networkId: number): Promise<string> {
switch (networkId) {
case 1:
return 'Mainnet'
return 'mainnet'
case 2:
return 'Morden'
return 'morden'
case 3:
return 'Ropsten'
return 'ropsten'
case 4:
return 'Rinkeby'
return 'rinkeby'
case 5:
return 'Goerli'
return 'goerli'
case 77:
return 'POA_Sokol'
return 'poa_sokol'
case 99:
return 'POA_Core'
return 'poa_core'
case 42:
return 'Kovan'
return 'kovan'
case 100:
return 'Gnosis'
return 'gnosis'
case 137:
return 'matic'
case 1337:
Expand Down
Loading