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

Pull from origin v4main

This commit is contained in:
Jamie Hewitt 2022-05-18 10:57:34 +03:00
commit 5716a904e0
21 changed files with 2811 additions and 2965 deletions

View File

@ -58,8 +58,6 @@ jobs:
working-directory: ${{ github.workspace }}/barge
run: |
bash -x start_ocean.sh --no-aquarius --no-elasticsearch --no-provider --no-dashboard 2>&1 > start_ocean.log &
env:
CONTRACTS_VERSION: v1.0.0-alpha.31
- run: npm ci
- name: Wait for contracts deployment
working-directory: ${{ github.workspace }}/barge
@ -117,8 +115,6 @@ jobs:
working-directory: ${{ github.workspace }}/barge
run: |
bash -x start_ocean.sh --with-provider2 --no-dashboard --with-c2d 2>&1 > start_ocean.log &
env:
CONTRACTS_VERSION: v1.0.0-alpha.31
- run: npm ci
- run: npm run build:metadata

File diff suppressed because it is too large Load Diff

32
package-lock.json generated
View File

@ -1,15 +1,15 @@
{
"name": "@oceanprotocol/lib",
"version": "1.0.0-next.41",
"version": "1.0.0-next.44",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@oceanprotocol/lib",
"version": "1.0.0-next.40",
"version": "1.0.0-next.44",
"license": "Apache-2.0",
"dependencies": {
"@oceanprotocol/contracts": "^1.0.0-alpha.31",
"@oceanprotocol/contracts": "^1.0.0-alpha.34",
"bignumber.js": "^9.0.2",
"cross-fetch": "^3.1.5",
"crypto-js": "^4.1.1",
@ -24,7 +24,7 @@
"@types/chai-spies": "^1.0.3",
"@types/crypto-js": "^4.1.1",
"@types/mocha": "^9.1.1",
"@types/node": "^17.0.31",
"@types/node": "^17.0.34",
"@types/node-fetch": "^3.0.3",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
@ -2471,9 +2471,9 @@
}
},
"node_modules/@oceanprotocol/contracts": {
"version": "1.0.0-alpha.31",
"resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.31.tgz",
"integrity": "sha512-WqrhjO0Qu8Bxdr2dAkdUL1Q/rHEkTuhx8OT4J/uJltnlxykCo6F8raNQAlhdh+84hm2Bv1irXE+PdpizNLwntQ=="
"version": "1.0.0-alpha.34",
"resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.34.tgz",
"integrity": "sha512-ZhNCakYbUpXrffpS98Hj0r5K70IzzTXNoYKBX4Ks3Qqc2T7mhXIxtakzygkM0lEk038ImWuzS2PAZKTATz+X2w=="
},
"node_modules/@octokit/auth-token": {
"version": "2.5.0",
@ -3021,9 +3021,9 @@
"dev": true
},
"node_modules/@types/node": {
"version": "17.0.31",
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.31.tgz",
"integrity": "sha512-AR0x5HbXGqkEx9CadRH3EBYx/VkiUgZIhP4wvPn/+5KIsgpNoyFaRlVe0Zlx9gRtg8fA06a9tskE2MSN7TcG4Q=="
"version": "17.0.34",
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.34.tgz",
"integrity": "sha512-XImEz7XwTvDBtzlTnm8YvMqGW/ErMWBsKZ+hMTvnDIjGCKxwK5Xpc+c/oQjOauwq8M4OS11hEkpjX8rrI/eEgA=="
},
"node_modules/@types/node-fetch": {
"version": "3.0.3",
@ -19610,9 +19610,9 @@
}
},
"@oceanprotocol/contracts": {
"version": "1.0.0-alpha.31",
"resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.31.tgz",
"integrity": "sha512-WqrhjO0Qu8Bxdr2dAkdUL1Q/rHEkTuhx8OT4J/uJltnlxykCo6F8raNQAlhdh+84hm2Bv1irXE+PdpizNLwntQ=="
"version": "1.0.0-alpha.34",
"resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-1.0.0-alpha.34.tgz",
"integrity": "sha512-ZhNCakYbUpXrffpS98Hj0r5K70IzzTXNoYKBX4Ks3Qqc2T7mhXIxtakzygkM0lEk038ImWuzS2PAZKTATz+X2w=="
},
"@octokit/auth-token": {
"version": "2.5.0",
@ -20079,9 +20079,9 @@
"dev": true
},
"@types/node": {
"version": "17.0.31",
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.31.tgz",
"integrity": "sha512-AR0x5HbXGqkEx9CadRH3EBYx/VkiUgZIhP4wvPn/+5KIsgpNoyFaRlVe0Zlx9gRtg8fA06a9tskE2MSN7TcG4Q=="
"version": "17.0.34",
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.34.tgz",
"integrity": "sha512-XImEz7XwTvDBtzlTnm8YvMqGW/ErMWBsKZ+hMTvnDIjGCKxwK5Xpc+c/oQjOauwq8M4OS11hEkpjX8rrI/eEgA=="
},
"@types/node-fetch": {
"version": "3.0.3",

View File

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

View File

@ -15,3 +15,14 @@ export interface ProviderInitialize {
computeAddress: string
providerFee: ProviderFees
}
export interface ProviderComputeInitialize {
datatoken?: string
validOrder?: string
providerFee?: ProviderFees
}
export interface ProviderComputeInitializeResults {
algorithm?: ProviderComputeInitialize
datasets?: ProviderComputeInitialize[]
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -7,7 +7,8 @@ import {
ComputeAlgorithm,
ComputeAsset,
ComputeEnvironment,
ProviderInitialize
ProviderInitialize,
ProviderComputeInitializeResults
} from '../@types/'
import { noZeroX } from '../utils/ConversionTypeHelper'
import fetch from 'cross-fetch'
@ -327,6 +328,60 @@ export class Provider {
}
}
/** Initialize a compute request.
* @param {ComputeAsset} assets
* @param {ComputeAlgorithmber} algorithm
* @param {string} computeEnv
* @param {number} validUntil
* @param {string} providerUri Identifier of the asset to be registered in ocean
* @param {string} accountId
* @param {AbortSignal} signal abort signal
* @return {Promise<ProviderComputeInitialize>} ProviderComputeInitialize data
*/
public async initializeCompute(
assets: ComputeAsset[],
algorithm: ComputeAlgorithm,
computeEnv: string,
validUntil: number,
providerUri: string,
accountId: string,
signal?: AbortSignal
): Promise<ProviderComputeInitializeResults> {
const providerEndpoints = await this.getEndpoints(providerUri)
const serviceEndpoints = await this.getServiceEndpoints(
providerUri,
providerEndpoints
)
const providerData = {
datasets: assets,
algorithm: algorithm,
compute: {
env: computeEnv,
validUntil: validUntil
},
consumerAddress: accountId
}
const initializeUrl = this.getEndpointURL(serviceEndpoints, 'initializeCompute')
? this.getEndpointURL(serviceEndpoints, 'initializeCompute').urlPath
: null
if (!initializeUrl) return null
try {
const response = await fetch(initializeUrl, {
method: 'POST',
body: JSON.stringify(providerData),
headers: {
'Content-Type': 'application/json'
},
signal: signal
})
const results = await response.json()
return results
} catch (e) {
LoggerInstance.error(e)
throw new Error('ComputeJob cannot be initialized')
}
}
/** Gets fully signed URL for download
* @param {string} did
* @param {string} accountId

View File

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

View File

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

View File

@ -11,7 +11,7 @@ import {
import { Config } from '../models'
import { minAbi } from './minAbi'
import LoggerInstance from './Logger'
import { ZERO_ADDRESS } from './Constants'
import { GASLIMIT_DEFAULT, ZERO_ADDRESS } from './Constants'
export function setContractDefaults(contract: Contract, config: Config): Contract {
if (config) {
@ -164,3 +164,29 @@ export async function amountToUnits(
LoggerInstance.error(`ERROR: FAILED TO CALL DECIMALS(), USING 18', ${e.message}`)
}
}
/**
* Estimates the gas used when a function would be executed on chain
* @param {string} from account that calls the function
* @param {Function} functionToEstimateGas function that we need to estimate the gas
* @param {...any[]} args arguments of the function
* @return {Promise<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

@ -2,11 +2,11 @@ import Decimal from 'decimal.js'
import { Pool } from '..'
export function calcMaxExactOut(balance: string): Decimal {
return new Decimal(balance).div(3.01)
return new Decimal(balance).div(2)
}
export function calcMaxExactIn(balance: string): Decimal {
return new Decimal(balance).div(2.01)
return new Decimal(balance).div(2)
}
export async function getMaxSwapExactOut(
poolInstance: Pool,

View File

@ -1,11 +1,15 @@
import Decimal from 'decimal.js'
import { Contract } from 'web3-eth-contract'
import { amountToUnits, getFairGasPrice, unitsToAmount } from './ContractUtils'
import {
amountToUnits,
estimateGas,
getFairGasPrice,
unitsToAmount
} from './ContractUtils'
import { minAbi } from './minAbi'
import LoggerInstance from './Logger'
import { TransactionReceipt } from 'web3-core'
import Web3 from 'web3'
import { GASLIMIT_DEFAULT } from './Constants'
/**
* Estimate gas cost for approval function
@ -27,17 +31,7 @@ export async function estApprove(
): Promise<number> {
const tokenContract = contractInstance || new web3.eth.Contract(minAbi, tokenAddress)
const gasLimitDefault = GASLIMIT_DEFAULT
let estGas
try {
estGas = await tokenContract.methods
.approve(spender, amount)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
LoggerInstance.error('estimate gas failed for approve!', e)
}
return estGas
return estimateGas(account, tokenContract.methods.approve, spender, amount)
}
/**
@ -45,7 +39,7 @@ export async function estApprove(
* @param {String} account
* @param {String} tokenAddress
* @param {String} spender
* @param {String} amount (always expressed as wei)
* @param {String} amount amount of ERC20 tokens (always expressed as wei)
* @param {boolean} force if true, will overwrite any previous allowence. Else, will check if allowence is enough and will not send a transaction if it's not needed
* @param {number} tokenDecimals optional number of decimals of the token
*/
@ -67,13 +61,11 @@ export async function approve(
}
let result = null
const amountFormatted = await amountToUnits(web3, tokenAddress, amount, tokenDecimals)
const estGas = await estApprove(
web3,
const estGas = await estimateGas(
account,
tokenAddress,
tokenContract.methods.approve,
spender,
amountFormatted,
tokenContract
amountFormatted
)
try {
@ -84,12 +76,73 @@ export async function approve(
})
} catch (e) {
LoggerInstance.error(
`ERRPR: Failed to approve spender to spend tokens : ${e.message}`
`ERROR: Failed to approve spender to spend tokens : ${e.message}`
)
}
return result
}
/**
* Estimate gas cost for transfer function
* @param {String} account
* @param {String} tokenAddress
* @param {String} recipient
* @param {String} amount
* @param {String} force
* @param {Contract} contractInstance optional contract instance
* @return {Promise<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
* @param {Web3} web3

View File

@ -8,11 +8,39 @@ import {
NftFactory,
NftCreateData,
Datatoken,
getHash,
Nft,
sleep
sleep,
ZERO_ADDRESS
} from '../../src'
import { ProviderFees, Erc20CreateParams, ComputeJob, Asset } from '../../src/@types'
import {
Erc20CreateParams,
ComputeJob,
ComputeAsset,
ComputeAlgorithm,
ProviderComputeInitialize,
ConsumeMarketFee
} from '../../src/@types'
let config: Config
let aquarius: Aquarius
let datatoken: Datatoken
let providerUrl: string
let consumerAccount: string
let publisherAccount: string
let computeJobId: string
let providerInitializeComputeResults
let computeEnvs
let addresses: any
let ddoWith1mTimeoutId
let ddoWithNoTimeoutId
let algoDdoWith1mTimeoutId
let algoDdoWithNoTimeoutId
let resolvedDdoWith1mTimeout
let resolvedDdoWithNoTimeout
let resolvedAlgoDdoWith1mTimeout
let resolvedAlgoDdoWithNoTimeout
const assetUrl = [
{
@ -21,7 +49,7 @@ const assetUrl = [
method: 'GET'
}
]
const ddo = {
const ddoWithNoTimeout = {
'@context': ['https://w3id.org/did/v1'],
id: 'did:op:efba17455c127a885ec7830d687a8f6e64f5ba559f8506f8723c1f10f05c049c',
version: '4.0.0',
@ -52,13 +80,44 @@ const ddo = {
publisherTrustedAlgorithmPublishers: [],
publisherTrustedAlgorithms: [],
allowRawAlgorithm: true,
allowNetworkAccess: true,
namespace: 'ocean-compute',
cpus: 2,
gpus: 4,
gpuType: 'NVIDIA Tesla V100 GPU',
memory: '128M',
volumeSize: '2G'
allowNetworkAccess: true
}
}
]
}
const ddoWith1mTimeout = {
'@context': ['https://w3id.org/did/v1'],
id: 'did:op:efba17455c127a885ec7830d687a8f6e64f5ba559f8506f8723c1f10f05c049c',
version: '4.0.0',
chainId: 4,
nftAddress: '0x0',
metadata: {
created: '2021-12-20T14:35:20Z',
updated: '2021-12-20T14:35:20Z',
type: 'dataset',
name: 'dfgdfgdg',
description: 'd dfgd fgd dfg dfgdfgd dfgdf',
tags: [''],
author: 'dd',
license: 'https://market.oceanprotocol.com/terms',
additionalInformation: {
termsAndConditions: true
}
},
services: [
{
id: 'notAnId',
type: 'compute',
files: '',
datatokenAddress: '0xa15024b732A8f2146423D14209eFd074e61964F3',
serviceEndpoint: 'https://providerv4.rinkeby.oceanprotocol.com',
timeout: 60,
compute: {
publisherTrustedAlgorithmPublishers: [],
publisherTrustedAlgorithms: [],
allowRawAlgorithm: true,
allowNetworkAccess: true
}
}
]
@ -70,7 +129,7 @@ const algoAssetUrl = [
method: 'GET'
}
]
const algoDdo = {
const algoDdoWithNoTimeout = {
'@context': ['https://w3id.org/did/v1'],
id: 'did:op:efba17455c127a885ec7830d687a8f6e64f5ba559f8506f8723c1f10f05c049c',
version: '4.0.0',
@ -110,144 +169,246 @@ const algoDdo = {
}
]
}
let providerUrl: string
let consumerAccount: string
let computeJobId: string
let resolvedDDOAsset: Asset
const algoDdoWith1mTimeout = {
'@context': ['https://w3id.org/did/v1'],
id: 'did:op:efba17455c127a885ec7830d687a8f6e64f5ba559f8506f8723c1f10f05c049c',
version: '4.0.0',
chainId: 4,
nftAddress: '0x0',
metadata: {
created: '2021-12-20T14:35:20Z',
updated: '2021-12-20T14:35:20Z',
type: 'algorithm',
name: 'dfgdfgdg',
description: 'd dfgd fgd dfg dfgdfgd dfgdf',
tags: [''],
author: 'dd',
license: 'https://market.oceanprotocol.com/terms',
additionalInformation: {
termsAndConditions: true
},
algorithm: {
language: 'Node.js',
version: '1.0.0',
container: {
entrypoint: 'node $ALGO',
image: 'ubuntu',
tag: 'latest',
checksum: '44e10daa6637893f4276bb8d7301eb35306ece50f61ca34dcab550'
}
}
},
services: [
{
id: 'notAnId',
type: 'access',
files: '',
datatokenAddress: '0xa15024b732A8f2146423D14209eFd074e61964F3',
serviceEndpoint: 'https://providerv4.rinkeby.oceanprotocol.com',
timeout: 60
}
]
}
async function createAsset(
name: string,
symbol: string,
owner: string,
assetUrl: any,
ddo: any,
providerUrl: string
) {
const nft = new Nft(web3)
const Factory = new NftFactory(addresses.ERC721Factory, web3)
const chain = await web3.eth.getChainId()
ddo.chainId = parseInt(chain.toString(10))
const nftParamsAsset: NftCreateData = {
name: name,
symbol: symbol,
templateIndex: 1,
tokenURI: 'aaa',
transferable: true,
owner: owner
}
const erc20ParamsAsset: Erc20CreateParams = {
templateIndex: 1,
cap: '100000',
feeAmount: '0',
paymentCollector: ZERO_ADDRESS,
feeToken: ZERO_ADDRESS,
minter: owner,
mpFeeAddress: ZERO_ADDRESS
}
const result = await Factory.createNftWithErc20(owner, nftParamsAsset, erc20ParamsAsset)
const erc721AddressAsset = result.events.NFTCreated.returnValues[0]
const datatokenAddressAsset = result.events.TokenCreated.returnValues[0]
// create the files encrypted string
let providerResponse = await ProviderInstance.encrypt(assetUrl, providerUrl)
ddo.services[0].files = await providerResponse
ddo.services[0].datatokenAddress = datatokenAddressAsset
ddo.services[0].serviceEndpoint = providerUrl
// update ddo and set the right did
ddo.nftAddress = web3.utils.toChecksumAddress(erc721AddressAsset)
ddo.id =
'did:op:' +
SHA256(web3.utils.toChecksumAddress(erc721AddressAsset) + chain.toString(10))
providerResponse = await ProviderInstance.encrypt(ddo, providerUrl)
const encryptedResponse = await providerResponse
const validateResult = await aquarius.validate(ddo)
assert(validateResult.valid, 'Could not validate metadata')
await nft.setMetadata(
erc721AddressAsset,
owner,
0,
providerUrl,
'',
'0x2',
encryptedResponse,
validateResult.hash
)
return ddo.id
}
async function handleOrder(
order: ProviderComputeInitialize,
datatokenAddress: string,
payerAccount: string,
consumerAccount: string,
serviceIndex: number,
consumeMarkerFee?: ConsumeMarketFee
) {
/* We do have 3 possible situations:
- have validOrder and no providerFees -> then order is valid, providerFees are valid, just use it in startCompute
- have validOrder and providerFees -> then order is valid but providerFees are not valid, we need to call reuseOrder and pay only providerFees
- no validOrder -> we need to call startOrder, to pay 1 DT & providerFees
*/
if (order.providerFee && order.providerFee.providerFeeAmount) {
await datatoken.approve(
order.providerFee.providerFeeToken,
datatokenAddress,
order.providerFee.providerFeeAmount,
payerAccount
)
}
if (order.validOrder) {
if (!order.providerFee) return order.validOrder
const tx = await datatoken.reuseOrder(
datatokenAddress,
payerAccount,
order.validOrder,
order.providerFee
)
return tx.transactionHash
}
const tx = await datatoken.startOrder(
datatokenAddress,
payerAccount,
consumerAccount,
serviceIndex,
order.providerFee,
consumeMarkerFee
)
return tx.transactionHash
}
describe('Simple compute tests', async () => {
let config: Config
let addresses: any
let aquarius: Aquarius
before(async () => {
config = await getTestConfig(web3)
addresses = getAddresses()
aquarius = new Aquarius(config.metadataCacheUri)
providerUrl = config.providerUri
datatoken = new Datatoken(web3)
})
it('should publish a dataset, algorithm and start a compute job', async () => {
const nft = new Nft(web3)
const datatoken = new Datatoken(web3)
const Factory = new NftFactory(addresses.ERC721Factory, web3)
it('should publish datasets and algorithms', async () => {
const accounts = await web3.eth.getAccounts()
const publisherAccount = accounts[0]
publisherAccount = accounts[0]
consumerAccount = accounts[1]
const chain = await web3.eth.getChainId()
const nftParamsAsset: NftCreateData = {
name: 'testNFT',
symbol: 'TST',
templateIndex: 1,
tokenURI: 'aaa',
transferable: true,
owner: publisherAccount
}
const erc20ParamsAsset: Erc20CreateParams = {
templateIndex: 1,
cap: '100000',
feeAmount: '0',
paymentCollector: '0x0000000000000000000000000000000000000000',
feeToken: '0x0000000000000000000000000000000000000000',
minter: publisherAccount,
mpFeeAddress: '0x0000000000000000000000000000000000000000'
}
const result = await Factory.createNftWithErc20(
ddoWith1mTimeoutId = await createAsset(
'D1Min',
'D1M',
publisherAccount,
nftParamsAsset,
erc20ParamsAsset
assetUrl,
ddoWith1mTimeout,
providerUrl
)
ddoWithNoTimeoutId = await createAsset(
'D1Min',
'D1M',
publisherAccount,
assetUrl,
ddoWithNoTimeout,
providerUrl
)
algoDdoWith1mTimeoutId = await createAsset(
'A1Min',
'A1M',
publisherAccount,
algoAssetUrl,
algoDdoWith1mTimeout,
providerUrl
)
const erc721AddressAsset = result.events.NFTCreated.returnValues[0]
const datatokenAddressAsset = result.events.TokenCreated.returnValues[0]
// create the files encrypted string
let providerResponse = await ProviderInstance.encrypt(assetUrl, providerUrl)
ddo.services[0].files = await providerResponse
ddo.services[0].datatokenAddress = datatokenAddressAsset
// update ddo and set the right did
ddo.nftAddress = erc721AddressAsset
ddo.id =
'did:op:' +
SHA256(web3.utils.toChecksumAddress(erc721AddressAsset) + chain.toString(10))
providerResponse = await ProviderInstance.encrypt(ddo, providerUrl)
let encryptedResponse = await providerResponse
let metadataHash = getHash(JSON.stringify(ddo))
let res = await nft.setMetadata(
erc721AddressAsset,
algoDdoWithNoTimeoutId = await createAsset(
'A1Min',
'A1M',
publisherAccount,
0,
providerUrl,
'',
'0x2',
encryptedResponse,
'0x' + metadataHash
algoAssetUrl,
algoDdoWithNoTimeout,
providerUrl
)
// let's publish the algorithm as well
const nftParamsAlgo: NftCreateData = {
name: 'testNFT',
symbol: 'TST',
templateIndex: 1,
tokenURI: '',
transferable: true,
owner: publisherAccount
}
const erc20ParamsAlgo: Erc20CreateParams = {
templateIndex: 1,
cap: '100000',
feeAmount: '0',
paymentCollector: '0x0000000000000000000000000000000000000000',
feeToken: '0x0000000000000000000000000000000000000000',
minter: publisherAccount,
mpFeeAddress: '0x0000000000000000000000000000000000000000'
}
const resultAlgo = await Factory.createNftWithErc20(
})
it('should resolve published datasets and algorithms', async () => {
resolvedDdoWith1mTimeout = await aquarius.waitForAqua(ddoWith1mTimeoutId)
assert(resolvedDdoWith1mTimeout, 'Cannot fetch DDO from Aquarius')
resolvedDdoWithNoTimeout = await aquarius.waitForAqua(ddoWithNoTimeoutId)
assert(resolvedDdoWithNoTimeout, 'Cannot fetch DDO from Aquarius')
resolvedAlgoDdoWith1mTimeout = await aquarius.waitForAqua(algoDdoWith1mTimeoutId)
assert(resolvedAlgoDdoWith1mTimeout, 'Cannot fetch DDO from Aquarius')
resolvedAlgoDdoWithNoTimeout = await aquarius.waitForAqua(algoDdoWithNoTimeoutId)
assert(resolvedAlgoDdoWithNoTimeout, 'Cannot fetch DDO from Aquarius')
})
it('should send DT to consumer', async () => {
const datatoken = new Datatoken(web3)
await datatoken.mint(
resolvedDdoWith1mTimeout.services[0].datatokenAddress,
publisherAccount,
nftParamsAlgo,
erc20ParamsAlgo
'10',
consumerAccount
)
const erc721AddressAlgo = resultAlgo.events.NFTCreated.returnValues[0]
const datatokenAddressAlgo = resultAlgo.events.TokenCreated.returnValues[0]
// create the files encrypted string
providerResponse = await ProviderInstance.encrypt(algoAssetUrl, providerUrl)
algoDdo.services[0].files = await providerResponse
algoDdo.services[0].datatokenAddress = datatokenAddressAlgo
// update ddo and set the right did
algoDdo.nftAddress = erc721AddressAlgo
algoDdo.id =
'did:op:' +
SHA256(web3.utils.toChecksumAddress(erc721AddressAlgo) + chain.toString(10))
providerResponse = await ProviderInstance.encrypt(algoDdo, providerUrl)
encryptedResponse = await providerResponse
metadataHash = getHash(JSON.stringify(algoDdo))
res = await nft.setMetadata(
erc721AddressAlgo,
await datatoken.mint(
resolvedDdoWithNoTimeout.services[0].datatokenAddress,
publisherAccount,
0,
providerUrl,
'',
'0x2',
encryptedResponse,
'0x' + metadataHash
'10',
consumerAccount
)
await datatoken.mint(
resolvedAlgoDdoWith1mTimeout.services[0].datatokenAddress,
publisherAccount,
'10',
consumerAccount
)
await datatoken.mint(
resolvedAlgoDdoWithNoTimeout.services[0].datatokenAddress,
publisherAccount,
'10',
consumerAccount
)
})
// let's wait
resolvedDDOAsset = await aquarius.waitForAqua(ddo.id)
assert(resolvedDDOAsset, 'Cannot fetch DDO from Aquarius')
const resolvedDDOAlgo = await aquarius.waitForAqua(algoDdo.id)
assert(resolvedDDOAlgo, 'Cannot fetch DDO from Aquarius')
// mint 1 ERC20 and send it to the consumer
await datatoken.mint(datatokenAddressAsset, publisherAccount, '1', consumerAccount)
await datatoken.mint(datatokenAddressAlgo, publisherAccount, '1', consumerAccount)
it('should fetch compute environments from provider', async () => {
// get compute environments
const computeEnvs = await ProviderInstance.getComputeEnvironments(providerUrl)
computeEnvs = await ProviderInstance.getComputeEnvironments(providerUrl)
assert(computeEnvs, 'No Compute environments found')
})
it('should start a computeJob', async () => {
// we choose the first env
const computeEnv = computeEnvs[0].id
const computeConsumerAddress = computeEnvs[0].consumerAddress
@ -255,89 +416,53 @@ describe('Simple compute tests', async () => {
const mytime = new Date()
mytime.setMinutes(mytime.getMinutes() + 19)
const computeValidUntil = Math.floor(mytime.getTime() / 1000)
// initialize provider orders for algo
const initializeDataAlgo = await ProviderInstance.initialize(
resolvedDDOAlgo.id,
resolvedDDOAlgo.services[0].id,
0,
consumerAccount,
providerUrl,
null,
null,
computeEnv,
computeValidUntil
)
const providerAlgoFees: ProviderFees = {
providerFeeAddress: initializeDataAlgo.providerFee.providerFeeAddress,
providerFeeToken: initializeDataAlgo.providerFee.providerFeeToken,
providerFeeAmount: initializeDataAlgo.providerFee.providerFeeAmount,
v: initializeDataAlgo.providerFee.v,
r: initializeDataAlgo.providerFee.r,
s: initializeDataAlgo.providerFee.s,
providerData: initializeDataAlgo.providerFee.providerData,
validUntil: initializeDataAlgo.providerFee.validUntil
const assets: ComputeAsset[] = [
{
documentId: resolvedDdoWith1mTimeout.id,
serviceId: resolvedDdoWith1mTimeout.services[0].id
}
]
const dtAddressArray = [resolvedDdoWith1mTimeout.services[0].datatokenAddress]
const algo: ComputeAlgorithm = {
documentId: resolvedAlgoDdoWith1mTimeout.id,
serviceId: resolvedAlgoDdoWith1mTimeout.services[0].id
}
// make the payment
const txidAlgo = await datatoken.startOrder(
datatokenAddressAlgo,
consumerAccount,
computeConsumerAddress, // this is important because the c2d is the consumer, and user is the payer. Otherwise, c2d will have no access to the asset
0,
providerAlgoFees
)
assert(txidAlgo, 'Failed to order algo')
const providerValidUntil = new Date()
providerValidUntil.setHours(providerValidUntil.getHours() + 1)
// initialize provider orders for asset
const initializeData = await ProviderInstance.initialize(
resolvedDDOAsset.id,
resolvedDDOAsset.services[0].id,
0,
consumerAccount,
providerUrl,
null,
null,
providerInitializeComputeResults = await ProviderInstance.initializeCompute(
assets,
algo,
computeEnv,
computeValidUntil
computeValidUntil,
providerUrl,
consumerAccount
)
const providerDatasetFees: ProviderFees = {
providerFeeAddress: initializeData.providerFee.providerFeeAddress,
providerFeeToken: initializeData.providerFee.providerFeeToken,
providerFeeAmount: initializeData.providerFee.providerFeeAmount,
v: initializeData.providerFee.v,
r: initializeData.providerFee.r,
s: initializeData.providerFee.s,
providerData: initializeData.providerFee.providerData,
validUntil: initializeData.providerFee.validUntil
}
// make the payment
const txidAsset = await datatoken.startOrder(
datatokenAddressAsset,
assert(
!('error' in providerInitializeComputeResults.algorithm),
'Cannot order algorithm'
)
algo.transferTxId = await handleOrder(
providerInitializeComputeResults.algorithm,
resolvedAlgoDdoWith1mTimeout.services[0].datatokenAddress,
consumerAccount,
computeConsumerAddress, // this is important because the c2d is the consumer, and user is the payer. Otherwise, c2d will have no access to the asset
0,
providerDatasetFees
computeConsumerAddress,
0
)
assert(txidAsset, 'Failed to order algo')
// start the compute job
for (let i = 0; i < providerInitializeComputeResults.datasets.length; i++) {
assets[i].transferTxId = await handleOrder(
providerInitializeComputeResults.datasets[i],
dtAddressArray[i],
consumerAccount,
computeConsumerAddress,
0
)
}
const computeJobs = await ProviderInstance.computeStart(
providerUrl,
web3,
consumerAccount,
computeEnv,
{
documentId: resolvedDDOAsset.id,
serviceId: resolvedDDOAsset.services[0].id,
transferTxId: txidAsset.transactionHash
},
{
documentId: resolvedDDOAlgo.id,
serviceId: resolvedDDOAlgo.services[0].id,
transferTxId: txidAlgo.transactionHash
}
assets[0],
algo
)
assert(computeJobs, 'Cannot start compute job')
computeJobId = computeJobs[0].jobId
@ -348,7 +473,7 @@ describe('Simple compute tests', async () => {
providerUrl,
consumerAccount,
computeJobId,
resolvedDDOAsset.id
resolvedDdoWith1mTimeout.id
)) as ComputeJob
assert(jobStatus, 'Cannot retrieve compute status!')
})

View File

@ -10,9 +10,11 @@ import {
Datatoken,
getHash,
Nft,
downloadFile
downloadFile,
ZERO_ADDRESS
} from '../../src'
import { ProviderFees, Erc20CreateParams, DDO } from '../../src/@types'
<<<<<<< HEAD
const assetUrl = [
{
@ -51,51 +53,93 @@ const ddo: DDO = {
}
]
}
=======
>>>>>>> 620b5d3a24e3d76a7b9ac1fc78a370add76f549a
describe('Simple Publish & consume test', async () => {
let config: Config
let addresses: any
let aquarius: Aquarius
let providerUrl: any
let publisherAccount: string
let consumerAccount: string
const assetUrl = [
{
type: 'url',
url: 'https://raw.githubusercontent.com/oceanprotocol/testdatasets/main/shs_dataset_test.txt',
method: 'GET'
}
]
const ddo: DDO = {
'@context': ['https://w3id.org/did/v1'],
id: '',
version: '4.0.0',
chainId: 4,
nftAddress: '0x0',
metadata: {
created: '2021-12-20T14:35:20Z',
updated: '2021-12-20T14:35:20Z',
type: 'dataset',
name: 'dataset-name',
description: 'Ocean protocol test dataset description',
author: 'oceanprotocol-team',
license: 'MIT'
},
services: [
{
id: 'testFakeId',
type: 'access',
files: '',
datatokenAddress: '0x0',
serviceEndpoint: 'https://providerv4.rinkeby.oceanprotocol.com',
timeout: 0
}
]
}
before(async () => {
config = await getTestConfig(web3)
addresses = getAddresses()
aquarius = new Aquarius(config.metadataCacheUri)
providerUrl = config.providerUri
addresses = getAddresses()
})
it('Initialize accounts', async () => {
const accounts = await web3.eth.getAccounts()
publisherAccount = accounts[0]
consumerAccount = accounts[1]
})
it('should publish a dataset (create NFT + ERC20)', async () => {
const nft = new Nft(web3)
const datatoken = new Datatoken(web3)
const Factory = new NftFactory(addresses.ERC721Factory, web3)
const accounts = await web3.eth.getAccounts()
const publisherAccount = accounts[0]
const consumerAccount = accounts[1]
const nftParams: NftCreateData = {
name: 'testNFT',
symbol: 'TST',
name: '72120Bundle',
symbol: '72Bundle',
templateIndex: 1,
tokenURI: '',
tokenURI: 'https://oceanprotocol.com/nft/',
transferable: true,
owner: publisherAccount
}
const erc20Params: Erc20CreateParams = {
templateIndex: 1,
cap: '100000',
feeAmount: '0',
paymentCollector: '0x0000000000000000000000000000000000000000',
feeToken: '0x0000000000000000000000000000000000000000',
paymentCollector: ZERO_ADDRESS,
feeToken: ZERO_ADDRESS,
minter: publisherAccount,
mpFeeAddress: '0x0000000000000000000000000000000000000000'
mpFeeAddress: ZERO_ADDRESS
}
const result = await Factory.createNftWithErc20(
publisherAccount,
nftParams,
erc20Params
)
const erc721Address = result.events.NFTCreated.returnValues[0]
const datatokenAddress = result.events.TokenCreated.returnValues[0]
const tx = await Factory.createNftWithErc20(publisherAccount, nftParams, erc20Params)
const erc721Address = tx.events.NFTCreated.returnValues[0]
const datatokenAddress = tx.events.TokenCreated.returnValues[0]
// create the files encrypted string
let providerResponse = await ProviderInstance.encrypt(assetUrl, providerUrl)
@ -110,7 +154,7 @@ describe('Simple Publish & consume test', async () => {
providerResponse = await ProviderInstance.encrypt(ddo, providerUrl)
const encryptedResponse = await providerResponse
const metadataHash = getHash(JSON.stringify(ddo))
const res = await nft.setMetadata(
await nft.setMetadata(
erc721Address,
publisherAccount,
0,
@ -120,10 +164,13 @@ describe('Simple Publish & consume test', async () => {
encryptedResponse,
'0x' + metadataHash
)
const resolvedDDO = await aquarius.waitForAqua(ddo.id)
assert(resolvedDDO, 'Cannot fetch DDO from Aquarius')
// mint 1 ERC20 and send it to the consumer
await datatoken.mint(datatokenAddress, publisherAccount, '1', consumerAccount)
// initialize provider
const initializeData = await ProviderInstance.initialize(
resolvedDDO.id,
@ -132,6 +179,7 @@ describe('Simple Publish & consume test', async () => {
consumerAccount,
providerUrl
)
const providerFees: ProviderFees = {
providerFeeAddress: initializeData.providerFee.providerFeeAddress,
providerFeeToken: initializeData.providerFee.providerFeeToken,
@ -142,6 +190,7 @@ describe('Simple Publish & consume test', async () => {
providerData: initializeData.providerFee.providerData,
validUntil: initializeData.providerFee.validUntil
}
// make the payment
const txid = await datatoken.startOrder(
datatokenAddress,
@ -150,6 +199,7 @@ describe('Simple Publish & consume test', async () => {
0,
providerFees
)
// get the url
const downloadURL = await ProviderInstance.getDownloadUrl(
ddo.id,
@ -160,9 +210,10 @@ describe('Simple Publish & consume test', async () => {
providerUrl,
web3
)
assert(downloadURL, 'Provider getDownloadUrl failed')
try {
const fileData = await downloadFile(downloadURL)
await downloadFile(downloadURL)
} catch (e) {
assert.fail('Download failed')
}

View File

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

View File

@ -132,11 +132,6 @@ describe('Fixed Rate unit test', () => {
it('#getOwner - should get exchange owner given an id', async () => {
expect(await fixedRate.getExchangeOwner(exchangeId)).to.equal(exchangeOwner)
})
it('#getOPFCollector - should get OPF collector', async () => {
expect(await fixedRate.getOPCCollector()).to.equal(
contracts.opfCommunityFeeCollectorAddress
)
})
it('#getRouter - should get Router address', async () => {
expect(await fixedRate.getRouter()).to.equal(contracts.routerAddress)
})
@ -453,11 +448,6 @@ describe('Fixed Rate unit test', () => {
it('#getOwner - should get exchange owner given an id', async () => {
expect(await fixedRate.getExchangeOwner(exchangeId)).to.equal(exchangeOwner)
})
it('#getOPFCollector - should get OPF collector', async () => {
expect(await fixedRate.getOPCCollector()).to.equal(
contracts.opfCommunityFeeCollectorAddress
)
})
it('#getRouter - should get Router address', async () => {
expect(await fixedRate.getRouter()).to.equal(contracts.routerAddress)
})