1
0
mirror of https://github.com/oceanprotocol/ocean.js.git synced 2024-11-26 20:39:05 +01:00

Merge branch 'v4main' into issue-1346-rewrite-datatoken-test

This commit is contained in:
Miquel A. Cabot 2022-05-17 11:50:26 +02:00
commit a5fc11365b
15 changed files with 900 additions and 1321 deletions

View File

@ -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). 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) #### [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) - 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) - 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) - 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) #### [v1.0.0-next.41](https://github.com/oceanprotocol/ocean.js/compare/v1.0.0-next.40...v1.0.0-next.41)

32
package-lock.json generated
View File

@ -1,15 +1,15 @@
{ {
"name": "@oceanprotocol/lib", "name": "@oceanprotocol/lib",
"version": "1.0.0-next.42", "version": "1.0.0-next.43",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@oceanprotocol/lib", "name": "@oceanprotocol/lib",
"version": "1.0.0-next.42", "version": "1.0.0-next.43",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@oceanprotocol/contracts": "^1.0.0-alpha.32", "@oceanprotocol/contracts": "^1.0.0-alpha.33",
"bignumber.js": "^9.0.2", "bignumber.js": "^9.0.2",
"cross-fetch": "^3.1.5", "cross-fetch": "^3.1.5",
"crypto-js": "^4.1.1", "crypto-js": "^4.1.1",
@ -24,7 +24,7 @@
"@types/chai-spies": "^1.0.3", "@types/chai-spies": "^1.0.3",
"@types/crypto-js": "^4.1.1", "@types/crypto-js": "^4.1.1",
"@types/mocha": "^9.1.1", "@types/mocha": "^9.1.1",
"@types/node": "^17.0.32", "@types/node": "^17.0.34",
"@types/node-fetch": "^3.0.3", "@types/node-fetch": "^3.0.3",
"@typescript-eslint/eslint-plugin": "^4.33.0", "@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0", "@typescript-eslint/parser": "^4.33.0",
@ -2471,9 +2471,9 @@
} }
}, },
"node_modules/@oceanprotocol/contracts": { "node_modules/@oceanprotocol/contracts": {
"version": "1.0.0-alpha.32", "version": "1.0.0-alpha.33",
"resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.32.tgz", "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.33.tgz",
"integrity": "sha512-gCHw4ZVnNjSozzCVT/cQiDqLNP0Xvy4fe+g5PKy8rwMR/h2rRW65Txi6wkb4HfZiUPKCdHbzpUFOwYfJFbW0Jw==" "integrity": "sha512-jx8fg9src7fjeqMXB2ZYLdp0BoJA0G5vau6pa48YOjasDuPekJtPdT0oRy0PVkyJ2HtkYjAwKVyiFfAbZcug6A=="
}, },
"node_modules/@octokit/auth-token": { "node_modules/@octokit/auth-token": {
"version": "2.5.0", "version": "2.5.0",
@ -3021,9 +3021,9 @@
"dev": true "dev": true
}, },
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "17.0.32", "version": "17.0.34",
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.32.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.34.tgz",
"integrity": "sha512-eAIcfAvhf/BkHcf4pkLJ7ECpBAhh9kcxRBpip9cTiO+hf+aJrsxYxBeS6OXvOd9WqNAJmavXVpZvY1rBjNsXmw==" "integrity": "sha512-XImEz7XwTvDBtzlTnm8YvMqGW/ErMWBsKZ+hMTvnDIjGCKxwK5Xpc+c/oQjOauwq8M4OS11hEkpjX8rrI/eEgA=="
}, },
"node_modules/@types/node-fetch": { "node_modules/@types/node-fetch": {
"version": "3.0.3", "version": "3.0.3",
@ -19610,9 +19610,9 @@
} }
}, },
"@oceanprotocol/contracts": { "@oceanprotocol/contracts": {
"version": "1.0.0-alpha.32", "version": "1.0.0-alpha.33",
"resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.32.tgz", "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.33.tgz",
"integrity": "sha512-gCHw4ZVnNjSozzCVT/cQiDqLNP0Xvy4fe+g5PKy8rwMR/h2rRW65Txi6wkb4HfZiUPKCdHbzpUFOwYfJFbW0Jw==" "integrity": "sha512-jx8fg9src7fjeqMXB2ZYLdp0BoJA0G5vau6pa48YOjasDuPekJtPdT0oRy0PVkyJ2HtkYjAwKVyiFfAbZcug6A=="
}, },
"@octokit/auth-token": { "@octokit/auth-token": {
"version": "2.5.0", "version": "2.5.0",
@ -20079,9 +20079,9 @@
"dev": true "dev": true
}, },
"@types/node": { "@types/node": {
"version": "17.0.32", "version": "17.0.34",
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.32.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.34.tgz",
"integrity": "sha512-eAIcfAvhf/BkHcf4pkLJ7ECpBAhh9kcxRBpip9cTiO+hf+aJrsxYxBeS6OXvOd9WqNAJmavXVpZvY1rBjNsXmw==" "integrity": "sha512-XImEz7XwTvDBtzlTnm8YvMqGW/ErMWBsKZ+hMTvnDIjGCKxwK5Xpc+c/oQjOauwq8M4OS11hEkpjX8rrI/eEgA=="
}, },
"@types/node-fetch": { "@types/node-fetch": {
"version": "3.0.3", "version": "3.0.3",

View File

@ -1,7 +1,7 @@
{ {
"name": "@oceanprotocol/lib", "name": "@oceanprotocol/lib",
"source": "./src/index.ts", "source": "./src/index.ts",
"version": "1.0.0-next.42", "version": "1.0.0-next.43",
"description": "JavaScript client library for Ocean Protocol", "description": "JavaScript client library for Ocean Protocol",
"main": "./dist/lib.js", "main": "./dist/lib.js",
"umd:main": "dist/lib.umd.js", "umd:main": "dist/lib.umd.js",
@ -58,7 +58,7 @@
"web3": "^1.7.3" "web3": "^1.7.3"
}, },
"dependencies": { "dependencies": {
"@oceanprotocol/contracts": "^1.0.0-alpha.32", "@oceanprotocol/contracts": "^1.0.0-alpha.33",
"bignumber.js": "^9.0.2", "bignumber.js": "^9.0.2",
"cross-fetch": "^3.1.5", "cross-fetch": "^3.1.5",
"crypto-js": "^4.1.1", "crypto-js": "^4.1.1",
@ -73,7 +73,7 @@
"@types/chai-spies": "^1.0.3", "@types/chai-spies": "^1.0.3",
"@types/crypto-js": "^4.1.1", "@types/crypto-js": "^4.1.1",
"@types/mocha": "^9.1.1", "@types/mocha": "^9.1.1",
"@types/node": "^17.0.32", "@types/node": "^17.0.34",
"@types/node-fetch": "^3.0.3", "@types/node-fetch": "^3.0.3",
"@typescript-eslint/eslint-plugin": "^4.33.0", "@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0", "@typescript-eslint/parser": "^4.33.0",

View File

@ -11,6 +11,7 @@ import {
getErcCreationParams, getErcCreationParams,
getPoolCreationParams, getPoolCreationParams,
setContractDefaults, setContractDefaults,
estimateGas,
ZERO_ADDRESS, ZERO_ADDRESS,
ConfigHelper ConfigHelper
} from '../utils' } from '../utils'
@ -50,7 +51,6 @@ export interface NftCreateData {
* Provides an interface for NFT Factory contract * Provides an interface for NFT Factory contract
*/ */
export class NftFactory { export class NftFactory {
public GASLIMIT_DEFAULT = 1000000
public factory721Address: string public factory721Address: string
public factory721Abi: AbiItem | AbiItem[] public factory721Abi: AbiItem | AbiItem[]
public web3: Web3 public web3: Web3
@ -87,25 +87,18 @@ export class NftFactory {
* @return {Promise<string>} NFT datatoken address * @return {Promise<string>} NFT datatoken address
*/ */
public async estGasCreateNFT(address: string, nftData: NftCreateData): Promise<string> { public async estGasCreateNFT(address: string, nftData: NftCreateData): Promise<string> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { this.factory721.methods.deployERC721Contract,
estGas = await this.factory721.methods nftData.name,
.deployERC721Contract( nftData.symbol,
nftData.name, nftData.templateIndex,
nftData.symbol, ZERO_ADDRESS,
nftData.templateIndex, ZERO_ADDRESS,
ZERO_ADDRESS, nftData.tokenURI,
ZERO_ADDRESS, nftData.transferable,
nftData.tokenURI, nftData.owner
nftData.transferable, )
nftData.owner
)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -132,7 +125,18 @@ export class NftFactory {
if ((await this.getNFTTemplate(nftData.templateIndex)).isActive === false) { if ((await this.getNFTTemplate(nftData.templateIndex)).isActive === false) {
throw new Error(`Template is not active`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
@ -254,16 +258,11 @@ export class NftFactory {
address: string, address: string,
templateAddress: string templateAddress: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { this.factory721.methods.add721TokenTemplate,
estGas = await this.factory721.methods templateAddress
.add721TokenTemplate(templateAddress) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -283,7 +282,11 @@ export class NftFactory {
throw new Error(`Template cannot be ZERO address`) 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 // Invoke add721TokenTemplate function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
@ -307,16 +310,11 @@ export class NftFactory {
address: string, address: string,
templateIndex: number templateIndex: number
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { this.factory721.methods.disable721TokenTemplate,
estGas = await this.factory721.methods templateIndex
.disable721TokenTemplate(templateIndex) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -339,7 +337,11 @@ export class NftFactory {
if (templateIndex === 0) { if (templateIndex === 0) {
throw new Error(`Template index cannot be ZERO`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
@ -363,16 +365,11 @@ export class NftFactory {
address: string, address: string,
templateIndex: number templateIndex: number
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { this.factory721.methods.reactivate721TokenTemplate,
estGas = await this.factory721.methods templateIndex
.reactivate721TokenTemplate(templateIndex) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -396,7 +393,11 @@ export class NftFactory {
throw new Error(`Template index cannot be ZERO`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
@ -420,17 +421,7 @@ export class NftFactory {
address: string, address: string,
templateAddress: string templateAddress: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.factory721.methods.addTokenTemplate, templateAddress)
let estGas
try {
estGas = await this.factory721.methods
.addTokenTemplate(templateAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -450,7 +441,11 @@ export class NftFactory {
throw new Error(`Template cannot be address ZERO`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
@ -474,16 +469,11 @@ export class NftFactory {
address: string, address: string,
templateIndex: number templateIndex: number
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { this.factory721.methods.disableTokenTemplate,
estGas = await this.factory721.methods templateIndex
.disableTokenTemplate(templateIndex) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -509,7 +499,11 @@ export class NftFactory {
if ((await this.getTokenTemplate(templateIndex)).isActive === false) { if ((await this.getTokenTemplate(templateIndex)).isActive === false) {
throw new Error(`Template is already disabled`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
@ -533,16 +527,11 @@ export class NftFactory {
address: string, address: string,
templateIndex: number templateIndex: number
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { this.factory721.methods.reactivateTokenTemplate,
estGas = await this.factory721.methods templateIndex
.reactivateTokenTemplate(templateIndex) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -569,7 +558,11 @@ export class NftFactory {
throw new Error(`Template is already active`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
@ -592,16 +585,7 @@ export class NftFactory {
address: string, address: string,
orders: TokenOrder[] orders: TokenOrder[]
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.factory721.methods.startMultipleTokenOrder, orders)
let estGas
try {
estGas = await this.factory721.methods
.startMultipleTokenOrder(orders)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -624,7 +608,11 @@ export class NftFactory {
throw new Error(`Too many orders`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
@ -651,18 +639,13 @@ export class NftFactory {
nftCreateData: NftCreateData, nftCreateData: NftCreateData,
ercParams: Erc20CreateParams ercParams: Erc20CreateParams
): Promise<any> { ): Promise<any> {
// Get estimated gas value const ercCreateData = getErcCreationParams(ercParams)
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { this.factory721.methods.createNftWithErc20,
const ercCreateData = getErcCreationParams(ercParams) nftCreateData,
estGas = await this.factory721.methods ercCreateData
.createNftWithErc20(nftCreateData, ercCreateData) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -681,7 +664,13 @@ export class NftFactory {
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
const ercCreateData = getErcCreationParams(ercParams) 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 // Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
.createNftWithErc20(nftCreateData, ercCreateData) .createNftWithErc20(nftCreateData, ercCreateData)
@ -708,18 +697,15 @@ export class NftFactory {
ercParams: Erc20CreateParams, ercParams: Erc20CreateParams,
poolParams: PoolCreationParams poolParams: PoolCreationParams
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT const ercCreateData = getErcCreationParams(ercParams)
let estGas const poolData = await getPoolCreationParams(this.web3, poolParams)
try { return estimateGas(
const ercCreateData = getErcCreationParams(ercParams) address,
const poolData = await getPoolCreationParams(this.web3, poolParams) this.factory721.methods.createNftWithErc20WithPool,
estGas = await this.factory721.methods nftCreateData,
.createNftWithErc20WithPool(nftCreateData, ercCreateData, poolData) ercCreateData,
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) poolData
} catch (e) { )
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -738,15 +724,17 @@ export class NftFactory {
ercParams: Erc20CreateParams, ercParams: Erc20CreateParams,
poolParams: PoolCreationParams poolParams: PoolCreationParams
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
const estGas = await this.estGasCreateNftErc20WithPool(
address,
nftCreateData,
ercParams,
poolParams
)
const ercCreateData = getErcCreationParams(ercParams) const ercCreateData = getErcCreationParams(ercParams)
const poolData = await getPoolCreationParams(this.web3, poolParams) 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 // Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods const trxReceipt = await this.factory721.methods
.createNftWithErc20WithPool(nftCreateData, ercCreateData, poolData) .createNftWithErc20WithPool(nftCreateData, ercCreateData, poolData)
@ -772,20 +760,15 @@ export class NftFactory {
ercParams: Erc20CreateParams, ercParams: Erc20CreateParams,
freParams: FreCreationParams freParams: FreCreationParams
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
const ercCreateData = getErcCreationParams(ercParams) const ercCreateData = getErcCreationParams(ercParams)
const fixedData = await getFreCreationParams(freParams) const fixedData = await getFreCreationParams(freParams)
return estimateGas(
try { address,
estGas = await this.factory721.methods this.factory721.methods.createNftWithErc20WithFixedRate,
.createNftWithErc20WithFixedRate(nftCreateData, ercCreateData, fixedData) nftCreateData,
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) ercCreateData,
} catch (e) { fixedData
estGas = gasLimitDefault )
}
return estGas
} }
/** /**
@ -807,11 +790,12 @@ export class NftFactory {
const ercCreateData = getErcCreationParams(ercParams) const ercCreateData = getErcCreationParams(ercParams)
const fixedData = getFreCreationParams(freParams) const fixedData = getFreCreationParams(freParams)
const estGas = await this.estGasCreateNftErc20WithFixedRate( const estGas = await estimateGas(
address, address,
this.factory721.methods.createNftWithErc20WithFixedRate,
nftCreateData, nftCreateData,
ercParams, ercCreateData,
freParams fixedData
) )
// Invoke createToken function of the contract // Invoke createToken function of the contract
@ -839,20 +823,14 @@ export class NftFactory {
ercParams: Erc20CreateParams, ercParams: Erc20CreateParams,
dispenserParams: DispenserCreationParams dispenserParams: DispenserCreationParams
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
const ercCreateData = getErcCreationParams(ercParams) const ercCreateData = getErcCreationParams(ercParams)
return estimateGas(
try { address,
estGas = await this.factory721.methods this.factory721.methods.createNftWithErc20WithDispenser,
.createNftWithErc20WithDispenser(nftCreateData, ercCreateData, dispenserParams) nftCreateData,
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) ercCreateData,
} catch (e) { dispenserParams
estGas = gasLimitDefault )
LoggerInstance.error('Failed to estimate gas for createNftErc20WithDispenser', e)
}
return estGas
} }
/** /**
@ -876,10 +854,11 @@ export class NftFactory {
dispenserParams.maxBalance = Web3.utils.toWei(dispenserParams.maxBalance) dispenserParams.maxBalance = Web3.utils.toWei(dispenserParams.maxBalance)
dispenserParams.maxTokens = Web3.utils.toWei(dispenserParams.maxTokens) dispenserParams.maxTokens = Web3.utils.toWei(dispenserParams.maxTokens)
const estGas = await this.estGasCreateNftErc20WithDispenser( const estGas = await estimateGas(
address, address,
this.factory721.methods.createNftWithErc20WithDispenser,
nftCreateData, nftCreateData,
ercParams, ercCreateData,
dispenserParams dispenserParams
) )

View File

@ -3,7 +3,7 @@ import Web3 from 'web3'
import { TransactionReceipt } from 'web3-core' import { TransactionReceipt } from 'web3-core'
import { AbiItem } from 'web3-utils' import { AbiItem } from 'web3-utils'
import defaultRouter from '@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json' 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 { Operation } from '../@types/Router'
import { Config } from '../models/index.js' import { Config } from '../models/index.js'
@ -11,7 +11,6 @@ import { Config } from '../models/index.js'
* Provides an interface for FactoryRouter contract * Provides an interface for FactoryRouter contract
*/ */
export class Router { export class Router {
public GASLIMIT_DEFAULT = 1000000
public routerAddress: string public routerAddress: string
public RouterAbi: AbiItem | AbiItem[] public RouterAbi: AbiItem | AbiItem[]
public web3: Web3 public web3: Web3
@ -48,16 +47,7 @@ export class Router {
* @return {Promise<TransactionReceipt>} Transaction receipt * @return {Promise<TransactionReceipt>} Transaction receipt
*/ */
public async estGasBuyDTBatch(address: string, operations: Operation[]): Promise<any> { public async estGasBuyDTBatch(address: string, operations: Operation[]): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.router.methods.buyDTBatch, operations)
let estGas
try {
estGas = await this.router.methods
.buyDTBatch(operations)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -70,7 +60,7 @@ export class Router {
address: string, address: string,
operations: Operation[] operations: Operation[]
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
const estGas = await this.estGasBuyDTBatch(address, operations) const estGas = await estimateGas(address, this.router.methods.buyDTBatch, operations)
// Invoke createToken function of the contract // Invoke createToken function of the contract
const trxReceipt = await this.router.methods.buyDTBatch(operations).send({ const trxReceipt = await this.router.methods.buyDTBatch(operations).send({
@ -135,19 +125,8 @@ export class Router {
address: string, address: string,
tokenAddress: string, tokenAddress: string,
contractInstance?: Contract contractInstance?: Contract
) { ): Promise<any> {
const routerContract = contractInstance || this.router return estimateGas(address, this.router.methods.addApprovedToken, tokenAddress)
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
} }
/** /**
@ -164,7 +143,11 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.router.methods.addApprovedToken(tokenAddress).send({ const trxReceipt = await this.router.methods.addApprovedToken(tokenAddress).send({
@ -187,19 +170,8 @@ export class Router {
address: string, address: string,
tokenAddress: string, tokenAddress: string,
contractInstance?: Contract contractInstance?: Contract
) { ): Promise<any> {
const routerContract = contractInstance || this.router return estimateGas(address, this.router.methods.removeApprovedToken, tokenAddress)
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
} }
/** /**
@ -216,7 +188,11 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.router.methods.removeApprovedToken(tokenAddress).send({ const trxReceipt = await this.router.methods.removeApprovedToken(tokenAddress).send({
@ -235,17 +211,7 @@ export class Router {
* @return {Promise<TransactionReceipt>} * @return {Promise<TransactionReceipt>}
*/ */
public async estGasAddSSContract(address: string, tokenAddress: string): Promise<any> { public async estGasAddSSContract(address: string, tokenAddress: string): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.router.methods.addSSContract, tokenAddress)
let estGas
try {
estGas = await this.router.methods
.addSSContract(tokenAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -262,7 +228,12 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.router.methods.addSSContract(tokenAddress).send({ const trxReceipt = await this.router.methods.addSSContract(tokenAddress).send({
from: address, from: address,
@ -283,17 +254,7 @@ export class Router {
address: string, address: string,
tokenAddress: string tokenAddress: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.router.methods.removeSSContract, tokenAddress)
let estGas
try {
estGas = await this.router.methods
.removeSSContract(tokenAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -310,7 +271,12 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.router.methods.removeSSContract(tokenAddress).send({ const trxReceipt = await this.router.methods.removeSSContract(tokenAddress).send({
from: address, from: address,
@ -331,17 +297,7 @@ export class Router {
address: string, address: string,
tokenAddress: string tokenAddress: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.router.methods.addFixedRateContract, tokenAddress)
let estGas
try {
estGas = await this.router.methods
.addFixedRateContract(tokenAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -358,7 +314,11 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.router.methods.addFixedRateContract(tokenAddress).send({ const trxReceipt = await this.router.methods.addFixedRateContract(tokenAddress).send({
@ -380,17 +340,7 @@ export class Router {
address: string, address: string,
tokenAddress: string tokenAddress: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.router.methods.removeFixedRateContract, tokenAddress)
let estGas
try {
estGas = await this.router.methods
.removeFixedRateContract(tokenAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -407,7 +357,11 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke removeFixedRateContract function of the contract
const trxReceipt = await this.router.methods const trxReceipt = await this.router.methods
@ -431,17 +385,7 @@ export class Router {
address: string, address: string,
tokenAddress: string tokenAddress: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.router.methods.addDispenserContract, tokenAddress)
let estGas
try {
estGas = await this.router.methods
.addDispenserContract(tokenAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -458,7 +402,11 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.router.methods.addDispenserContract(tokenAddress).send({ const trxReceipt = await this.router.methods.addDispenserContract(tokenAddress).send({
@ -480,17 +428,7 @@ export class Router {
address: string, address: string,
tokenAddress: string tokenAddress: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.router.methods.removeDispenserContract, tokenAddress)
let estGas
try {
estGas = await this.router.methods
.removeDispenserContract(tokenAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -507,7 +445,11 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.router.methods const trxReceipt = await this.router.methods
@ -548,17 +490,14 @@ export class Router {
newConsumeFee: number, newConsumeFee: number,
newProviderFee: number newProviderFee: number
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { this.router.methods.updateOPCFee,
estGas = await this.router.methods newSwapOceanFee,
.updateOPCFee(newSwapOceanFee, newSwapNonOceanFee, newConsumeFee, newProviderFee) newSwapNonOceanFee,
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) newConsumeFee,
} catch (e) { newProviderFee
estGas = gasLimitDefault )
}
return estGas
} }
/** /**
@ -581,8 +520,9 @@ export class Router {
throw new Error(`Caller is not Router Owner`) throw new Error(`Caller is not Router Owner`)
} }
const estGas = await this.estGasUpdateOPCFee( const estGas = await estimateGas(
address, address,
this.router.methods.updateOPCFee,
newSwapOceanFee, newSwapOceanFee,
newSwapNonOceanFee, newSwapNonOceanFee,
newConsumeFee, newConsumeFee,
@ -611,17 +551,7 @@ export class Router {
address: string, address: string,
templateAddress: string templateAddress: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.router.methods.addPoolTemplate, templateAddress)
let estGas
try {
estGas = await this.router.methods
.addPoolTemplate(templateAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -638,7 +568,11 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.router.methods.addPoolTemplate(templateAddress).send({ const trxReceipt = await this.router.methods.addPoolTemplate(templateAddress).send({
@ -660,16 +594,7 @@ export class Router {
address: string, address: string,
templateAddress: string templateAddress: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, this.router.methods.removePoolTemplate, templateAddress)
let estGas
try {
estGas = await this.router.methods
.removePoolTemplate(templateAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -686,7 +611,11 @@ export class Router {
throw new Error(`Caller is not Router Owner`) 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 // Invoke createToken function of the contract
const trxReceipt = await this.router.methods const trxReceipt = await this.router.methods

View File

@ -8,6 +8,7 @@ import {
unitsToAmount, unitsToAmount,
amountToUnits, amountToUnits,
LoggerInstance, LoggerInstance,
estimateGas,
ConfigHelper ConfigHelper
} from '../../utils' } from '../../utils'
import BigNumber from 'bignumber.js' import BigNumber from 'bignumber.js'
@ -37,7 +38,6 @@ const MaxUint256 =
export class Pool { export class Pool {
public poolAbi: AbiItem | AbiItem[] public poolAbi: AbiItem | AbiItem[]
public web3: Web3 public web3: Web3
public GASLIMIT_DEFAULT = 1000000
private config: Config private config: Config
constructor( constructor(
@ -112,16 +112,7 @@ export class Pool {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(account, poolContract.methods.setSwapFee, fee)
let estGas
try {
estGas = await poolContract.methods
.setSwapFee(fee)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -142,7 +133,7 @@ export class Pool {
this.config this.config
) )
let result = null let result = null
const estGas = await this.estSetSwapFee(account, poolAddress, fee) const estGas = await estimateGas(account, pool.methods.setSwapFee, fee)
try { try {
result = await pool.methods.setSwapFee(this.web3.utils.toWei(fee)).send({ result = await pool.methods.setSwapFee(this.web3.utils.toWei(fee)).send({
@ -338,25 +329,6 @@ export class Pool {
return result return result
} }
/**
* Get OPC Collector of this pool
* @param {String} poolAddress
* @return {String}
*/
async getOPCCollector(poolAddress: string): Promise<string> {
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 * Get if a token is bounded to a pool
* Returns true if token is bound * Returns true if token is bound
@ -631,16 +603,7 @@ export class Pool {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, poolContract.methods.collectOPC)
let estGas
try {
estGas = await poolContract.methods
.collectOPC()
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -655,7 +618,7 @@ export class Pool {
this.config this.config
) )
let result = null let result = null
const estGas = await this.estCollectOPC(address, poolAddress) const estGas = await estimateGas(address, pool.methods.collectOPC)
try { try {
result = await pool.methods.collectOPC().send({ result = await pool.methods.collectOPC().send({
@ -689,16 +652,7 @@ export class Pool {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, poolContract.methods.collectMarketFee)
let estGas
try {
estGas = await poolContract.methods
.collectMarketFee()
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -720,7 +674,7 @@ export class Pool {
this.config this.config
) )
let result = null let result = null
const estGas = await this.estCollectMarketFee(address, poolAddress) const estGas = await estimateGas(address, pool.methods.collectMarketFee)
try { try {
result = await pool.methods.collectMarketFee().send({ result = await pool.methods.collectMarketFee().send({
@ -757,16 +711,12 @@ export class Pool {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { poolContract.methods.updatePublishMarketFee,
estGas = await poolContract.methods newPublishMarketAddress,
.updatePublishMarketFee(newPublishMarketAddress, newPublishMarketSwapFee) this.web3.utils.toWei(newPublishMarketSwapFee)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) )
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -792,9 +742,9 @@ export class Pool {
) )
let result = null let result = null
const estGas = await this.estUpdatePublishMarketFee( const estGas = await estimateGas(
address, address,
poolAddress, pool.methods.updatePublishMarketFee,
newPublishMarketAddress, newPublishMarketAddress,
this.web3.utils.toWei(newPublishMarketSwapFee) this.web3.utils.toWei(newPublishMarketSwapFee)
) )
@ -857,28 +807,21 @@ export class Pool {
) )
: MaxUint256 : MaxUint256
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { poolContract.methods.swapExactAmountIn,
estGas = await poolContract.methods [
.swapExactAmountIn( tokenInOutMarket.tokenIn,
[ tokenInOutMarket.tokenOut,
tokenInOutMarket.tokenIn, tokenInOutMarket.marketFeeAddress
tokenInOutMarket.tokenOut, ],
tokenInOutMarket.marketFeeAddress [
], tokenAmountIn,
[ minAmountOut,
tokenAmountIn, maxPrice,
minAmountOut, this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee)
maxPrice, ]
this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee) )
]
)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -910,13 +853,6 @@ export class Pool {
throw new Error(`tokenAmountIn is greater than ${maxSwap.toString()}`) throw new Error(`tokenAmountIn is greater than ${maxSwap.toString()}`)
} }
const estGas = await this.estSwapExactAmountIn(
address,
poolAddress,
tokenInOutMarket,
amountsInOutMaxFee
)
const tokenAmountIn = await this.amountToUnits( const tokenAmountIn = await this.amountToUnits(
tokenInOutMarket.tokenIn, tokenInOutMarket.tokenIn,
amountsInOutMaxFee.tokenAmountIn, amountsInOutMaxFee.tokenAmountIn,
@ -929,8 +865,6 @@ export class Pool {
tokenInOutMarket.tokenOutDecimals tokenInOutMarket.tokenOutDecimals
) )
let result = null
const maxPrice = amountsInOutMaxFee.maxPrice const maxPrice = amountsInOutMaxFee.maxPrice
? await this.amountToUnits( ? await this.amountToUnits(
await this.getBaseToken(poolAddress), await this.getBaseToken(poolAddress),
@ -938,6 +872,23 @@ export class Pool {
) )
: MaxUint256 : 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 { try {
result = await pool.methods result = await pool.methods
.swapExactAmountIn( .swapExactAmountIn(
@ -988,8 +939,6 @@ export class Pool {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT
const maxAmountIn = await this.amountToUnits( const maxAmountIn = await this.amountToUnits(
tokenInOutMarket.tokenIn, tokenInOutMarket.tokenIn,
amountsInOutMaxFee.maxAmountIn, amountsInOutMaxFee.maxAmountIn,
@ -1009,27 +958,21 @@ export class Pool {
) )
: MaxUint256 : MaxUint256
let estGas return estimateGas(
try { address,
estGas = await poolContract.methods poolContract.methods.swapExactAmountOut,
.swapExactAmountOut( [
[ tokenInOutMarket.tokenIn,
tokenInOutMarket.tokenIn, tokenInOutMarket.tokenOut,
tokenInOutMarket.tokenOut, tokenInOutMarket.marketFeeAddress
tokenInOutMarket.marketFeeAddress ],
], [
[ maxAmountIn,
maxAmountIn, tokenAmountOut,
tokenAmountOut, maxPrice,
maxPrice, this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee)
this.web3.utils.toWei(amountsInOutMaxFee.swapMarketFee) ]
] )
)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1057,13 +1000,6 @@ export class Pool {
throw new Error(`tokenAmountOut is greater than ${maxSwap.toString()}`) throw new Error(`tokenAmountOut is greater than ${maxSwap.toString()}`)
} }
const estGas = await this.estSwapExactAmountOut(
account,
poolAddress,
tokenInOutMarket,
amountsInOutMaxFee
)
const maxAmountIn = await this.amountToUnits( const maxAmountIn = await this.amountToUnits(
tokenInOutMarket.tokenIn, tokenInOutMarket.tokenIn,
amountsInOutMaxFee.maxAmountIn, amountsInOutMaxFee.maxAmountIn,
@ -1083,6 +1019,22 @@ export class Pool {
) )
: MaxUint256 : 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 { try {
result = await pool.methods result = await pool.methods
.swapExactAmountOut( .swapExactAmountOut(
@ -1133,16 +1085,12 @@ export class Pool {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { poolContract.methods.joinswapExternAmountIn,
estGas = await poolContract.methods tokenAmountIn,
.joinswapExternAmountIn(tokenAmountIn, minPoolAmountOut) minPoolAmountOut
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) )
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1179,9 +1127,9 @@ export class Pool {
tokenAmountIn, tokenAmountIn,
tokenInDecimals tokenInDecimals
) )
const estGas = await this.estJoinswapExternAmountIn( const estGas = await estimateGas(
account, account,
poolAddress, pool.methods.joinswapExternAmountIn,
amountInFormatted, amountInFormatted,
this.web3.utils.toWei(minPoolAmountOut) this.web3.utils.toWei(minPoolAmountOut)
) )
@ -1227,16 +1175,12 @@ export class Pool {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { poolContract.methods.exitswapPoolAmountIn,
estGas = await poolContract.methods poolAmountIn,
.exitswapPoolAmountIn(poolAmountIn, minTokenAmountOut) minTokenAmountOut
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) )
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1280,9 +1224,9 @@ export class Pool {
minTokenAmountOut, minTokenAmountOut,
poolDecimals poolDecimals
) )
const estGas = await this.estExitswapPoolAmountIn( const estGas = await estimateGas(
account, account,
poolAddress, pool.methods.exitswapPoolAmountIn,
this.web3.utils.toWei(poolAmountIn), this.web3.utils.toWei(poolAmountIn),
minTokenOutFormatted minTokenOutFormatted
) )

View File

@ -8,6 +8,7 @@ import {
LoggerInstance as logger, LoggerInstance as logger,
getFairGasPrice, getFairGasPrice,
setContractDefaults, setContractDefaults,
estimateGas,
ConfigHelper ConfigHelper
} from '../../utils/' } from '../../utils/'
import { Datatoken } from '../../tokens' import { Datatoken } from '../../tokens'
@ -24,7 +25,6 @@ export interface DispenserToken {
} }
export class Dispenser { export class Dispenser {
public GASLIMIT_DEFAULT = 1000000
public web3: Web3 = null public web3: Web3 = null
public dispenserAddress: string public dispenserAddress: string
public config: Config public config: Config
@ -91,23 +91,15 @@ export class Dispenser {
maxBalance: string, maxBalance: string,
allowedSwapper: string allowedSwapper: string
): Promise<any> { ): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { this.dispenserContract.methods.create,
estGas = await this.dispenserContract.methods dtAddress,
.create( this.web3.utils.toWei(maxTokens),
dtAddress, this.web3.utils.toWei(maxBalance),
this.web3.utils.toWei(maxTokens), address,
this.web3.utils.toWei(maxBalance), allowedSwapper
address, )
allowedSwapper
)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -126,11 +118,13 @@ export class Dispenser {
maxBalance: string, maxBalance: string,
allowedSwapper: string allowedSwapper: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
const estGas = await this.estGasCreate( const estGas = await estimateGas(
dtAddress, address,
this.dispenserContract.methods.create,
dtAddress,
this.web3.utils.toWei(maxTokens),
this.web3.utils.toWei(maxBalance),
address, address,
maxTokens,
maxBalance,
allowedSwapper allowedSwapper
) )
@ -165,20 +159,13 @@ export class Dispenser {
maxBalance: string, maxBalance: string,
address: string address: string
): Promise<any> { ): Promise<any> {
let estGas return estimateGas(
const gasLimitDefault = this.GASLIMIT_DEFAULT address,
try { this.dispenserContract.methods.activate,
estGas = await this.dispenserContract.methods dtAddress,
.activate( this.web3.utils.toWei(maxTokens),
dtAddress, this.web3.utils.toWei(maxBalance)
this.web3.utils.toWei(maxTokens), )
this.web3.utils.toWei(maxBalance)
)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -196,7 +183,14 @@ export class Dispenser {
address: string address: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
try { 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 const trxReceipt = await this.dispenserContract.methods
.activate( .activate(
dtAddress, dtAddress,
@ -222,16 +216,7 @@ export class Dispenser {
* @return {Promise<any>} * @return {Promise<any>}
*/ */
public async estGasDeactivate(dtAddress: string, address: string): Promise<any> { public async estGasDeactivate(dtAddress: string, address: string): Promise<any> {
let estGas return estimateGas(address, this.dispenserContract.methods.deactivate, dtAddress)
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
} }
/** /**
@ -245,7 +230,12 @@ export class Dispenser {
address: string address: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
try { 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({ const trxReceipt = await this.dispenserContract.methods.deactivate(dtAddress).send({
from: address, from: address,
gas: estGas + 1, gas: estGas + 1,
@ -270,16 +260,12 @@ export class Dispenser {
address: string, address: string,
newAllowedSwapper: string newAllowedSwapper: string
): Promise<any> { ): Promise<any> {
let estGas return estimateGas(
const gasLimitDefault = this.GASLIMIT_DEFAULT address,
try { this.dispenserContract.methods.setAllowedSwapper,
estGas = await this.dispenserContract.methods dtAddress,
.setAllowedSwapper(dtAddress, newAllowedSwapper) newAllowedSwapper
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) )
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -295,11 +281,13 @@ export class Dispenser {
newAllowedSwapper: string newAllowedSwapper: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
try { try {
const estGas = await this.estGasSetAllowedSwapper( const estGas = await estimateGas(
dtAddress,
address, address,
this.dispenserContract.methods.setAllowedSwapper,
dtAddress,
newAllowedSwapper newAllowedSwapper
) )
const trxReceipt = await this.dispenserContract.methods const trxReceipt = await this.dispenserContract.methods
.setAllowedSwapper(dtAddress, newAllowedSwapper) .setAllowedSwapper(dtAddress, newAllowedSwapper)
.send({ .send({
@ -327,16 +315,13 @@ export class Dispenser {
amount: string = '1', amount: string = '1',
destination: string destination: string
): Promise<any> { ): Promise<any> {
let estGas return estimateGas(
const gasLimitDefault = this.GASLIMIT_DEFAULT address,
try { this.dispenserContract.methods.dispense,
estGas = await this.dispenserContract.methods dtAddress,
.dispense(dtAddress, this.web3.utils.toWei(amount), destination) this.web3.utils.toWei(amount),
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) destination
} catch (e) { )
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -355,7 +340,14 @@ export class Dispenser {
amount: string = '1', amount: string = '1',
destination: string destination: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
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 { try {
const trxReceipt = await this.dispenserContract.methods const trxReceipt = await this.dispenserContract.methods
.dispense(dtAddress, this.web3.utils.toWei(amount), destination) .dispense(dtAddress, this.web3.utils.toWei(amount), destination)
@ -379,16 +371,7 @@ export class Dispenser {
* @return {Promise<any>} * @return {Promise<any>}
*/ */
public async estGasOwnerWithdraw(dtAddress: string, address: string): Promise<any> { public async estGasOwnerWithdraw(dtAddress: string, address: string): Promise<any> {
let estGas return estimateGas(address, this.dispenserContract.methods.ownerWithdraw, dtAddress)
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
} }
/** /**
@ -401,7 +384,12 @@ export class Dispenser {
dtAddress: string, dtAddress: string,
address: string address: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
const estGas = await this.estGasOwnerWithdraw(dtAddress, address) const estGas = await estimateGas(
address,
this.dispenserContract.methods.ownerWithdraw,
dtAddress
)
try { try {
const trxReceipt = await this.dispenserContract.methods const trxReceipt = await this.dispenserContract.methods
.ownerWithdraw(dtAddress) .ownerWithdraw(dtAddress)

View File

@ -9,6 +9,7 @@ import {
setContractDefaults, setContractDefaults,
amountToUnits, amountToUnits,
unitsToAmount, unitsToAmount,
estimateGas,
ZERO_ADDRESS, ZERO_ADDRESS,
ConfigHelper ConfigHelper
} from '../../utils' } from '../../utils'
@ -55,7 +56,6 @@ export enum FixedRateCreateProgressStep {
/* eslint-enable no-unused-vars */ /* eslint-enable no-unused-vars */
export class FixedRateExchange { export class FixedRateExchange {
public GASLIMIT_DEFAULT = 1000000
/** Ocean related functions */ /** Ocean related functions */
public oceanAddress: string = null public oceanAddress: string = null
public fixedRateAddress: string public fixedRateAddress: string
@ -141,22 +141,16 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(
try { account,
estGas = await fixedRate.methods fixedRate.methods.buyDT,
.buyDT( datatokenAddress,
datatokenAddress, dtAmount,
dtAmount, maxBaseTokenAmount,
maxBaseTokenAmount, consumeMarketAddress,
consumeMarketAddress, consumeMarketFee
consumeMarketFee )
)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -190,8 +184,9 @@ export class FixedRateExchange {
+exchange.btDecimals +exchange.btDecimals
) )
const estGas = await this.estBuyDT( const estGas = await estimateGas(
address, address,
this.contract.methods.buyDT,
exchangeId, exchangeId,
dtAmountFormatted, dtAmountFormatted,
maxBtFormatted, maxBtFormatted,
@ -239,22 +234,16 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(
try { account,
estGas = await fixedRate.methods fixedRate.methods.sellDT,
.sellDT( datatokenAddress,
datatokenAddress, dtAmount,
dtAmount, maxBaseTokenAmount,
maxBaseTokenAmount, consumeMarketAddress,
consumeMarketAddress, consumeMarketFee
consumeMarketFee )
)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -287,8 +276,9 @@ export class FixedRateExchange {
minBaseTokenAmount, minBaseTokenAmount,
+exchange.btDecimals +exchange.btDecimals
) )
const estGas = await this.estBuyDT( const estGas = await estimateGas(
address, address,
this.contract.methods.sellDT,
exchangeId, exchangeId,
dtAmountFormatted, dtAmountFormatted,
minBtFormatted, minBtFormatted,
@ -342,16 +332,13 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(
try { account,
estGas = await fixedRate.methods fixedRate.methods.setRate,
.setRate(exchangeId, await this.web3.utils.toWei(newRate)) exchangeId,
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) await this.web3.utils.toWei(newRate)
} catch (e) { )
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -366,7 +353,12 @@ export class FixedRateExchange {
exchangeId: string, exchangeId: string,
newRate: string newRate: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
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 const trxReceipt = await this.contract.methods
.setRate(exchangeId, this.web3.utils.toWei(newRate)) .setRate(exchangeId, this.web3.utils.toWei(newRate))
.send({ .send({
@ -392,16 +384,8 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(account, fixedRate.methods.setRate, exchangeId, newAllowedSwapper)
try {
estGas = await fixedRate.methods
.setRate(exchangeId, newAllowedSwapper)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -416,7 +400,12 @@ export class FixedRateExchange {
exchangeId: string, exchangeId: string,
newAllowedSwapper: string newAllowedSwapper: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
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 const trxReceipt = await this.contract.methods
.setAllowedSwapper(exchangeId, newAllowedSwapper) .setAllowedSwapper(exchangeId, newAllowedSwapper)
.send({ .send({
@ -440,16 +429,8 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(account, fixedRate.methods.toggleExchangeState, exchangeId)
try {
estGas = await fixedRate.methods
.toggleExchangeState(exchangeId)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -466,7 +447,11 @@ export class FixedRateExchange {
if (!exchange) return null if (!exchange) return null
if (exchange.active === true) 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({ const trxReceipt = await this.contract.methods.toggleExchangeState(exchangeId).send({
from: address, from: address,
gas: estGas + 1, gas: estGas + 1,
@ -488,16 +473,8 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(account, fixedRate.methods.toggleExchangeState, exchangeId)
try {
estGas = await fixedRate.methods
.toggleExchangeState(exchangeId)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -514,7 +491,11 @@ export class FixedRateExchange {
if (!exchange) return null if (!exchange) return null
if (exchange.active === false) 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({ const trxReceipt = await this.contract.methods.toggleExchangeState(exchangeId).send({
from: address, from: address,
@ -739,16 +720,8 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(account, fixedRate.methods.toggleMintState, exchangeId, true)
try {
estGas = await fixedRate.methods
.toggleMintState(exchangeId, true)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -765,7 +738,12 @@ export class FixedRateExchange {
if (!exchange) return null if (!exchange) return null
if (exchange.withMint === true) 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 const trxReceipt = await this.contract.methods
.toggleMintState(exchangeId, true) .toggleMintState(exchangeId, true)
.send({ .send({
@ -789,16 +767,8 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(account, fixedRate.methods.toggleMintState, exchangeId)
try {
estGas = await fixedRate.methods
.toggleMintState(exchangeId)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -815,7 +785,12 @@ export class FixedRateExchange {
if (!exchange) return null if (!exchange) return null
if (exchange.withMint === false) 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 const trxReceipt = await this.contract.methods
.toggleMintState(exchangeId, false) .toggleMintState(exchangeId, false)
@ -843,8 +818,6 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
const fixedrate: FixedPriceExchange = await this.contract.methods const fixedrate: FixedPriceExchange = await this.contract.methods
.getExchange(exchangeId) .getExchange(exchangeId)
.call() .call()
@ -853,14 +826,7 @@ export class FixedRateExchange {
amount, amount,
+fixedrate.btDecimals +fixedrate.btDecimals
) )
try { return estimateGas(account, fixedRate.methods.collectBT, exchangeId, amountWei)
estGas = await fixedRate.methods
.collectBT(exchangeId, amountWei)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -878,7 +844,6 @@ export class FixedRateExchange {
const exchange = await this.getExchange(exchangeId) const exchange = await this.getExchange(exchangeId)
if (!exchange) return null if (!exchange) return null
const estGas = await this.estCollectBT(address, exchangeId, amount)
const fixedrate: FixedPriceExchange = await this.contract.methods const fixedrate: FixedPriceExchange = await this.contract.methods
.getExchange(exchangeId) .getExchange(exchangeId)
.call() .call()
@ -887,6 +852,14 @@ export class FixedRateExchange {
amount, amount,
+fixedrate.btDecimals +fixedrate.btDecimals
) )
const estGas = await estimateGas(
address,
this.contract.methods.collectBT,
exchangeId,
amountWei
)
const trxReceipt = await this.contract.methods.collectBT(exchangeId, amountWei).send({ const trxReceipt = await this.contract.methods.collectBT(exchangeId, amountWei).send({
from: address, from: address,
gas: estGas + 1, gas: estGas + 1,
@ -910,24 +883,16 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
const fixedrate: FixedPriceExchange = await this.contract.methods const fixedrate: FixedPriceExchange = await this.contract.methods
.getExchange(exchangeId) .getExchange(exchangeId)
.call() .call()
const amountWei = await this.amountToUnits( const amountWei = await this.amountToUnits(
fixedrate.datatoken, fixedrate.datatoken,
amount, amount,
+fixedrate.dtDecimals +fixedrate.dtDecimals
) )
try { return estimateGas(account, fixedRate.methods.collectDT, exchangeId, amountWei)
estGas = await fixedRate.methods
.collectDT(exchangeId, amountWei)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -945,7 +910,6 @@ export class FixedRateExchange {
const exchange = await this.getExchange(exchangeId) const exchange = await this.getExchange(exchangeId)
if (!exchange) return null if (!exchange) return null
const estGas = await this.estCollectDT(address, exchangeId, amount)
const fixedrate: FixedPriceExchange = await this.contract.methods const fixedrate: FixedPriceExchange = await this.contract.methods
.getExchange(exchangeId) .getExchange(exchangeId)
.call() .call()
@ -954,6 +918,14 @@ export class FixedRateExchange {
amount, amount,
+fixedrate.dtDecimals +fixedrate.dtDecimals
) )
const estGas = await estimateGas(
address,
this.contract.methods.collectDT,
exchangeId,
amountWei
)
const trxReceipt = await this.contract.methods.collectDT(exchangeId, amountWei).send({ const trxReceipt = await this.contract.methods.collectDT(exchangeId, amountWei).send({
from: address, from: address,
gas: estGas + 1, gas: estGas + 1,
@ -975,16 +947,8 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(account, fixedRate.methods.collectMarketFee, exchangeId)
try {
estGas = await fixedRate.methods
.collectMarketFee(exchangeId)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1000,7 +964,11 @@ export class FixedRateExchange {
const exchange = await this.getExchange(exchangeId) const exchange = await this.getExchange(exchangeId)
if (!exchange) return null 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({ const trxReceipt = await this.contract.methods.collectMarketFee(exchangeId).send({
from: address, from: address,
gas: estGas + 1, gas: estGas + 1,
@ -1022,16 +990,8 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(account, fixedRate.methods.collectMarketFee, exchangeId)
try {
estGas = await fixedRate.methods
.collectMarketFee(exchangeId)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1047,7 +1007,11 @@ export class FixedRateExchange {
const exchange = await this.getExchange(exchangeId) const exchange = await this.getExchange(exchangeId)
if (!exchange) return null 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({ const trxReceipt = await this.contract.methods.collectOceanFee(exchangeId).send({
from: address, from: address,
gas: estGas + 1, gas: estGas + 1,
@ -1056,20 +1020,6 @@ export class FixedRateExchange {
return trxReceipt return trxReceipt
} }
/**
* Get OPF Collector of fixed rate contract
* @return {String}
*/
async getOPCCollector(): Promise<string> {
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 * Get Router address set in fixed rate contract
* @return {String} * @return {String}
@ -1114,16 +1064,13 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(
try { account,
estGas = await fixedRate.methods fixedRate.methods.updateMarketFee,
.updateMarketFee(exchangeId, newMarketFee) exchangeId,
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) newMarketFee
} catch (e) { )
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1138,8 +1085,9 @@ export class FixedRateExchange {
exchangeId: string, exchangeId: string,
newMarketFee: string newMarketFee: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
const estGas = await this.estSetRate( const estGas = await estimateGas(
address, address,
this.contract.methods.updateMarketFee,
exchangeId, exchangeId,
this.web3.utils.toWei(newMarketFee) this.web3.utils.toWei(newMarketFee)
) )
@ -1168,16 +1116,13 @@ export class FixedRateExchange {
contractInstance?: Contract contractInstance?: Contract
): Promise<number> { ): Promise<number> {
const fixedRate = contractInstance || this.fixedRateContract const fixedRate = contractInstance || this.fixedRateContract
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas return estimateGas(
try { account,
estGas = await fixedRate.methods fixedRate.methods.updateMarketFeeCollector,
.updateMarketFeeCollector(exchangeId, newMarketFeeCollector) exchangeId,
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) newMarketFeeCollector
} catch (e) { )
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1192,8 +1137,9 @@ export class FixedRateExchange {
exchangeId: string, exchangeId: string,
newMarketFeeCollector: string newMarketFeeCollector: string
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
const estGas = await this.estUpdateMarketFeeCollector( const estGas = await estimateGas(
address, address,
this.contract.methods.updateMarketFeeCollector,
exchangeId, exchangeId,
newMarketFeeCollector newMarketFeeCollector
) )

View File

@ -2,14 +2,19 @@ import Web3 from 'web3'
import { AbiItem } from 'web3-utils/types' import { AbiItem } from 'web3-utils/types'
import { TransactionReceipt } from 'web3-core' import { TransactionReceipt } from 'web3-core'
import { Contract } from 'web3-eth-contract' 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 SideStakingTemplate from '@oceanprotocol/contracts/artifacts/contracts/pools/ssContracts/SideStaking.sol/SideStaking.json'
import { Config } from '../../models' import { Config } from '../../models'
export class SideStaking { export class SideStaking {
public ssAbi: AbiItem | AbiItem[] public ssAbi: AbiItem | AbiItem[]
public web3: Web3 public web3: Web3
public GASLIMIT_DEFAULT = 1000000
public config: Config public config: Config
constructor( constructor(
@ -274,16 +279,7 @@ export class SideStaking {
const sideStaking = const sideStaking =
contractInstance || new this.web3.eth.Contract(this.ssAbi as AbiItem[], ssAddress) contractInstance || new this.web3.eth.Contract(this.ssAbi as AbiItem[], ssAddress)
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(account, sideStaking.methods.getVesting, datatokenAddress)
let estGas
try {
estGas = await sideStaking.methods
.getVesting(datatokenAddress)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** Send vested tokens available to the publisher address, can be called by anyone /** 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) const sideStaking = new this.web3.eth.Contract(this.ssAbi, ssAddress)
let result = null let result = null
const estGas = await this.estGetVesting( const estGas = await estimateGas(
account, account,
ssAddress, sideStaking.methods.getVesting,
datatokenAddress, datatokenAddress
sideStaking
) )
try { try {
result = await sideStaking.methods.getVesting(datatokenAddress).send({ result = await sideStaking.methods.getVesting(datatokenAddress).send({
from: account, from: account,
@ -338,16 +334,13 @@ export class SideStaking {
const sideStaking = const sideStaking =
contractInstance || new this.web3.eth.Contract(this.ssAbi as AbiItem[], ssAddress) contractInstance || new this.web3.eth.Contract(this.ssAbi as AbiItem[], ssAddress)
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas account,
try { sideStaking.methods.setPoolSwapFee,
estGas = await sideStaking.methods datatokenAddress,
.setPoolSwapFee(datatokenAddress, poolAddress, swapFee) poolAddress,
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas)) swapFee
} catch (e) { )
estGas = gasLimitDefault
}
return estGas
} }
/** Send vested tokens available to the publisher address, can be called by anyone /** 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) const sideStaking = new this.web3.eth.Contract(this.ssAbi, ssAddress)
let result = null let result = null
const estGas = await this.estSetPoolSwapFee( const estGas = await estimateGas(
account, account,
ssAddress, sideStaking.methods.setPoolSwapFee,
datatokenAddress, datatokenAddress,
poolAddress, poolAddress,
swapFee, swapFee
sideStaking
) )
try { try {
result = await sideStaking.methods result = await sideStaking.methods
.setPoolSwapFee(datatokenAddress, poolAddress, swapFee) .setPoolSwapFee(datatokenAddress, poolAddress, swapFee)

View File

@ -10,6 +10,7 @@ import {
getFairGasPrice, getFairGasPrice,
setContractDefaults, setContractDefaults,
getFreOrderParams, getFreOrderParams,
estimateGas,
ZERO_ADDRESS, ZERO_ADDRESS,
ConfigHelper ConfigHelper
} from '../utils' } from '../utils'
@ -45,7 +46,6 @@ export interface DispenserParams {
} }
export class Datatoken { export class Datatoken {
public GASLIMIT_DEFAULT = 1000000
public factoryAddress: string public factoryAddress: string
public factoryABI: AbiItem | AbiItem[] public factoryABI: AbiItem | AbiItem[]
public datatokensAbi: AbiItem | AbiItem[] public datatokensAbi: AbiItem | AbiItem[]
@ -97,17 +97,12 @@ export class Datatoken {
this.config this.config
) )
// Estimate gas cost for mint method return estimateGas(
const gasLimitDefault = this.GASLIMIT_DEFAULT address,
let estGas dtContract.methods.approve,
try { spender,
estGas = await dtContract.methods this.web3.utils.toWei(amount)
.approve(spender, this.web3.utils.toWei(amount)) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -129,12 +124,11 @@ export class Datatoken {
this.config this.config
) )
const estGas = await this.estGasApprove( const estGas = await estimateGas(
dtAddress,
spender,
amount,
address, address,
dtContract dtContract.methods.approve,
spender,
this.web3.utils.toWei(amount)
) )
// Call mint contract method // Call mint contract method
@ -171,17 +165,12 @@ export class Datatoken {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { dtContract.methods.mint,
estGas = await dtContract.methods toAddress || address,
.mint(toAddress || address, this.web3.utils.toWei(amount)) this.web3.utils.toWei(amount)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) )
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -206,36 +195,27 @@ export class Datatoken {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT
if (!fixedRateParams.allowedConsumer) fixedRateParams.allowedConsumer = ZERO_ADDRESS if (!fixedRateParams.allowedConsumer) fixedRateParams.allowedConsumer = ZERO_ADDRESS
const withMint = fixedRateParams.withMint ? 1 : 0 const withMint = fixedRateParams.withMint ? 1 : 0
let estGas return estimateGas(
try { address,
estGas = await dtContract.methods dtContract.methods.createFixedRate,
.createFixedRate( fixedRateParams.fixedRateAddress,
fixedRateParams.fixedRateAddress, [
[ fixedRateParams.baseTokenAddress,
fixedRateParams.baseTokenAddress, address,
address, fixedRateParams.marketFeeCollector,
fixedRateParams.marketFeeCollector, fixedRateParams.allowedConsumer
fixedRateParams.allowedConsumer ],
], [
[ fixedRateParams.baseTokenDecimals,
fixedRateParams.baseTokenDecimals, fixedRateParams.datatokenDecimals,
fixedRateParams.datatokenDecimals, fixedRateParams.fixedRate,
fixedRateParams.fixedRate, fixedRateParams.marketFee,
fixedRateParams.marketFee, withMint
withMint ]
] )
)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -264,11 +244,23 @@ export class Datatoken {
// should check ERC20Deployer role using erc721 level .. // should check ERC20Deployer role using erc721 level ..
const estGas = await this.estGasCreateFixedRate( const estGas = await estimateGas(
dtAddress,
address, address,
fixedRateParams, dtContract.methods.createFixedRate,
dtContract fixedRateParams.fixedRateAddress,
[
fixedRateParams.baseTokenAddress,
fixedRateParams.owner,
fixedRateParams.marketFeeCollector,
fixedRateParams.allowedConsumer
],
[
fixedRateParams.baseTokenDecimals,
fixedRateParams.datatokenDecimals,
fixedRateParams.fixedRate,
fixedRateParams.marketFee,
withMint
]
) )
// Call createFixedRate contract method // Call createFixedRate contract method
@ -324,23 +316,15 @@ export class Datatoken {
if (!dispenserParams.withMint) dispenserParams.withMint = false if (!dispenserParams.withMint) dispenserParams.withMint = false
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { dtContract.methods.createDispenser,
estGas = await dtContract.methods dispenserAddress,
.createDispenser( dispenserParams.maxTokens,
dispenserAddress, dispenserParams.maxBalance,
dispenserParams.maxTokens, dispenserParams.withMint,
dispenserParams.maxBalance, dispenserParams.allowedSwapper
dispenserParams.withMint, )
dispenserParams.allowedSwapper
)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -372,12 +356,14 @@ export class Datatoken {
// should check ERC20Deployer role using erc721 level .. // should check ERC20Deployer role using erc721 level ..
const estGas = await this.estGasCreateDispenser( const estGas = await estimateGas(
dtAddress,
address, address,
dtContract.methods.createDispenser,
dispenserAddress, dispenserAddress,
dispenserParams, dispenserParams.maxTokens,
dtContract dispenserParams.maxBalance,
dispenserParams.withMint,
dispenserParams.allowedSwapper
) )
// Call createFixedRate contract method // Call createFixedRate contract method
@ -422,12 +408,11 @@ export class Datatoken {
const capAvailble = await this.getCap(dtAddress) const capAvailble = await this.getCap(dtAddress)
if (new Decimal(capAvailble).gte(amount)) { if (new Decimal(capAvailble).gte(amount)) {
const estGas = await this.estGasMint( const estGas = await estimateGas(
dtAddress,
address, address,
amount, dtContract.methods.mint,
toAddress, toAddress || address,
dtContract this.web3.utils.toWei(amount)
) )
// Call mint contract method // Call mint contract method
@ -465,17 +450,7 @@ export class Datatoken {
this.config this.config
) )
// Estimate gas cost for addMinter method return estimateGas(address, dtContract.methods.addMinter, minter)
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
} }
/** /**
@ -500,7 +475,7 @@ export class Datatoken {
throw new Error(`Caller is not ERC20Deployer`) throw new Error(`Caller is not ERC20Deployer`)
} }
// Estimate gas cost for addMinter method // 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 // Call addMinter function of the contract
const trxReceipt = await dtContract.methods.addMinter(minter).send({ const trxReceipt = await dtContract.methods.addMinter(minter).send({
@ -535,18 +510,7 @@ export class Datatoken {
// should check ERC20Deployer role using erc721 level .. // should check ERC20Deployer role using erc721 level ..
// Estimate gas for removeMinter method return estimateGas(address, dtContract.methods.removeMinter, minter)
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
} }
/** /**
@ -572,7 +536,7 @@ export class Datatoken {
throw new Error(`Caller is not ERC20Deployer`) 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 // Call dtContract function of the contract
const trxReceipt = await dtContract.methods.removeMinter(minter).send({ const trxReceipt = await dtContract.methods.removeMinter(minter).send({
@ -605,18 +569,7 @@ export class Datatoken {
this.config this.config
) )
// Estimate gas for addFeeManager method return estimateGas(address, dtContract.methods.addPaymentManager, paymentManager)
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
} }
/** /**
@ -641,11 +594,10 @@ export class Datatoken {
throw new Error(`Caller is not ERC20Deployer`) throw new Error(`Caller is not ERC20Deployer`)
} }
const estGas = await this.estGasAddPaymentManager( const estGas = await estimateGas(
dtAddress,
address, address,
paymentManager, dtContract.methods.addPaymentManager,
dtContract paymentManager
) )
// Call addPaymentManager function of the contract // Call addPaymentManager function of the contract
@ -679,16 +631,7 @@ export class Datatoken {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, dtContract.methods.removePaymentManager, paymentManager)
let estGas
try {
estGas = await dtContract.methods
.removePaymentManager(paymentManager)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -713,11 +656,10 @@ export class Datatoken {
throw new Error(`Caller is not ERC20Deployer`) throw new Error(`Caller is not ERC20Deployer`)
} }
const estGas = await this.estGasRemovePaymentManager( const estGas = await estimateGas(
dtAddress,
address, address,
paymentManager, dtContract.methods.removePaymentManager,
dtContract paymentManager
) )
// Call removeFeeManager function of the contract // Call removeFeeManager function of the contract
@ -753,16 +695,7 @@ export class Datatoken {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, dtContract.methods.setPaymentCollector, paymentCollector)
let estGas
try {
estGas = await dtContract.methods
.setPaymentCollector(paymentCollector)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -794,11 +727,10 @@ export class Datatoken {
throw new Error(`Caller is not Fee Manager, owner or erc20 Deployer`) throw new Error(`Caller is not Fee Manager, owner or erc20 Deployer`)
} }
const estGas = await this.estGasSetPaymentCollector( const estGas = await estimateGas(
dtAddress,
address, address,
paymentCollector, dtContract.methods.setPaymentCollector,
dtContract paymentCollector
) )
// Call setFeeCollector method of the contract // Call setFeeCollector method of the contract
@ -867,16 +799,7 @@ export class Datatoken {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, dtContract.methods.transfer, toAddress, amount)
let estGas
try {
estGas = await dtContract.methods
.transfer(toAddress, amount)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -898,12 +821,11 @@ export class Datatoken {
this.config this.config
) )
try { try {
const estGas = await this.estGasTransfer( const estGas = await estimateGas(
dtAddress,
toAddress,
amount,
address, address,
dtContract dtContract.methods.transfer,
toAddress,
amount
) )
// Call transfer function of the contract // Call transfer function of the contract
const trxReceipt = await dtContract.methods.transfer(toAddress, amount).send({ const trxReceipt = await dtContract.methods.transfer(toAddress, amount).send({
@ -944,17 +866,14 @@ export class Datatoken {
this.config this.config
) )
// Estimate gas for startOrder method return estimateGas(
const gasLimitDefault = this.GASLIMIT_DEFAULT address,
let estGas dtContract.methods.startOrder,
try { consumer,
estGas = await dtContract.methods serviceIndex,
.startOrder(consumer, serviceIndex, providerFees, consumeMarketFee) providerFees,
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) consumeMarketFee
} catch (e) { )
estGas = gasLimitDefault
}
return estGas
} }
/** Start Order: called by payer or consumer prior ordering a service consume on a marketplace. /** Start Order: called by payer or consumer prior ordering a service consume on a marketplace.
@ -986,14 +905,13 @@ export class Datatoken {
} }
} }
try { try {
const estGas = await this.estGasStartOrder( const estGas = await estimateGas(
dtAddress,
address, address,
dtContract.methods.startOrder,
consumer, consumer,
serviceIndex, serviceIndex,
providerFees, providerFees,
consumeMarketFee, consumeMarketFee
dtContract
) )
const trxReceipt = await dtContract.methods const trxReceipt = await dtContract.methods
@ -1032,17 +950,7 @@ export class Datatoken {
this.config this.config
) )
// Estimate gas for reuseOrder method return estimateGas(address, dtContract.methods.reuseOrder, orderTxId, providerFees)
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
} }
/** Reuse Order: called by payer or consumer having a valid order, but with expired provider access. /** 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 this.config
) )
try { try {
const estGas = await this.estGasReuseOrder( const estGas = await estimateGas(
dtAddress,
address, address,
dtContract.methods.reuseOrder,
orderTxId, orderTxId,
providerFees, providerFees
dtContract
) )
const trxReceipt = await dtContract.methods const trxReceipt = await dtContract.methods
@ -1106,17 +1013,12 @@ export class Datatoken {
contractInstance || contractInstance ||
new this.web3.eth.Contract(this.datatokensEnterpriseAbi, dtAddress) new this.web3.eth.Contract(this.datatokensEnterpriseAbi, dtAddress)
// Estimate gas for startOrder method return estimateGas(
const gasLimitDefault = this.GASLIMIT_DEFAULT address,
let estGas dtContract.methods.buyFromFreAndOrder,
try { orderParams,
estGas = await dtContract.methods freParams
.buyFromFreAndOrder(orderParams, freParams) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** Buys 1 DT from the FRE and then startsOrder, while burning that DT /** Buys 1 DT from the FRE and then startsOrder, while burning that DT
@ -1136,12 +1038,11 @@ export class Datatoken {
try { try {
const freContractParams = getFreOrderParams(freParams) const freContractParams = getFreOrderParams(freParams)
const estGas = await this.estGasBuyFromFreAndOrder( const estGas = await estimateGas(
dtAddress,
address, address,
dtContract.methods.buyFromFreAndOrder,
orderParams, orderParams,
freContractParams, freContractParams
dtContract
) )
const trxReceipt = await dtContract.methods const trxReceipt = await dtContract.methods
@ -1177,17 +1078,12 @@ export class Datatoken {
contractInstance || contractInstance ||
new this.web3.eth.Contract(this.datatokensEnterpriseAbi, dtAddress) new this.web3.eth.Contract(this.datatokensEnterpriseAbi, dtAddress)
// Estimate gas for startOrder method return estimateGas(
const gasLimitDefault = this.GASLIMIT_DEFAULT address,
let estGas dtContract.methods.buyFromDispenserAndOrder,
try { orderParams,
estGas = await dtContract.methods dispenserContract
.buyFromDispenserAndOrder(orderParams, dispenserContract) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** Gets DT from dispenser and then startsOrder, while burning that DT /** Gets DT from dispenser and then startsOrder, while burning that DT
@ -1205,12 +1101,11 @@ export class Datatoken {
): Promise<TransactionReceipt> { ): Promise<TransactionReceipt> {
const dtContract = new this.web3.eth.Contract(this.datatokensEnterpriseAbi, dtAddress) const dtContract = new this.web3.eth.Contract(this.datatokensEnterpriseAbi, dtAddress)
try { try {
const estGas = await this.estGasBuyFromDispenserAndOrder( const estGas = await estimateGas(
dtAddress,
address, address,
dtContract.methods.buyFromDispenserAndOrder,
orderParams, orderParams,
dispenserContract, dispenserContract
dtContract
) )
const trxReceipt = await dtContract.methods const trxReceipt = await dtContract.methods
@ -1247,16 +1142,7 @@ export class Datatoken {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, dtContract.methods.setData, value)
let estGas
try {
estGas = await dtContract.methods
.setData(value)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** setData /** setData
@ -1281,7 +1167,7 @@ export class Datatoken {
this.config 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 // Call setData function of the contract
const trxReceipt = await dtContract.methods.setData(value).send({ const trxReceipt = await dtContract.methods.setData(value).send({
@ -1311,17 +1197,7 @@ export class Datatoken {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, dtContract.methods.cleanPermissions)
let estGas
try {
estGas = await dtContract.methods
.cleanPermissions()
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1343,7 +1219,7 @@ export class Datatoken {
this.config this.config
) )
const estGas = await this.estGasCleanPermissions(dtAddress, address, dtContract) const estGas = await estimateGas(address, dtContract.methods.cleanPermissions)
// Call cleanPermissions function of the contract // Call cleanPermissions function of the contract
const trxReceipt = await dtContract.methods.cleanPermissions().send({ const trxReceipt = await dtContract.methods.cleanPermissions().send({

View File

@ -7,6 +7,7 @@ import {
getFairGasPrice, getFairGasPrice,
generateDtName, generateDtName,
setContractDefaults, setContractDefaults,
estimateGas,
ConfigHelper ConfigHelper
} from '../utils' } from '../utils'
import { Contract } from 'web3-eth-contract' import { Contract } from 'web3-eth-contract'
@ -25,7 +26,6 @@ interface Roles {
} }
export class Nft { export class Nft {
public GASLIMIT_DEFAULT = 1000000
public factory721Address: string public factory721Address: string
public factory721Abi: AbiItem | AbiItem[] public factory721Abi: AbiItem | AbiItem[]
public nftAbi: AbiItem | AbiItem[] public nftAbi: AbiItem | AbiItem[]
@ -80,22 +80,15 @@ export class Nft {
new this.web3.eth.Contract(this.nftAbi, nftAddress), new this.web3.eth.Contract(this.nftAbi, nftAddress),
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { nftContract.methods.createERC20,
estGas = await nftContract.methods templateIndex,
.createERC20( [name, symbol],
templateIndex, [minter, paymentCollector, mpFeeAddress, feeToken],
[name, symbol], [this.web3.utils.toWei(cap), this.web3.utils.toWei(feeAmount)],
[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
} }
/** /**
@ -142,19 +135,14 @@ export class Nft {
this.config this.config
) )
const estGas = await this.estGasCreateErc20( const estGas = await estimateGas(
nftAddress,
address, address,
minter, nftContract.methods.createERC20,
paymentCollector,
mpFeeAddress,
feeToken,
feeAmount,
cap,
name,
symbol,
templateIndex, 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 // Call createERC20 token function of the contract
@ -202,16 +190,7 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, nftContract.methods.addManager, manager)
let estGas
try {
estGas = await nftContract.methods
.addManager(manager)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -231,7 +210,7 @@ export class Nft {
throw new Error(`Caller is not NFT Owner`) 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 // Invoke addManager function of the contract
const trxReceipt = await nftContract.methods.addManager(manager).send({ const trxReceipt = await nftContract.methods.addManager(manager).send({
@ -263,16 +242,7 @@ export class Nft {
new this.web3.eth.Contract(this.nftAbi, nftAddress), new this.web3.eth.Contract(this.nftAbi, nftAddress),
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, nftContract.methods.removeManager, manager)
let estGas
try {
estGas = await nftContract.methods
.removeManager(manager)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -292,12 +262,7 @@ export class Nft {
throw new Error(`Caller is not NFT Owner`) throw new Error(`Caller is not NFT Owner`)
} }
const estGas = await this.estGasRemoveManager( const estGas = await estimateGas(address, nftContract.methods.removeManager, manager)
nftAddress,
address,
manager,
nftContract
)
// Invoke removeManager function of the contract // Invoke removeManager function of the contract
const trxReceipt = await nftContract.methods.removeManager(manager).send({ const trxReceipt = await nftContract.methods.removeManager(manager).send({
@ -329,17 +294,7 @@ export class Nft {
new this.web3.eth.Contract(this.nftAbi, nftAddress), new this.web3.eth.Contract(this.nftAbi, nftAddress),
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, nftContract.methods.addToCreateERC20List, erc20Deployer)
let estGas
try {
estGas = await nftContract.methods
.addToCreateERC20List(erc20Deployer)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -364,11 +319,10 @@ export class Nft {
} }
// Estimate gas for addToCreateERC20List method // Estimate gas for addToCreateERC20List method
const estGas = await this.estGasAddErc20Deployer( const estGas = await estimateGas(
nftAddress,
address, address,
erc20Deployer, nftContract.methods.addToCreateERC20List,
nftContract erc20Deployer
) )
// Invoke addToCreateERC20List function of the contract // Invoke addToCreateERC20List function of the contract
@ -404,17 +358,11 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { nftContract.methods.removeFromCreateERC20List,
estGas = await nftContract.methods erc20Deployer
.removeFromCreateErc20List(erc20Deployer) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -441,11 +389,10 @@ export class Nft {
) { ) {
throw new Error(`Caller is not Manager nor ERC20Deployer`) throw new Error(`Caller is not Manager nor ERC20Deployer`)
} }
const estGas = await this.estGasRemoveErc20Deployer( const estGas = await estimateGas(
nftAddress,
address, address,
erc20Deployer, nftContract.methods.removeFromCreateERC20List,
nftContract erc20Deployer
) )
// Call removeFromCreateERC20List function of the contract // Call removeFromCreateERC20List function of the contract
@ -481,16 +428,7 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, nftContract.methods.addToMetadataList, metadataUpdater)
let estGas
try {
estGas = await nftContract.methods
.addToMetadataList(metadataUpdater)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -514,11 +452,10 @@ export class Nft {
throw new Error(`Caller is not Manager`) throw new Error(`Caller is not Manager`)
} }
const estGas = await this.estGasAddMetadataUpdater( const estGas = await estimateGas(
nftAddress,
address, address,
metadataUpdater, nftContract.methods.addToMetadataList,
nftContract metadataUpdater
) )
// Call addToMetadataList function of the contract // Call addToMetadataList function of the contract
@ -552,17 +489,11 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas address,
try { nftContract.methods.removeFromMetadataList,
estGas = await nftContract.methods metadataUpdater
.removeFromMetadataList(metadataUpdater) )
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -630,16 +561,7 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, nftContract.methods.addTo725StoreList, storeUpdater)
let estGas
try {
estGas = await nftContract.methods
.addTo725StoreList(storeUpdater)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -663,11 +585,10 @@ export class Nft {
throw new Error(`Caller is not Manager`) throw new Error(`Caller is not Manager`)
} }
const estGas = await this.estGasAddStoreUpdater( const estGas = await estimateGas(
nftAddress,
address, address,
storeUpdater, nftContract.methods.addTo725StoreList,
nftContract storeUpdater
) )
// Call addTo725StoreList function of the contract // Call addTo725StoreList function of the contract
@ -701,16 +622,7 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, nftContract.methods.removeFrom725StoreList, storeUpdater)
let estGas
try {
estGas = await nftContract.methods
.removeFrom725StoreList(storeUpdater)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -738,11 +650,10 @@ export class Nft {
throw new Error(`Caller is not Manager nor storeUpdater`) throw new Error(`Caller is not Manager nor storeUpdater`)
} }
const estGas = await this.estGasRemoveStoreUpdater( const estGas = await estimateGas(
nftAddress,
address, address,
storeUpdater, nftContract.methods.removeFrom725StoreList,
nftContract storeUpdater
) )
// Call removeFrom725StoreList function of the contract // Call removeFrom725StoreList function of the contract
@ -776,16 +687,7 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, nftContract.methods.cleanPermissions)
let estGas
try {
estGas = await nftContract.methods
.cleanPermissions()
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -811,7 +713,7 @@ export class Nft {
throw new Error(`Caller is not NFT Owner`) 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 // Call cleanPermissions function of the contract
const trxReceipt = await nftContract.methods.cleanPermissions().send({ const trxReceipt = await nftContract.methods.cleanPermissions().send({
@ -846,19 +748,13 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas nftOwner,
try { nftContract.methods.transferFrom,
estGas = await nftContract.methods nftOwner,
.transferFrom(nftOwner, nftReceiver, tokenId) nftReceiver,
.estimateGas({ from: nftOwner }, (err, estGas) => tokenId
err ? gasLimitDefault : estGas )
)
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -887,12 +783,12 @@ export class Nft {
const tokenIdentifier = tokenId || 1 const tokenIdentifier = tokenId || 1
const estGas = await this.estGasTransferNft( const estGas = await estimateGas(
nftAddress, nftOwner,
nftContract.methods.transferFrom,
nftOwner, nftOwner,
nftReceiver, nftReceiver,
tokenIdentifier, tokenIdentifier
nftContract
) )
// Call transferFrom function of the contract // Call transferFrom function of the contract
@ -930,19 +826,13 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas nftOwner,
try { nftContract.methods.safeTransferFrom,
estGas = await nftContract.methods nftOwner,
.safeTransferFrom(nftOwner, nftReceiver, tokenId) nftReceiver,
.estimateGas({ from: nftOwner }, (err, estGas) => tokenId
err ? gasLimitDefault : estGas )
)
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -971,12 +861,12 @@ export class Nft {
const tokenIdentifier = tokenId || 1 const tokenIdentifier = tokenId || 1
const estGas = await this.estGasSafeTransferNft( const estGas = await estimateGas(
nftAddress, nftOwner,
nftContract.methods.safeTransferFrom,
nftOwner, nftOwner,
nftReceiver, nftReceiver,
tokenIdentifier, tokenIdentifier
nftContract
) )
// Call transferFrom function of the contract // Call transferFrom function of the contract
@ -1021,28 +911,17 @@ export class Nft {
this.config this.config
) )
if (!metadataProofs) metadataProofs = [] if (!metadataProofs) metadataProofs = []
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas metadataUpdater,
try { nftContract.methods.setMetaData,
estGas = await nftContract.methods metadataState,
.setMetaData( metadataDecryptorUrl,
metadataState, metadataDecryptorAddress,
metadataDecryptorUrl, flags,
metadataDecryptorAddress, data,
flags, metadataHash,
data, metadataProofs
metadataHash, )
metadataProofs
)
.estimateGas({ from: metadataUpdater }, (err, estGas) =>
err ? gasLimitDefault : estGas
)
} catch (e) {
LoggerInstance.error('estGasSetMetadata error: ', e.message)
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1071,17 +950,16 @@ export class Nft {
if (!(await this.getNftPermissions(nftAddress, address)).updateMetadata) { if (!(await this.getNftPermissions(nftAddress, address)).updateMetadata) {
throw new Error(`Caller is not Metadata updater`) throw new Error(`Caller is not Metadata updater`)
} }
const estGas = await this.estGasSetMetadata( const estGas = await estimateGas(
nftAddress,
address, address,
nftContract.methods.setMetaData,
metadataState, metadataState,
metadataDecryptorUrl, metadataDecryptorUrl,
metadataDecryptorAddress, metadataDecryptorAddress,
flags, flags,
data, data,
metadataHash, metadataHash,
metadataProofs, metadataProofs
nftContract
) )
const trxReceipt = await nftContract.methods const trxReceipt = await nftContract.methods
.setMetaData( .setMetaData(
@ -1122,23 +1000,15 @@ export class Nft {
new this.web3.eth.Contract(this.nftAbi, nftAddress), new this.web3.eth.Contract(this.nftAbi, nftAddress),
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
const sanitizedMetadataAndTokenURI = { const sanitizedMetadataAndTokenURI = {
...metadataAndTokenURI, ...metadataAndTokenURI,
metadataProofs: metadataAndTokenURI.metadataProofs || [] metadataProofs: metadataAndTokenURI.metadataProofs || []
} }
try { return estimateGas(
estGas = await nftContract.methods metadataUpdater,
.setMetaDataAndTokenURI(sanitizedMetadataAndTokenURI) nftContract.methods.setMetaDataAndTokenURI,
.estimateGas({ from: metadataUpdater }, (err, estGas) => sanitizedMetadataAndTokenURI
err ? gasLimitDefault : estGas )
)
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1160,16 +1030,15 @@ export class Nft {
if (!(await this.getNftPermissions(nftAddress, metadataUpdater)).updateMetadata) { if (!(await this.getNftPermissions(nftAddress, metadataUpdater)).updateMetadata) {
throw new Error(`Caller is not Metadata updater`) throw new Error(`Caller is not Metadata updater`)
} }
const estGas = await this.estGasSetMetadataAndTokenURI(
nftAddress,
metadataUpdater,
metadataAndTokenURI,
nftContract
)
const sanitizedMetadataAndTokenURI = { const sanitizedMetadataAndTokenURI = {
...metadataAndTokenURI, ...metadataAndTokenURI,
metadataProofs: metadataAndTokenURI.metadataProofs || [] metadataProofs: metadataAndTokenURI.metadataProofs || []
} }
const estGas = await estimateGas(
metadataUpdater,
nftContract.methods.setMetaDataAndTokenURI,
sanitizedMetadataAndTokenURI
)
const trxReceipt = await nftContract.methods const trxReceipt = await nftContract.methods
.setMetaDataAndTokenURI(sanitizedMetadataAndTokenURI) .setMetaDataAndTokenURI(sanitizedMetadataAndTokenURI)
.send({ .send({
@ -1202,19 +1071,11 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(
let estGas metadataUpdater,
try { nftContract.methods.setMetaDataState,
estGas = await nftContract.methods metadataState
.setMetaDataState(metadataState) )
.estimateGas({ from: metadataUpdater }, (err, estGas) =>
err ? gasLimitDefault : estGas
)
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** /**
@ -1238,7 +1099,11 @@ export class Nft {
throw new Error(`Caller is not Metadata updater`) 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 // Call transferFrom function of the contract
const trxReceipt = await nftContract.methods.setMetaDataState(metadataState).send({ const trxReceipt = await nftContract.methods.setMetaDataState(metadataState).send({
@ -1266,17 +1131,7 @@ export class Nft {
this.config this.config
) )
const gasLimitDefault = this.GASLIMIT_DEFAULT return estimateGas(address, nftContract.methods.setTokenURI, '1', data)
let estGas
try {
estGas = await nftContract.methods
.setTokenURI('1', data)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
} }
/** set TokenURI on an nft /** set TokenURI on an nft
@ -1295,7 +1150,7 @@ export class Nft {
this.config 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({ const trxReceipt = await nftContract.methods.setTokenURI('1', data).send({
from: address, from: address,
gas: estGas + 1, gas: estGas + 1,

View File

@ -11,7 +11,7 @@ import {
import { Config } from '../models' import { Config } from '../models'
import { minAbi } from './minAbi' import { minAbi } from './minAbi'
import LoggerInstance from './Logger' import LoggerInstance from './Logger'
import { ZERO_ADDRESS } from './Constants' import { GASLIMIT_DEFAULT, ZERO_ADDRESS } from './Constants'
export function setContractDefaults(contract: Contract, config: Config): Contract { export function setContractDefaults(contract: Contract, config: Config): Contract {
if (config) { if (config) {
@ -164,3 +164,29 @@ export async function amountToUnits(
LoggerInstance.error(`ERROR: FAILED TO CALL DECIMALS(), USING 18', ${e.message}`) 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<number>} gas cost of the function
*/
export async function estimateGas(
from: string,
functionToEstimateGas: Function,
...args: any[]
): Promise<any> {
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
}

View File

@ -1,11 +1,15 @@
import Decimal from 'decimal.js' import Decimal from 'decimal.js'
import { Contract } from 'web3-eth-contract' import { Contract } from 'web3-eth-contract'
import { amountToUnits, getFairGasPrice, unitsToAmount } from './ContractUtils' import {
amountToUnits,
estimateGas,
getFairGasPrice,
unitsToAmount
} from './ContractUtils'
import { minAbi } from './minAbi' import { minAbi } from './minAbi'
import LoggerInstance from './Logger' import LoggerInstance from './Logger'
import { TransactionReceipt } from 'web3-core' import { TransactionReceipt } from 'web3-core'
import Web3 from 'web3' import Web3 from 'web3'
import { GASLIMIT_DEFAULT } from './Constants'
/** /**
* Estimate gas cost for approval function * Estimate gas cost for approval function
@ -27,17 +31,7 @@ export async function estApprove(
): Promise<number> { ): Promise<number> {
const tokenContract = contractInstance || new web3.eth.Contract(minAbi, tokenAddress) const tokenContract = contractInstance || new web3.eth.Contract(minAbi, tokenAddress)
const gasLimitDefault = GASLIMIT_DEFAULT return estimateGas(account, tokenContract.methods.approve, spender, amount)
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
} }
/** /**
@ -45,7 +39,7 @@ export async function estApprove(
* @param {String} account * @param {String} account
* @param {String} tokenAddress * @param {String} tokenAddress
* @param {String} spender * @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 {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 * @param {number} tokenDecimals optional number of decimals of the token
*/ */
@ -67,13 +61,11 @@ export async function approve(
} }
let result = null let result = null
const amountFormatted = await amountToUnits(web3, tokenAddress, amount, tokenDecimals) const amountFormatted = await amountToUnits(web3, tokenAddress, amount, tokenDecimals)
const estGas = await estApprove( const estGas = await estimateGas(
web3,
account, account,
tokenAddress, tokenContract.methods.approve,
spender, spender,
amountFormatted, amountFormatted
tokenContract
) )
try { try {
@ -84,12 +76,73 @@ export async function approve(
}) })
} catch (e) { } catch (e) {
LoggerInstance.error( LoggerInstance.error(
`ERRPR: Failed to approve spender to spend tokens : ${e.message}` `ERROR: Failed to approve spender to spend tokens : ${e.message}`
) )
} }
return result 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<number>}
*/
export async function estTransfer(
web3: Web3,
account: string,
tokenAddress: string,
recipient: string,
amount: string,
contractInstance?: Contract
): Promise<number> {
const tokenContract = contractInstance || new web3.eth.Contract(minAbi, tokenAddress)
return estimateGas(account, tokenContract.methods.transfer, recipient, amount)
}
/**
* Moves amount tokens from the callers 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<TransactionReceipt | string> {
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 * Get Allowance for any erc20
* @param {Web3} web3 * @param {Web3} web3

View File

@ -468,13 +468,6 @@ describe('Pool unit test', () => {
assert((await pool.getMarketFeeCollector(poolAddress)) === factoryOwner) 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 () => { it('#collectCommunityFee- should get community fees for each token', async () => {
const spotPriceBefore = await pool.getSpotPrice( const spotPriceBefore = await pool.getSpotPrice(
poolAddress, poolAddress,
@ -953,13 +946,6 @@ describe('Pool unit test', () => {
assert((await pool.getMarketFeeCollector(poolAddress)) === factoryOwner) 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 () => { it('#getCurrentMarketFees- should get curent market fees for each token', async () => {
const currentMarketFees: CurrentFees = await pool.getCurrentMarketFees(poolAddress) const currentMarketFees: CurrentFees = await pool.getCurrentMarketFees(poolAddress)
assert(currentMarketFees !== null) assert(currentMarketFees !== null)

View File

@ -132,11 +132,6 @@ describe('Fixed Rate unit test', () => {
it('#getOwner - should get exchange owner given an id', async () => { it('#getOwner - should get exchange owner given an id', async () => {
expect(await fixedRate.getExchangeOwner(exchangeId)).to.equal(exchangeOwner) 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 () => { it('#getRouter - should get Router address', async () => {
expect(await fixedRate.getRouter()).to.equal(contracts.routerAddress) 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 () => { it('#getOwner - should get exchange owner given an id', async () => {
expect(await fixedRate.getExchangeOwner(exchangeId)).to.equal(exchangeOwner) 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 () => { it('#getRouter - should get Router address', async () => {
expect(await fixedRate.getRouter()).to.equal(contracts.routerAddress) expect(await fixedRate.getRouter()).to.equal(contracts.routerAddress)
}) })