diff --git a/CHANGELOG.md b/CHANGELOG.md index 595058c0..d4d4d10b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,25 @@ All notable changes to this project will be documented in this file. Dates are d Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). +#### [v1.0.0-next.43](https://github.com/oceanprotocol/ocean.js/compare/v1.0.0-next.42...v1.0.0-next.43) + +- bump contracts to alpha.33 [`#1472`](https://github.com/oceanprotocol/ocean.js/pull/1472) +- Bump @types/node from 17.0.32 to 17.0.34 [`#1471`](https://github.com/oceanprotocol/ocean.js/pull/1471) +- Add transfer() function to TokenUtils [`#1387`](https://github.com/oceanprotocol/ocean.js/pull/1387) +- Issue-#1391: Add generic estimateGas() function [`#1394`](https://github.com/oceanprotocol/ocean.js/pull/1394) +- Bump @types/node from 17.0.31 to 17.0.32 [`#1465`](https://github.com/oceanprotocol/ocean.js/pull/1465) +- use estimateGas() function in NFT [`4cee7bb`](https://github.com/oceanprotocol/ocean.js/commit/4cee7bb08cd11e38ecddbc0c14f6eebf88755c9b) +- use estimateGas() function in Datatoken [`f9aa47c`](https://github.com/oceanprotocol/ocean.js/commit/f9aa47c4d21f34aa31addd3a37054800f0e8fb6d) +- use estimateGas() function in NFTFactory [`00fc5d2`](https://github.com/oceanprotocol/ocean.js/commit/00fc5d21e9e819e0ef47254dd5e4721b52c9d2fa) + #### [v1.0.0-next.42](https://github.com/oceanprotocol/ocean.js/compare/v1.0.0-next.41...v1.0.0-next.42) +> 9 May 2022 + - bump contracts to alpha.32 [`#1464`](https://github.com/oceanprotocol/ocean.js/pull/1464) - simple compute flow [`#1458`](https://github.com/oceanprotocol/ocean.js/pull/1458) - add optional decimals parameter at joinswapExternAmountIn() and exitswapPoolAmountIn() [`#1461`](https://github.com/oceanprotocol/ocean.js/pull/1461) +- Release 1.0.0-next.42 [`56f992e`](https://github.com/oceanprotocol/ocean.js/commit/56f992e760712a88f4c9a236d75d784d6dd1c4b1) #### [v1.0.0-next.41](https://github.com/oceanprotocol/ocean.js/compare/v1.0.0-next.40...v1.0.0-next.41) diff --git a/package-lock.json b/package-lock.json index 06f6d044..32efbef6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,15 @@ { "name": "@oceanprotocol/lib", - "version": "1.0.0-next.42", + "version": "1.0.0-next.43", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@oceanprotocol/lib", - "version": "1.0.0-next.42", + "version": "1.0.0-next.43", "license": "Apache-2.0", "dependencies": { - "@oceanprotocol/contracts": "^1.0.0-alpha.32", + "@oceanprotocol/contracts": "^1.0.0-alpha.33", "bignumber.js": "^9.0.2", "cross-fetch": "^3.1.5", "crypto-js": "^4.1.1", @@ -24,7 +24,7 @@ "@types/chai-spies": "^1.0.3", "@types/crypto-js": "^4.1.1", "@types/mocha": "^9.1.1", - "@types/node": "^17.0.32", + "@types/node": "^17.0.34", "@types/node-fetch": "^3.0.3", "@typescript-eslint/eslint-plugin": "^4.33.0", "@typescript-eslint/parser": "^4.33.0", @@ -2471,9 +2471,9 @@ } }, "node_modules/@oceanprotocol/contracts": { - "version": "1.0.0-alpha.32", - "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.32.tgz", - "integrity": "sha512-gCHw4ZVnNjSozzCVT/cQiDqLNP0Xvy4fe+g5PKy8rwMR/h2rRW65Txi6wkb4HfZiUPKCdHbzpUFOwYfJFbW0Jw==" + "version": "1.0.0-alpha.33", + "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.33.tgz", + "integrity": "sha512-jx8fg9src7fjeqMXB2ZYLdp0BoJA0G5vau6pa48YOjasDuPekJtPdT0oRy0PVkyJ2HtkYjAwKVyiFfAbZcug6A==" }, "node_modules/@octokit/auth-token": { "version": "2.5.0", @@ -3021,9 +3021,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "17.0.32", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.32.tgz", - "integrity": "sha512-eAIcfAvhf/BkHcf4pkLJ7ECpBAhh9kcxRBpip9cTiO+hf+aJrsxYxBeS6OXvOd9WqNAJmavXVpZvY1rBjNsXmw==" + "version": "17.0.34", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.34.tgz", + "integrity": "sha512-XImEz7XwTvDBtzlTnm8YvMqGW/ErMWBsKZ+hMTvnDIjGCKxwK5Xpc+c/oQjOauwq8M4OS11hEkpjX8rrI/eEgA==" }, "node_modules/@types/node-fetch": { "version": "3.0.3", @@ -19610,9 +19610,9 @@ } }, "@oceanprotocol/contracts": { - "version": "1.0.0-alpha.32", - "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.32.tgz", - "integrity": "sha512-gCHw4ZVnNjSozzCVT/cQiDqLNP0Xvy4fe+g5PKy8rwMR/h2rRW65Txi6wkb4HfZiUPKCdHbzpUFOwYfJFbW0Jw==" + "version": "1.0.0-alpha.33", + "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.33.tgz", + "integrity": "sha512-jx8fg9src7fjeqMXB2ZYLdp0BoJA0G5vau6pa48YOjasDuPekJtPdT0oRy0PVkyJ2HtkYjAwKVyiFfAbZcug6A==" }, "@octokit/auth-token": { "version": "2.5.0", @@ -20079,9 +20079,9 @@ "dev": true }, "@types/node": { - "version": "17.0.32", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.32.tgz", - "integrity": "sha512-eAIcfAvhf/BkHcf4pkLJ7ECpBAhh9kcxRBpip9cTiO+hf+aJrsxYxBeS6OXvOd9WqNAJmavXVpZvY1rBjNsXmw==" + "version": "17.0.34", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.34.tgz", + "integrity": "sha512-XImEz7XwTvDBtzlTnm8YvMqGW/ErMWBsKZ+hMTvnDIjGCKxwK5Xpc+c/oQjOauwq8M4OS11hEkpjX8rrI/eEgA==" }, "@types/node-fetch": { "version": "3.0.3", diff --git a/package.json b/package.json index a4725d46..7e2405d3 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@oceanprotocol/lib", "source": "./src/index.ts", - "version": "1.0.0-next.42", + "version": "1.0.0-next.43", "description": "JavaScript client library for Ocean Protocol", "main": "./dist/lib.js", "umd:main": "dist/lib.umd.js", @@ -58,7 +58,7 @@ "web3": "^1.7.3" }, "dependencies": { - "@oceanprotocol/contracts": "^1.0.0-alpha.32", + "@oceanprotocol/contracts": "^1.0.0-alpha.33", "bignumber.js": "^9.0.2", "cross-fetch": "^3.1.5", "crypto-js": "^4.1.1", @@ -73,7 +73,7 @@ "@types/chai-spies": "^1.0.3", "@types/crypto-js": "^4.1.1", "@types/mocha": "^9.1.1", - "@types/node": "^17.0.32", + "@types/node": "^17.0.34", "@types/node-fetch": "^3.0.3", "@typescript-eslint/eslint-plugin": "^4.33.0", "@typescript-eslint/parser": "^4.33.0", diff --git a/src/factories/NFTFactory.ts b/src/factories/NFTFactory.ts index 8dff31b1..9b697282 100644 --- a/src/factories/NFTFactory.ts +++ b/src/factories/NFTFactory.ts @@ -11,6 +11,7 @@ import { getErcCreationParams, getPoolCreationParams, setContractDefaults, + estimateGas, ZERO_ADDRESS, ConfigHelper } from '../utils' @@ -50,7 +51,6 @@ export interface NftCreateData { * Provides an interface for NFT Factory contract */ export class NftFactory { - public GASLIMIT_DEFAULT = 1000000 public factory721Address: string public factory721Abi: AbiItem | AbiItem[] public web3: Web3 @@ -87,25 +87,18 @@ export class NftFactory { * @return {Promise} NFT datatoken address */ public async estGasCreateNFT(address: string, nftData: NftCreateData): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.factory721.methods - .deployERC721Contract( - nftData.name, - nftData.symbol, - nftData.templateIndex, - ZERO_ADDRESS, - ZERO_ADDRESS, - nftData.tokenURI, - nftData.transferable, - nftData.owner - ) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.factory721.methods.deployERC721Contract, + nftData.name, + nftData.symbol, + nftData.templateIndex, + ZERO_ADDRESS, + ZERO_ADDRESS, + nftData.tokenURI, + nftData.transferable, + nftData.owner + ) } /** @@ -132,7 +125,18 @@ export class NftFactory { if ((await this.getNFTTemplate(nftData.templateIndex)).isActive === false) { throw new Error(`Template is not active`) } - const estGas = await this.estGasCreateNFT(address, nftData) + const estGas = await estimateGas( + address, + this.factory721.methods.deployERC721Contract, + nftData.name, + nftData.symbol, + nftData.templateIndex, + ZERO_ADDRESS, + ZERO_ADDRESS, + nftData.tokenURI, + nftData.transferable, + nftData.owner + ) // Invoke createToken function of the contract const trxReceipt = await this.factory721.methods @@ -254,16 +258,11 @@ export class NftFactory { address: string, templateAddress: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.factory721.methods - .add721TokenTemplate(templateAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.factory721.methods.add721TokenTemplate, + templateAddress + ) } /** @@ -283,7 +282,11 @@ export class NftFactory { throw new Error(`Template cannot be ZERO address`) } - const estGas = await this.estGasAddNFTTemplate(address, templateAddress) + const estGas = await estimateGas( + address, + this.factory721.methods.add721TokenTemplate, + templateAddress + ) // Invoke add721TokenTemplate function of the contract const trxReceipt = await this.factory721.methods @@ -307,16 +310,11 @@ export class NftFactory { address: string, templateIndex: number ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.factory721.methods - .disable721TokenTemplate(templateIndex) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.factory721.methods.disable721TokenTemplate, + templateIndex + ) } /** @@ -339,7 +337,11 @@ export class NftFactory { if (templateIndex === 0) { throw new Error(`Template index cannot be ZERO`) } - const estGas = await this.estGasDisableNFTTemplate(address, templateIndex) + const estGas = await estimateGas( + address, + this.factory721.methods.disable721TokenTemplate, + templateIndex + ) // Invoke createToken function of the contract const trxReceipt = await this.factory721.methods @@ -363,16 +365,11 @@ export class NftFactory { address: string, templateIndex: number ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.factory721.methods - .reactivate721TokenTemplate(templateIndex) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.factory721.methods.reactivate721TokenTemplate, + templateIndex + ) } /** @@ -396,7 +393,11 @@ export class NftFactory { throw new Error(`Template index cannot be ZERO`) } - const estGas = await this.estGasReactivateNFTTemplate(address, templateIndex) + const estGas = await estimateGas( + address, + this.factory721.methods.reactivate721TokenTemplate, + templateIndex + ) // Invoke createToken function of the contract const trxReceipt = await this.factory721.methods @@ -420,17 +421,7 @@ export class NftFactory { address: string, templateAddress: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.factory721.methods - .addTokenTemplate(templateAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, this.factory721.methods.addTokenTemplate, templateAddress) } /** @@ -450,7 +441,11 @@ export class NftFactory { throw new Error(`Template cannot be address ZERO`) } - const estGas = await this.estGasAddTokenTemplate(address, templateAddress) + const estGas = await estimateGas( + address, + this.factory721.methods.addTokenTemplate, + templateAddress + ) // Invoke createToken function of the contract const trxReceipt = await this.factory721.methods @@ -474,16 +469,11 @@ export class NftFactory { address: string, templateIndex: number ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.factory721.methods - .disableTokenTemplate(templateIndex) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.factory721.methods.disableTokenTemplate, + templateIndex + ) } /** @@ -509,7 +499,11 @@ export class NftFactory { if ((await this.getTokenTemplate(templateIndex)).isActive === false) { throw new Error(`Template is already disabled`) } - const estGas = await this.estGasDisableTokenTemplate(address, templateIndex) + const estGas = await estimateGas( + address, + this.factory721.methods.disableTokenTemplate, + templateIndex + ) // Invoke createToken function of the contract const trxReceipt = await this.factory721.methods @@ -533,16 +527,11 @@ export class NftFactory { address: string, templateIndex: number ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.factory721.methods - .reactivateTokenTemplate(templateIndex) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.factory721.methods.reactivateTokenTemplate, + templateIndex + ) } /** @@ -569,7 +558,11 @@ export class NftFactory { throw new Error(`Template is already active`) } - const estGas = await this.estGasReactivateTokenTemplate(address, templateIndex) + const estGas = await estimateGas( + address, + this.factory721.methods.reactivateTokenTemplate, + templateIndex + ) // Invoke createToken function of the contract const trxReceipt = await this.factory721.methods @@ -592,16 +585,7 @@ export class NftFactory { address: string, orders: TokenOrder[] ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.factory721.methods - .startMultipleTokenOrder(orders) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, this.factory721.methods.startMultipleTokenOrder, orders) } /** @@ -624,7 +608,11 @@ export class NftFactory { throw new Error(`Too many orders`) } - const estGas = await this.estGasStartMultipleTokenOrder(address, orders) + const estGas = await estimateGas( + address, + this.factory721.methods.startMultipleTokenOrder, + orders + ) // Invoke createToken function of the contract const trxReceipt = await this.factory721.methods @@ -651,18 +639,13 @@ export class NftFactory { nftCreateData: NftCreateData, ercParams: Erc20CreateParams ): Promise { - // Get estimated gas value - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - const ercCreateData = getErcCreationParams(ercParams) - estGas = await this.factory721.methods - .createNftWithErc20(nftCreateData, ercCreateData) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + const ercCreateData = getErcCreationParams(ercParams) + return estimateGas( + address, + this.factory721.methods.createNftWithErc20, + nftCreateData, + ercCreateData + ) } /** @@ -681,7 +664,13 @@ export class NftFactory { ): Promise { const ercCreateData = getErcCreationParams(ercParams) - const estGas = await this.estGasCreateNftWithErc20(address, nftCreateData, ercParams) + const estGas = await estimateGas( + address, + this.factory721.methods.createNftWithErc20, + nftCreateData, + ercCreateData + ) + // Invoke createToken function of the contract const trxReceipt = await this.factory721.methods .createNftWithErc20(nftCreateData, ercCreateData) @@ -708,18 +697,15 @@ export class NftFactory { ercParams: Erc20CreateParams, poolParams: PoolCreationParams ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - const ercCreateData = getErcCreationParams(ercParams) - const poolData = await getPoolCreationParams(this.web3, poolParams) - estGas = await this.factory721.methods - .createNftWithErc20WithPool(nftCreateData, ercCreateData, poolData) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + const ercCreateData = getErcCreationParams(ercParams) + const poolData = await getPoolCreationParams(this.web3, poolParams) + return estimateGas( + address, + this.factory721.methods.createNftWithErc20WithPool, + nftCreateData, + ercCreateData, + poolData + ) } /** @@ -738,15 +724,17 @@ export class NftFactory { ercParams: Erc20CreateParams, poolParams: PoolCreationParams ): Promise { - const estGas = await this.estGasCreateNftErc20WithPool( - address, - nftCreateData, - ercParams, - poolParams - ) const ercCreateData = getErcCreationParams(ercParams) const poolData = await getPoolCreationParams(this.web3, poolParams) + const estGas = await estimateGas( + address, + this.factory721.methods.createNftWithErc20WithPool, + nftCreateData, + ercCreateData, + poolData + ) + // Invoke createToken function of the contract const trxReceipt = await this.factory721.methods .createNftWithErc20WithPool(nftCreateData, ercCreateData, poolData) @@ -772,20 +760,15 @@ export class NftFactory { ercParams: Erc20CreateParams, freParams: FreCreationParams ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - const ercCreateData = getErcCreationParams(ercParams) const fixedData = await getFreCreationParams(freParams) - - try { - estGas = await this.factory721.methods - .createNftWithErc20WithFixedRate(nftCreateData, ercCreateData, fixedData) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.factory721.methods.createNftWithErc20WithFixedRate, + nftCreateData, + ercCreateData, + fixedData + ) } /** @@ -807,11 +790,12 @@ export class NftFactory { const ercCreateData = getErcCreationParams(ercParams) const fixedData = getFreCreationParams(freParams) - const estGas = await this.estGasCreateNftErc20WithFixedRate( + const estGas = await estimateGas( address, + this.factory721.methods.createNftWithErc20WithFixedRate, nftCreateData, - ercParams, - freParams + ercCreateData, + fixedData ) // Invoke createToken function of the contract @@ -839,20 +823,14 @@ export class NftFactory { ercParams: Erc20CreateParams, dispenserParams: DispenserCreationParams ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - const ercCreateData = getErcCreationParams(ercParams) - - try { - estGas = await this.factory721.methods - .createNftWithErc20WithDispenser(nftCreateData, ercCreateData, dispenserParams) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - LoggerInstance.error('Failed to estimate gas for createNftErc20WithDispenser', e) - } - return estGas + return estimateGas( + address, + this.factory721.methods.createNftWithErc20WithDispenser, + nftCreateData, + ercCreateData, + dispenserParams + ) } /** @@ -876,10 +854,11 @@ export class NftFactory { dispenserParams.maxBalance = Web3.utils.toWei(dispenserParams.maxBalance) dispenserParams.maxTokens = Web3.utils.toWei(dispenserParams.maxTokens) - const estGas = await this.estGasCreateNftErc20WithDispenser( + const estGas = await estimateGas( address, + this.factory721.methods.createNftWithErc20WithDispenser, nftCreateData, - ercParams, + ercCreateData, dispenserParams ) diff --git a/src/pools/Router.ts b/src/pools/Router.ts index a111eec4..25567847 100644 --- a/src/pools/Router.ts +++ b/src/pools/Router.ts @@ -3,7 +3,7 @@ import Web3 from 'web3' import { TransactionReceipt } from 'web3-core' import { AbiItem } from 'web3-utils' import defaultRouter from '@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json' -import { getFairGasPrice, setContractDefaults, ConfigHelper } from '../utils' +import { getFairGasPrice, setContractDefaults, ConfigHelper, estimateGas } from '../utils' import { Operation } from '../@types/Router' import { Config } from '../models/index.js' @@ -11,7 +11,6 @@ import { Config } from '../models/index.js' * Provides an interface for FactoryRouter contract */ export class Router { - public GASLIMIT_DEFAULT = 1000000 public routerAddress: string public RouterAbi: AbiItem | AbiItem[] public web3: Web3 @@ -48,16 +47,7 @@ export class Router { * @return {Promise} Transaction receipt */ public async estGasBuyDTBatch(address: string, operations: Operation[]): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .buyDTBatch(operations) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, this.router.methods.buyDTBatch, operations) } /** @@ -70,7 +60,7 @@ export class Router { address: string, operations: Operation[] ): Promise { - const estGas = await this.estGasBuyDTBatch(address, operations) + const estGas = await estimateGas(address, this.router.methods.buyDTBatch, operations) // Invoke createToken function of the contract const trxReceipt = await this.router.methods.buyDTBatch(operations).send({ @@ -135,19 +125,8 @@ export class Router { address: string, tokenAddress: string, contractInstance?: Contract - ) { - const routerContract = contractInstance || this.router - - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await routerContract.methods - .addApprovedToken(tokenAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + ): Promise { + return estimateGas(address, this.router.methods.addApprovedToken, tokenAddress) } /** @@ -164,7 +143,11 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasAddApprovedToken(address, tokenAddress) + const estGas = await estimateGas( + address, + this.router.methods.addApprovedToken, + tokenAddress + ) // Invoke createToken function of the contract const trxReceipt = await this.router.methods.addApprovedToken(tokenAddress).send({ @@ -187,19 +170,8 @@ export class Router { address: string, tokenAddress: string, contractInstance?: Contract - ) { - const routerContract = contractInstance || this.router - - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await routerContract.methods - .removeApprovedToken(tokenAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + ): Promise { + return estimateGas(address, this.router.methods.removeApprovedToken, tokenAddress) } /** @@ -216,7 +188,11 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasRemoveApprovedToken(address, tokenAddress) + const estGas = await estimateGas( + address, + this.router.methods.removeApprovedToken, + tokenAddress + ) // Invoke createToken function of the contract const trxReceipt = await this.router.methods.removeApprovedToken(tokenAddress).send({ @@ -235,17 +211,7 @@ export class Router { * @return {Promise} */ public async estGasAddSSContract(address: string, tokenAddress: string): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .addSSContract(tokenAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, this.router.methods.addSSContract, tokenAddress) } /** @@ -262,7 +228,12 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasAddSSContract(address, tokenAddress) + const estGas = await estimateGas( + address, + this.router.methods.addSSContract, + tokenAddress + ) + // Invoke createToken function of the contract const trxReceipt = await this.router.methods.addSSContract(tokenAddress).send({ from: address, @@ -283,17 +254,7 @@ export class Router { address: string, tokenAddress: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .removeSSContract(tokenAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, this.router.methods.removeSSContract, tokenAddress) } /** @@ -310,7 +271,12 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasRemoveSSContract(address, tokenAddress) + const estGas = await estimateGas( + address, + this.router.methods.removeSSContract, + tokenAddress + ) + // Invoke createToken function of the contract const trxReceipt = await this.router.methods.removeSSContract(tokenAddress).send({ from: address, @@ -331,17 +297,7 @@ export class Router { address: string, tokenAddress: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .addFixedRateContract(tokenAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, this.router.methods.addFixedRateContract, tokenAddress) } /** @@ -358,7 +314,11 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasAddFixedRateContract(address, tokenAddress) + const estGas = await estimateGas( + address, + this.router.methods.addFixedRateContract, + tokenAddress + ) // Invoke createToken function of the contract const trxReceipt = await this.router.methods.addFixedRateContract(tokenAddress).send({ @@ -380,17 +340,7 @@ export class Router { address: string, tokenAddress: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .removeFixedRateContract(tokenAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, this.router.methods.removeFixedRateContract, tokenAddress) } /** @@ -407,7 +357,11 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasRemoveFixedRateContract(address, tokenAddress) + const estGas = await estimateGas( + address, + this.router.methods.removeFixedRateContract, + tokenAddress + ) // Invoke removeFixedRateContract function of the contract const trxReceipt = await this.router.methods @@ -431,17 +385,7 @@ export class Router { address: string, tokenAddress: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .addDispenserContract(tokenAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, this.router.methods.addDispenserContract, tokenAddress) } /** @@ -458,7 +402,11 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasAddDispenserContract(address, tokenAddress) + const estGas = await estimateGas( + address, + this.router.methods.addDispenserContract, + tokenAddress + ) // Invoke createToken function of the contract const trxReceipt = await this.router.methods.addDispenserContract(tokenAddress).send({ @@ -480,17 +428,7 @@ export class Router { address: string, tokenAddress: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .removeDispenserContract(tokenAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, this.router.methods.removeDispenserContract, tokenAddress) } /** @@ -507,7 +445,11 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasRemoveDispenserContract(address, tokenAddress) + const estGas = await estimateGas( + address, + this.router.methods.removeDispenserContract, + tokenAddress + ) // Invoke createToken function of the contract const trxReceipt = await this.router.methods @@ -548,17 +490,14 @@ export class Router { newConsumeFee: number, newProviderFee: number ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .updateOPCFee(newSwapOceanFee, newSwapNonOceanFee, newConsumeFee, newProviderFee) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + address, + this.router.methods.updateOPCFee, + newSwapOceanFee, + newSwapNonOceanFee, + newConsumeFee, + newProviderFee + ) } /** @@ -581,8 +520,9 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasUpdateOPCFee( + const estGas = await estimateGas( address, + this.router.methods.updateOPCFee, newSwapOceanFee, newSwapNonOceanFee, newConsumeFee, @@ -611,17 +551,7 @@ export class Router { address: string, templateAddress: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .addPoolTemplate(templateAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, this.router.methods.addPoolTemplate, templateAddress) } /** @@ -638,7 +568,11 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasAddPoolTemplate(address, templateAddress) + const estGas = await estimateGas( + address, + this.router.methods.addPoolTemplate, + templateAddress + ) // Invoke createToken function of the contract const trxReceipt = await this.router.methods.addPoolTemplate(templateAddress).send({ @@ -660,16 +594,7 @@ export class Router { address: string, templateAddress: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.router.methods - .removePoolTemplate(templateAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, this.router.methods.removePoolTemplate, templateAddress) } /** @@ -686,7 +611,11 @@ export class Router { throw new Error(`Caller is not Router Owner`) } - const estGas = await this.estGasRemovePoolTemplate(address, templateAddress) + const estGas = await estimateGas( + address, + this.router.methods.removePoolTemplate, + templateAddress + ) // Invoke createToken function of the contract const trxReceipt = await this.router.methods diff --git a/src/pools/balancer/Pool.ts b/src/pools/balancer/Pool.ts index 915131d6..95096265 100644 --- a/src/pools/balancer/Pool.ts +++ b/src/pools/balancer/Pool.ts @@ -8,6 +8,7 @@ import { unitsToAmount, amountToUnits, LoggerInstance, + estimateGas, ConfigHelper } from '../../utils' import BigNumber from 'bignumber.js' @@ -37,7 +38,6 @@ const MaxUint256 = export class Pool { public poolAbi: AbiItem | AbiItem[] public web3: Web3 - public GASLIMIT_DEFAULT = 1000000 private config: Config constructor( @@ -112,16 +112,7 @@ export class Pool { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await poolContract.methods - .setSwapFee(fee) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(account, poolContract.methods.setSwapFee, fee) } /** @@ -142,7 +133,7 @@ export class Pool { this.config ) let result = null - const estGas = await this.estSetSwapFee(account, poolAddress, fee) + const estGas = await estimateGas(account, pool.methods.setSwapFee, fee) try { result = await pool.methods.setSwapFee(this.web3.utils.toWei(fee)).send({ @@ -338,25 +329,6 @@ export class Pool { return result } - /** - * Get OPC Collector of this pool - * @param {String} poolAddress - * @return {String} - */ - async getOPCCollector(poolAddress: string): Promise { - const pool = setContractDefaults( - new this.web3.eth.Contract(this.poolAbi, poolAddress), - this.config - ) - let result = null - try { - result = await pool.methods._opcCollector().call() - } catch (e) { - LoggerInstance.error(`ERROR: Failed to get OPF Collector address: ${e.message}`) - } - return result - } - /** * Get if a token is bounded to a pool * Returns true if token is bound @@ -631,16 +603,7 @@ export class Pool { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await poolContract.methods - .collectOPC() - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, poolContract.methods.collectOPC) } /** @@ -655,7 +618,7 @@ export class Pool { this.config ) let result = null - const estGas = await this.estCollectOPC(address, poolAddress) + const estGas = await estimateGas(address, pool.methods.collectOPC) try { result = await pool.methods.collectOPC().send({ @@ -689,16 +652,7 @@ export class Pool { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await poolContract.methods - .collectMarketFee() - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, poolContract.methods.collectMarketFee) } /** @@ -720,7 +674,7 @@ export class Pool { this.config ) let result = null - const estGas = await this.estCollectMarketFee(address, poolAddress) + const estGas = await estimateGas(address, pool.methods.collectMarketFee) try { result = await pool.methods.collectMarketFee().send({ @@ -757,16 +711,12 @@ export class Pool { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await poolContract.methods - .updatePublishMarketFee(newPublishMarketAddress, newPublishMarketSwapFee) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + poolContract.methods.updatePublishMarketFee, + newPublishMarketAddress, + this.web3.utils.toWei(newPublishMarketSwapFee) + ) } /** @@ -792,9 +742,9 @@ export class Pool { ) let result = null - const estGas = await this.estUpdatePublishMarketFee( + const estGas = await estimateGas( address, - poolAddress, + pool.methods.updatePublishMarketFee, newPublishMarketAddress, this.web3.utils.toWei(newPublishMarketSwapFee) ) @@ -857,28 +807,21 @@ export class Pool { ) : MaxUint256 - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await poolContract.methods - .swapExactAmountIn( - [ - tokenInOutMarket.tokenIn, - tokenInOutMarket.tokenOut, - tokenInOutMarket.marketFeeAddress - ], - [ - tokenAmountIn, - minAmountOut, - maxPrice, - this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee) - ] - ) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + poolContract.methods.swapExactAmountIn, + [ + tokenInOutMarket.tokenIn, + tokenInOutMarket.tokenOut, + tokenInOutMarket.marketFeeAddress + ], + [ + tokenAmountIn, + minAmountOut, + maxPrice, + this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee) + ] + ) } /** @@ -910,13 +853,6 @@ export class Pool { throw new Error(`tokenAmountIn is greater than ${maxSwap.toString()}`) } - const estGas = await this.estSwapExactAmountIn( - address, - poolAddress, - tokenInOutMarket, - amountsInOutMaxFee - ) - const tokenAmountIn = await this.amountToUnits( tokenInOutMarket.tokenIn, amountsInOutMaxFee.tokenAmountIn, @@ -929,8 +865,6 @@ export class Pool { tokenInOutMarket.tokenOutDecimals ) - let result = null - const maxPrice = amountsInOutMaxFee.maxPrice ? await this.amountToUnits( await this.getBaseToken(poolAddress), @@ -938,6 +872,23 @@ export class Pool { ) : MaxUint256 + const estGas = await estimateGas( + address, + pool.methods.swapExactAmountIn, + [ + tokenInOutMarket.tokenIn, + tokenInOutMarket.tokenOut, + tokenInOutMarket.marketFeeAddress + ], + [ + tokenAmountIn, + minAmountOut, + maxPrice, + this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee) + ] + ) + + let result = null try { result = await pool.methods .swapExactAmountIn( @@ -988,8 +939,6 @@ export class Pool { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - const maxAmountIn = await this.amountToUnits( tokenInOutMarket.tokenIn, amountsInOutMaxFee.maxAmountIn, @@ -1009,27 +958,21 @@ export class Pool { ) : MaxUint256 - let estGas - try { - estGas = await poolContract.methods - .swapExactAmountOut( - [ - tokenInOutMarket.tokenIn, - tokenInOutMarket.tokenOut, - tokenInOutMarket.marketFeeAddress - ], - [ - maxAmountIn, - tokenAmountOut, - maxPrice, - this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee) - ] - ) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + poolContract.methods.swapExactAmountOut, + [ + tokenInOutMarket.tokenIn, + tokenInOutMarket.tokenOut, + tokenInOutMarket.marketFeeAddress + ], + [ + maxAmountIn, + tokenAmountOut, + maxPrice, + this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee) + ] + ) } /** @@ -1057,13 +1000,6 @@ export class Pool { throw new Error(`tokenAmountOut is greater than ${maxSwap.toString()}`) } - const estGas = await this.estSwapExactAmountOut( - account, - poolAddress, - tokenInOutMarket, - amountsInOutMaxFee - ) - const maxAmountIn = await this.amountToUnits( tokenInOutMarket.tokenIn, amountsInOutMaxFee.maxAmountIn, @@ -1083,6 +1019,22 @@ export class Pool { ) : MaxUint256 + const estGas = await estimateGas( + account, + pool.methods.swapExactAmountOut, + [ + tokenInOutMarket.tokenIn, + tokenInOutMarket.tokenOut, + tokenInOutMarket.marketFeeAddress + ], + [ + maxAmountIn, + tokenAmountOut, + maxPrice, + this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee) + ] + ) + try { result = await pool.methods .swapExactAmountOut( @@ -1133,16 +1085,12 @@ export class Pool { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await poolContract.methods - .joinswapExternAmountIn(tokenAmountIn, minPoolAmountOut) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + poolContract.methods.joinswapExternAmountIn, + tokenAmountIn, + minPoolAmountOut + ) } /** @@ -1179,9 +1127,9 @@ export class Pool { tokenAmountIn, tokenInDecimals ) - const estGas = await this.estJoinswapExternAmountIn( + const estGas = await estimateGas( account, - poolAddress, + pool.methods.joinswapExternAmountIn, amountInFormatted, this.web3.utils.toWei(minPoolAmountOut) ) @@ -1227,16 +1175,12 @@ export class Pool { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await poolContract.methods - .exitswapPoolAmountIn(poolAmountIn, minTokenAmountOut) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + poolContract.methods.exitswapPoolAmountIn, + poolAmountIn, + minTokenAmountOut + ) } /** @@ -1280,9 +1224,9 @@ export class Pool { minTokenAmountOut, poolDecimals ) - const estGas = await this.estExitswapPoolAmountIn( + const estGas = await estimateGas( account, - poolAddress, + pool.methods.exitswapPoolAmountIn, this.web3.utils.toWei(poolAmountIn), minTokenOutFormatted ) diff --git a/src/pools/dispenser/Dispenser.ts b/src/pools/dispenser/Dispenser.ts index 31916eb8..c26e0ea4 100644 --- a/src/pools/dispenser/Dispenser.ts +++ b/src/pools/dispenser/Dispenser.ts @@ -8,6 +8,7 @@ import { LoggerInstance as logger, getFairGasPrice, setContractDefaults, + estimateGas, ConfigHelper } from '../../utils/' import { Datatoken } from '../../tokens' @@ -24,7 +25,6 @@ export interface DispenserToken { } export class Dispenser { - public GASLIMIT_DEFAULT = 1000000 public web3: Web3 = null public dispenserAddress: string public config: Config @@ -91,23 +91,15 @@ export class Dispenser { maxBalance: string, allowedSwapper: string ): Promise { - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await this.dispenserContract.methods - .create( - dtAddress, - this.web3.utils.toWei(maxTokens), - this.web3.utils.toWei(maxBalance), - address, - allowedSwapper - ) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + address, + this.dispenserContract.methods.create, + dtAddress, + this.web3.utils.toWei(maxTokens), + this.web3.utils.toWei(maxBalance), + address, + allowedSwapper + ) } /** @@ -126,11 +118,13 @@ export class Dispenser { maxBalance: string, allowedSwapper: string ): Promise { - const estGas = await this.estGasCreate( - dtAddress, + const estGas = await estimateGas( + address, + this.dispenserContract.methods.create, + dtAddress, + this.web3.utils.toWei(maxTokens), + this.web3.utils.toWei(maxBalance), address, - maxTokens, - maxBalance, allowedSwapper ) @@ -165,20 +159,13 @@ export class Dispenser { maxBalance: string, address: string ): Promise { - let estGas - const gasLimitDefault = this.GASLIMIT_DEFAULT - try { - estGas = await this.dispenserContract.methods - .activate( - dtAddress, - this.web3.utils.toWei(maxTokens), - this.web3.utils.toWei(maxBalance) - ) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.dispenserContract.methods.activate, + dtAddress, + this.web3.utils.toWei(maxTokens), + this.web3.utils.toWei(maxBalance) + ) } /** @@ -196,7 +183,14 @@ export class Dispenser { address: string ): Promise { try { - const estGas = await this.estGasActivate(dtAddress, maxTokens, maxBalance, address) + const estGas = await estimateGas( + address, + this.dispenserContract.methods.activate, + dtAddress, + this.web3.utils.toWei(maxTokens), + this.web3.utils.toWei(maxBalance) + ) + const trxReceipt = await this.dispenserContract.methods .activate( dtAddress, @@ -222,16 +216,7 @@ export class Dispenser { * @return {Promise} */ public async estGasDeactivate(dtAddress: string, address: string): Promise { - let estGas - const gasLimitDefault = this.GASLIMIT_DEFAULT - try { - estGas = await this.dispenserContract.methods - .deactivate(dtAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, this.dispenserContract.methods.deactivate, dtAddress) } /** @@ -245,7 +230,12 @@ export class Dispenser { address: string ): Promise { try { - const estGas = await this.estGasDeactivate(dtAddress, address) + const estGas = await estimateGas( + address, + this.dispenserContract.methods.deactivate, + dtAddress + ) + const trxReceipt = await this.dispenserContract.methods.deactivate(dtAddress).send({ from: address, gas: estGas + 1, @@ -270,16 +260,12 @@ export class Dispenser { address: string, newAllowedSwapper: string ): Promise { - let estGas - const gasLimitDefault = this.GASLIMIT_DEFAULT - try { - estGas = await this.dispenserContract.methods - .setAllowedSwapper(dtAddress, newAllowedSwapper) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.dispenserContract.methods.setAllowedSwapper, + dtAddress, + newAllowedSwapper + ) } /** @@ -295,11 +281,13 @@ export class Dispenser { newAllowedSwapper: string ): Promise { try { - const estGas = await this.estGasSetAllowedSwapper( - dtAddress, + const estGas = await estimateGas( address, + this.dispenserContract.methods.setAllowedSwapper, + dtAddress, newAllowedSwapper ) + const trxReceipt = await this.dispenserContract.methods .setAllowedSwapper(dtAddress, newAllowedSwapper) .send({ @@ -327,16 +315,13 @@ export class Dispenser { amount: string = '1', destination: string ): Promise { - let estGas - const gasLimitDefault = this.GASLIMIT_DEFAULT - try { - estGas = await this.dispenserContract.methods - .dispense(dtAddress, this.web3.utils.toWei(amount), destination) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + this.dispenserContract.methods.dispense, + dtAddress, + this.web3.utils.toWei(amount), + destination + ) } /** @@ -355,7 +340,14 @@ export class Dispenser { amount: string = '1', destination: string ): Promise { - const estGas = await this.estGasDispense(dtAddress, address, amount, destination) + const estGas = await estimateGas( + address, + this.dispenserContract.methods.dispense, + dtAddress, + this.web3.utils.toWei(amount), + destination + ) + try { const trxReceipt = await this.dispenserContract.methods .dispense(dtAddress, this.web3.utils.toWei(amount), destination) @@ -379,16 +371,7 @@ export class Dispenser { * @return {Promise} */ public async estGasOwnerWithdraw(dtAddress: string, address: string): Promise { - let estGas - const gasLimitDefault = this.GASLIMIT_DEFAULT - try { - estGas = await this.dispenserContract.methods - .ownerWithdraw(dtAddress) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, this.dispenserContract.methods.ownerWithdraw, dtAddress) } /** @@ -401,7 +384,12 @@ export class Dispenser { dtAddress: string, address: string ): Promise { - const estGas = await this.estGasOwnerWithdraw(dtAddress, address) + const estGas = await estimateGas( + address, + this.dispenserContract.methods.ownerWithdraw, + dtAddress + ) + try { const trxReceipt = await this.dispenserContract.methods .ownerWithdraw(dtAddress) diff --git a/src/pools/fixedRate/FixedRateExchange.ts b/src/pools/fixedRate/FixedRateExchange.ts index e1bdcf56..75c381cf 100644 --- a/src/pools/fixedRate/FixedRateExchange.ts +++ b/src/pools/fixedRate/FixedRateExchange.ts @@ -9,6 +9,7 @@ import { setContractDefaults, amountToUnits, unitsToAmount, + estimateGas, ZERO_ADDRESS, ConfigHelper } from '../../utils' @@ -55,7 +56,6 @@ export enum FixedRateCreateProgressStep { /* eslint-enable no-unused-vars */ export class FixedRateExchange { - public GASLIMIT_DEFAULT = 1000000 /** Ocean related functions */ public oceanAddress: string = null public fixedRateAddress: string @@ -141,22 +141,16 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .buyDT( - datatokenAddress, - dtAmount, - maxBaseTokenAmount, - consumeMarketAddress, - consumeMarketFee - ) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas( + account, + fixedRate.methods.buyDT, + datatokenAddress, + dtAmount, + maxBaseTokenAmount, + consumeMarketAddress, + consumeMarketFee + ) } /** @@ -190,8 +184,9 @@ export class FixedRateExchange { +exchange.btDecimals ) - const estGas = await this.estBuyDT( + const estGas = await estimateGas( address, + this.contract.methods.buyDT, exchangeId, dtAmountFormatted, maxBtFormatted, @@ -239,22 +234,16 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .sellDT( - datatokenAddress, - dtAmount, - maxBaseTokenAmount, - consumeMarketAddress, - consumeMarketFee - ) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas( + account, + fixedRate.methods.sellDT, + datatokenAddress, + dtAmount, + maxBaseTokenAmount, + consumeMarketAddress, + consumeMarketFee + ) } /** @@ -287,8 +276,9 @@ export class FixedRateExchange { minBaseTokenAmount, +exchange.btDecimals ) - const estGas = await this.estBuyDT( + const estGas = await estimateGas( address, + this.contract.methods.sellDT, exchangeId, dtAmountFormatted, minBtFormatted, @@ -342,16 +332,13 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .setRate(exchangeId, await this.web3.utils.toWei(newRate)) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas( + account, + fixedRate.methods.setRate, + exchangeId, + await this.web3.utils.toWei(newRate) + ) } /** @@ -366,7 +353,12 @@ export class FixedRateExchange { exchangeId: string, newRate: string ): Promise { - const estGas = await this.estSetRate(address, exchangeId, newRate) + const estGas = await estimateGas( + address, + this.contract.methods.setRate, + exchangeId, + this.web3.utils.toWei(newRate) + ) const trxReceipt = await this.contract.methods .setRate(exchangeId, this.web3.utils.toWei(newRate)) .send({ @@ -392,16 +384,8 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .setRate(exchangeId, newAllowedSwapper) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas(account, fixedRate.methods.setRate, exchangeId, newAllowedSwapper) } /** @@ -416,7 +400,12 @@ export class FixedRateExchange { exchangeId: string, newAllowedSwapper: string ): Promise { - const estGas = await this.estSetAllowedSwapper(address, exchangeId, newAllowedSwapper) + const estGas = await estimateGas( + address, + this.contract.methods.setAllowedSwapper, + exchangeId, + newAllowedSwapper + ) const trxReceipt = await this.contract.methods .setAllowedSwapper(exchangeId, newAllowedSwapper) .send({ @@ -440,16 +429,8 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .toggleExchangeState(exchangeId) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas(account, fixedRate.methods.toggleExchangeState, exchangeId) } /** @@ -466,7 +447,11 @@ export class FixedRateExchange { if (!exchange) return null if (exchange.active === true) return null - const estGas = await this.estActivate(address, exchangeId) + const estGas = await estimateGas( + address, + this.contract.methods.toggleExchangeState, + exchangeId + ) const trxReceipt = await this.contract.methods.toggleExchangeState(exchangeId).send({ from: address, gas: estGas + 1, @@ -488,16 +473,8 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .toggleExchangeState(exchangeId) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas(account, fixedRate.methods.toggleExchangeState, exchangeId) } /** @@ -514,7 +491,11 @@ export class FixedRateExchange { if (!exchange) return null if (exchange.active === false) return null - const estGas = await this.estDeactivate(address, exchangeId) + const estGas = await estimateGas( + address, + this.contract.methods.toggleExchangeState, + exchangeId + ) const trxReceipt = await this.contract.methods.toggleExchangeState(exchangeId).send({ from: address, @@ -739,16 +720,8 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .toggleMintState(exchangeId, true) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas(account, fixedRate.methods.toggleMintState, exchangeId, true) } /** @@ -765,7 +738,12 @@ export class FixedRateExchange { if (!exchange) return null if (exchange.withMint === true) return null - const estGas = await this.estActivateMint(address, exchangeId) + const estGas = await estimateGas( + address, + this.contract.methods.toggleMintState, + exchangeId, + true + ) const trxReceipt = await this.contract.methods .toggleMintState(exchangeId, true) .send({ @@ -789,16 +767,8 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .toggleMintState(exchangeId) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas(account, fixedRate.methods.toggleMintState, exchangeId) } /** @@ -815,7 +785,12 @@ export class FixedRateExchange { if (!exchange) return null if (exchange.withMint === false) return null - const estGas = await this.estDeactivate(address, exchangeId) + const estGas = await estimateGas( + address, + this.contract.methods.toggleMintState, + exchangeId, + false + ) const trxReceipt = await this.contract.methods .toggleMintState(exchangeId, false) @@ -843,8 +818,6 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas const fixedrate: FixedPriceExchange = await this.contract.methods .getExchange(exchangeId) .call() @@ -853,14 +826,7 @@ export class FixedRateExchange { amount, +fixedrate.btDecimals ) - try { - estGas = await fixedRate.methods - .collectBT(exchangeId, amountWei) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(account, fixedRate.methods.collectBT, exchangeId, amountWei) } /** @@ -878,7 +844,6 @@ export class FixedRateExchange { const exchange = await this.getExchange(exchangeId) if (!exchange) return null - const estGas = await this.estCollectBT(address, exchangeId, amount) const fixedrate: FixedPriceExchange = await this.contract.methods .getExchange(exchangeId) .call() @@ -887,6 +852,14 @@ export class FixedRateExchange { amount, +fixedrate.btDecimals ) + + const estGas = await estimateGas( + address, + this.contract.methods.collectBT, + exchangeId, + amountWei + ) + const trxReceipt = await this.contract.methods.collectBT(exchangeId, amountWei).send({ from: address, gas: estGas + 1, @@ -910,24 +883,16 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas const fixedrate: FixedPriceExchange = await this.contract.methods .getExchange(exchangeId) .call() + const amountWei = await this.amountToUnits( fixedrate.datatoken, amount, +fixedrate.dtDecimals ) - try { - estGas = await fixedRate.methods - .collectDT(exchangeId, amountWei) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(account, fixedRate.methods.collectDT, exchangeId, amountWei) } /** @@ -945,7 +910,6 @@ export class FixedRateExchange { const exchange = await this.getExchange(exchangeId) if (!exchange) return null - const estGas = await this.estCollectDT(address, exchangeId, amount) const fixedrate: FixedPriceExchange = await this.contract.methods .getExchange(exchangeId) .call() @@ -954,6 +918,14 @@ export class FixedRateExchange { amount, +fixedrate.dtDecimals ) + + const estGas = await estimateGas( + address, + this.contract.methods.collectDT, + exchangeId, + amountWei + ) + const trxReceipt = await this.contract.methods.collectDT(exchangeId, amountWei).send({ from: address, gas: estGas + 1, @@ -975,16 +947,8 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .collectMarketFee(exchangeId) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas(account, fixedRate.methods.collectMarketFee, exchangeId) } /** @@ -1000,7 +964,11 @@ export class FixedRateExchange { const exchange = await this.getExchange(exchangeId) if (!exchange) return null - const estGas = await this.estCollectMarketFee(address, exchangeId) + const estGas = await estimateGas( + address, + this.contract.methods.collectMarketFee, + exchangeId + ) const trxReceipt = await this.contract.methods.collectMarketFee(exchangeId).send({ from: address, gas: estGas + 1, @@ -1022,16 +990,8 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .collectMarketFee(exchangeId) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas(account, fixedRate.methods.collectMarketFee, exchangeId) } /** @@ -1047,7 +1007,11 @@ export class FixedRateExchange { const exchange = await this.getExchange(exchangeId) if (!exchange) return null - const estGas = await this.estCollectOceanFee(address, exchangeId) + const estGas = await estimateGas( + address, + this.contract.methods.collectOceanFee, + exchangeId + ) const trxReceipt = await this.contract.methods.collectOceanFee(exchangeId).send({ from: address, gas: estGas + 1, @@ -1056,20 +1020,6 @@ export class FixedRateExchange { return trxReceipt } - /** - * Get OPF Collector of fixed rate contract - * @return {String} - */ - async getOPCCollector(): Promise { - let result = null - try { - result = await this.contract.methods.opcCollector().call() - } catch (e) { - LoggerInstance.error(`ERROR: Failed to get OPC Collector address: ${e.message}`) - } - return result - } - /** * Get Router address set in fixed rate contract * @return {String} @@ -1114,16 +1064,13 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .updateMarketFee(exchangeId, newMarketFee) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas( + account, + fixedRate.methods.updateMarketFee, + exchangeId, + newMarketFee + ) } /** @@ -1138,8 +1085,9 @@ export class FixedRateExchange { exchangeId: string, newMarketFee: string ): Promise { - const estGas = await this.estSetRate( + const estGas = await estimateGas( address, + this.contract.methods.updateMarketFee, exchangeId, this.web3.utils.toWei(newMarketFee) ) @@ -1168,16 +1116,13 @@ export class FixedRateExchange { contractInstance?: Contract ): Promise { const fixedRate = contractInstance || this.fixedRateContract - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await fixedRate.methods - .updateMarketFeeCollector(exchangeId, newMarketFeeCollector) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + + return estimateGas( + account, + fixedRate.methods.updateMarketFeeCollector, + exchangeId, + newMarketFeeCollector + ) } /** @@ -1192,8 +1137,9 @@ export class FixedRateExchange { exchangeId: string, newMarketFeeCollector: string ): Promise { - const estGas = await this.estUpdateMarketFeeCollector( + const estGas = await estimateGas( address, + this.contract.methods.updateMarketFeeCollector, exchangeId, newMarketFeeCollector ) diff --git a/src/pools/ssContracts/SideStaking.ts b/src/pools/ssContracts/SideStaking.ts index 957514bf..154ea1a5 100644 --- a/src/pools/ssContracts/SideStaking.ts +++ b/src/pools/ssContracts/SideStaking.ts @@ -2,14 +2,19 @@ import Web3 from 'web3' import { AbiItem } from 'web3-utils/types' import { TransactionReceipt } from 'web3-core' import { Contract } from 'web3-eth-contract' -import { LoggerInstance, getFairGasPrice, ConfigHelper, unitsToAmount } from '../../utils' +import { + LoggerInstance, + getFairGasPrice, + ConfigHelper, + estimateGas, + unitsToAmount +} from '../../utils' import SideStakingTemplate from '@oceanprotocol/contracts/artifacts/contracts/pools/ssContracts/SideStaking.sol/SideStaking.json' import { Config } from '../../models' export class SideStaking { public ssAbi: AbiItem | AbiItem[] public web3: Web3 - public GASLIMIT_DEFAULT = 1000000 public config: Config constructor( @@ -274,16 +279,7 @@ export class SideStaking { const sideStaking = contractInstance || new this.web3.eth.Contract(this.ssAbi as AbiItem[], ssAddress) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await sideStaking.methods - .getVesting(datatokenAddress) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(account, sideStaking.methods.getVesting, datatokenAddress) } /** Send vested tokens available to the publisher address, can be called by anyone @@ -301,12 +297,12 @@ export class SideStaking { const sideStaking = new this.web3.eth.Contract(this.ssAbi, ssAddress) let result = null - const estGas = await this.estGetVesting( + const estGas = await estimateGas( account, - ssAddress, - datatokenAddress, - sideStaking + sideStaking.methods.getVesting, + datatokenAddress ) + try { result = await sideStaking.methods.getVesting(datatokenAddress).send({ from: account, @@ -338,16 +334,13 @@ export class SideStaking { const sideStaking = contractInstance || new this.web3.eth.Contract(this.ssAbi as AbiItem[], ssAddress) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await sideStaking.methods - .setPoolSwapFee(datatokenAddress, poolAddress, swapFee) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + account, + sideStaking.methods.setPoolSwapFee, + datatokenAddress, + poolAddress, + swapFee + ) } /** Send vested tokens available to the publisher address, can be called by anyone @@ -367,14 +360,14 @@ export class SideStaking { const sideStaking = new this.web3.eth.Contract(this.ssAbi, ssAddress) let result = null - const estGas = await this.estSetPoolSwapFee( + const estGas = await estimateGas( account, - ssAddress, + sideStaking.methods.setPoolSwapFee, datatokenAddress, poolAddress, - swapFee, - sideStaking + swapFee ) + try { result = await sideStaking.methods .setPoolSwapFee(datatokenAddress, poolAddress, swapFee) diff --git a/src/tokens/Datatoken.ts b/src/tokens/Datatoken.ts index d1197b5f..152cc498 100644 --- a/src/tokens/Datatoken.ts +++ b/src/tokens/Datatoken.ts @@ -10,6 +10,7 @@ import { getFairGasPrice, setContractDefaults, getFreOrderParams, + estimateGas, ZERO_ADDRESS, ConfigHelper } from '../utils' @@ -45,7 +46,6 @@ export interface DispenserParams { } export class Datatoken { - public GASLIMIT_DEFAULT = 1000000 public factoryAddress: string public factoryABI: AbiItem | AbiItem[] public datatokensAbi: AbiItem | AbiItem[] @@ -97,17 +97,12 @@ export class Datatoken { this.config ) - // Estimate gas cost for mint method - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .approve(spender, this.web3.utils.toWei(amount)) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + dtContract.methods.approve, + spender, + this.web3.utils.toWei(amount) + ) } /** @@ -129,12 +124,11 @@ export class Datatoken { this.config ) - const estGas = await this.estGasApprove( - dtAddress, - spender, - amount, + const estGas = await estimateGas( address, - dtContract + dtContract.methods.approve, + spender, + this.web3.utils.toWei(amount) ) // Call mint contract method @@ -171,17 +165,12 @@ export class Datatoken { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .mint(toAddress || address, this.web3.utils.toWei(amount)) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + address, + dtContract.methods.mint, + toAddress || address, + this.web3.utils.toWei(amount) + ) } /** @@ -206,36 +195,27 @@ export class Datatoken { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - if (!fixedRateParams.allowedConsumer) fixedRateParams.allowedConsumer = ZERO_ADDRESS const withMint = fixedRateParams.withMint ? 1 : 0 - let estGas - try { - estGas = await dtContract.methods - .createFixedRate( - fixedRateParams.fixedRateAddress, - [ - fixedRateParams.baseTokenAddress, - address, - fixedRateParams.marketFeeCollector, - fixedRateParams.allowedConsumer - ], - [ - fixedRateParams.baseTokenDecimals, - fixedRateParams.datatokenDecimals, - fixedRateParams.fixedRate, - fixedRateParams.marketFee, - withMint - ] - ) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + address, + dtContract.methods.createFixedRate, + fixedRateParams.fixedRateAddress, + [ + fixedRateParams.baseTokenAddress, + address, + fixedRateParams.marketFeeCollector, + fixedRateParams.allowedConsumer + ], + [ + fixedRateParams.baseTokenDecimals, + fixedRateParams.datatokenDecimals, + fixedRateParams.fixedRate, + fixedRateParams.marketFee, + withMint + ] + ) } /** @@ -264,11 +244,23 @@ export class Datatoken { // should check ERC20Deployer role using erc721 level .. - const estGas = await this.estGasCreateFixedRate( - dtAddress, + const estGas = await estimateGas( address, - fixedRateParams, - dtContract + dtContract.methods.createFixedRate, + fixedRateParams.fixedRateAddress, + [ + fixedRateParams.baseTokenAddress, + fixedRateParams.owner, + fixedRateParams.marketFeeCollector, + fixedRateParams.allowedConsumer + ], + [ + fixedRateParams.baseTokenDecimals, + fixedRateParams.datatokenDecimals, + fixedRateParams.fixedRate, + fixedRateParams.marketFee, + withMint + ] ) // Call createFixedRate contract method @@ -324,23 +316,15 @@ export class Datatoken { if (!dispenserParams.withMint) dispenserParams.withMint = false - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .createDispenser( - dispenserAddress, - dispenserParams.maxTokens, - dispenserParams.maxBalance, - dispenserParams.withMint, - dispenserParams.allowedSwapper - ) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + address, + dtContract.methods.createDispenser, + dispenserAddress, + dispenserParams.maxTokens, + dispenserParams.maxBalance, + dispenserParams.withMint, + dispenserParams.allowedSwapper + ) } /** @@ -372,12 +356,14 @@ export class Datatoken { // should check ERC20Deployer role using erc721 level .. - const estGas = await this.estGasCreateDispenser( - dtAddress, + const estGas = await estimateGas( address, + dtContract.methods.createDispenser, dispenserAddress, - dispenserParams, - dtContract + dispenserParams.maxTokens, + dispenserParams.maxBalance, + dispenserParams.withMint, + dispenserParams.allowedSwapper ) // Call createFixedRate contract method @@ -422,12 +408,11 @@ export class Datatoken { const capAvailble = await this.getCap(dtAddress) if (new Decimal(capAvailble).gte(amount)) { - const estGas = await this.estGasMint( - dtAddress, + const estGas = await estimateGas( address, - amount, - toAddress, - dtContract + dtContract.methods.mint, + toAddress || address, + this.web3.utils.toWei(amount) ) // Call mint contract method @@ -465,17 +450,7 @@ export class Datatoken { this.config ) - // Estimate gas cost for addMinter method - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .addMinter(minter) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, dtContract.methods.addMinter, minter) } /** @@ -500,7 +475,7 @@ export class Datatoken { throw new Error(`Caller is not ERC20Deployer`) } // Estimate gas cost for addMinter method - const estGas = await this.estGasAddMinter(dtAddress, address, minter, dtContract) + const estGas = await estimateGas(address, dtContract.methods.addMinter, minter) // Call addMinter function of the contract const trxReceipt = await dtContract.methods.addMinter(minter).send({ @@ -535,18 +510,7 @@ export class Datatoken { // should check ERC20Deployer role using erc721 level .. - // Estimate gas for removeMinter method - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .removeMinter(minter) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, dtContract.methods.removeMinter, minter) } /** @@ -572,7 +536,7 @@ export class Datatoken { throw new Error(`Caller is not ERC20Deployer`) } - const estGas = await this.estGasRemoveMinter(dtAddress, address, minter, dtContract) + const estGas = await estimateGas(address, dtContract.methods.removeMinter, minter) // Call dtContract function of the contract const trxReceipt = await dtContract.methods.removeMinter(minter).send({ @@ -605,18 +569,7 @@ export class Datatoken { this.config ) - // Estimate gas for addFeeManager method - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .addPaymentManager(paymentManager) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, dtContract.methods.addPaymentManager, paymentManager) } /** @@ -641,11 +594,10 @@ export class Datatoken { throw new Error(`Caller is not ERC20Deployer`) } - const estGas = await this.estGasAddPaymentManager( - dtAddress, + const estGas = await estimateGas( address, - paymentManager, - dtContract + dtContract.methods.addPaymentManager, + paymentManager ) // Call addPaymentManager function of the contract @@ -679,16 +631,7 @@ export class Datatoken { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .removePaymentManager(paymentManager) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, dtContract.methods.removePaymentManager, paymentManager) } /** @@ -713,11 +656,10 @@ export class Datatoken { throw new Error(`Caller is not ERC20Deployer`) } - const estGas = await this.estGasRemovePaymentManager( - dtAddress, + const estGas = await estimateGas( address, - paymentManager, - dtContract + dtContract.methods.removePaymentManager, + paymentManager ) // Call removeFeeManager function of the contract @@ -753,16 +695,7 @@ export class Datatoken { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .setPaymentCollector(paymentCollector) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, dtContract.methods.setPaymentCollector, paymentCollector) } /** @@ -794,11 +727,10 @@ export class Datatoken { throw new Error(`Caller is not Fee Manager, owner or erc20 Deployer`) } - const estGas = await this.estGasSetPaymentCollector( - dtAddress, + const estGas = await estimateGas( address, - paymentCollector, - dtContract + dtContract.methods.setPaymentCollector, + paymentCollector ) // Call setFeeCollector method of the contract @@ -867,16 +799,7 @@ export class Datatoken { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .transfer(toAddress, amount) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, dtContract.methods.transfer, toAddress, amount) } /** @@ -898,12 +821,11 @@ export class Datatoken { this.config ) try { - const estGas = await this.estGasTransfer( - dtAddress, - toAddress, - amount, + const estGas = await estimateGas( address, - dtContract + dtContract.methods.transfer, + toAddress, + amount ) // Call transfer function of the contract const trxReceipt = await dtContract.methods.transfer(toAddress, amount).send({ @@ -944,17 +866,14 @@ export class Datatoken { this.config ) - // Estimate gas for startOrder method - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .startOrder(consumer, serviceIndex, providerFees, consumeMarketFee) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + dtContract.methods.startOrder, + consumer, + serviceIndex, + providerFees, + consumeMarketFee + ) } /** Start Order: called by payer or consumer prior ordering a service consume on a marketplace. @@ -986,14 +905,13 @@ export class Datatoken { } } try { - const estGas = await this.estGasStartOrder( - dtAddress, + const estGas = await estimateGas( address, + dtContract.methods.startOrder, consumer, serviceIndex, providerFees, - consumeMarketFee, - dtContract + consumeMarketFee ) const trxReceipt = await dtContract.methods @@ -1032,17 +950,7 @@ export class Datatoken { this.config ) - // Estimate gas for reuseOrder method - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .reuseOrder(orderTxId, providerFees) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, dtContract.methods.reuseOrder, orderTxId, providerFees) } /** Reuse Order: called by payer or consumer having a valid order, but with expired provider access. @@ -1065,12 +973,11 @@ export class Datatoken { this.config ) try { - const estGas = await this.estGasReuseOrder( - dtAddress, + const estGas = await estimateGas( address, + dtContract.methods.reuseOrder, orderTxId, - providerFees, - dtContract + providerFees ) const trxReceipt = await dtContract.methods @@ -1106,17 +1013,12 @@ export class Datatoken { contractInstance || new this.web3.eth.Contract(this.datatokensEnterpriseAbi, dtAddress) - // Estimate gas for startOrder method - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .buyFromFreAndOrder(orderParams, freParams) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + dtContract.methods.buyFromFreAndOrder, + orderParams, + freParams + ) } /** Buys 1 DT from the FRE and then startsOrder, while burning that DT @@ -1136,12 +1038,11 @@ export class Datatoken { try { const freContractParams = getFreOrderParams(freParams) - const estGas = await this.estGasBuyFromFreAndOrder( - dtAddress, + const estGas = await estimateGas( address, + dtContract.methods.buyFromFreAndOrder, orderParams, - freContractParams, - dtContract + freContractParams ) const trxReceipt = await dtContract.methods @@ -1177,17 +1078,12 @@ export class Datatoken { contractInstance || new this.web3.eth.Contract(this.datatokensEnterpriseAbi, dtAddress) - // Estimate gas for startOrder method - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .buyFromDispenserAndOrder(orderParams, dispenserContract) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + dtContract.methods.buyFromDispenserAndOrder, + orderParams, + dispenserContract + ) } /** Gets DT from dispenser and then startsOrder, while burning that DT @@ -1205,12 +1101,11 @@ export class Datatoken { ): Promise { const dtContract = new this.web3.eth.Contract(this.datatokensEnterpriseAbi, dtAddress) try { - const estGas = await this.estGasBuyFromDispenserAndOrder( - dtAddress, + const estGas = await estimateGas( address, + dtContract.methods.buyFromDispenserAndOrder, orderParams, - dispenserContract, - dtContract + dispenserContract ) const trxReceipt = await dtContract.methods @@ -1247,16 +1142,7 @@ export class Datatoken { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .setData(value) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, dtContract.methods.setData, value) } /** setData @@ -1281,7 +1167,7 @@ export class Datatoken { this.config ) - const estGas = await this.estGasSetData(dtAddress, address, value, dtContract) + const estGas = await estimateGas(address, dtContract.methods.setData, value) // Call setData function of the contract const trxReceipt = await dtContract.methods.setData(value).send({ @@ -1311,17 +1197,7 @@ export class Datatoken { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await dtContract.methods - .cleanPermissions() - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, dtContract.methods.cleanPermissions) } /** @@ -1343,7 +1219,7 @@ export class Datatoken { this.config ) - const estGas = await this.estGasCleanPermissions(dtAddress, address, dtContract) + const estGas = await estimateGas(address, dtContract.methods.cleanPermissions) // Call cleanPermissions function of the contract const trxReceipt = await dtContract.methods.cleanPermissions().send({ diff --git a/src/tokens/NFT.ts b/src/tokens/NFT.ts index 0b93160b..7fd2b4b1 100644 --- a/src/tokens/NFT.ts +++ b/src/tokens/NFT.ts @@ -7,6 +7,7 @@ import { getFairGasPrice, generateDtName, setContractDefaults, + estimateGas, ConfigHelper } from '../utils' import { Contract } from 'web3-eth-contract' @@ -25,7 +26,6 @@ interface Roles { } export class Nft { - public GASLIMIT_DEFAULT = 1000000 public factory721Address: string public factory721Abi: AbiItem | AbiItem[] public nftAbi: AbiItem | AbiItem[] @@ -80,22 +80,15 @@ export class Nft { new this.web3.eth.Contract(this.nftAbi, nftAddress), this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .createERC20( - templateIndex, - [name, symbol], - [minter, paymentCollector, mpFeeAddress, feeToken], - [this.web3.utils.toWei(cap), this.web3.utils.toWei(feeAmount)], - [] - ) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas( + address, + nftContract.methods.createERC20, + templateIndex, + [name, symbol], + [minter, paymentCollector, mpFeeAddress, feeToken], + [this.web3.utils.toWei(cap), this.web3.utils.toWei(feeAmount)], + [] + ) } /** @@ -142,19 +135,14 @@ export class Nft { this.config ) - const estGas = await this.estGasCreateErc20( - nftAddress, + const estGas = await estimateGas( address, - minter, - paymentCollector, - mpFeeAddress, - feeToken, - feeAmount, - cap, - name, - symbol, + nftContract.methods.createERC20, templateIndex, - nftContract + [name, symbol], + [minter, paymentCollector, mpFeeAddress, feeToken], + [this.web3.utils.toWei(cap), this.web3.utils.toWei(feeAmount)], + [] ) // Call createERC20 token function of the contract @@ -202,16 +190,7 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .addManager(manager) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, nftContract.methods.addManager, manager) } /** @@ -231,7 +210,7 @@ export class Nft { throw new Error(`Caller is not NFT Owner`) } - const estGas = await this.estGasAddManager(nftAddress, address, manager, nftContract) + const estGas = await estimateGas(address, nftContract.methods.addManager, manager) // Invoke addManager function of the contract const trxReceipt = await nftContract.methods.addManager(manager).send({ @@ -263,16 +242,7 @@ export class Nft { new this.web3.eth.Contract(this.nftAbi, nftAddress), this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .removeManager(manager) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, nftContract.methods.removeManager, manager) } /** @@ -292,12 +262,7 @@ export class Nft { throw new Error(`Caller is not NFT Owner`) } - const estGas = await this.estGasRemoveManager( - nftAddress, - address, - manager, - nftContract - ) + const estGas = await estimateGas(address, nftContract.methods.removeManager, manager) // Invoke removeManager function of the contract const trxReceipt = await nftContract.methods.removeManager(manager).send({ @@ -329,17 +294,7 @@ export class Nft { new this.web3.eth.Contract(this.nftAbi, nftAddress), this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .addToCreateERC20List(erc20Deployer) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, nftContract.methods.addToCreateERC20List, erc20Deployer) } /** @@ -364,11 +319,10 @@ export class Nft { } // Estimate gas for addToCreateERC20List method - const estGas = await this.estGasAddErc20Deployer( - nftAddress, + const estGas = await estimateGas( address, - erc20Deployer, - nftContract + nftContract.methods.addToCreateERC20List, + erc20Deployer ) // Invoke addToCreateERC20List function of the contract @@ -404,17 +358,11 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .removeFromCreateErc20List(erc20Deployer) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + address, + nftContract.methods.removeFromCreateERC20List, + erc20Deployer + ) } /** @@ -441,11 +389,10 @@ export class Nft { ) { throw new Error(`Caller is not Manager nor ERC20Deployer`) } - const estGas = await this.estGasRemoveErc20Deployer( - nftAddress, + const estGas = await estimateGas( address, - erc20Deployer, - nftContract + nftContract.methods.removeFromCreateERC20List, + erc20Deployer ) // Call removeFromCreateERC20List function of the contract @@ -481,16 +428,7 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .addToMetadataList(metadataUpdater) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, nftContract.methods.addToMetadataList, metadataUpdater) } /** @@ -514,11 +452,10 @@ export class Nft { throw new Error(`Caller is not Manager`) } - const estGas = await this.estGasAddMetadataUpdater( - nftAddress, + const estGas = await estimateGas( address, - metadataUpdater, - nftContract + nftContract.methods.addToMetadataList, + metadataUpdater ) // Call addToMetadataList function of the contract @@ -552,17 +489,11 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .removeFromMetadataList(metadataUpdater) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + address, + nftContract.methods.removeFromMetadataList, + metadataUpdater + ) } /** @@ -630,16 +561,7 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .addTo725StoreList(storeUpdater) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, nftContract.methods.addTo725StoreList, storeUpdater) } /** @@ -663,11 +585,10 @@ export class Nft { throw new Error(`Caller is not Manager`) } - const estGas = await this.estGasAddStoreUpdater( - nftAddress, + const estGas = await estimateGas( address, - storeUpdater, - nftContract + nftContract.methods.addTo725StoreList, + storeUpdater ) // Call addTo725StoreList function of the contract @@ -701,16 +622,7 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .removeFrom725StoreList(storeUpdater) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, nftContract.methods.removeFrom725StoreList, storeUpdater) } /** @@ -738,11 +650,10 @@ export class Nft { throw new Error(`Caller is not Manager nor storeUpdater`) } - const estGas = await this.estGasRemoveStoreUpdater( - nftAddress, + const estGas = await estimateGas( address, - storeUpdater, - nftContract + nftContract.methods.removeFrom725StoreList, + storeUpdater ) // Call removeFrom725StoreList function of the contract @@ -776,16 +687,7 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .cleanPermissions() - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - return estGas + return estimateGas(address, nftContract.methods.cleanPermissions) } /** @@ -811,7 +713,7 @@ export class Nft { throw new Error(`Caller is not NFT Owner`) } - const estGas = await this.estGasCleanPermissions(nftAddress, address, nftContract) + const estGas = await estimateGas(address, nftContract.methods.cleanPermissions) // Call cleanPermissions function of the contract const trxReceipt = await nftContract.methods.cleanPermissions().send({ @@ -846,19 +748,13 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .transferFrom(nftOwner, nftReceiver, tokenId) - .estimateGas({ from: nftOwner }, (err, estGas) => - err ? gasLimitDefault : estGas - ) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + nftOwner, + nftContract.methods.transferFrom, + nftOwner, + nftReceiver, + tokenId + ) } /** @@ -887,12 +783,12 @@ export class Nft { const tokenIdentifier = tokenId || 1 - const estGas = await this.estGasTransferNft( - nftAddress, + const estGas = await estimateGas( + nftOwner, + nftContract.methods.transferFrom, nftOwner, nftReceiver, - tokenIdentifier, - nftContract + tokenIdentifier ) // Call transferFrom function of the contract @@ -930,19 +826,13 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .safeTransferFrom(nftOwner, nftReceiver, tokenId) - .estimateGas({ from: nftOwner }, (err, estGas) => - err ? gasLimitDefault : estGas - ) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + nftOwner, + nftContract.methods.safeTransferFrom, + nftOwner, + nftReceiver, + tokenId + ) } /** @@ -971,12 +861,12 @@ export class Nft { const tokenIdentifier = tokenId || 1 - const estGas = await this.estGasSafeTransferNft( - nftAddress, + const estGas = await estimateGas( + nftOwner, + nftContract.methods.safeTransferFrom, nftOwner, nftReceiver, - tokenIdentifier, - nftContract + tokenIdentifier ) // Call transferFrom function of the contract @@ -1021,28 +911,17 @@ export class Nft { this.config ) if (!metadataProofs) metadataProofs = [] - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .setMetaData( - metadataState, - metadataDecryptorUrl, - metadataDecryptorAddress, - flags, - data, - metadataHash, - metadataProofs - ) - .estimateGas({ from: metadataUpdater }, (err, estGas) => - err ? gasLimitDefault : estGas - ) - } catch (e) { - LoggerInstance.error('estGasSetMetadata error: ', e.message) - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + metadataUpdater, + nftContract.methods.setMetaData, + metadataState, + metadataDecryptorUrl, + metadataDecryptorAddress, + flags, + data, + metadataHash, + metadataProofs + ) } /** @@ -1071,17 +950,16 @@ export class Nft { if (!(await this.getNftPermissions(nftAddress, address)).updateMetadata) { throw new Error(`Caller is not Metadata updater`) } - const estGas = await this.estGasSetMetadata( - nftAddress, + const estGas = await estimateGas( address, + nftContract.methods.setMetaData, metadataState, metadataDecryptorUrl, metadataDecryptorAddress, flags, data, metadataHash, - metadataProofs, - nftContract + metadataProofs ) const trxReceipt = await nftContract.methods .setMetaData( @@ -1122,23 +1000,15 @@ export class Nft { new this.web3.eth.Contract(this.nftAbi, nftAddress), this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas const sanitizedMetadataAndTokenURI = { ...metadataAndTokenURI, metadataProofs: metadataAndTokenURI.metadataProofs || [] } - try { - estGas = await nftContract.methods - .setMetaDataAndTokenURI(sanitizedMetadataAndTokenURI) - .estimateGas({ from: metadataUpdater }, (err, estGas) => - err ? gasLimitDefault : estGas - ) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + metadataUpdater, + nftContract.methods.setMetaDataAndTokenURI, + sanitizedMetadataAndTokenURI + ) } /** @@ -1160,16 +1030,15 @@ export class Nft { if (!(await this.getNftPermissions(nftAddress, metadataUpdater)).updateMetadata) { throw new Error(`Caller is not Metadata updater`) } - const estGas = await this.estGasSetMetadataAndTokenURI( - nftAddress, - metadataUpdater, - metadataAndTokenURI, - nftContract - ) const sanitizedMetadataAndTokenURI = { ...metadataAndTokenURI, metadataProofs: metadataAndTokenURI.metadataProofs || [] } + const estGas = await estimateGas( + metadataUpdater, + nftContract.methods.setMetaDataAndTokenURI, + sanitizedMetadataAndTokenURI + ) const trxReceipt = await nftContract.methods .setMetaDataAndTokenURI(sanitizedMetadataAndTokenURI) .send({ @@ -1202,19 +1071,11 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .setMetaDataState(metadataState) - .estimateGas({ from: metadataUpdater }, (err, estGas) => - err ? gasLimitDefault : estGas - ) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas( + metadataUpdater, + nftContract.methods.setMetaDataState, + metadataState + ) } /** @@ -1238,7 +1099,11 @@ export class Nft { throw new Error(`Caller is not Metadata updater`) } - const estGas = await this.estGasSetMetadataState(nftAddress, address, metadataState) + const estGas = await estimateGas( + address, + nftContract.methods.setMetaDataState, + metadataState + ) // Call transferFrom function of the contract const trxReceipt = await nftContract.methods.setMetaDataState(metadataState).send({ @@ -1266,17 +1131,7 @@ export class Nft { this.config ) - const gasLimitDefault = this.GASLIMIT_DEFAULT - let estGas - try { - estGas = await nftContract.methods - .setTokenURI('1', data) - .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - } - - return estGas + return estimateGas(address, nftContract.methods.setTokenURI, '1', data) } /** set TokenURI on an nft @@ -1295,7 +1150,7 @@ export class Nft { this.config ) - const estGas = await this.estSetTokenURI(nftAddress, address, data) + const estGas = await estimateGas(address, nftContract.methods.setTokenURI, '1', data) const trxReceipt = await nftContract.methods.setTokenURI('1', data).send({ from: address, gas: estGas + 1, diff --git a/src/utils/ContractUtils.ts b/src/utils/ContractUtils.ts index d7502b9f..17066603 100644 --- a/src/utils/ContractUtils.ts +++ b/src/utils/ContractUtils.ts @@ -11,7 +11,7 @@ import { import { Config } from '../models' import { minAbi } from './minAbi' import LoggerInstance from './Logger' -import { ZERO_ADDRESS } from './Constants' +import { GASLIMIT_DEFAULT, ZERO_ADDRESS } from './Constants' export function setContractDefaults(contract: Contract, config: Config): Contract { if (config) { @@ -164,3 +164,29 @@ export async function amountToUnits( LoggerInstance.error(`ERROR: FAILED TO CALL DECIMALS(), USING 18', ${e.message}`) } } + +/** + * Estimates the gas used when a function would be executed on chain + * @param {string} from account that calls the function + * @param {Function} functionToEstimateGas function that we need to estimate the gas + * @param {...any[]} args arguments of the function + * @return {Promise} gas cost of the function + */ +export async function estimateGas( + from: string, + functionToEstimateGas: Function, + ...args: any[] +): Promise { + let estimatedGas = GASLIMIT_DEFAULT + try { + estimatedGas = await functionToEstimateGas.apply(null, args).estimateGas( + { + from: from + }, + (err, estGas) => (err ? GASLIMIT_DEFAULT : estGas) + ) + } catch (e) { + LoggerInstance.error(`ERROR: Estimate gas failed!`, e) + } + return estimatedGas +} diff --git a/src/utils/TokenUtils.ts b/src/utils/TokenUtils.ts index 64e9f83f..c8008c3f 100644 --- a/src/utils/TokenUtils.ts +++ b/src/utils/TokenUtils.ts @@ -1,11 +1,15 @@ import Decimal from 'decimal.js' import { Contract } from 'web3-eth-contract' -import { amountToUnits, getFairGasPrice, unitsToAmount } from './ContractUtils' +import { + amountToUnits, + estimateGas, + getFairGasPrice, + unitsToAmount +} from './ContractUtils' import { minAbi } from './minAbi' import LoggerInstance from './Logger' import { TransactionReceipt } from 'web3-core' import Web3 from 'web3' -import { GASLIMIT_DEFAULT } from './Constants' /** * Estimate gas cost for approval function @@ -27,17 +31,7 @@ export async function estApprove( ): Promise { const tokenContract = contractInstance || new web3.eth.Contract(minAbi, tokenAddress) - const gasLimitDefault = GASLIMIT_DEFAULT - let estGas - try { - estGas = await tokenContract.methods - .approve(spender, amount) - .estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) - } catch (e) { - estGas = gasLimitDefault - LoggerInstance.error('estimate gas failed for approve!', e) - } - return estGas + return estimateGas(account, tokenContract.methods.approve, spender, amount) } /** @@ -45,7 +39,7 @@ export async function estApprove( * @param {String} account * @param {String} tokenAddress * @param {String} spender - * @param {String} amount (always expressed as wei) + * @param {String} amount amount of ERC20 tokens (always expressed as wei) * @param {boolean} force if true, will overwrite any previous allowence. Else, will check if allowence is enough and will not send a transaction if it's not needed * @param {number} tokenDecimals optional number of decimals of the token */ @@ -67,13 +61,11 @@ export async function approve( } let result = null const amountFormatted = await amountToUnits(web3, tokenAddress, amount, tokenDecimals) - const estGas = await estApprove( - web3, + const estGas = await estimateGas( account, - tokenAddress, + tokenContract.methods.approve, spender, - amountFormatted, - tokenContract + amountFormatted ) try { @@ -84,12 +76,73 @@ export async function approve( }) } catch (e) { LoggerInstance.error( - `ERRPR: Failed to approve spender to spend tokens : ${e.message}` + `ERROR: Failed to approve spender to spend tokens : ${e.message}` ) } return result } +/** + * Estimate gas cost for transfer function + * @param {String} account + * @param {String} tokenAddress + * @param {String} recipient + * @param {String} amount + * @param {String} force + * @param {Contract} contractInstance optional contract instance + * @return {Promise} + */ +export async function estTransfer( + web3: Web3, + account: string, + tokenAddress: string, + recipient: string, + amount: string, + contractInstance?: Contract +): Promise { + const tokenContract = contractInstance || new web3.eth.Contract(minAbi, tokenAddress) + + return estimateGas(account, tokenContract.methods.transfer, recipient, amount) +} + +/** + * Moves amount tokens from the caller’s account to recipient. + * @param {String} account + * @param {String} tokenAddress + * @param {String} recipient + * @param {String} amount amount of ERC20 tokens (not as wei) + * @param {String} force if true, will overwrite any previous allowence. Else, will check if allowence is enough and will not send a transaction if it's not needed + */ +export async function transfer( + web3: Web3, + account: string, + tokenAddress: string, + recipient: string, + amount: string +): Promise { + const tokenContract = new web3.eth.Contract(minAbi, tokenAddress) + + let result = null + const amountFormatted = await amountToUnits(web3, tokenAddress, amount) + const estGas = await estimateGas( + account, + tokenContract.methods.transfer, + recipient, + amountFormatted + ) + + try { + result = await tokenContract.methods.transfer(recipient, amountFormatted).send({ + from: account, + gas: estGas + 1, + gasPrice: await getFairGasPrice(web3, null) + }) + } catch (e) { + LoggerInstance.error(`ERROR: Failed to transfer tokens : ${e.message}`) + } + return result +} + /** * Get Allowance for any erc20 * @param {Web3} web3 diff --git a/test/unit/pools/balancer/Pool.test.ts b/test/unit/pools/balancer/Pool.test.ts index 68ce2b4e..1b2452c2 100644 --- a/test/unit/pools/balancer/Pool.test.ts +++ b/test/unit/pools/balancer/Pool.test.ts @@ -468,13 +468,6 @@ describe('Pool unit test', () => { assert((await pool.getMarketFeeCollector(poolAddress)) === factoryOwner) }) - it('#getOPCCollector- should get market fees for each token', async () => { - assert( - (await pool.getOPCCollector(poolAddress)) === - contracts.opfCommunityFeeCollectorAddress - ) - }) - it('#collectCommunityFee- should get community fees for each token', async () => { const spotPriceBefore = await pool.getSpotPrice( poolAddress, @@ -953,13 +946,6 @@ describe('Pool unit test', () => { assert((await pool.getMarketFeeCollector(poolAddress)) === factoryOwner) }) - it('#getOPCCollector- should get market fees for each token', async () => { - assert( - (await pool.getOPCCollector(poolAddress)) === - contracts.opfCommunityFeeCollectorAddress - ) - }) - it('#getCurrentMarketFees- should get curent market fees for each token', async () => { const currentMarketFees: CurrentFees = await pool.getCurrentMarketFees(poolAddress) assert(currentMarketFees !== null) diff --git a/test/unit/pools/fixedRate/FixedRateExchange.test.ts b/test/unit/pools/fixedRate/FixedRateExchange.test.ts index 28e43472..58744acd 100644 --- a/test/unit/pools/fixedRate/FixedRateExchange.test.ts +++ b/test/unit/pools/fixedRate/FixedRateExchange.test.ts @@ -132,11 +132,6 @@ describe('Fixed Rate unit test', () => { it('#getOwner - should get exchange owner given an id', async () => { expect(await fixedRate.getExchangeOwner(exchangeId)).to.equal(exchangeOwner) }) - it('#getOPFCollector - should get OPF collector', async () => { - expect(await fixedRate.getOPCCollector()).to.equal( - contracts.opfCommunityFeeCollectorAddress - ) - }) it('#getRouter - should get Router address', async () => { expect(await fixedRate.getRouter()).to.equal(contracts.routerAddress) }) @@ -453,11 +448,6 @@ describe('Fixed Rate unit test', () => { it('#getOwner - should get exchange owner given an id', async () => { expect(await fixedRate.getExchangeOwner(exchangeId)).to.equal(exchangeOwner) }) - it('#getOPFCollector - should get OPF collector', async () => { - expect(await fixedRate.getOPCCollector()).to.equal( - contracts.opfCommunityFeeCollectorAddress - ) - }) it('#getRouter - should get Router address', async () => { expect(await fixedRate.getRouter()).to.equal(contracts.routerAddress) })