From f431f1d2c63fb941ac08058e728044e411759332 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Thu, 9 Feb 2023 11:38:19 +0200 Subject: [PATCH 01/82] add ethers --- package-lock.json | 114 +++++++++++++++++++++++++++++++++++++++++++--- package.json | 5 +- 2 files changed, 110 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index 61587ae02..8d2a68584 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "cross-fetch": "^3.1.5", "crypto-js": "^4.1.1", "decimal.js": "^10.4.1", + "ethers": "^6.0.2", "web3": "^1.8.1", "web3-core": "^1.8.1", "web3-eth-contract": "^1.8.1" @@ -54,6 +55,11 @@ "web3": "^1.8.0" } }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.8.9", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.8.9.tgz", + "integrity": "sha512-93OmGCV0vO8+JQ3FHG+gZk/MPHzzMPDRiCiFcCQNTCnHaaxsacO3ScTPGlu2wX2dOtgfalbchPcw1cOYYjHCYQ==" + }, "node_modules/@babel/code-frame": { "version": "7.12.11", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", @@ -2568,7 +2574,6 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.1.2.tgz", "integrity": "sha512-KYRCASVTv6aeUi1tsF8/vpyR7zpfs3FUzy2Jqm+MU+LmUKhQ0y2FpfwqkCcxSg2ua4GALJd8k2R76WxwZGbQpA==", - "dev": true, "funding": [ { "type": "individual", @@ -3714,6 +3719,11 @@ "node": ">=0.4.0" } }, + "node_modules/aes-js": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.3.tgz", + "integrity": "sha512-/xJX0/VTPcbc5xQE2VUP91y1xN8q/rDfhEzLm+vLc3hYvb5+qHCnpJRuFcrKn63zumK/sCwYYzhG8HP78JYSTA==" + }, "node_modules/agent-base": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", @@ -7812,6 +7822,63 @@ "rlp": "^2.2.3" } }, + "node_modules/ethers": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.0.2.tgz", + "integrity": "sha512-YOHvShFjKordVEN7kVcKRp6xhpjq4ggZPcsAVuadXravZ7Z4qOflOEGfIaMnKp2ZQJqyR07iYVD6YVty4dI3Fw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/ethers-io/" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@adraffy/ens-normalize": "1.8.9", + "@noble/hashes": "1.1.2", + "@noble/secp256k1": "1.7.1", + "aes-js": "4.0.0-beta.3", + "tslib": "2.4.0", + "ws": "8.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/ethers/node_modules/@noble/secp256k1": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/@noble/secp256k1/-/secp256k1-1.7.1.tgz", + "integrity": "sha512-hOUk6AyBFmqVrv7k5WAw/LpszxVbj9gGN4JRkIX52fdFAj1UA61KXmZDvqVEm+pOyec3+fIeZB02LYa/pWOArw==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ] + }, + "node_modules/ethers/node_modules/ws": { + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz", + "integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/ethjs-unit": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/ethjs-unit/-/ethjs-unit-0.1.6.tgz", @@ -16057,8 +16124,7 @@ "node_modules/tslib": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", - "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==", - "dev": true + "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==" }, "node_modules/tsutils": { "version": "3.21.0", @@ -17518,6 +17584,11 @@ } }, "dependencies": { + "@adraffy/ens-normalize": { + "version": "1.8.9", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.8.9.tgz", + "integrity": "sha512-93OmGCV0vO8+JQ3FHG+gZk/MPHzzMPDRiCiFcCQNTCnHaaxsacO3ScTPGlu2wX2dOtgfalbchPcw1cOYYjHCYQ==" + }, "@babel/code-frame": { "version": "7.12.11", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", @@ -19256,8 +19327,7 @@ "@noble/hashes": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.1.2.tgz", - "integrity": "sha512-KYRCASVTv6aeUi1tsF8/vpyR7zpfs3FUzy2Jqm+MU+LmUKhQ0y2FpfwqkCcxSg2ua4GALJd8k2R76WxwZGbQpA==", - "dev": true + "integrity": "sha512-KYRCASVTv6aeUi1tsF8/vpyR7zpfs3FUzy2Jqm+MU+LmUKhQ0y2FpfwqkCcxSg2ua4GALJd8k2R76WxwZGbQpA==" }, "@noble/secp256k1": { "version": "1.6.3", @@ -20086,6 +20156,11 @@ "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", "dev": true }, + "aes-js": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.3.tgz", + "integrity": "sha512-/xJX0/VTPcbc5xQE2VUP91y1xN8q/rDfhEzLm+vLc3hYvb5+qHCnpJRuFcrKn63zumK/sCwYYzhG8HP78JYSTA==" + }, "agent-base": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", @@ -23288,6 +23363,32 @@ } } }, + "ethers": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.0.2.tgz", + "integrity": "sha512-YOHvShFjKordVEN7kVcKRp6xhpjq4ggZPcsAVuadXravZ7Z4qOflOEGfIaMnKp2ZQJqyR07iYVD6YVty4dI3Fw==", + "requires": { + "@adraffy/ens-normalize": "1.8.9", + "@noble/hashes": "1.1.2", + "@noble/secp256k1": "1.7.1", + "aes-js": "4.0.0-beta.3", + "tslib": "2.4.0", + "ws": "8.5.0" + }, + "dependencies": { + "@noble/secp256k1": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/@noble/secp256k1/-/secp256k1-1.7.1.tgz", + "integrity": "sha512-hOUk6AyBFmqVrv7k5WAw/LpszxVbj9gGN4JRkIX52fdFAj1UA61KXmZDvqVEm+pOyec3+fIeZB02LYa/pWOArw==" + }, + "ws": { + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz", + "integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==", + "requires": {} + } + } + }, "ethjs-unit": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/ethjs-unit/-/ethjs-unit-0.1.6.tgz", @@ -29465,8 +29566,7 @@ "tslib": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", - "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==", - "dev": true + "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==" }, "tsutils": { "version": "3.21.0", diff --git a/package.json b/package.json index a991929ee..2435928fe 100644 --- a/package.json +++ b/package.json @@ -56,9 +56,10 @@ "cross-fetch": "^3.1.5", "crypto-js": "^4.1.1", "decimal.js": "^10.4.1", + "ethers": "^6.0.2", + "web3": "^1.8.0", "web3-core": "^1.8.1", - "web3-eth-contract": "^1.8.1", - "web3": "^1.8.1" + "web3-eth-contract": "^1.8.1" }, "devDependencies": { "@truffle/hdwallet-provider": "^2.0.14", From 8d6288f63b5f38566c6434b298b953db7f288a07 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Thu, 9 Feb 2023 11:38:43 +0200 Subject: [PATCH 02/82] global updates --- src/@types/ReturnTypes.ts | 8 +-- src/contracts/SmartContract.ts | 39 +++++------ src/contracts/SmartContractWithAddress.ts | 18 ++--- src/utils/Constants.ts | 2 +- src/utils/ContractUtils.ts | 85 ++++++++++++++++------- src/utils/minAbi.ts | 5 +- 6 files changed, 93 insertions(+), 64 deletions(-) diff --git a/src/@types/ReturnTypes.ts b/src/@types/ReturnTypes.ts index 8202e808d..6728e9e68 100644 --- a/src/@types/ReturnTypes.ts +++ b/src/@types/ReturnTypes.ts @@ -1,5 +1,5 @@ -import { TransactionReceipt } from 'web3-core' - +// import { TransactionReceipt } from 'web3-core' +import { TransactionResponse } from 'ethers' export type ReceiptOrEstimate = G extends false - ? TransactionReceipt - : number + ? TransactionResponse + : bigint diff --git a/src/contracts/SmartContract.ts b/src/contracts/SmartContract.ts index fc3ec70f1..3f6d1b908 100644 --- a/src/contracts/SmartContract.ts +++ b/src/contracts/SmartContract.ts @@ -1,6 +1,7 @@ -import Web3 from 'web3' -import { Contract } from 'web3-eth-contract' -import { AbiItem } from 'web3-utils' +// import Web3 from 'web3' +// import { Contract } from 'web3-eth-contract' +// import { AbiItem } from 'web3-utils' +import { ethers, Signer, Interface, Contract, InterfaceAbi } from 'ethers' import { Config, ConfigHelper } from '../config' import { amountToUnits, @@ -10,28 +11,28 @@ import { } from '../utils' export abstract class SmartContract { - public web3: Web3 + public signer: Signer public config: Config - public abi: AbiItem | AbiItem[] + public abi: InterfaceAbi - abstract getDefaultAbi(): AbiItem | AbiItem[] + abstract getDefaultAbi() /** * Instantiate the smart contract. - * @param {Web3} web3 + * @param {Signer} signer * @param {string | number} network Network id or name * @param {Config} config Configutation of the smart contract * @param {AbiItem | AbiItem[]} abi ABI of the smart contract */ constructor( - web3: Web3, + signer: Signer, network?: string | number, config?: Config, - abi?: AbiItem | AbiItem[] + abi?: InterfaceAbi ) { - this.web3 = web3 + this.signer = signer this.config = config || new ConfigHelper().getConfig(network || 'unknown') - this.abi = abi || (this.getDefaultAbi() as AbiItem[]) + this.abi = abi || this.getDefaultAbi() } protected async amountToUnits( @@ -39,7 +40,7 @@ export abstract class SmartContract { amount: string, tokenDecimals?: number ): Promise { - return amountToUnits(this.web3, token, amount, tokenDecimals) + return amountToUnits(this.signer, token, amount, tokenDecimals) } protected async unitsToAmount( @@ -47,21 +48,15 @@ export abstract class SmartContract { amount: string, tokenDecimals?: number ): Promise { - return unitsToAmount(this.web3, token, amount, tokenDecimals) + return unitsToAmount(this.signer, token, amount, tokenDecimals) } protected async getFairGasPrice(): Promise { - return getFairGasPrice(this.web3, this.config?.gasFeeMultiplier) + return getFairGasPrice(this.signer, this.config?.gasFeeMultiplier) } - protected getContract( - address: string, - account?: string, - abi?: AbiItem | AbiItem[] - ): Contract { - const contract = new this.web3.eth.Contract(abi || this.abi, address, { - from: account - }) + protected getContract(address: string, account?: string, abi?: InterfaceAbi): Contract { + const contract = new ethers.Contract(address, abi || this.abi, this.signer) return setContractDefaults(contract, this.config) } } diff --git a/src/contracts/SmartContractWithAddress.ts b/src/contracts/SmartContractWithAddress.ts index 71db1b2bc..42b966c65 100644 --- a/src/contracts/SmartContractWithAddress.ts +++ b/src/contracts/SmartContractWithAddress.ts @@ -1,6 +1,8 @@ -import Web3 from 'web3' -import { Contract } from 'web3-eth-contract' -import { AbiItem } from 'web3-utils' +// import Web3 from 'web3' +// import { Contract } from 'web3-eth-contract' +// import { AbiItem } from 'web3-utils' + +import { Signer, InterfaceAbi, Contract } from 'ethers' import { Config } from '../config' import { SmartContract } from './SmartContract' @@ -11,19 +13,19 @@ export abstract class SmartContractWithAddress extends SmartContract { /** * Instantiate the smart contract. * @param {string} address Address of the smart contract - * @param {Web3} web3 + * @param {Signer} signer * @param {string | number} network Network id or name * @param {Config} config Configutation of the smart contract - * @param {AbiItem | AbiItem[]} abi ABI of the smart contract + * @param {InterfaceAbi} abi ABI of the smart contract */ constructor( address: string, - web3: Web3, + signer: Signer, network?: string | number, config?: Config, - abi?: AbiItem | AbiItem[] + abi?: InterfaceAbi ) { - super(web3, network, config, abi) + super(signer, network, config, abi) this.address = address this.contract = this.getContract(this.address) } diff --git a/src/utils/Constants.ts b/src/utils/Constants.ts index 59474b1a2..0141f2cfe 100644 --- a/src/utils/Constants.ts +++ b/src/utils/Constants.ts @@ -1,5 +1,5 @@ export const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' -export const GASLIMIT_DEFAULT = 1000000 +export const GASLIMIT_DEFAULT = BigInt(1000000) export const MAX_UINT_256 = '115792089237316195423570985008687907853269984665640564039457584007913129639934' export const FEE_HISTORY_NOT_SUPPORTED = diff --git a/src/utils/ContractUtils.ts b/src/utils/ContractUtils.ts index 7576c999d..44c13db62 100644 --- a/src/utils/ContractUtils.ts +++ b/src/utils/ContractUtils.ts @@ -1,16 +1,25 @@ -import Web3 from 'web3' +// import Web3 from 'web3' +// import { Contract } from 'web3-eth-contract' +// import { TransactionReceipt } from 'web3-core' +import { + ethers, + Signer, + InterfaceAbi, + Contract, + TransactionResponse, + ContractMethod +} from 'ethers' import BigNumber from 'bignumber.js' -import { Contract } from 'web3-eth-contract' import { Config } from '../config' import { minAbi, GASLIMIT_DEFAULT, LoggerInstance, FEE_HISTORY_NOT_SUPPORTED } from '.' -import { TransactionReceipt } from 'web3-core' const MIN_GAS_FEE_POLYGON = 30000000000 // minimum recommended 30 gwei polygon main and mumbai fees const POLYGON_NETWORK_ID = 137 const MUMBAI_NETWORK_ID = 80001 export function setContractDefaults(contract: Contract, config: Config): Contract { - if (config) { + // TO DO - since ethers does not provide this + /* if (config) { if (config.transactionBlockTimeout) contract.transactionBlockTimeout = config.transactionBlockTimeout if (config.transactionConfirmationBlocks) @@ -18,14 +27,16 @@ export function setContractDefaults(contract: Contract, config: Config): Contrac if (config.transactionPollingTimeout) contract.transactionPollingTimeout = config.transactionPollingTimeout } + */ return contract } export async function getFairGasPrice( - web3: Web3, + signer: Signer, gasFeeMultiplier: number ): Promise { - const x = new BigNumber(await web3.eth.getGasPrice()) + const price = await (await signer.provider.getFeeData()).gasPrice + const x = BigNumber(price.toString()) if (gasFeeMultiplier) return x .multipliedBy(gasFeeMultiplier) @@ -34,14 +45,17 @@ export async function getFairGasPrice( else return x.toString(10) } +export async function getTokenDecimals(signer: Signer, token: string) { + const tokenContract = new ethers.Contract(token, minAbi, signer) + return tokenContract.decimals() +} export async function unitsToAmount( - web3: Web3, + signer: Signer, token: string, amount: string, tokenDecimals?: number ): Promise { - const tokenContract = new web3.eth.Contract(minAbi, token) - let decimals = tokenDecimals || (await tokenContract.methods.decimals().call()) + let decimals = tokenDecimals || (await getTokenDecimals(signer, token)) if (decimals === '0') { decimals = 18 } @@ -55,13 +69,12 @@ export async function unitsToAmount( } export async function amountToUnits( - web3: Web3, + signer: Signer, token: string, amount: string, tokenDecimals?: number ): Promise { - const tokenContract = new web3.eth.Contract(minAbi, token) - let decimals = tokenDecimals || (await tokenContract.methods.decimals().call()) + let decimals = tokenDecimals || (await getTokenDecimals(signer, token)) if (decimals === '0') { decimals = 18 } @@ -75,20 +88,27 @@ export async function amountToUnits( /** * Estimates the gas used when a function would be executed on chain - * @param {string} from account that calls the function * @param {Function} functionToEstimateGas function that we need to estimate the gas * @param {...any[]} args arguments of the function * @return {Promise} gas cost of the function */ export async function calculateEstimatedGas( - from: string, - functionToEstimateGas: Function, + functionToEstimateGas: ContractMethod, ...args: any[] -): Promise { - const estimatedGas = await functionToEstimateGas +): Promise { + const estimate = await functionToEstimateGas.estimateGas(args) + return estimate || GASLIMIT_DEFAULT + /* const estimatedGas = await functionToEstimateGas .apply(null, args) .estimateGas({ from }, (err, estGas) => (err ? GASLIMIT_DEFAULT : estGas)) return estimatedGas + */ +} + +export function getEventFromTx(txReceipt, eventName) { + return txReceipt.events.filter((log) => { + return log.event === eventName + })[0] } /** @@ -101,20 +121,30 @@ export async function calculateEstimatedGas( * @return {Promise} transaction receipt */ export async function sendTx( - from: string, - estGas: number, - web3: Web3, + estGas: bigint, + signer: Signer, gasFeeMultiplier: number, functionToSend: Function, ...args: any[] -): Promise { - const sendTxValue: Record = { - from, - gas: estGas + 1 +): Promise { + const { chainId } = await signer.provider.getNetwork() + const feeHistory = await signer.provider.getFeeData() + let overrides + if (feeHistory.maxPriorityFeePerGas) { + overrides = { + maxPriorityFeePerGas: feeHistory.maxPriorityFeePerGas, + maxFeePerGas: feeHistory.maxFeePerGas + } + } else { + overrides = { + gasPrice: feeHistory.gasPrice + } } - const networkId = await web3.eth.getChainId() - try { - const feeHistory = await web3.eth.getFeeHistory(1, 'latest', [75]) + overrides.gasLimit = estGas + const trxReceipt = await functionToSend(args, overrides) + return trxReceipt + /* try { + const feeHistory = await signer.provider,web3.eth.getFeeHistory(1, 'latest', [75]) if (feeHistory && feeHistory?.baseFeePerGas?.[0] && feeHistory?.reward?.[0]?.[0]) { let aggressiveFee = new BigNumber(feeHistory?.reward?.[0]?.[0]) if (gasFeeMultiplier > 1) { @@ -161,4 +191,5 @@ export async function sendTx( const trxReceipt = await functionToSend.apply(null, args).send(sendTxValue) return trxReceipt + */ } diff --git a/src/utils/minAbi.ts b/src/utils/minAbi.ts index 46db9cba9..d963f9920 100644 --- a/src/utils/minAbi.ts +++ b/src/utils/minAbi.ts @@ -1,4 +1,5 @@ -import { AbiItem } from 'web3-utils/types' +// import { AbiItem } from 'web3-utils/types' +import { ethers } from 'ethers' export const minAbi = [ { @@ -221,4 +222,4 @@ export const minAbi = [ name: 'Transfer', type: 'event' } -] as AbiItem[] +] From abf0c9bbccdadffc261a34086278348ad9e6ba21 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Thu, 9 Feb 2023 11:38:57 +0200 Subject: [PATCH 03/82] ve updates --- src/contracts/ve/VeAllocate.ts | 37 +++++-------- src/contracts/ve/VeFeeDistributor.ts | 33 +++++------- src/contracts/ve/VeFeeEstimate.ts | 14 +++-- src/contracts/ve/VeOcean.ts | 77 +++++++++++----------------- 4 files changed, 61 insertions(+), 100 deletions(-) diff --git a/src/contracts/ve/VeAllocate.ts b/src/contracts/ve/VeAllocate.ts index 912b9e155..305662548 100644 --- a/src/contracts/ve/VeAllocate.ts +++ b/src/contracts/ve/VeAllocate.ts @@ -1,4 +1,5 @@ -import { AbiItem } from 'web3-utils' +// import { AbiItem } from 'web3-utils' +import { ethers, Signer, Interface, InterfaceAbi, Contract } from 'ethers' import veAllocateABI from '@oceanprotocol/contracts/artifacts/contracts/ve/veAllocate.sol/veAllocate.json' import { calculateEstimatedGas, sendTx } from '../../utils' import { SmartContractWithAddress } from '../SmartContractWithAddress' @@ -7,29 +8,26 @@ import { ReceiptOrEstimate } from '../../@types' * Provides an interface for veOcean contract */ export class VeAllocate extends SmartContractWithAddress { - getDefaultAbi(): AbiItem | AbiItem[] { - return veAllocateABI.abi as AbiItem[] + getDefaultAbi() { + return veAllocateABI.abi } /** * set a specific percentage of veOcean to a specific nft * Maximum allocated percentage is 10000, so 1% is specified as 100 - * @param {String} userAddress user address * @param {String} amount Percentage used * @param {String} nft NFT address to allocate to * @param {String} chainId chainId of NFT * @return {Promise} */ public async setAllocation( - userAddress: string, amount: string, nft: string, chainId: number, estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - userAddress, - this.contract.methods.setAllocation, + this.contract.setAllocation, amount, nft, chainId @@ -38,11 +36,10 @@ export class VeAllocate extends SmartContractWithAddress { // Invoke function of the contract const trxReceipt = await sendTx( - userAddress, - estGas + 1, - this.web3, + estGas + BigInt(1), + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.setAllocation, + this.contract.setAllocation, amount, nft, chainId @@ -53,22 +50,19 @@ export class VeAllocate extends SmartContractWithAddress { /** * set specific percetage of veOcean to multiple nfts * Maximum allocated percentage is 10000, so 1% is specified as 100 - * @param {String} userAddress user address * @param {String[]} amount Array of percentages used * @param {String[]} nft Array of NFT addresses * @param {String[]} chainId Array of chainIds * @return {Promise} */ public async setBatchAllocation( - userAddress: string, amount: string[], nft: string[], chainId: number[], estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - userAddress, - this.contract.methods.setBatchAllocation, + this.contract.setBatchAllocation, amount, nft, chainId @@ -77,11 +71,10 @@ export class VeAllocate extends SmartContractWithAddress { // Invoke function of the contract const trxReceipt = await sendTx( - userAddress, - estGas + 1, - this.web3, + estGas + BigInt(1), + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.setBatchAllocation, + this.contract.setBatchAllocation, amount, nft, chainId @@ -94,7 +87,7 @@ export class VeAllocate extends SmartContractWithAddress { * @return {Promise} */ public async getTotalAllocation(userAddress: string): Promise { - const allocation = await this.contract.methods.getTotalAllocation(userAddress).call() + const allocation = await this.contract.getTotalAllocation(userAddress) return allocation } @@ -109,9 +102,7 @@ export class VeAllocate extends SmartContractWithAddress { nft: string, chainId: string ): Promise { - const allocation = await this.contract.methods - .getveAllocation(userAddress, nft, chainId) - .call() + const allocation = await this.contract.getveAllocation(userAddress, nft, chainId) return allocation } } diff --git a/src/contracts/ve/VeFeeDistributor.ts b/src/contracts/ve/VeFeeDistributor.ts index 956fd4a31..84420bb28 100644 --- a/src/contracts/ve/VeFeeDistributor.ts +++ b/src/contracts/ve/VeFeeDistributor.ts @@ -1,4 +1,5 @@ -import { AbiItem } from 'web3-utils' +// import { AbiItem } from 'web3-utils' +import { ethers, InterfaceAbi, Interface } from 'ethers' import veFeeABI from '@oceanprotocol/contracts/artifacts/contracts/ve/veFeeDistributor.vy/veFeeDistributor.json' import { calculateEstimatedGas, sendTx } from '../../utils' import { SmartContractWithAddress } from '../SmartContractWithAddress' @@ -7,8 +8,8 @@ import { ReceiptOrEstimate } from '../../@types' * Provides an interface for veOcean contract */ export class VeFeeDistributor extends SmartContractWithAddress { - getDefaultAbi(): AbiItem | AbiItem[] { - return veFeeABI.abi as AbiItem[] + getDefaultAbi() { + return veFeeABI.abi } /** @@ -18,23 +19,20 @@ export class VeFeeDistributor extends SmartContractWithAddress { may need to be called more than once to claim all available fees. In the `Claimed` event that fires, if `claim_epoch` is less than `max_epoch`, the account may claim again - * @param {String} userAddress user address * @return {Promise} */ public async claim( - userAddress: string, estimateGas?: G ): Promise> { - const estGas = await calculateEstimatedGas(userAddress, this.contract.methods.claim) + const estGas = await calculateEstimatedGas(this.contract.claim) if (estimateGas) return >estGas // Invoke function of the contract const trxReceipt = await sendTx( - userAddress, - estGas + 20000, - this.web3, + estGas + BigInt(20000), + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.claim + this.contract.claim ) return >trxReceipt } @@ -44,29 +42,22 @@ export class VeFeeDistributor extends SmartContractWithAddress { Used to claim for many accounts at once, or to make multiple claims for the same address when that address has significant veOCEAN history - * @param {String} fromUserAddress user address that sends the tx * @param {String} addresses array of addresses to claim * @return {Promise} */ public async claimMany( - fromUserAddress: string, addresses: string[], estimateGas?: G ): Promise> { - const estGas = await calculateEstimatedGas( - fromUserAddress, - this.contract.methods.claim_many, - addresses - ) + const estGas = await calculateEstimatedGas(this.contract.claim_many, addresses) if (estimateGas) return >estGas // Invoke function of the contract const trxReceipt = await sendTx( - fromUserAddress, - estGas + 20000, - this.web3, + estGas + BigInt(20000), + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.claim_many, + this.contract.claim_many, addresses ) return >trxReceipt diff --git a/src/contracts/ve/VeFeeEstimate.ts b/src/contracts/ve/VeFeeEstimate.ts index ea2348c12..ff356e22d 100644 --- a/src/contracts/ve/VeFeeEstimate.ts +++ b/src/contracts/ve/VeFeeEstimate.ts @@ -1,4 +1,5 @@ -import { AbiItem } from 'web3-utils' +// import { AbiItem } from 'web3-utils' +import { ethers, InterfaceAbi, Interface } from 'ethers' import veFeeEstimate from '@oceanprotocol/contracts/artifacts/contracts/ve/veFeeEstimate.vy/veFeeEstimate.json' import { SmartContractWithAddress } from '../SmartContractWithAddress' import { VeOcean } from './VeOcean' @@ -6,8 +7,8 @@ import { VeOcean } from './VeOcean' * Provides an interface for veOcean contract */ export class VeFeeEstimate extends SmartContractWithAddress { - getDefaultAbi(): AbiItem | AbiItem[] { - return veFeeEstimate.abi as AbiItem[] + getDefaultAbi() { + return veFeeEstimate.abi } /** @@ -16,11 +17,8 @@ export class VeFeeEstimate extends SmartContractWithAddress { * @return {Promise} */ public async estimateClaim(userAddress: string): Promise { - const amount = await this.contract.methods.estimateClaim(userAddress).call() - const veOcean = new VeOcean( - await this.contract.methods.voting_escrow().call(), - this.web3 - ) + const amount = await this.contract.estimateClaim(userAddress) + const veOcean = new VeOcean(await this.contract.voting_escrow(), this.signer) const amountFormated = await this.unitsToAmount(await veOcean.getToken(), amount) return amountFormated } diff --git a/src/contracts/ve/VeOcean.ts b/src/contracts/ve/VeOcean.ts index 6e28c41ab..9e7e22bb1 100644 --- a/src/contracts/ve/VeOcean.ts +++ b/src/contracts/ve/VeOcean.ts @@ -1,4 +1,5 @@ -import { AbiItem } from 'web3-utils' +// import { AbiItem } from 'web3-utils' +import { ethers, Interface, InterfaceAbi } from 'ethers' import veOceanABI from '@oceanprotocol/contracts/artifacts/contracts/ve/veOCEAN.vy/veOCEAN.json' import { calculateEstimatedGas, sendTx } from '../../utils' import { SmartContractWithAddress } from '../SmartContractWithAddress' @@ -7,27 +8,24 @@ import { ReceiptOrEstimate } from '../../@types' * Provides an interface for veOcean contract */ export class VeOcean extends SmartContractWithAddress { - getDefaultAbi(): AbiItem | AbiItem[] { - return veOceanABI.abi as AbiItem[] + getDefaultAbi() { + return veOceanABI.abi } /** * Deposit `amount` tokens for `userAddress` and lock until `unlockTime` - * @param {String} userAddress user address * @param {String} amount Amount of tokens to be locked * @param {Number} unlockTime Timestamp for unlock * @return {Promise} */ public async lockTokens( - userAddress: string, amount: string, unlockTime: number, estimateGas?: G ): Promise> { const amountFormatted = await this.amountToUnits(await this.getToken(), amount) const estGas = await calculateEstimatedGas( - userAddress, - this.contract.methods.create_lock, + this.contract.create_lock, amountFormatted, unlockTime ) @@ -35,11 +33,10 @@ export class VeOcean extends SmartContractWithAddress { // Invoke function of the contract const trxReceipt = await sendTx( - userAddress, - estGas + 20000, // sometimes, it's not enough - this.web3, + estGas + BigInt(20000), + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.create_lock, + this.contract.create_lock, amountFormatted, unlockTime ) @@ -55,15 +52,13 @@ export class VeOcean extends SmartContractWithAddress { * @return {Promise} */ public async depositFor( - fromUserAddress: string, toAddress: string, amount: string, estimateGas?: G ): Promise> { const amountFormatted = await this.amountToUnits(await this.getToken(), amount) const estGas = await calculateEstimatedGas( - fromUserAddress, - this.contract.methods.deposit_for, + this.contract.deposit_for, toAddress, amountFormatted ) @@ -71,11 +66,10 @@ export class VeOcean extends SmartContractWithAddress { // Invoke function of the contract const trxReceipt = await sendTx( - fromUserAddress, - estGas + 20000, // sometimes, it's not enough - this.web3, + estGas + BigInt(20000), + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.deposit_for, + this.contract.deposit_for, toAddress, amountFormatted ) @@ -84,30 +78,26 @@ export class VeOcean extends SmartContractWithAddress { /** * Deposit `amount` additional tokens for `userAddress` without modifying the unlock time - * @param {String} userAddress user address that sends the tx * @param {String} amount Amount of tokens to be locked * @return {Promise} */ public async increaseAmount( - userAddress: string, amount: string, estimateGas?: G ): Promise> { const amountFormatted = await this.amountToUnits(await this.getToken(), amount) const estGas = await calculateEstimatedGas( - userAddress, - this.contract.methods.increase_amount, + this.contract.increase_amount, amountFormatted ) if (estimateGas) return >estGas // Invoke function of the contract const trxReceipt = await sendTx( - userAddress, - estGas + 20000, // sometimes, it's not enough - this.web3, + estGas + BigInt(20000), + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.increase_amount, + this.contract.increase_amount, amountFormatted ) return >trxReceipt @@ -120,24 +110,21 @@ export class VeOcean extends SmartContractWithAddress { * @return {Promise} */ public async increaseUnlockTime( - userAddress: string, unlockTime: number, estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - userAddress, - this.contract.methods.increase_unlock_time, + this.contract.increase_unlock_time, unlockTime ) if (estimateGas) return >estGas // Invoke function of the contract const trxReceipt = await sendTx( - userAddress, - estGas + 20000, // sometimes, it's not enough - this.web3, + estGas + BigInt(20000), + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.increase_unlock_time, + this.contract.increase_unlock_time, unlockTime ) return >trxReceipt @@ -145,26 +132,20 @@ export class VeOcean extends SmartContractWithAddress { /** * Withdraw all tokens for `userAddress` - * @param {String} userAddress user address that sends the tx * @return {Promise} */ public async withdraw( - userAddress: string, estimateGas?: G ): Promise> { - const estGas = await calculateEstimatedGas( - userAddress, - this.contract.methods.withdraw - ) + const estGas = await calculateEstimatedGas(this.contract.withdraw) if (estimateGas) return >estGas // Invoke function of the contract const trxReceipt = await sendTx( - userAddress, - estGas + 1, - this.web3, + estGas + BigInt(1), + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.withdraw + this.contract.withdraw ) return >trxReceipt } @@ -174,7 +155,7 @@ export class VeOcean extends SmartContractWithAddress { * @return {Promise} */ public async getVotingPower(userAddress: string): Promise { - const balance = await this.contract.methods.balanceOf(userAddress).call() + const balance = await this.contract.balanceOf(userAddress) return balance } @@ -183,7 +164,7 @@ export class VeOcean extends SmartContractWithAddress { * @return {Promise} */ public async getLockedAmount(userAddress: string): Promise { - const balance = await this.contract.methods.locked(userAddress).call() + const balance = await this.contract.locked(userAddress) const balanceFormated = await this.unitsToAmount( await this.getToken(), balance.amount @@ -197,7 +178,7 @@ export class VeOcean extends SmartContractWithAddress { * @return {Promise} */ public async lockEnd(userAddress: string): Promise { - const untilLock = await this.contract.methods.locked__end(userAddress).call() + const untilLock = await this.contract.locked__end(userAddress) return untilLock } @@ -207,7 +188,7 @@ export class VeOcean extends SmartContractWithAddress { public async totalSupply(): Promise { const supplyFormated = await this.unitsToAmount( await this.getToken(), - await this.contract.methods.totalSupply().call() + await this.contract.totalSupply() ) return supplyFormated } @@ -216,7 +197,7 @@ export class VeOcean extends SmartContractWithAddress { * @return {Promise} */ public async getToken(): Promise { - const tokenAddress = await this.contract.methods.token().call() + const tokenAddress = await this.contract.token() return tokenAddress } } From 7289220ca4f409fba20014ec25756d1e2e05e17d Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Thu, 9 Feb 2023 11:39:04 +0200 Subject: [PATCH 04/82] ve tests --- test/config.ts | 12 ++- test/unit/veOcean.test.ts | 164 ++++++++++++++++++++++---------------- 2 files changed, 106 insertions(+), 70 deletions(-) diff --git a/test/config.ts b/test/config.ts index 19519b188..56e5e84ee 100644 --- a/test/config.ts +++ b/test/config.ts @@ -1,4 +1,5 @@ import Web3 from 'web3' +import { ethers, Wallet, JsonRpcProvider, Signer } from 'ethers' import fs from 'fs' import { homedir } from 'os' import { ConfigHelper, configHelperNetworks } from '../src/config' @@ -11,8 +12,15 @@ export const GAS_PRICE = '3000000000' // by default, we connect with development network export const web3 = new Web3(process.env.NODE_URI || configHelperNetworks[1].nodeUri) -export const getTestConfig = async (web3: Web3) => { - const config = new ConfigHelper().getConfig(await web3.eth.getChainId()) +export const provider = new JsonRpcProvider( + process.env.NODE_URI || configHelperNetworks[1].nodeUri +) +// const wallet = new Wallet.fromMnemonic(process.env.MNEMONIC); +// export const signer = wallet.connect(provider) + +export const getTestConfig = async (signer: Signer) => { + const { chainId } = await signer.provider.getNetwork() + const config = new ConfigHelper().getConfig(String(chainId)) config.providerUri = process.env.PROVIDER_URL || config.providerUri return config } diff --git a/test/unit/veOcean.test.ts b/test/unit/veOcean.test.ts index de7044bfc..aef8b91f7 100644 --- a/test/unit/veOcean.test.ts +++ b/test/unit/veOcean.test.ts @@ -1,6 +1,6 @@ import { assert } from 'chai' import { AbiItem } from 'web3-utils' -import { web3, getTestConfig, getAddresses } from '../config' +import { web3, getTestConfig, getAddresses, provider } from '../config' import { Config, approve, @@ -10,8 +10,10 @@ import { calculateEstimatedGas, NftFactory, VeAllocate, - VeFeeEstimate + VeFeeEstimate, + getEventFromTx } from '../../src' +import { ethers, InterfaceAbi, Interface, Signer } from 'ethers' describe('veOcean tests', async () => { let config: Config @@ -21,23 +23,18 @@ describe('veOcean tests', async () => { let veFeeDistributor: VeFeeDistributor let veFeeEstimate: VeFeeEstimate let veAllocate: VeAllocate - let ownerAccount: string - let Alice: string - let Bob: string + const ownerAccount = (await provider.getSigner(0)) as Signer + const Alice = (await provider.getSigner(1)) as Signer + const Bob = (await provider.getSigner(2)) as Signer let nft1, nft2, nft3 let chainId before(async () => { - config = await getTestConfig(web3) + config = await getTestConfig(ownerAccount as Signer) }) it('initialize accounts', async () => { - addresses = getAddresses() - const accounts = await web3.eth.getAccounts() - chainId = await web3.eth.getChainId() - ownerAccount = accounts[0] - Alice = accounts[1] - Bob = accounts[2] + chainId = (await Alice.provider.getNetwork()).chainId const minAbi = [ { constant: false, @@ -51,85 +48,99 @@ describe('veOcean tests', async () => { stateMutability: 'nonpayable', type: 'function' } - ] as AbiItem[] - const tokenContract = new web3.eth.Contract(minAbi, addresses.Ocean) + ] + const tokenContract = new ethers.Contract(addresses.Ocean, minAbi) const estGas = await calculateEstimatedGas( - ownerAccount, - tokenContract.methods.mint, + tokenContract.mint, Alice, web3.utils.toWei('1000') ) await sendTx( - ownerAccount, estGas, - web3, + ownerAccount, 1, - tokenContract.methods.mint, + tokenContract.mint, Alice, web3.utils.toWei('1000') ) await sendTx( - ownerAccount, estGas, - web3, + ownerAccount, 1, - tokenContract.methods.mint, + tokenContract.mint, Bob, web3.utils.toWei('1000') ) - veOcean = new VeOcean(addresses.veOCEAN, web3) - veFeeDistributor = new VeFeeDistributor(addresses.veFeeDistributor, web3) - veAllocate = new VeAllocate(addresses.veAllocate, web3) - veFeeEstimate = new VeFeeEstimate(addresses.veFeeEstimate, web3) - nftFactory = new NftFactory(addresses.ERC721Factory, web3) + veOcean = new VeOcean(addresses.veOCEAN, Alice) + veFeeDistributor = new VeFeeDistributor(addresses.veFeeDistributor, Alice) + veAllocate = new VeAllocate(addresses.veAllocate, Alice) + veFeeEstimate = new VeFeeEstimate(addresses.veFeeEstimate, Alice) + nftFactory = new NftFactory(addresses.ERC721Factory, Alice) }) it('Alice should lock 100 Ocean', async () => { // since we can only lock once, we test if tx fails or not // so if there is already a lock, skip it - const currentBalance = await veOcean.getLockedAmount(Alice) - const currentLock = await veOcean.lockEnd(Alice) + const currentBalance = await veOcean.getLockedAmount(await Alice.getAddress()) + const currentLock = await veOcean.lockEnd(await Alice.getAddress()) const amount = '100' - await approve(web3, config, Alice, addresses.Ocean, addresses.veOCEAN, amount) + await approve( + web3, + config, + await Alice.getAddress(), + addresses.Ocean, + addresses.veOCEAN, + amount + ) const timestamp = Math.floor(Date.now() / 1000) const unlockTime = timestamp + 7 * 86400 if (parseInt(currentBalance) > 0 || currentLock > 0) { // we already have some locked tokens, so our transaction should fail try { - await veOcean.lockTokens(Alice, amount, unlockTime) + await veOcean.lockTokens(amount, unlockTime) assert(false, 'This should fail!') } catch (e) { // do nothing } } else { - const estGas = await veOcean.lockTokens(Alice, amount, unlockTime, true) + const estGas = await veOcean.lockTokens(amount, unlockTime, true) console.log('Estimate gas for lockTokens:' + estGas) - const tx = await veOcean.lockTokens(Alice, amount, unlockTime) + const response = await veOcean.lockTokens(amount, unlockTime) + const tx = await response.wait() // check events - assert(tx.events.Deposit.returnValues[0] === Alice) - assert(tx.events.Deposit.returnValues[1] === web3.utils.toWei(amount)) - assert(tx.events.Deposit.returnValues[2] > 0) // we cannot compare it to the actual untiLock, because contract will round it to weeks - assert(tx.events.Supply.returnValues[1] > tx.events.Supply.returnValues[0]) // supply has increased + const depositEvent = getEventFromTx(tx, 'Deposit') + const supplyEvent = getEventFromTx(tx, 'Supply') + assert(depositEvent.args[0] === Alice) + assert(depositEvent.args[1] === web3.utils.toWei(amount)) + assert(depositEvent.args[2] > 0) // we cannot compare it to the actual untiLock, because contract will round it to weeks + assert(depositEvent.args[1] > supplyEvent.args[0]) // supply has increased } }) it('Alice should increase the lock time', async () => { - const currentLock = await veOcean.lockEnd(Alice) + const currentLock = await veOcean.lockEnd(await Alice.getAddress()) const newLock = parseInt(String(currentLock)) + 7 * 86400 - await veOcean.increaseUnlockTime(Alice, newLock) - const newCurrentLock = await veOcean.lockEnd(Alice) + await veOcean.increaseUnlockTime(newLock) + const newCurrentLock = await veOcean.lockEnd(await Alice.getAddress()) assert(newCurrentLock > currentLock, 'Lock time should change"') }) it('Alice should increase the locked amount', async () => { - const currentBalance = await veOcean.getLockedAmount(Alice) - const currentLock = await veOcean.lockEnd(Alice) + const currentBalance = await veOcean.getLockedAmount(await Alice.getAddress()) + const currentLock = await veOcean.lockEnd(await Alice.getAddress()) const amount = '200' - await approve(web3, config, Alice, addresses.Ocean, addresses.veOCEAN, amount) - await veOcean.increaseAmount(Alice, amount) - const newCurrentBalance = await veOcean.getLockedAmount(Alice) - const newCurrentLock = await veOcean.lockEnd(Alice) + await approve( + web3, + config, + await Alice.getAddress(), + addresses.Ocean, + addresses.veOCEAN, + amount + ) + await veOcean.increaseAmount(amount) + const newCurrentBalance = await veOcean.getLockedAmount(await Alice.getAddress()) + const newCurrentLock = await veOcean.lockEnd(await Alice.getAddress()) assert(newCurrentLock === currentLock, 'Lock time should not change') assert( newCurrentBalance > currentBalance, @@ -166,19 +177,27 @@ describe('veOcean tests', async () => { }) it('Alice should allocate 10% to NFT1', async () => { - const totalAllocation = await veAllocate.getTotalAllocation(Alice) - const tx = await veAllocate.setAllocation(Alice, '1000', nft1, chainId) - assert(tx.events.AllocationSet.returnValues[0] === Alice) - assert(tx.events.AllocationSet.returnValues[1] === nft1) - assert(parseInt(tx.events.AllocationSet.returnValues[2]) === parseInt(chainId)) - assert(tx.events.AllocationSet.returnValues[3] === '1000') - const newTotalAllocation = await veAllocate.getTotalAllocation(Alice) + const totalAllocation = await veAllocate.getTotalAllocation(await Alice.getAddress()) + const response = await veAllocate.setAllocation('1000', nft1, chainId) + const tx = await response.wait() + const allocationSetEvent = getEventFromTx(tx, 'AllocationSet') + assert(allocationSetEvent.args[0] === Alice) + assert(allocationSetEvent.args[1] === nft1) + assert(parseInt(allocationSetEvent.args[2]) === parseInt(chainId)) + assert(allocationSetEvent.args[3] === '1000') + const newTotalAllocation = await veAllocate.getTotalAllocation( + await Alice.getAddress() + ) const expectedAllocation = parseInt(String(totalAllocation)) + 1000 assert( parseInt(String(newTotalAllocation)) === parseInt(String(expectedAllocation)), 'NewAllocation (' + newTotalAllocation + ') should be ' + expectedAllocation ) - const nftAllocation = await veAllocate.getVeAllocation(Alice, nft1, chainId) + const nftAllocation = await veAllocate.getVeAllocation( + await Alice.getAddress(), + nft1, + chainId + ) assert( parseInt(String(nftAllocation)) === parseInt('1000'), nftAllocation + ' should be 1000' @@ -186,33 +205,42 @@ describe('veOcean tests', async () => { }) it('Alice should allocate 10% to NFT2 and 20% to NFT3', async () => { - const totalAllocation = await veAllocate.getTotalAllocation(Alice) - const tx = await veAllocate.setBatchAllocation( - Alice, + const totalAllocation = await veAllocate.getTotalAllocation(await Alice.getAddress()) + const response = await veAllocate.setBatchAllocation( ['1000', '2000'], [nft2, nft3], [chainId, chainId] ) - assert(tx.events.AllocationSetMultiple.returnValues[0] === Alice) - assert(tx.events.AllocationSetMultiple.returnValues[1][0] === nft2) - assert(tx.events.AllocationSetMultiple.returnValues[1][1] === nft3) - assert( - parseInt(tx.events.AllocationSetMultiple.returnValues[2][0]) === parseInt(chainId) + const tx = await response.wait() + const allocationSetEvent = getEventFromTx(tx, 'AllocationSetMultiple') + assert(allocationSetEvent.args[0] === Alice) + assert(allocationSetEvent.args[1][0] === nft2) + assert(allocationSetEvent.args[1][1] === nft3) + assert(parseInt(allocationSetEvent.args[2][0]) === parseInt(chainId)) + assert(allocationSetEvent.args[3][0] === '1000') + assert(allocationSetEvent.args[3][1] === '2000') + const newTotalAllocation = await veAllocate.getTotalAllocation( + await Alice.getAddress() ) - assert(tx.events.AllocationSetMultiple.returnValues[3][0] === '1000') - assert(tx.events.AllocationSetMultiple.returnValues[3][1] === '2000') - const newTotalAllocation = await veAllocate.getTotalAllocation(Alice) const expectedAllocation = parseInt(String(totalAllocation)) + 3000 assert( parseInt(String(newTotalAllocation)) === parseInt(String(expectedAllocation)), 'NewAllocation (' + newTotalAllocation + ') should be ' + expectedAllocation ) - let nftAllocation = await veAllocate.getVeAllocation(Alice, nft2, chainId) + let nftAllocation = await veAllocate.getVeAllocation( + await Alice.getAddress(), + nft2, + chainId + ) assert( parseInt(String(nftAllocation)) === parseInt('1000'), nftAllocation + ' should be 1000' ) - nftAllocation = await veAllocate.getVeAllocation(Alice, nft3, chainId) + nftAllocation = await veAllocate.getVeAllocation( + await Alice.getAddress(), + nft3, + chainId + ) assert( parseInt(String(nftAllocation)) === parseInt('2000'), nftAllocation + ' should be 2000' @@ -220,7 +248,7 @@ describe('veOcean tests', async () => { }) it('Alice should be able to estimate her claim amount', async () => { - const estimatedClaim = await veFeeEstimate.estimateClaim(Alice) + const estimatedClaim = await veFeeEstimate.estimateClaim(await Alice.getAddress()) // since we have no rewards, we are expecting 0 assert(estimatedClaim === '0') }) From 8b6962bd318af62316257dce813dac5a94feac64 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Tue, 21 Feb 2023 16:18:09 +0200 Subject: [PATCH 05/82] contract updates --- src/@types/ReturnTypes.ts | 2 +- src/contracts/Datatoken.ts | 259 +++++++++++---------------- src/contracts/Dispenser.ts | 105 +++++------ src/contracts/FixedRateExchange.ts | 256 ++++++++++---------------- src/contracts/NFT.ts | 239 +++++++++++------------- src/contracts/NFTFactory.ts | 163 ++++++++--------- src/contracts/Router.ts | 96 +++++----- src/contracts/df/DfRewards.ts | 29 +-- src/contracts/df/DfStrategyV1.ts | 19 +- src/contracts/ve/VeAllocate.ts | 4 +- src/contracts/ve/VeFeeDistributor.ts | 6 +- src/contracts/ve/VeOcean.ts | 18 +- src/utils/Constants.ts | 2 +- src/utils/ContractUtils.ts | 6 +- src/utils/TokenUtils.ts | 100 +++++------ src/utils/minAbi.ts | 2 - 16 files changed, 551 insertions(+), 755 deletions(-) diff --git a/src/@types/ReturnTypes.ts b/src/@types/ReturnTypes.ts index 6728e9e68..42f178a51 100644 --- a/src/@types/ReturnTypes.ts +++ b/src/@types/ReturnTypes.ts @@ -2,4 +2,4 @@ import { TransactionResponse } from 'ethers' export type ReceiptOrEstimate = G extends false ? TransactionResponse - : bigint + : number diff --git a/src/contracts/Datatoken.ts b/src/contracts/Datatoken.ts index 883ca7535..9eb4bebbc 100644 --- a/src/contracts/Datatoken.ts +++ b/src/contracts/Datatoken.ts @@ -1,6 +1,7 @@ -import Web3 from 'web3' -import { AbiItem } from 'web3-utils' -import { TransactionReceipt } from 'web3-eth' +// import Web3 from 'web3' +// import { AbiItem } from 'web3-utils' +// import { TransactionReceipt } from 'web3-eth' +import { ethers, Signer, InterfaceAbi } from 'ethers' import Decimal from 'decimal.js' import ERC20Template from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json' import ERC20TemplateEnterprise from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json' @@ -21,11 +22,11 @@ import { Config } from '../config' import { SmartContract } from './SmartContract' export class Datatoken extends SmartContract { - public abiEnterprise: AbiItem | AbiItem[] + public abiEnterprise: InterfaceAbi public nft: Nft - getDefaultAbi(): AbiItem | AbiItem[] { - return ERC20Template.abi as AbiItem[] + getDefaultAbi() { + return ERC20Template.abi } /** @@ -34,15 +35,15 @@ export class Datatoken extends SmartContract { * @param {Web3} web3 */ constructor( - web3: Web3, + signer: Signer, network?: string | number, config?: Config, - abi?: AbiItem | AbiItem[], - abiEnterprise?: AbiItem | AbiItem[] + abi?: InterfaceAbi, + abiEnterprise?: InterfaceAbi ) { - super(web3, network, config, abi) - this.abiEnterprise = abiEnterprise || (ERC20TemplateEnterprise.abi as AbiItem[]) - this.nft = new Nft(this.web3) + super(signer, network, config, abi) + this.abiEnterprise = abiEnterprise || (ERC20TemplateEnterprise.abi as InterfaceAbi) + this.nft = new Nft(this.signer) } /** @@ -50,34 +51,31 @@ export class Datatoken extends SmartContract { * @param {String} dtAddress Datatoken address * @param {String} spender Spender address * @param {string} amount Number of datatokens, as number. Will be converted to wei - * @param {String} address User adress + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async approve( dtAddress: string, spender: string, amount: string, - address: string, estimateGas?: G ): Promise> { const dtContract = this.getContract(dtAddress) const estGas = await calculateEstimatedGas( - address, - dtContract.methods.approve, + dtContract.approve, spender, - this.web3.utils.toWei(amount) + ethers.parseUnits(amount, 'ether') ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.approve, + dtContract.approve, spender, - this.web3.utils.toWei(amount) + ethers.parseUnits(amount, 'ether') ) return >trxReceipt } @@ -86,8 +84,8 @@ export class Datatoken extends SmartContract { * Creates a new FixedRateExchange setup. * @param {String} dtAddress Datatoken address * @param {String} address Caller address - * @param {String} fixedPriceAddress * @param {FixedRateParams} fixedRateParams + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ public async createFixedRate( @@ -107,8 +105,7 @@ export class Datatoken extends SmartContract { // should check DatatokenDeployer role using NFT level .. const estGas = await calculateEstimatedGas( - address, - dtContract.methods.createFixedRate, + dtContract.createFixedRate, fixedRateParams.fixedRateAddress, [ fixedRateParams.baseTokenAddress, @@ -127,11 +124,10 @@ export class Datatoken extends SmartContract { if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.createFixedRate, + dtContract.createFixedRate, fixedRateParams.fixedRateAddress, [ fixedRateParams.baseTokenAddress, @@ -156,6 +152,7 @@ export class Datatoken extends SmartContract { * @param {String} address Caller address * @param {String} dispenserAddress ispenser contract address * @param {String} dispenserParams + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ public async createDispenser( @@ -178,8 +175,7 @@ export class Datatoken extends SmartContract { // should check DatatokenDeployer role using NFT level .. const estGas = await calculateEstimatedGas( - address, - dtContract.methods.createDispenser, + dtContract.createDispenser, dispenserAddress, dispenserParams.maxTokens, dispenserParams.maxBalance, @@ -189,11 +185,10 @@ export class Datatoken extends SmartContract { if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.createDispenser, + dtContract.createDispenser, dispenserAddress, dispenserParams.maxTokens, dispenserParams.maxBalance, @@ -209,6 +204,7 @@ export class Datatoken extends SmartContract { * @param {String} address Minter address * @param {String} amount Number of datatokens, as number. Will be converted to wei * @param {String} toAddress only if toAddress is different from the minter + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ public async mint( @@ -227,21 +223,19 @@ export class Datatoken extends SmartContract { const capAvailble = await this.getCap(dtAddress) if (new Decimal(capAvailble).gte(amount)) { const estGas = await calculateEstimatedGas( - address, - dtContract.methods.mint, + dtContract.mint, toAddress || address, - this.web3.utils.toWei(amount) + ethers.parseUnits(amount, 'ether') ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.mint, + dtContract.mint, toAddress || address, - this.web3.utils.toWei(amount) + ethers.parseUnits(amount, 'ether') ) return >trxReceipt } else { @@ -255,6 +249,7 @@ export class Datatoken extends SmartContract { * @param {String} dtAddress Datatoken address * @param {String} address User address * @param {String} minter User which is going to be a Minter + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ public async addMinter( @@ -269,19 +264,14 @@ export class Datatoken extends SmartContract { throw new Error(`Caller is not DatatokenDeployer`) } // Estimate gas cost for addMinter method - const estGas = await calculateEstimatedGas( - address, - dtContract.methods.addMinter, - minter - ) + const estGas = await calculateEstimatedGas(dtContract.addMinter, minter) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.addMinter, + dtContract.addMinter, minter ) @@ -294,7 +284,7 @@ export class Datatoken extends SmartContract { * @param {String} dtAddress Datatoken address * @param {String} address User address * @param {String} minter User which will be removed from Minter permission - * @param {Contract} contractInstance optional contract instance + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} */ public async removeMinter( @@ -309,19 +299,14 @@ export class Datatoken extends SmartContract { throw new Error(`Caller is not DatatokenDeployer`) } - const estGas = await calculateEstimatedGas( - address, - dtContract.methods.removeMinter, - minter - ) + const estGas = await calculateEstimatedGas(dtContract.removeMinter, minter) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.removeMinter, + dtContract.removeMinter, minter ) @@ -334,6 +319,7 @@ export class Datatoken extends SmartContract { * @param {String} dtAddress Datatoken address * @param {String} address User address * @param {String} paymentManager User which is going to be a Minter + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ public async addPaymentManager( @@ -349,18 +335,16 @@ export class Datatoken extends SmartContract { } const estGas = await calculateEstimatedGas( - address, - dtContract.methods.addPaymentManager, + dtContract.addPaymentManager, paymentManager ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.addPaymentManager, + dtContract.addPaymentManager, paymentManager ) @@ -373,6 +357,7 @@ export class Datatoken extends SmartContract { * @param {String} dtAddress Datatoken address * @param {String} address User address * @param {String} paymentManager User which will be removed from paymentManager permission + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async removePaymentManager( @@ -388,18 +373,16 @@ export class Datatoken extends SmartContract { } const estGas = await calculateEstimatedGas( - address, - dtContract.methods.removePaymentManager, + dtContract.removePaymentManager, paymentManager ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.removePaymentManager, + dtContract.removePaymentManager, paymentManager ) @@ -413,6 +396,7 @@ export class Datatoken extends SmartContract { * @param dtAddress datatoken address * @param address Caller address * @param paymentCollector User to be set as new payment collector + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async setPaymentCollector( @@ -434,18 +418,16 @@ export class Datatoken extends SmartContract { } const estGas = await calculateEstimatedGas( - address, - dtContract.methods.setPaymentCollector, + dtContract.setPaymentCollector, paymentCollector ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.setPaymentCollector, + dtContract.setPaymentCollector, paymentCollector ) return >trxReceipt @@ -457,7 +439,7 @@ export class Datatoken extends SmartContract { */ public async getPaymentCollector(dtAddress: string): Promise { const dtContract = this.getContract(dtAddress) - const paymentCollector = await dtContract.methods.getPaymentCollector().call() + const paymentCollector = await dtContract.getPaymentCollector() return paymentCollector } @@ -466,17 +448,17 @@ export class Datatoken extends SmartContract { * @param {String} dtAddress Datatoken address * @param {String} toAddress Receiver address * @param {String} amount Number of datatokens, as number. To be converted to wei. - * @param {String} address User adress + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ - public async transfer( + public async transfer( dtAddress: string, toAddress: string, amount: string, - address: string - ): Promise { - const weiAmount = this.web3.utils.toWei(amount) - return this.transferWei(dtAddress, toAddress, weiAmount, address) + estimateGas?: G + ): Promise> { + const weiAmount = ethers.parseUnits(amount, 'ether') + return this.transferWei(dtAddress, toAddress, String(weiAmount), estimateGas) } /** @@ -484,32 +466,25 @@ export class Datatoken extends SmartContract { * @param {String} dtAddress Datatoken address * @param {String} toAddress Receiver address * @param {String} amount Number of datatokens, as number. Expressed as wei - * @param {String} address User adress + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ public async transferWei( dtAddress: string, toAddress: string, amount: string, - address: string, estimateGas?: G ): Promise> { const dtContract = this.getContract(dtAddress) - const estGas = await calculateEstimatedGas( - address, - dtContract.methods.transfer, - toAddress, - amount - ) + const estGas = await calculateEstimatedGas(dtContract.transfer, toAddress, amount) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.transfer, + dtContract.transfer, toAddress, amount ) @@ -518,16 +493,15 @@ export class Datatoken extends SmartContract { /** Start Order: called by payer or consumer prior ordering a service consume on a marketplace. * @param {String} dtAddress Datatoken address - * @param {String} address User address which calls * @param {String} consumer Consumer Address * @param {Number} serviceIndex Service index in the metadata * @param {providerFees} providerFees provider fees * @param {consumeMarketFee} ConsumeMarketFee consume market fees + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} string */ public async startOrder( dtAddress: string, - address: string, consumer: string, serviceIndex: number, providerFees: ProviderFees, @@ -544,8 +518,7 @@ export class Datatoken extends SmartContract { } const estGas = await calculateEstimatedGas( - address, - dtContract.methods.startOrder, + dtContract.startOrder, consumer, serviceIndex, providerFees, @@ -554,11 +527,10 @@ export class Datatoken extends SmartContract { if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.startOrder, + dtContract.startOrder, consumer, serviceIndex, providerFees, @@ -571,14 +543,13 @@ export class Datatoken extends SmartContract { * Pays the provider fee again, but it will not require a new datatoken payment * Requires previous approval of provider fee. * @param {String} dtAddress Datatoken address - * @param {String} address User address which calls * @param {String} orderTxId previous valid order * @param {providerFees} providerFees provider fees + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} string */ public async reuseOrder( dtAddress: string, - address: string, orderTxId: string, providerFees: ProviderFees, estimateGas?: G @@ -586,19 +557,17 @@ export class Datatoken extends SmartContract { const dtContract = this.getContract(dtAddress) const estGas = await calculateEstimatedGas( - address, - dtContract.methods.reuseOrder, + dtContract.reuseOrder, orderTxId, providerFees ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.reuseOrder, + dtContract.reuseOrder, orderTxId, providerFees ) @@ -607,14 +576,13 @@ export class Datatoken extends SmartContract { /** Buys 1 DT from the FRE and then startsOrder, while burning that DT * @param {String} dtAddress Datatoken address - * @param {String} address User address which calls * @param {OrderParams} orderParams Consumer Address * @param {FreParams} freParams Amount of tokens that is going to be transfered + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} */ public async buyFromFreAndOrder( dtAddress: string, - address: string, orderParams: OrderParams, freParams: FreOrderParams, estimateGas?: G @@ -624,19 +592,17 @@ export class Datatoken extends SmartContract { const freContractParams = await this.getFreOrderParams(freParams) const estGas = await calculateEstimatedGas( - address, - dtContract.methods.buyFromFreAndOrder, + dtContract.buyFromFreAndOrder, orderParams, freContractParams ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.buyFromFreAndOrder, + dtContract.buyFromFreAndOrder, orderParams, freContractParams ) @@ -645,14 +611,13 @@ export class Datatoken extends SmartContract { /** Gets DT from dispenser and then startsOrder, while burning that DT * @param {String} dtAddress Datatoken address - * @param {String} address User address which calls * @param {OrderParams} orderParams * @param {String} dispenserContract + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} */ public async buyFromDispenserAndOrder( dtAddress: string, - address: string, orderParams: OrderParams, dispenserContract: string, estimateGas?: G @@ -660,19 +625,17 @@ export class Datatoken extends SmartContract { const dtContract = this.getContract(dtAddress, null, this.abiEnterprise) const estGas = await calculateEstimatedGas( - address, - dtContract.methods.buyFromDispenserAndOrder, + dtContract.buyFromDispenserAndOrder, orderParams, dispenserContract ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.buyFromDispenserAndOrder, + dtContract.buyFromDispenserAndOrder, orderParams, dispenserContract ) @@ -685,6 +648,7 @@ export class Datatoken extends SmartContract { * @param {String} dtAddress Datatoken address * @param {String} address User address * @param {String} value Data to be stored into 725Y standard + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ public async setData( @@ -699,21 +663,16 @@ export class Datatoken extends SmartContract { const dtContract = this.getContract(dtAddress) - const valueHex = this.web3.utils.asciiToHex(value) + const valueHex = ethers.hexlify(value) - const estGas = await calculateEstimatedGas( - address, - dtContract.methods.setData, - valueHex - ) + const estGas = await calculateEstimatedGas(dtContract.setData, valueHex) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.setData, + dtContract.setData, valueHex ) @@ -725,6 +684,7 @@ export class Datatoken extends SmartContract { * Only NFT Owner (at 721 level) can call it. * @param dtAddress Datatoken address where we want to clean permissions * @param address User adress + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ public async cleanPermissions( @@ -737,18 +697,14 @@ export class Datatoken extends SmartContract { } const dtContract = this.getContract(dtAddress) - const estGas = await calculateEstimatedGas( - address, - dtContract.methods.cleanPermissions - ) + const estGas = await calculateEstimatedGas(dtContract.cleanPermissions) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.cleanPermissions + dtContract.cleanPermissions ) return >trxReceipt @@ -764,7 +720,7 @@ export class Datatoken extends SmartContract { address: string ): Promise { const dtContract = this.getContract(dtAddress) - const roles = await dtContract.methods.permissions(address).call() + const roles = await dtContract.permissions(address) return roles } @@ -774,8 +730,8 @@ export class Datatoken extends SmartContract { */ public async getCap(dtAddress: string): Promise { const dtContract = this.getContract(dtAddress) - const cap = await dtContract.methods.cap().call() - return this.web3.utils.fromWei(cap) + const cap = await dtContract.cap() + return ethers.formatEther(cap) } /** It returns the token decimals, how many supported decimal points @@ -784,7 +740,7 @@ export class Datatoken extends SmartContract { */ public async getDecimals(dtAddress: string): Promise { const dtContract = this.getContract(dtAddress) - const decimals = await dtContract.methods.decimals().call() + const decimals = await dtContract.decimals() return decimals } @@ -794,7 +750,7 @@ export class Datatoken extends SmartContract { */ public async getSymbol(dtAddress: string): Promise { const dtContract = this.getContract(dtAddress) - const symbol = await dtContract.methods.symbol().call() + const symbol = await dtContract.symbol() return symbol } @@ -804,7 +760,7 @@ export class Datatoken extends SmartContract { */ public async getName(dtAddress: string): Promise { const dtContract = this.getContract(dtAddress) - const name = await dtContract.methods.name().call() + const name = await dtContract.name() return name } @@ -814,7 +770,7 @@ export class Datatoken extends SmartContract { */ public async getNFTAddress(dtAddress: string): Promise { const dtContract = this.getContract(dtAddress) - const nftAddress = await dtContract.methods.getERC721Address().call() + const nftAddress = await dtContract.getERC721Address() return nftAddress } @@ -825,7 +781,7 @@ export class Datatoken extends SmartContract { */ public async isDatatokenDeployer(dtAddress: string, address: string): Promise { const dtContract = this.getContract(dtAddress) - const isDatatokenDeployer = await dtContract.methods.isERC20Deployer(address).call() + const isDatatokenDeployer = await dtContract.isERC20Deployer(address) return isDatatokenDeployer } @@ -837,8 +793,8 @@ export class Datatoken extends SmartContract { */ public async balance(datatokenAddress: string, address: string): Promise { const dtContract = this.getContract(datatokenAddress, address) - const balance = await dtContract.methods.balanceOf(address).call() - return this.web3.utils.fromWei(balance) + const balance = await dtContract.balanceOf(address) + return ethers.formatEther(balance) } /** @@ -850,6 +806,7 @@ export class Datatoken extends SmartContract { * @param {string} publishMarketFeeToken new publish Market Fee Token * @param {string} publishMarketFeeAmount new fee amount * @param {String} address user adress + * @param {Boolean} estimateGas if True, return gas estimate */ public async setPublishingMarketFee( datatokenAddress: string, @@ -860,13 +817,12 @@ export class Datatoken extends SmartContract { estimateGas?: G ): Promise> { const dtContract = this.getContract(datatokenAddress, address) - const mktFeeAddress = (await dtContract.methods.getPublishingMarketFee().call())[0] + const mktFeeAddress = (await dtContract.getPublishingMarketFee())[0] if (mktFeeAddress !== address) { throw new Error(`Caller is not the Publishing Market Fee Address`) } const estGas = await calculateEstimatedGas( - address, - dtContract.methods.setPublishingMarketFee, + dtContract.setPublishingMarketFee, publishMarketFeeAddress, publishMarketFeeToken, publishMarketFeeAmount @@ -874,11 +830,10 @@ export class Datatoken extends SmartContract { if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - dtContract.methods.setPublishingMarketFee, + dtContract.setPublishingMarketFee, publishMarketFeeAddress, publishMarketFeeToken, publishMarketFeeAmount @@ -901,7 +856,7 @@ export class Datatoken extends SmartContract { ): Promise { const dtContract = this.getContract(datatokenAddress, address) - const publishingMarketFee = await dtContract.methods.getPublishingMarketFee().call() + const publishingMarketFee = await dtContract.getPublishingMarketFee() const returnValues = { publishMarketFeeAddress: publishingMarketFee[0], publishMarketFeeToken: publishingMarketFee[1], @@ -915,13 +870,13 @@ export class Datatoken extends SmartContract { exchangeContract: freParams.exchangeContract, exchangeId: freParams.exchangeId, maxBaseTokenAmount: await amountToUnits( - this.web3, + this.signer, freParams.baseTokenAddress, freParams.maxBaseTokenAmount, freParams.baseTokenDecimals ), swapMarketFee: await amountToUnits( - this.web3, + this.signer, freParams.baseTokenAddress, freParams.swapMarketFee, freParams.baseTokenDecimals diff --git a/src/contracts/Dispenser.ts b/src/contracts/Dispenser.ts index 2bf2c6591..a19600812 100644 --- a/src/contracts/Dispenser.ts +++ b/src/contracts/Dispenser.ts @@ -1,4 +1,5 @@ -import { AbiItem } from 'web3-utils' +// import { AbiItem } from 'web3-utils' +import { ethers, Signer, InterfaceAbi } from 'ethers' import Decimal from 'decimal.js' import DispenserAbi from '@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json' import { calculateEstimatedGas, sendTx } from '../utils' @@ -7,8 +8,8 @@ import { SmartContractWithAddress } from './SmartContractWithAddress' import { DispenserToken, ReceiptOrEstimate } from '../@types' export class Dispenser extends SmartContractWithAddress { - getDefaultAbi(): AbiItem | AbiItem[] { - return DispenserAbi.abi as AbiItem[] + getDefaultAbi() { + return DispenserAbi.abi } /** @@ -17,13 +18,13 @@ export class Dispenser extends SmartContractWithAddress { * @return {Promise} Exchange details */ public async status(dtAdress: string): Promise { - const status: DispenserToken = await this.contract.methods.status(dtAdress).call() + const status: DispenserToken = await this.contract.status(dtAdress) if (!status) { throw new Error(`Np dispenser found for the given datatoken address`) } - status.maxTokens = this.web3.utils.fromWei(status.maxTokens) - status.maxBalance = this.web3.utils.fromWei(status.maxBalance) - status.balance = this.web3.utils.fromWei(status.balance) + status.maxTokens = ethers.formatEther(status.maxTokens) + status.maxBalance = ethers.formatEther(status.maxBalance) + status.balance = ethers.formatEther(status.balance) return status } @@ -34,6 +35,7 @@ export class Dispenser extends SmartContractWithAddress { * @param {String} maxTokens max tokens to dispense * @param {String} maxBalance max balance of requester * @param {String} allowedSwapper only account that can ask tokens. set address(0) if not required + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ public async create( @@ -45,11 +47,10 @@ export class Dispenser extends SmartContractWithAddress { estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - address, - this.contract.methods.create, + this.contract.create, dtAddress, - this.web3.utils.toWei(maxTokens), - this.web3.utils.toWei(maxBalance), + ethers.parseUnits(maxTokens, 'ethers'), + ethers.parseUnits(maxBalance, 'ethers'), address, allowedSwapper ) @@ -57,14 +58,13 @@ export class Dispenser extends SmartContractWithAddress { // Call createFixedRate contract method const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.create, + this.contract.create, dtAddress, - this.web3.utils.toWei(maxTokens), - this.web3.utils.toWei(maxBalance), + ethers.parseUnits(maxTokens, 'ethers'), + ethers.parseUnits(maxBalance, 'ethers'), address, allowedSwapper ) @@ -77,34 +77,31 @@ export class Dispenser extends SmartContractWithAddress { * @param {String} dtAddress refers to datatoken address. * @param {Number} maxTokens max amount of tokens to dispense * @param {Number} maxBalance max balance of user. If user balance is >, then dispense will be rejected - * @param {String} address User address (must be owner of the datatoken) + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} TransactionReceipt */ public async activate( dtAddress: string, maxTokens: string, maxBalance: string, - address: string, estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - address, - this.contract.methods.activate, + this.contract.activate, dtAddress, - this.web3.utils.toWei(maxTokens), - this.web3.utils.toWei(maxBalance) + ethers.parseUnits(maxTokens, 'ethers'), + ethers.parseUnits(maxBalance, 'ethers') ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.activate, + this.contract.activate, dtAddress, - this.web3.utils.toWei(maxTokens), - this.web3.utils.toWei(maxBalance) + ethers.parseUnits(maxTokens, 'ethers'), + ethers.parseUnits(maxBalance, 'ethers') ) return >trxReceipt @@ -113,27 +110,21 @@ export class Dispenser extends SmartContractWithAddress { /** * Deactivate an existing dispenser. * @param {String} dtAddress refers to datatoken address. - * @param {String} address User address (must be owner of the datatoken) + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} TransactionReceipt */ public async deactivate( dtAddress: string, - address: string, estimateGas?: G ): Promise> { - const estGas = await calculateEstimatedGas( - address, - this.contract.methods.deactivate, - dtAddress - ) + const estGas = await calculateEstimatedGas(this.contract.deactivate, dtAddress) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.deactivate, + this.contract.deactivate, dtAddress ) @@ -143,30 +134,27 @@ export class Dispenser extends SmartContractWithAddress { /** * Sets a new allowedSwapper. * @param {String} dtAddress refers to datatoken address. - * @param {String} address User address (must be owner of the datatoken) * @param {String} newAllowedSwapper refers to the new allowedSwapper + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} TransactionReceipt */ public async setAllowedSwapper( dtAddress: string, - address: string, newAllowedSwapper: string, estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - address, - this.contract.methods.setAllowedSwapper, + this.contract.setAllowedSwapper, dtAddress, newAllowedSwapper ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.setAllowedSwapper, + this.contract.setAllowedSwapper, dtAddress, newAllowedSwapper ) @@ -178,35 +166,32 @@ export class Dispenser extends SmartContractWithAddress { * The dispenser must be active, hold enough DT (or be able to mint more) * and respect maxTokens/maxBalance requirements * @param {String} dtAddress refers to datatoken address. - * @param {String} address User address * @param {String} amount amount of datatokens required. * @param {String} destination who will receive the tokens + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} TransactionReceipt */ public async dispense( dtAddress: string, - address: string, amount: string = '1', destination: string, estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - address, - this.contract.methods.dispense, + this.contract.dispense, dtAddress, - this.web3.utils.toWei(amount), + ethers.parseUnits(amount, 'ether'), destination ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.dispense, + this.contract.dispense, dtAddress, - this.web3.utils.toWei(amount), + ethers.parseUnits(amount, 'ether'), destination ) return >trxReceipt @@ -215,27 +200,21 @@ export class Dispenser extends SmartContractWithAddress { /** * Withdraw all tokens from the dispenser * @param {String} dtAddress refers to datatoken address. - * @param {String} address User address (must be owner of the dispenser) + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} TransactionReceipt */ public async ownerWithdraw( dtAddress: string, - address: string, estimateGas?: G ): Promise> { - const estGas = await calculateEstimatedGas( - address, - this.contract.methods.ownerWithdraw, - dtAddress - ) + const estGas = await calculateEstimatedGas(this.contract.ownerWithdraw, dtAddress) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.ownerWithdraw, + this.contract.ownerWithdraw, dtAddress ) diff --git a/src/contracts/FixedRateExchange.ts b/src/contracts/FixedRateExchange.ts index ca6e79954..b4c45a51b 100644 --- a/src/contracts/FixedRateExchange.ts +++ b/src/contracts/FixedRateExchange.ts @@ -1,12 +1,12 @@ import FixedRateExchangeAbi from '@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json' -import { AbiItem } from 'web3-utils/types' +import { ethers, Signer, InterfaceAbi } from 'ethers' import { calculateEstimatedGas, sendTx, ZERO_ADDRESS } from '../utils' import { PriceAndFees, FeesInfo, FixedPriceExchange, ReceiptOrEstimate } from '../@types' import { SmartContractWithAddress } from './SmartContractWithAddress' export class FixedRateExchange extends SmartContractWithAddress { - getDefaultAbi(): AbiItem | AbiItem[] { - return FixedRateExchangeAbi.abi as AbiItem[] + getDefaultAbi() { + return FixedRateExchangeAbi.abi } /** @@ -16,9 +16,7 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} exchangeId */ public async generateExchangeId(baseToken: string, datatoken: string): Promise { - const exchangeId = await this.contract.methods - .generateExchangeId(baseToken, datatoken) - .call() + const exchangeId = await this.contract.generateExchangeId(baseToken, datatoken) return exchangeId } @@ -27,13 +25,12 @@ export class FixedRateExchange extends SmartContractWithAddress { * @param {String} exchangeId ExchangeId * @param {String} datatokenAmount Amount of datatokens * @param {String} maxBaseTokenAmount max amount of baseToken we want to pay for datatokenAmount - * @param {String} address User address * @param {String} consumeMarketAddress consumeMarketAddress * @param {String} consumeMarketFee consumeMarketFee in fraction + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async buyDatatokens( - address: string, exchangeId: string, datatokenAmount: string, maxBaseTokenAmount: string, @@ -42,7 +39,7 @@ export class FixedRateExchange extends SmartContractWithAddress { estimateGas?: G ): Promise> { const exchange = await this.getExchange(exchangeId) - const consumeMarketFeeFormatted = this.web3.utils.toWei(consumeMarketFee) + const consumeMarketFeeFormatted = ethers.parseUnits(consumeMarketFee, 'ether') const dtAmountFormatted = await this.amountToUnits( exchange.datatoken, datatokenAmount, @@ -55,8 +52,7 @@ export class FixedRateExchange extends SmartContractWithAddress { ) const estGas = await calculateEstimatedGas( - address, - this.contract.methods.buyDT, + this.contract.buyDT, exchangeId, dtAmountFormatted, maxBtFormatted, @@ -66,11 +62,10 @@ export class FixedRateExchange extends SmartContractWithAddress { if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.buyDT, + this.contract.buyDT, exchangeId, dtAmountFormatted, maxBtFormatted, @@ -86,13 +81,12 @@ export class FixedRateExchange extends SmartContractWithAddress { * @param {String} exchangeId ExchangeId * @param {String} datatokenAmount Amount of datatokens * @param {String} minBaseTokenAmount min amount of baseToken we want to receive back - * @param {String} address User address * @param {String} consumeMarketAddress consumeMarketAddress * @param {String} consumeMarketFee consumeMarketFee in fraction + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async sellDatatokens( - address: string, exchangeId: string, datatokenAmount: string, minBaseTokenAmount: string, @@ -101,7 +95,7 @@ export class FixedRateExchange extends SmartContractWithAddress { estimateGas?: G ): Promise> { const exchange = await this.getExchange(exchangeId) - const consumeMarketFeeFormatted = this.web3.utils.toWei(consumeMarketFee) + const consumeMarketFeeFormatted = ethers.parseUnits(consumeMarketFee, 'ether') const dtAmountFormatted = await this.amountToUnits( exchange.datatoken, datatokenAmount, @@ -113,8 +107,7 @@ export class FixedRateExchange extends SmartContractWithAddress { +exchange.btDecimals ) const estGas = await calculateEstimatedGas( - address, - this.contract.methods.sellDT, + this.contract.sellDT, exchangeId, dtAmountFormatted, minBtFormatted, @@ -124,11 +117,10 @@ export class FixedRateExchange extends SmartContractWithAddress { if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.sellDT, + this.contract.sellDT, exchangeId, dtAmountFormatted, minBtFormatted, @@ -145,7 +137,7 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} no of available exchanges */ public async getNumberOfExchanges(): Promise { - const numExchanges = await this.contract.methods.getNumberOfExchanges().call() + const numExchanges = await this.contract.getNumberOfExchanges() return numExchanges } @@ -153,31 +145,28 @@ export class FixedRateExchange extends SmartContractWithAddress { * Set new rate * @param {String} exchangeId ExchangeId * @param {String} newRate New rate - * @param {String} address User account + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async setRate( - address: string, exchangeId: string, newRate: string, estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - address, - this.contract.methods.setRate, + this.contract.setRate, exchangeId, - this.web3.utils.toWei(newRate) + ethers.formatEther(newRate) ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.setRate, + this.contract.setRate, exchangeId, - this.web3.utils.toWei(newRate) + ethers.formatEther(newRate) ) return >trxReceipt @@ -187,29 +176,26 @@ export class FixedRateExchange extends SmartContractWithAddress { * Sets a new allowedSwapper * @param {String} exchangeId ExchangeId * @param {String} newAllowedSwapper newAllowedSwapper (set address zero if we want to remove allowed swapper) - * @param {String} address User account + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async setAllowedSwapper( - address: string, exchangeId: string, newAllowedSwapper: string, estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - address, - this.contract.methods.setAllowedSwapper, + this.contract.setAllowedSwapper, exchangeId, newAllowedSwapper ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.setAllowedSwapper, + this.contract.setAllowedSwapper, exchangeId, newAllowedSwapper ) @@ -223,7 +209,6 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} transaction receipt */ public async activate( - address: string, exchangeId: string, estimateGas?: G ): Promise> { @@ -231,18 +216,16 @@ export class FixedRateExchange extends SmartContractWithAddress { if (!exchange) return null if (exchange.active === true) return null const estGas = await calculateEstimatedGas( - address, - this.contract.methods.toggleExchangeState, + this.contract.toggleExchangeState, exchangeId ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.toggleExchangeState, + this.contract.toggleExchangeState, exchangeId ) return >trxReceipt @@ -251,11 +234,10 @@ export class FixedRateExchange extends SmartContractWithAddress { /** * Deactivate an exchange * @param {String} exchangeId ExchangeId - * @param {String} address User address + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async deactivate( - address: string, exchangeId: string, estimateGas?: G ): Promise> { @@ -264,18 +246,16 @@ export class FixedRateExchange extends SmartContractWithAddress { if (exchange.active === false) return null const estGas = await calculateEstimatedGas( - address, - this.contract.methods.toggleExchangeState, + this.contract.toggleExchangeState, exchangeId ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.toggleExchangeState, + this.contract.toggleExchangeState, exchangeId ) return >trxReceipt @@ -287,8 +267,8 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} Rate (converted from wei) */ public async getRate(exchangeId: string): Promise { - const weiRate = await this.contract.methods.getRate(exchangeId).call() - const rate = await this.web3.utils.fromWei(weiRate) + const weiRate = await this.contract.getRate(exchangeId) + const rate = ethers.formatEther(weiRate) return rate } @@ -298,7 +278,7 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} dt supply formatted */ public async getDatatokenSupply(exchangeId: string): Promise { - const dtSupply = await this.contract.methods.getDTSupply(exchangeId).call() + const dtSupply = await this.contract.getDTSupply(exchangeId) const exchange = await this.getExchange(exchangeId) return await this.unitsToAmount(exchange.datatoken, dtSupply, +exchange.dtDecimals) } @@ -309,7 +289,7 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} dt supply formatted */ public async getBasetokenSupply(exchangeId: string): Promise { - const btSupply = await this.contract.methods.getBTSupply(exchangeId).call() + const btSupply = await this.contract.getBTSupply(exchangeId) const exchange = await this.getExchange(exchangeId) return await this.unitsToAmount(exchange.baseToken, btSupply, +exchange.btDecimals) } @@ -320,7 +300,7 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} address of allowedSwapper */ public async getAllowedSwapper(exchangeId: string): Promise { - return await this.contract.methods.getAllowedSwapper(exchangeId).call() + return await this.contract.getAllowedSwapper(exchangeId) } /** @@ -336,17 +316,15 @@ export class FixedRateExchange extends SmartContractWithAddress { consumeMarketFee: string = '0' ): Promise { const fixedRateExchange = await this.getExchange(exchangeId) - const outDT = await this.contract.methods - .calcBaseInGivenOutDT( - exchangeId, - await this.amountToUnits( - fixedRateExchange.datatoken, - datatokenAmount, - +fixedRateExchange.dtDecimals - ), - this.web3.utils.toWei(consumeMarketFee) - ) - .call() + const outDT = await this.contract.calcBaseInGivenOutDT( + exchangeId, + await this.amountToUnits( + fixedRateExchange.datatoken, + datatokenAmount, + +fixedRateExchange.dtDecimals + ), + ethers.parseUnits(consumeMarketFee, 'ethers') + ) const priceAndFees = { baseTokenAmount: await this.unitsToAmount( @@ -386,17 +364,11 @@ export class FixedRateExchange extends SmartContractWithAddress { consumeMarketFee: string = '0' ): Promise { const exchange = await this.getExchange(exchangeId) - const amount = await this.contract.methods - .calcBaseOutGivenInDT( - exchangeId, - await this.amountToUnits( - exchange.datatoken, - datatokenAmount, - +exchange.dtDecimals - ), - this.web3.utils.toWei(consumeMarketFee) - ) - .call() + const amount = await this.contract.calcBaseOutGivenInDT( + exchangeId, + await this.amountToUnits(exchange.datatoken, datatokenAmount, +exchange.dtDecimals), + ethers.parseUnits(consumeMarketFee, 'ethers') + ) return await this.unitsToAmount(exchange.baseToken, amount[0], +exchange.btDecimals) } @@ -407,9 +379,7 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} Exchange details */ public async getExchange(exchangeId: string): Promise { - const exchange: FixedPriceExchange = await this.contract.methods - .getExchange(exchangeId) - .call() + const exchange: FixedPriceExchange = await this.contract.getExchange(exchangeId) exchange.dtDecimals = exchange.dtDecimals.toString() exchange.btDecimals = exchange.btDecimals.toString() exchange.dtBalance = await this.unitsToAmount( @@ -432,7 +402,7 @@ export class FixedRateExchange extends SmartContractWithAddress { exchange.btSupply, +exchange.btDecimals ) - exchange.fixedRate = this.web3.utils.fromWei(exchange.fixedRate) + exchange.fixedRate = ethers.formatEther(exchange.fixedRate) exchange.exchangeId = exchangeId return exchange } @@ -443,9 +413,9 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} Exchange details */ public async getFeesInfo(exchangeId: string): Promise { - const feesInfo: FeesInfo = await this.contract.methods.getFeesInfo(exchangeId).call() - feesInfo.opcFee = this.web3.utils.fromWei(feesInfo.opcFee.toString()) - feesInfo.marketFee = this.web3.utils.fromWei(feesInfo.marketFee.toString()) + const feesInfo: FeesInfo = await this.contract.getFeesInfo(exchangeId) + feesInfo.opcFee = ethers.formatEther(feesInfo.opcFee.toString()) + feesInfo.marketFee = ethers.formatEther(feesInfo.marketFee.toString()) const exchange = await this.getExchange(exchangeId) feesInfo.marketFeeAvailable = await this.unitsToAmount( @@ -469,7 +439,7 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} Exchanges list */ public async getExchanges(): Promise { - return await this.contract.methods.getExchanges().call() + return await this.contract.getExchanges() } /** @@ -478,18 +448,17 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {Promise} Result */ public async isActive(exchangeId: string): Promise { - const active = await this.contract.methods.isActive(exchangeId).call() + const active = await this.contract.isActive(exchangeId) return active } /** * Activate minting option for fixed rate contract * @param {String} exchangeId ExchangeId - * @param {String} address User address + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async activateMint( - address: string, exchangeId: string, estimateGas?: G ): Promise> { @@ -498,19 +467,17 @@ export class FixedRateExchange extends SmartContractWithAddress { if (exchange.withMint === true) return null const estGas = await calculateEstimatedGas( - address, - this.contract.methods.toggleMintState, + this.contract.toggleMintState, exchangeId, true ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.toggleMintState, + this.contract.toggleMintState, exchangeId, true ) @@ -520,11 +487,10 @@ export class FixedRateExchange extends SmartContractWithAddress { /** * Deactivate minting for fixed rate * @param {String} exchangeId ExchangeId - * @param {String} address User address + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async deactivateMint( - address: string, exchangeId: string, estimateGas?: G ): Promise> { @@ -533,19 +499,17 @@ export class FixedRateExchange extends SmartContractWithAddress { if (exchange.withMint === false) return null const estGas = await calculateEstimatedGas( - address, - this.contract.methods.toggleMintState, + this.contract.toggleMintState, exchangeId, false ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.toggleMintState, + this.contract.toggleMintState, exchangeId, false ) @@ -554,13 +518,12 @@ export class FixedRateExchange extends SmartContractWithAddress { /** * Collect BaseTokens in the contract (anyone can call this, funds are sent to Datatoken.paymentCollector) - * @param {String} address User address * @param {String} exchangeId ExchangeId * @param {String} amount amount to be collected + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async collectBasetokens( - address: string, exchangeId: string, amount: string, estimateGas?: G @@ -568,9 +531,7 @@ export class FixedRateExchange extends SmartContractWithAddress { const exchange = await this.getExchange(exchangeId) if (!exchange) return null - const fixedrate: FixedPriceExchange = await this.contract.methods - .getExchange(exchangeId) - .call() + const fixedrate: FixedPriceExchange = await this.contract.getExchange(exchangeId) const amountWei = await this.amountToUnits( fixedrate.baseToken, amount, @@ -578,19 +539,17 @@ export class FixedRateExchange extends SmartContractWithAddress { ) const estGas = await calculateEstimatedGas( - address, - this.contract.methods.collectBT, + this.contract.collectBT, exchangeId, amountWei ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.collectBT, + this.contract.collectBT, exchangeId, amountWei ) @@ -599,13 +558,12 @@ export class FixedRateExchange extends SmartContractWithAddress { /** * Collect datatokens in the contract (anyone can call this, funds are sent to Datatoken.paymentCollector) - * @param {String} address User address * @param {String} exchangeId ExchangeId * @param {String} amount amount to be collected + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async collectDatatokens( - address: string, exchangeId: string, amount: string, estimateGas?: G @@ -613,9 +571,7 @@ export class FixedRateExchange extends SmartContractWithAddress { const exchange = await this.getExchange(exchangeId) if (!exchange) return null - const fixedrate: FixedPriceExchange = await this.contract.methods - .getExchange(exchangeId) - .call() + const fixedrate: FixedPriceExchange = await this.contract.getExchange(exchangeId) const amountWei = await this.amountToUnits( fixedrate.datatoken, amount, @@ -623,19 +579,17 @@ export class FixedRateExchange extends SmartContractWithAddress { ) const estGas = await calculateEstimatedGas( - address, - this.contract.methods.collectDT, + this.contract.collectDT, exchangeId, amountWei ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.collectDT, + this.contract.collectDT, exchangeId, amountWei ) @@ -645,30 +599,24 @@ export class FixedRateExchange extends SmartContractWithAddress { /** * Collect market fee and send it to marketFeeCollector (anyone can call it) * @param {String} exchangeId ExchangeId - * @param {String} address User address + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async collectMarketFee( - address: string, exchangeId: string, estimateGas?: G ): Promise> { const exchange = await this.getExchange(exchangeId) if (!exchange) return null - const estGas = await calculateEstimatedGas( - address, - this.contract.methods.collectMarketFee, - exchangeId - ) + const estGas = await calculateEstimatedGas(this.contract.collectMarketFee, exchangeId) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.collectMarketFee, + this.contract.collectMarketFee, exchangeId ) @@ -678,30 +626,24 @@ export class FixedRateExchange extends SmartContractWithAddress { /** * Collect ocean fee and send it to OPF collector (anyone can call it) * @param {String} exchangeId ExchangeId - * @param {String} address User address + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async collectOceanFee( - address: string, exchangeId: string, estimateGas?: G ): Promise> { const exchange = await this.getExchange(exchangeId) if (!exchange) return null - const estGas = await calculateEstimatedGas( - address, - this.contract.methods.collectOceanFee, - exchangeId - ) + const estGas = await calculateEstimatedGas(this.contract.collectOceanFee, exchangeId) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.collectOceanFee, + this.contract.collectOceanFee, exchangeId ) @@ -713,7 +655,7 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {String} */ async getOPCCollector(): Promise { - const address = await this.contract.methods.opcCollector().call() + const address = await this.contract.opcCollector() return address } @@ -722,7 +664,7 @@ export class FixedRateExchange extends SmartContractWithAddress { * @return {String} */ public async getRouter(): Promise { - const address = await this.contract.methods.router().call() + const address = await this.contract.router() return address } @@ -738,33 +680,30 @@ export class FixedRateExchange extends SmartContractWithAddress { /** * Set new market fee, only market fee collector can update it - * @param {String} address user address * @param {String} exchangeId ExchangeId * @param {String} newMarketFee New market fee + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async updateMarketFee( - address: string, exchangeId: string, newMarketFee: string, estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - address, - this.contract.methods.updateMarketFee, + this.contract.updateMarketFee, exchangeId, - this.web3.utils.toWei(newMarketFee) + ethers.parseUnits(newMarketFee) ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.updateMarketFee, + this.contract.updateMarketFee, exchangeId, - this.web3.utils.toWei(newMarketFee) + ethers.parseUnits(newMarketFee) ) return >trxReceipt @@ -772,31 +711,28 @@ export class FixedRateExchange extends SmartContractWithAddress { /** * Set new market fee collector, only market fee collector can update it - * @param {String} address user address * @param {String} exchangeId ExchangeId * @param {String} newMarketFeeCollector New market fee collector + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async updateMarketFeeCollector( - address: string, exchangeId: string, newMarketFeeCollector: string, estimateGas?: G ): Promise> { const estGas = await calculateEstimatedGas( - address, - this.contract.methods.updateMarketFeeCollector, + this.contract.updateMarketFeeCollector, exchangeId, newMarketFeeCollector ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.updateMarketFeeCollector, + this.contract.updateMarketFeeCollector, exchangeId, newMarketFeeCollector ) diff --git a/src/contracts/NFT.ts b/src/contracts/NFT.ts index 5e51a8669..e6ca28e7e 100644 --- a/src/contracts/NFT.ts +++ b/src/contracts/NFT.ts @@ -1,7 +1,8 @@ -import { AbiItem } from 'web3-utils' -import { TransactionReceipt } from 'web3-eth' +// import { AbiItem } from 'web3-utils' +// import { TransactionReceipt } from 'web3-eth' +import { ethers, Signer, InterfaceAbi } from 'ethers' import ERC721Template from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json' -import { generateDtName, calculateEstimatedGas, sendTx } from '../utils' +import { generateDtName, calculateEstimatedGas, sendTx, getEventFromTx } from '../utils' import { MetadataProof, MetadataAndTokenURI, @@ -11,8 +12,8 @@ import { import { SmartContract } from './SmartContract' export class Nft extends SmartContract { - getDefaultAbi(): AbiItem | AbiItem[] { - return ERC721Template.abi as AbiItem[] + getDefaultAbi() { + return ERC721Template.abi } /** @@ -28,6 +29,7 @@ export class Nft extends SmartContract { * @param {String} name Token name * @param {String} symbol Token symbol * @param {Number} templateIndex NFT template index + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} ERC20 Datatoken address */ public async createDatatoken( @@ -58,30 +60,28 @@ export class Nft extends SmartContract { const nftContract = this.getContract(nftAddress) const estGas = await calculateEstimatedGas( - address, - nftContract.methods.createERC20, + nftContract.createERC20, templateIndex, [name, symbol], [minter, paymentCollector, mpFeeAddress, feeToken], - [this.web3.utils.toWei(cap), this.web3.utils.toWei(feeAmount)], + [ethers.parseEther(cap), ethers.parseEther(feeAmount)], [] ) if (estimateGas) return estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.createERC20, + nftContract.createERC20, templateIndex, [name, symbol], [minter, paymentCollector, mpFeeAddress, feeToken], - [this.web3.utils.toWei(cap), this.web3.utils.toWei(feeAmount)], + [ethers.parseEther(cap), ethers.parseEther(feeAmount)], [] ) - - return trxReceipt?.events?.TokenCreated?.returnValues?.[0] + const event = getEventFromTx(trxReceipt, 'TokenCreated') + return event.args[0] } /** @@ -89,6 +89,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address NFT Owner adress * @param {String} manager User adress which is going to be assing manager + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async addManager( @@ -103,19 +104,14 @@ export class Nft extends SmartContract { throw new Error(`Caller is not NFT Owner`) } - const estGas = await calculateEstimatedGas( - address, - nftContract.methods.addManager, - manager - ) + const estGas = await calculateEstimatedGas(nftContract.addManager, manager) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.addManager, + nftContract.addManager, manager ) @@ -127,6 +123,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address NFT Owner adress * @param {String} manager User adress which is going to be removed as manager + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async removeManager( @@ -141,19 +138,14 @@ export class Nft extends SmartContract { throw new Error(`Caller is not NFT Owner`) } - const estGas = await calculateEstimatedGas( - address, - nftContract.methods.removeManager, - manager - ) + const estGas = await calculateEstimatedGas(nftContract.removeManager, manager) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.removeManager, + nftContract.removeManager, manager ) @@ -165,6 +157,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address NFT Manager adress * @param {String} datatokenDeployer User adress which is going to have DatatokenDeployer permission + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async addDatatokenDeployer( @@ -181,18 +174,16 @@ export class Nft extends SmartContract { // Estimate gas for addToCreateERC20List method const estGas = await calculateEstimatedGas( - address, - nftContract.methods.addToCreateERC20List, + nftContract.addToCreateERC20List, datatokenDeployer ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.addToCreateERC20List, + nftContract.addToCreateERC20List, datatokenDeployer ) @@ -204,6 +195,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address NFT Manager adress * @param {String} datatokenDeployer Address of the user to be revoked DatatokenDeployer Permission + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async removeDatatokenDeployer( @@ -222,18 +214,16 @@ export class Nft extends SmartContract { throw new Error(`Caller is not Manager nor DatatokenDeployer`) } const estGas = await calculateEstimatedGas( - address, - nftContract.methods.removeFromCreateERC20List, + nftContract.removeFromCreateERC20List, datatokenDeployer ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.removeFromCreateERC20List, + nftContract.removeFromCreateERC20List, datatokenDeployer ) @@ -245,6 +235,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address NFT Manager adress * @param {String} metadataUpdater User adress which is going to have Metadata Updater permission + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async addMetadataUpdater( @@ -260,18 +251,16 @@ export class Nft extends SmartContract { } const estGas = await calculateEstimatedGas( - address, - nftContract.methods.addToMetadataList, + nftContract.addToMetadataList, metadataUpdater ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.addToMetadataList, + nftContract.addToMetadataList, metadataUpdater ) return >trxReceipt @@ -282,6 +271,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address NFT Manager adress * @param {String} metadataUpdater Address of the user to be revoked Metadata updater Permission + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async removeMetadataUpdater( @@ -301,18 +291,16 @@ export class Nft extends SmartContract { } const estGas = await calculateEstimatedGas( - address, - nftContract.methods.removeFromMetadataList, + nftContract.removeFromMetadataList, metadataUpdater ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.removeFromMetadataList, + nftContract.removeFromMetadataList, metadataUpdater ) return >trxReceipt @@ -323,6 +311,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address NFT Manager adress * @param {String} storeUpdater User adress which is going to have Store Updater permission + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async addStoreUpdater( @@ -338,18 +327,16 @@ export class Nft extends SmartContract { } const estGas = await calculateEstimatedGas( - address, - nftContract.methods.addTo725StoreList, + nftContract.addTo725StoreList, storeUpdater ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.addTo725StoreList, + nftContract.addTo725StoreList, storeUpdater ) @@ -361,6 +348,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address NFT Manager adress * @param {String} storeUpdater Address of the user to be revoked Store Updater Permission + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async removeStoreUpdater( @@ -380,18 +368,16 @@ export class Nft extends SmartContract { } const estGas = await calculateEstimatedGas( - address, - nftContract.methods.removeFrom725StoreList, + nftContract.removeFrom725StoreList, storeUpdater ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.removeFrom725StoreList, + nftContract.removeFrom725StoreList, storeUpdater ) @@ -405,6 +391,7 @@ export class Nft extends SmartContract { * Only NFT Owner can call it. * @param {String} nftAddress NFT contract address * @param {String} address NFT Owner adress + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async cleanPermissions( @@ -418,18 +405,14 @@ export class Nft extends SmartContract { throw new Error(`Caller is not NFT Owner`) } - const estGas = await calculateEstimatedGas( - address, - nftContract.methods.cleanPermissions - ) + const estGas = await calculateEstimatedGas(nftContract.cleanPermissions) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.cleanPermissions + nftContract.cleanPermissions ) return >trxReceipt @@ -442,6 +425,7 @@ export class Nft extends SmartContract { * @param {String} nftOwner Current NFT Owner adress * @param {String} nftReceiver User which will receive the NFT, will also be set as Manager * @param {Number} tokenId The id of the token to be transfered + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async transferNft( @@ -460,8 +444,7 @@ export class Nft extends SmartContract { const tokenIdentifier = tokenId || 1 const estGas = await calculateEstimatedGas( - nftOwner, - nftContract.methods.transferFrom, + nftContract.transferFrom, nftOwner, nftReceiver, tokenIdentifier @@ -469,11 +452,10 @@ export class Nft extends SmartContract { if (estimateGas) return >estGas const trxReceipt = await sendTx( - nftOwner, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.transferFrom, + nftContract.transferFrom, nftOwner, nftReceiver, tokenIdentifier @@ -489,6 +471,7 @@ export class Nft extends SmartContract { * @param {String} nftOwner Current NFT Owner adress * @param {String} nftReceiver User which will receive the NFT, will also be set as Manager * @param {Number} tokenId The id of the token to be transfered + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async safeTransferNft( @@ -507,8 +490,7 @@ export class Nft extends SmartContract { const tokenIdentifier = tokenId || 1 const estGas = await calculateEstimatedGas( - nftOwner, - nftContract.methods.safeTransferFrom, + nftContract.safeTransferFrom, nftOwner, nftReceiver, tokenIdentifier @@ -516,11 +498,10 @@ export class Nft extends SmartContract { if (estimateGas) return >estGas const trxReceipt = await sendTx( - nftOwner, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.safeTransferFrom, + nftContract.safeTransferFrom, nftOwner, nftReceiver, tokenIdentifier @@ -533,12 +514,14 @@ export class Nft extends SmartContract { * Creates or update Metadata cached by Aquarius. Also, updates the METADATA_DECRYPTOR key * @param {String} nftAddress NFT contract address * @param {String} address Caller address NFT Owner adress - * @param {String} address Caller address NFT Owner adress - * @param {String} address Caller address NFT Owner adress - * @param {String} address Caller address NFT Owner adress - * @param {String} address Caller address NFT Owner adress - * @param {String} address Caller address NFT Owner adress - * @param {String} address Caller address NFT Owner adress + * @param {Number} metadataState + * @param {String} metadataDecryptorUrl + * @param {String} metadataDecryptorAddress + * @param {String} flags + * @param {String} data + * @param {String} metadataHash + * @param {MetadataProof[]} metadataProofs + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async setMetadata( @@ -559,8 +542,7 @@ export class Nft extends SmartContract { throw new Error(`Caller is not Metadata updater`) } const estGas = await calculateEstimatedGas( - address, - nftContract.methods.setMetaData, + nftContract.setMetaData, metadataState, metadataDecryptorUrl, metadataDecryptorAddress, @@ -572,11 +554,10 @@ export class Nft extends SmartContract { if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.setMetaData, + nftContract.setMetaData, metadataState, metadataDecryptorUrl, metadataDecryptorAddress, @@ -594,6 +575,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address Caller address * @param {MetadataAndTokenURI} metadataAndTokenURI metaDataAndTokenURI object + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async setMetadataAndTokenURI( @@ -611,18 +593,16 @@ export class Nft extends SmartContract { metadataProofs: metadataAndTokenURI.metadataProofs || [] } const estGas = await calculateEstimatedGas( - metadataUpdater, - nftContract.methods.setMetaDataAndTokenURI, + nftContract.setMetaDataAndTokenURI, sanitizedMetadataAndTokenURI ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - metadataUpdater, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.setMetaDataAndTokenURI, + nftContract.setMetaDataAndTokenURI, sanitizedMetadataAndTokenURI ) @@ -634,6 +614,7 @@ export class Nft extends SmartContract { * @param {String} nftAddress NFT contract address * @param {String} address Caller address => metadata updater * @param {Number} metadataState new metadata state + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} trxReceipt */ public async setMetadataState( @@ -649,51 +630,42 @@ export class Nft extends SmartContract { } const estGas = await calculateEstimatedGas( - address, - nftContract.methods.setMetaDataState, + nftContract.setMetaDataState, metadataState ) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.setMetaDataState, + nftContract.setMetaDataState, metadataState ) return >trxReceipt } /** set TokenURI on an nft - * @param nftAddress NFT contract address - * @param address user adress - * @param data input data for TokenURI + * @param {String} nftAddress NFT contract address + * @param {String} data input data for TokenURI + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transaction receipt */ public async setTokenURI( nftAddress: string, - address: string, data: string, estimateGas?: G ): Promise> { const nftContract = this.getContract(nftAddress) - const estGas = await calculateEstimatedGas( - address, - nftContract.methods.setTokenURI, - '1', - data - ) + const estGas = await calculateEstimatedGas(nftContract.setTokenURI, '1', data) if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.setTokenURI, + nftContract.setTokenURI, '1', data ) @@ -706,7 +678,7 @@ export class Nft extends SmartContract { */ public async getNftOwner(nftAddress: string): Promise { const nftContract = this.getContract(nftAddress) - const trxReceipt = await nftContract.methods.ownerOf(1).call() + const trxReceipt = await nftContract.ownerOf(1) return trxReceipt } @@ -717,7 +689,7 @@ export class Nft extends SmartContract { */ public async getNftPermissions(nftAddress: string, address: string): Promise { const nftContract = this.getContract(nftAddress) - const roles = await nftContract.methods.getPermissions(address).call() + const roles = await nftContract.getPermissions(address) return roles } @@ -727,7 +699,7 @@ export class Nft extends SmartContract { */ public async getMetadata(nftAddress: string): Promise { const nftContract = this.getContract(nftAddress) - return await nftContract.methods.getMetaData().call() + return await nftContract.getMetaData() } /** Get users DatatokenDeployer role @@ -740,7 +712,7 @@ export class Nft extends SmartContract { address: string ): Promise { const nftContract = this.getContract(nftAddress) - const isDatatokenDeployer = await nftContract.methods.isERC20Deployer(address).call() + const isDatatokenDeployer = await nftContract.isERC20Deployer(address) return isDatatokenDeployer } @@ -751,41 +723,37 @@ export class Nft extends SmartContract { * @param address user adress * @param key Key of the data to be stored into 725Y standard * @param value Data to be stored into 725Y standard + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} transactionId */ - public async setData( + public async setData( nftAddress: string, address: string, key: string, - value: string - ): Promise { + value: string, + estimateGas?: G + ): Promise> { if ((await this.getNftPermissions(nftAddress, address)).store !== true) { throw new Error(`User is not ERC20 store updater`) } const nftContract = this.getContract(nftAddress) - const keyHash = this.web3.utils.keccak256(key) - const valueHex = this.web3.utils.asciiToHex(value) - - const estGas = await calculateEstimatedGas( - address, - nftContract.methods.setNewData, - keyHash, - valueHex - ) + const keyHash = ethers.keccak256(key) + const valueHex = ethers.hexlify(value) + const estGas = await calculateEstimatedGas(nftContract.setNewData, keyHash, valueHex) + if (estimateGas) return >estGas const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - nftContract.methods.setNewData, + nftContract.setNewData, keyHash, valueHex ) - return trxReceipt + return >trxReceipt } /** Gets data at a given `key` @@ -795,9 +763,10 @@ export class Nft extends SmartContract { */ public async getData(nftAddress: string, key: string): Promise { const nftContract = this.getContract(nftAddress) - const keyHash = this.web3.utils.keccak256(key) - const data = await nftContract.methods.getData(keyHash).call() - return data ? this.web3.utils.hexToAscii(data) : null + const keyHash = ethers.keccak256(key) + const data = await nftContract.getData(keyHash) + return data + // return data ? this.web3.utils.hexToAscii(data) : null } /** Gets data at a given `key` @@ -807,7 +776,7 @@ export class Nft extends SmartContract { */ public async getTokenURI(nftAddress: string, id: number): Promise { const nftContract = this.getContract(nftAddress) - const data = await nftContract.methods.tokenURI(id).call() + const data = await nftContract.tokenURI(id) return data } } diff --git a/src/contracts/NFTFactory.ts b/src/contracts/NFTFactory.ts index 5c3640004..d73ace7b0 100644 --- a/src/contracts/NFTFactory.ts +++ b/src/contracts/NFTFactory.ts @@ -1,7 +1,14 @@ -import Web3 from 'web3' -import { AbiItem } from 'web3-utils' +// import Web3 from 'web3' +// import { AbiItem } from 'web3-utils' +import { ethers, Signer, InterfaceAbi } from 'ethers' import ERC721Factory from '@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json' -import { generateDtName, calculateEstimatedGas, ZERO_ADDRESS, sendTx } from '../utils' +import { + generateDtName, + calculateEstimatedGas, + ZERO_ADDRESS, + sendTx, + getEventFromTx +} from '../utils' import { FreCreationParams, DatatokenCreateParams, @@ -17,18 +24,17 @@ import { SmartContractWithAddress } from './SmartContractWithAddress' * Provides an interface for NFT Factory contract */ export class NftFactory extends SmartContractWithAddress { - getDefaultAbi(): AbiItem | AbiItem[] { - return ERC721Factory.abi as AbiItem[] + getDefaultAbi() { + return ERC721Factory.abi } /** * Create new NFT - * @param {String} address * @param {NFTCreateData} nftData + * @param {Boolean} estimateGas if True, return gas estimate * @return {Promise} NFT datatoken address */ public async createNFT( - address: string, nftData: NftCreateData, estimateGas?: G ): Promise { @@ -50,8 +56,7 @@ export class NftFactory extends SmartContractWithAddress { throw new Error(`Template is not active`) } const estGas = await calculateEstimatedGas( - address, - this.contract.methods.deployERC721Contract, + this.contract.deployERC721Contract, nftData.name, nftData.symbol, nftData.templateIndex, @@ -65,11 +70,10 @@ export class NftFactory extends SmartContractWithAddress { // Invoke createToken function of the contract const trxReceipt = await sendTx( - address, estGas + 1, - this.web3, + this.signer, this.config?.gasFeeMultiplier, - this.contract.methods.deployERC721Contract, + this.contract.deployERC721Contract, nftData.name, nftData.symbol, nftData.templateIndex, @@ -79,14 +83,15 @@ export class NftFactory extends SmartContractWithAddress { nftData.transferable, nftData.owner ) - return trxReceipt?.events?.NFTCreated?.returnValues?.[0] + const events = getEventFromTx(trxReceipt, 'NFTCreated') + return events.args[0] } /** Get Current NFT Count (NFT created) * @return {Promise} Number of NFT created from this factory */ public async getCurrentNFTCount(): Promise { - const nftCount = await this.contract.methods.getCurrentNFTCount().call() + const nftCount = await this.contract.getCurrentNFTCount() return nftCount } @@ -94,7 +99,7 @@ export class NftFactory extends SmartContractWithAddress { * @return {Promise} Number of DTs created from this factory */ public async getCurrentTokenCount(): Promise { - const tokenCount = await this.contract.methods.getCurrentTokenCount().call() + const tokenCount = await this.contract.getCurrentTokenCount() return tokenCount } @@ -102,7 +107,7 @@ export class NftFactory extends SmartContractWithAddress { * @return {Promise} Factory Owner address */ public async getOwner(): Promise { - const owner = await this.contract.methods.owner().call() + const owner = await this.contract.owner() return owner } @@ -110,7 +115,7 @@ export class NftFactory extends SmartContractWithAddress { * @return {Promise} Number of NFT Template added to this factory */ public async getCurrentNFTTemplateCount(): Promise { - const count = await this.contract.methods.getCurrentNFTTemplateCount().call() + const count = await this.contract.getCurrentNFTTemplateCount() return count } @@ -118,7 +123,7 @@ export class NftFactory extends SmartContractWithAddress { * @return {Promise} Number of Datatoken Template added to this factory */ public async getCurrentTokenTemplateCount(): Promise { - const count = await this.contract.methods.getCurrentTemplateCount().call() + const count = await this.contract.getCurrentTemplateCount() return count } @@ -134,7 +139,7 @@ export class NftFactory extends SmartContractWithAddress { if (index === 0) { throw new Error(`Template index cannot be ZERO`) } - const template = await this.contract.methods.getNFTTemplate(index).call() + const template = await this.contract.getNFTTemplate(index) return template } @@ -143,7 +148,7 @@ export class NftFactory extends SmartContractWithAddress { * @return {Promise