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

rename nft files

This commit is contained in:
Bogdan Fazakas 2021-12-09 12:50:30 +02:00
parent 4d7b70af76
commit b16163041a
4 changed files with 2467 additions and 0 deletions

758
src/factories/NftFactory.ts Normal file
View File

@ -0,0 +1,758 @@
import { Contract } from 'web3-eth-contract'
import Web3 from 'web3'
import { TransactionReceipt } from 'web3-core'
import { AbiItem } from 'web3-utils'
import defaultFactory721Abi from '@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json'
import {
LoggerInstance,
getFairGasPrice,
generateDtName,
getFreCreationParams,
getErcCreationParams,
getPoolCreationParams
} from '../utils'
import { FreCreationParams, Erc20CreateParams, PoolCreationParams } from '../interfaces'
interface Template {
templateAddress: string
isActive: boolean
}
export interface TokenOrder {
tokenAddress: string
consumer: string
amount: string | number
serviceIndex: number
providerFeeAddress: string
providerFeeToken: string
providerFeeAmount: string
}
export interface NftCreateData {
name: string
symbol: string
templateIndex: number
tokenURI: string
}
/**
* Provides an interface for NFT Factory contract
*/
export class NftFactory {
public GASLIMIT_DEFAULT = 1000000
public factory721Address: string
public factory721Abi: AbiItem | AbiItem[]
public web3: Web3
public startBlock: number
public factory721: Contract
/**
* Instantiate DataTokens.
* @param {String} factory721Address
* @param {AbiItem | AbiItem[]} factory721ABI
* @param {Web3} web3
*/
constructor(
factory721Address: string,
web3: Web3,
factory721Abi?: AbiItem | AbiItem[],
startBlock?: number
) {
this.factory721Address = factory721Address
this.factory721Abi = factory721Abi || (defaultFactory721Abi.abi as AbiItem[])
this.web3 = web3
this.startBlock = startBlock || 0
this.factory721 = new this.web3.eth.Contract(
this.factory721Abi,
this.factory721Address
)
}
/**
* Get estimated gas cost for deployERC721Contract value
* @param {String} address
* @param {String} nftData
* @return {Promise<string>} NFT datatoken address
*/
public async estGasCreateNFT(address: string, nftData: NftCreateData): Promise<string> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await this.factory721.methods
.deployERC721Contract(
nftData.name,
nftData.symbol,
nftData.templateIndex,
'0x0000000000000000000000000000000000000000',
nftData.tokenURI
)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* Create new NFT
* @param {String} address
* @param {NFTCreateData} nftData
* @return {Promise<string>} NFT datatoken address
*/
public async createNFT(address: string, nftData: NftCreateData): Promise<string> {
if (!nftData.templateIndex) nftData.templateIndex = 1
if (!nftData.name || !nftData.symbol) {
const { name, symbol } = generateDtName()
nftData.name = name
nftData.symbol = symbol
}
const estGas = await this.estGasCreateNFT(address, nftData)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.deployERC721Contract(
nftData.name,
nftData.symbol,
nftData.templateIndex,
'0x0000000000000000000000000000000000000000',
nftData.tokenURI
)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
let tokenAddress = null
try {
tokenAddress = trxReceipt.events.NFTCreated.returnValues[0]
} catch (e) {
LoggerInstance.error(`ERROR: Failed to create datatoken : ${e.message}`)
}
return tokenAddress
}
/** Get Current NFT Count (NFT created)
* @return {Promise<number>} Number of NFT created from this factory
*/
public async getCurrentNFTCount(): Promise<number> {
const trxReceipt = await this.factory721.methods.getCurrentNFTCount().call()
return trxReceipt
}
/** Get Current Datatoken Count
* @return {Promise<number>} Number of DTs created from this factory
*/
public async getCurrentTokenCount(): Promise<number> {
const trxReceipt = await this.factory721.methods.getCurrentTokenCount().call()
return trxReceipt
}
/** Get Factory Owner
* @return {Promise<string>} Factory Owner address
*/
public async getOwner(): Promise<string> {
const trxReceipt = await this.factory721.methods.owner().call()
return trxReceipt
}
/** Get Current NFT Template Count
* @return {Promise<number>} Number of NFT Template added to this factory
*/
public async getCurrentNFTTemplateCount(): Promise<number> {
const count = await this.factory721.methods.getCurrentNFTTemplateCount().call()
return count
}
/** Get Current Template Datatoken (ERC20) Count
* @return {Promise<number>} Number of ERC20 Template added to this factory
*/
public async getCurrentTokenTemplateCount(): Promise<number> {
const count = await this.factory721.methods.getCurrentTemplateCount().call()
return count
}
/** Get NFT Template
* @param {Number} index Template index
* @return {Promise<Template>} Number of Template added to this factory
*/
public async getNFTTemplate(index: number): Promise<Template> {
const template = await this.factory721.methods.getNFTTemplate(index).call()
return template
}
/** Get Datatoken(erc20) Template
* @param {Number} index Template index
* @return {Promise<Template>} DT Template info
*/
public async getTokenTemplate(index: number): Promise<Template> {
const template = await this.factory721.methods.getTokenTemplate(index).call()
return template
}
/** Check if ERC20 is deployed from the factory
* @param {String} datatoken Datatoken address we want to check
* @return {Promise<Boolean>} return true if deployed from this factory
*/
public async checkDatatoken(datatoken: string): Promise<Boolean> {
const isDeployed = await this.factory721.methods.erc20List(datatoken).call()
return isDeployed
}
/** Check if NFT is deployed from the factory
* @param {String} nftAddress nftAddress address we want to check
* @return {Promise<String>} return address(0) if it's not, or the nftAddress if true
*/
public async checkNFT(nftAddress: string): Promise<String> {
const confirmAddress = await this.factory721.methods.erc721List(nftAddress).call()
return confirmAddress
}
/**
* Estimate gas cost for add721TokenTemplate method
* @param {String} address
* @param {String} templateAddress template address to add
* @return {Promise<TransactionReceipt>}
*/
public async estGasAddNFTTemplate(
address: string,
templateAddress: string
): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await this.factory721.methods
.add721TokenTemplate(templateAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* Add a new erc721 token template - only factory Owner
* @param {String} address
* @param {String} templateAddress template address to add
* @return {Promise<TransactionReceipt>}
*/
public async addNFTTemplate(
address: string,
templateAddress: string
): Promise<TransactionReceipt> {
if ((await this.getOwner()) !== address) {
throw new Error(`Caller is not Factory Owner`)
}
const estGas = await this.estGasAddNFTTemplate(address, templateAddress)
// Invoke add721TokenTemplate function of the contract
const trxReceipt = await this.factory721.methods
.add721TokenTemplate(templateAddress)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
/**
* Estimate gas cost for disable721TokenTemplate method
* @param {String} address
* @param {Number} templateIndex index of the template we want to disable
* @return {Promise<TransactionReceipt>} current token template count
*/
public async estGasDisableNFTTemplate(
address: string,
templateIndex: number
): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await this.factory721.methods
.disable721TokenTemplate(templateIndex)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* Disable token template - only factory Owner
* @param {String} address
* @param {Number} templateIndex index of the template we want to disable
* @return {Promise<TransactionReceipt>} current token template count
*/
public async disableNFTTemplate(
address: string,
templateIndex: number
): Promise<TransactionReceipt> {
if ((await this.getOwner()) !== address) {
throw new Error(`Caller is not Factory Owner`)
}
const estGas = await this.estGasDisableNFTTemplate(address, templateIndex)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.disable721TokenTemplate(templateIndex)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
/**
* Reactivate a previously disabled token template - only factory Owner
* @param {String} address
* @param {Number} templateIndex index of the template we want to reactivate
* @return {Promise<TransactionReceipt>} current token template count
*/
public async estGasReactivateNFTTemplate(
address: string,
templateIndex: number
): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await this.factory721.methods
.reactivate721TokenTemplate(templateIndex)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* Reactivate a previously disabled token template - only factory Owner
* @param {String} address
* @param {Number} templateIndex index of the template we want to reactivate
* @return {Promise<TransactionReceipt>} current token template count
*/
public async reactivateNFTTemplate(
address: string,
templateIndex: number
): Promise<TransactionReceipt> {
if ((await this.getOwner()) !== address) {
throw new Error(`Caller is not Factory Owner`)
}
const estGas = await this.estGasReactivateNFTTemplate(address, templateIndex)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.reactivate721TokenTemplate(templateIndex)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
/**
* Estimate gas cost for addTokenTemplate method
* @param {String} address
* @param {String} templateAddress template address to add
* @return {Promise<TransactionReceipt>}
*/
public async estGasAddTokenTemplate(
address: string,
templateAddress: string
): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await this.factory721.methods
.addTokenTemplate(templateAddress)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* Add a new erc721 token template - only factory Owner
* @param {String} address
* @param {String} templateAddress template address to add
* @return {Promise<TransactionReceipt>}
*/
public async addTokenTemplate(
address: string,
templateAddress: string
): Promise<TransactionReceipt> {
if ((await this.getOwner()) !== address) {
throw new Error(`Caller is not Factory Owner`)
}
const estGas = await this.estGasAddTokenTemplate(address, templateAddress)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.addTokenTemplate(templateAddress)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
/**
* Estimate gas cost for disableTokenTemplate method
* @param {String} address
* @param {Number} templateIndex index of the template we want to disable
* @return {Promise<TransactionReceipt>} current token template count
*/
public async estGasDisableTokenTemplate(
address: string,
templateIndex: number
): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await this.factory721.methods
.disableTokenTemplate(templateIndex)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* Disable token template - only factory Owner
* @param {String} address
* @param {Number} templateIndex index of the template we want to disable
* @return {Promise<TransactionReceipt>} current token template count
*/
public async disableTokenTemplate(
address: string,
templateIndex: number
): Promise<TransactionReceipt> {
if ((await this.getOwner()) !== address) {
throw new Error(`Caller is not Factory Owner`)
}
const estGas = await this.estGasDisableTokenTemplate(address, templateIndex)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.disableTokenTemplate(templateIndex)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
/**
* Estimate gas cost for reactivateTokenTemplate method
* @param {String} address
* @param {Number} templateIndex index of the template we want to reactivate
* @return {Promise<TransactionReceipt>} current token template count
*/
public async estGasReactivateTokenTemplate(
address: string,
templateIndex: number
): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await this.factory721.methods
.reactivateTokenTemplate(templateIndex)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* Reactivate a previously disabled token template - only factory Owner
* @param {String} address
* @param {Number} templateIndex index of the template we want to reactivate
* @return {Promise<TransactionReceipt>} current token template count
*/
public async reactivateTokenTemplate(
address: string,
templateIndex: number
): Promise<TransactionReceipt> {
if ((await this.getOwner()) !== address) {
throw new Error(`Caller is not Factory Owner`)
}
const estGas = await this.estGasReactivateTokenTemplate(address, templateIndex)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.reactivateTokenTemplate(templateIndex)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
/** Estimate gas cost for startMultipleTokenOrder method
* @param address Caller address
* @param orders an array of struct tokenOrder
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async estGasStartMultipleTokenOrder(
address: string,
orders: TokenOrder[]
): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await this.factory721.methods
.startMultipleTokenOrder(orders)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* @dev startMultipleTokenOrder
* Used as a proxy to order multiple services
* Users can have inifinite approvals for fees for factory instead of having one approval/ erc20 contract
* Requires previous approval of all :
* - consumeFeeTokens
* - publishMarketFeeTokens
* - erc20 datatokens
* @param address Caller address
* @param orders an array of struct tokenOrder
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async startMultipleTokenOrder(
address: string,
orders: TokenOrder[]
): Promise<TransactionReceipt> {
const estGas = await this.estGasStartMultipleTokenOrder(address, orders)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.startMultipleTokenOrder(orders)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
/**
* Estimate gas cost for createNftWithErc method
* @param address Caller address
* @param _NftCreateData input data for nft creation
* @param _ErcCreateData input data for erc20 creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async estGasCreateNftWithErc(
address: string,
nftCreateData: NftCreateData,
ercParams: Erc20CreateParams
): Promise<any> {
// Get estimated gas value
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
const ercCreateData = getErcCreationParams(ercParams, this.web3)
estGas = await this.factory721.methods
.createNftWithErc(nftCreateData, ercCreateData)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* @dev createNftWithErc
* Creates a new NFT, then a ERC20,all in one call
* @param address Caller address
* @param _NftCreateData input data for nft creation
* @param _ErcCreateData input data for erc20 creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async createNftWithErc(
address: string,
nftCreateData: NftCreateData,
ercParams: Erc20CreateParams
): Promise<TransactionReceipt> {
const ercCreateData = getErcCreationParams(ercParams, this.web3)
const estGas = await this.estGasCreateNftWithErc(
address,
nftCreateData,
ercCreateData
)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.createNftWithErc(nftCreateData, ercCreateData)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
/**
* Estimate gas cost for createNftErcWithPool method
* @param address Caller address
* @param nftCreateData input data for NFT Creation
* @param ercParams input data for ERC20 Creation
* @param poolParams input data for Pool Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async estGasCreateNftErcWithPool(
address: string,
nftCreateData: NftCreateData,
ercParams: Erc20CreateParams,
poolParams: PoolCreationParams
): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
const ercCreateData = getErcCreationParams(ercParams, this.web3)
const poolData = getPoolCreationParams(poolParams, this.web3)
estGas = await this.factory721.methods
.createNftErcWithPool(nftCreateData, ercCreateData, poolData)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* @dev createNftErcWithPool
* Creates a new NFT, then a ERC20, then a Pool, all in one call
* Use this carefully, because if Pool creation fails, you are still going to pay a lot of gas
* @param address Caller address
* @param nftCreateData input data for NFT Creation
* @param ercParams input data for ERC20 Creation
* @param poolParams input data for Pool Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async createNftErcWithPool(
address: string,
nftCreateData: NftCreateData,
ercParams: Erc20CreateParams,
poolParams: PoolCreationParams
): Promise<TransactionReceipt> {
const estGas = await this.estGasCreateNftErcWithPool(
address,
nftCreateData,
ercParams,
poolParams
)
const ercCreateData = getErcCreationParams(ercParams, this.web3)
const poolData = getPoolCreationParams(poolParams, this.web3)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.createNftErcWithPool(nftCreateData, ercCreateData, poolData)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
/** Estimate gas cost for createNftErcWithFixedRate method
* @param address Caller address
* @param nftCreateData input data for NFT Creation
* @param ercParams input data for ERC20 Creation
* @param freParams input data for FixedRate Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async estGasCreateNftErcWithFixedRate(
address: string,
nftCreateData: NftCreateData,
ercParams: Erc20CreateParams,
freParams: FreCreationParams
): Promise<any> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
const ercCreateData = getErcCreationParams(ercParams, this.web3)
const fixedData = getFreCreationParams(freParams, this.web3)
try {
estGas = await this.factory721.methods
.createNftErcWithFixedRate(nftCreateData, ercCreateData, fixedData)
.estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
}
return estGas
}
/**
* @dev createNftErcWithFixedRate
* Creates a new NFT, then a ERC20, then a FixedRateExchange, all in one call
* Use this carefully, because if Fixed Rate creation fails, you are still going to pay a lot of gas
* @param address Caller address
* @param nftCreateData input data for NFT Creation
* @param ercParams input data for ERC20 Creation
* @param freParams input data for FixedRate Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async createNftErcWithFixedRate(
address: string,
nftCreateData: NftCreateData,
ercParams: Erc20CreateParams,
freParams: FreCreationParams
): Promise<TransactionReceipt> {
const ercCreateData = getErcCreationParams(ercParams, this.web3)
const fixedData = getFreCreationParams(freParams, this.web3)
const estGas = await this.estGasCreateNftErcWithFixedRate(
address,
nftCreateData,
ercParams,
freParams
)
// Invoke createToken function of the contract
const trxReceipt = await this.factory721.methods
.createNftErcWithFixedRate(nftCreateData, ercCreateData, fixedData)
.send({
from: address,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
return trxReceipt
}
}

1024
src/tokens/Nft.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,385 @@
import { assert, expect } from 'chai'
import { AbiItem } from 'web3-utils/types'
import { TestContractHandler } from '../TestContractHandler'
import Web3 from 'web3'
import ERC721Factory from '@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json'
import ERC721Template from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json'
import SideStaking from '@oceanprotocol/contracts/artifacts/contracts/pools/ssContracts/SideStaking.sol/SideStaking.json'
import Router from '@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json'
import ERC20Template from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json'
import Dispenser from '@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json'
import FixedRate from '@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json'
import OPFCommunityFeeCollector from '@oceanprotocol/contracts/artifacts/contracts/communityFee/OPFCommunityFeeCollector.sol/OPFCommunityFeeCollector.json'
import PoolTemplate from '@oceanprotocol/contracts/artifacts/contracts/pools/balancer/BPool.sol/BPool.json'
import { NftFactory, NftCreateData, TokenOrder } from '../../src/factories/NftFactory'
import {
FreCreationParams,
Erc20CreateParams,
PoolCreationParams
} from '../../src/interfaces'
const web3 = new Web3('http://127.0.0.1:8545')
describe('Nft Factory test', () => {
let factoryOwner: string
let nftOwner: string
let user1: string
let user2: string
let user3: string
let contracts: TestContractHandler
let nftFactory: NftFactory
let dtAddress: string
let dtAddress2: string
let nftAddress: string
it('should deploy contracts', async () => {
contracts = new TestContractHandler(
web3,
ERC721Template.abi as AbiItem[],
ERC20Template.abi as AbiItem[],
PoolTemplate.abi as AbiItem[],
ERC721Factory.abi as AbiItem[],
Router.abi as AbiItem[],
SideStaking.abi as AbiItem[],
FixedRate.abi as AbiItem[],
Dispenser.abi as AbiItem[],
OPFCommunityFeeCollector.abi as AbiItem[],
ERC721Template.bytecode,
ERC20Template.bytecode,
PoolTemplate.bytecode,
ERC721Factory.bytecode,
Router.bytecode,
SideStaking.bytecode,
FixedRate.bytecode,
Dispenser.bytecode,
OPFCommunityFeeCollector.bytecode
)
await contracts.getAccounts()
factoryOwner = contracts.accounts[0]
nftOwner = contracts.accounts[1]
user1 = contracts.accounts[2]
user2 = contracts.accounts[3]
user3 = contracts.accounts[4]
await contracts.deployContracts(factoryOwner, Router.abi as AbiItem[])
console.log(
'address',
contracts.factory721Address,
contracts.poolTemplateAddress,
contracts.routerAddress,
contracts.fixedRateAddress,
contracts.dispenserAddress,
contracts.sideStakingAddress,
contracts.template721Address,
contracts.template20Address
)
const daiContract = new web3.eth.Contract(
contracts.MockERC20.options.jsonInterface,
contracts.daiAddress
)
await daiContract.methods
.approve(contracts.factory721Address, web3.utils.toWei('10000'))
.send({ from: contracts.accounts[0] })
})
it('should initiate NFTFactory instance', async () => {
nftFactory = new NftFactory(contracts.factory721Address, web3)
})
it('#getCurrentNFTCount - should return actual nft count (0)', async () => {
const nftCount = await nftFactory.getCurrentNFTCount()
expect(nftCount).to.equal('0')
})
it('#getCurrentTokenCount - should return actual token count (0)', async () => {
const tokenCount = await nftFactory.getCurrentTokenCount()
expect(tokenCount).to.equal('0')
})
it('#getOwner - should return actual owner', async () => {
const owner = await nftFactory.getOwner()
assert(owner === contracts.accounts[0])
})
it('#getCurrentNFTTemplateCount - should return actual nft template count (1)', async () => {
const nftTemplateCount = await nftFactory.getCurrentNFTTemplateCount()
expect(nftTemplateCount).to.equal('1')
})
it('#getCurrentTokenTemplateCount - should return actual token template count (1)', async () => {
const tokenTemplateCount = await nftFactory.getCurrentTokenTemplateCount()
expect(tokenTemplateCount).to.equal('1')
})
it('#getNFTTemplate - should return NFT template struct', async () => {
const nftTemplate = await nftFactory.getNFTTemplate(1)
assert(nftTemplate.isActive === true)
assert(nftTemplate.templateAddress === contracts.template721Address)
})
it('#getTokenTemplate - should return Token template struct', async () => {
const tokenTemplate = await nftFactory.getTokenTemplate(1)
assert(tokenTemplate.isActive === true)
assert(tokenTemplate.templateAddress === contracts.template20Address)
})
it('#addNFTTemplate - should add NFT template if factory owner', async () => {
await nftFactory.addNFTTemplate(contracts.accounts[0], contracts.fixedRateAddress) // contracts.fixedRateAddress it's just a dummy contract in this case
const nftTemplateCount = await nftFactory.getCurrentNFTTemplateCount()
expect(nftTemplateCount).to.equal('2')
const nftTemplate = await nftFactory.getNFTTemplate(2)
assert(nftTemplate.isActive === true)
assert(nftTemplate.templateAddress === contracts.fixedRateAddress)
})
it('#disableNFTTemplate - should disable NFT template if factory owner', async () => {
let nftTemplate = await nftFactory.getNFTTemplate(2)
assert(nftTemplate.isActive === true)
await nftFactory.disableNFTTemplate(contracts.accounts[0], 2) // owner disables template index = 2
nftTemplate = await nftFactory.getNFTTemplate(2)
assert(nftTemplate.isActive === false)
})
it('#reactivateNFTTemplate - should disable NFT template if factory owner', async () => {
let nftTemplate = await nftFactory.getNFTTemplate(2)
assert(nftTemplate.isActive === false)
await nftFactory.reactivateNFTTemplate(contracts.accounts[0], 2) // owner reactivates template index = 2
nftTemplate = await nftFactory.getNFTTemplate(2)
assert(nftTemplate.isActive === true)
})
it('#addTokenTemplate - should add Datatoken template if factory owner', async () => {
await nftFactory.addTokenTemplate(contracts.accounts[0], contracts.fixedRateAddress) // contracts.fixedRateAddress it's just a dummy contract in this case
const tokenTemplateCount = await nftFactory.getCurrentTokenTemplateCount()
expect(tokenTemplateCount).to.equal('2')
const nftTemplate = await nftFactory.getTokenTemplate(2)
assert(nftTemplate.isActive === true)
assert(nftTemplate.templateAddress === contracts.fixedRateAddress)
})
it('#disableTokenTemplate - should disable Token template if factory owner', async () => {
let tokenTemplate = await nftFactory.getTokenTemplate(2)
assert(tokenTemplate.isActive === true)
await nftFactory.disableTokenTemplate(contracts.accounts[0], 2) // owner disables template index = 2
tokenTemplate = await nftFactory.getTokenTemplate(2)
assert(tokenTemplate.isActive === false)
})
it('#reactivateTokenTemplate - should disable Token template if factory owner', async () => {
let tokenTemplate = await nftFactory.getTokenTemplate(2)
assert(tokenTemplate.isActive === false)
await nftFactory.reactivateTokenTemplate(contracts.accounts[0], 2) // owner reactivates template index = 2
tokenTemplate = await nftFactory.getTokenTemplate(2)
assert(tokenTemplate.isActive === true)
})
it('#createNftwithErc - should create an NFT and a Datatoken ', async () => {
// we prepare transaction parameters objects
const nftData: NftCreateData = {
name: '72120Bundle',
symbol: '72Bundle',
templateIndex: 1,
tokenURI: 'https://oceanprotocol.com/nft/'
}
const ercParams: Erc20CreateParams = {
templateIndex: 1,
minter: contracts.accounts[0],
feeManager: user3,
mpFeeAddress: user2,
feeToken: '0x0000000000000000000000000000000000000000',
cap: '10000',
feeAmount: '0',
name: 'ERC20B1',
symbol: 'ERC20DT1Symbol'
}
const txReceipt = await nftFactory.createNftWithErc(
contracts.accounts[0],
nftData,
ercParams
)
// EVENTS HAVE BEEN EMITTED
expect(txReceipt.events.NFTCreated.event === 'NFTCreated')
expect(txReceipt.events.TokenCreated.event === 'TokenCreated')
// stored for later use in startMultipleTokenOrder test
nftAddress = txReceipt.events.NFTCreated.returnValues.newTokenAddress
dtAddress = txReceipt.events.TokenCreated.returnValues.newTokenAddress
})
it('#createNftErcWithPool- should create an NFT, a Datatoken and a pool DT/DAI', async () => {
// we prepare transaction parameters objects
const nftData: NftCreateData = {
name: '72120Bundle',
symbol: '72Bundle',
templateIndex: 1,
tokenURI: 'https://oceanprotocol.com/nft/'
}
const ercParams: Erc20CreateParams = {
templateIndex: 1,
minter: user2,
feeManager: user3,
mpFeeAddress: user2,
feeToken: '0x0000000000000000000000000000000000000000',
cap: '1000000',
feeAmount: '0',
name: 'ERC20B1',
symbol: 'ERC20DT1Symbol'
}
const poolParams: PoolCreationParams = {
ssContract: contracts.sideStakingAddress,
basetokenAddress: contracts.daiAddress,
basetokenSender: contracts.factory721Address,
publisherAddress: contracts.accounts[0],
marketFeeCollector: contracts.accounts[0],
poolTemplateAddress: contracts.poolTemplateAddress,
rate: '1',
basetokenDecimals: 18,
vestingAmount: '10000',
vestedBlocks: 2500000,
initialBasetokenLiquidity: '2000',
swapFeeLiquidityProvider: 1e15,
swapFeeMarketPlaceRunner: 1e15
}
const txReceipt = await nftFactory.createNftErcWithPool(
contracts.accounts[0],
nftData,
ercParams,
poolParams
)
// EVENTS HAVE BEEN EMITTED
expect(txReceipt.events.NFTCreated.event === 'NFTCreated')
expect(txReceipt.events.TokenCreated.event === 'TokenCreated')
expect(txReceipt.events.NewPool.event === 'NewPool')
})
it('#createNftErcWithFixedRate- should create an NFT, a datatoken and create a Fixed Rate Exchange', async () => {
// we prepare transaction parameters objects
const nftData: NftCreateData = {
name: '72120Bundle',
symbol: '72Bundle',
templateIndex: 1,
tokenURI: 'https://oceanprotocol.com/nft/'
}
const ercParams: Erc20CreateParams = {
templateIndex: 1,
minter: contracts.accounts[0],
feeManager: user3,
mpFeeAddress: user2,
feeToken: '0x0000000000000000000000000000000000000000',
cap: '1000000',
feeAmount: '0',
name: 'ERC20B1',
symbol: 'ERC20DT1Symbol'
}
const freParams: FreCreationParams = {
fixedRateAddress: contracts.fixedRateAddress,
baseTokenAddress: contracts.daiAddress,
owner: contracts.accounts[0],
marketFeeCollector: contracts.accounts[0],
baseTokenDecimals: 18,
dataTokenDecimals: 18,
fixedRate: '1',
marketFee: 1e15,
allowedConsumer: contracts.accounts[0],
withMint: false
}
const txReceipt = await nftFactory.createNftErcWithFixedRate(
contracts.accounts[0],
nftData,
ercParams,
freParams
)
// EVENTS HAVE BEEN EMITTED
expect(txReceipt.events.NFTCreated.event === 'NFTCreated')
expect(txReceipt.events.TokenCreated.event === 'TokenCreated')
expect(txReceipt.events.NewFixedRate.event === 'NewFixedRate')
// stored for later use in startMultipleTokenOrder test
dtAddress2 = txReceipt.events.TokenCreated.returnValues.newTokenAddress
})
it('#startMultipleTokenOrder- should succed to start multiple orders', async () => {
const consumer = user2 // could be different user
const dtAmount = web3.utils.toWei('1')
const serviceIndex = 1 // dummy index
const consumeFeeAddress = user3 // marketplace fee Collector
const consumeFeeAmount = '0' // fee to be collected on top, requires approval
const consumeFeeToken = contracts.daiAddress // token address for the feeAmount, in this case DAI
// we reuse a DT created in a previous test
const dtContract = new web3.eth.Contract(ERC20Template.abi as AbiItem[], dtAddress)
expect(await dtContract.methods.balanceOf(user2).call()).to.equal('0')
// dt owner mint dtAmount to user2
await dtContract.methods.mint(user2, dtAmount).send({ from: contracts.accounts[0] })
// user2 approves NFTFactory to move his dtAmount
await dtContract.methods
.approve(contracts.factory721Address, dtAmount)
.send({ from: user2 })
// we reuse another DT created in a previous test
const dtContract2 = new web3.eth.Contract(ERC20Template.abi as AbiItem[], dtAddress2)
expect(await dtContract2.methods.balanceOf(user2).call()).to.equal('0')
// dt owner mint dtAmount to user2
await dtContract2.methods.mint(user2, dtAmount).send({ from: contracts.accounts[0] })
// user2 approves NFTFactory to move his dtAmount
await dtContract2.methods
.approve(contracts.factory721Address, dtAmount)
.send({ from: user2 })
// we check user2 has enought DTs
expect(await dtContract.methods.balanceOf(user2).call()).to.equal(dtAmount)
expect(await dtContract2.methods.balanceOf(user2).call()).to.equal(dtAmount)
const orders: TokenOrder[] = [
{
tokenAddress: dtAddress,
consumer: consumer,
amount: dtAmount,
serviceIndex: serviceIndex,
providerFeeAddress: consumeFeeAddress,
providerFeeToken: consumeFeeToken,
providerFeeAmount: consumeFeeAmount
},
{
tokenAddress: dtAddress2,
consumer: consumer,
amount: dtAmount,
serviceIndex: serviceIndex,
providerFeeAddress: consumeFeeAddress,
providerFeeToken: consumeFeeToken,
providerFeeAmount: consumeFeeAmount
}
]
await nftFactory.startMultipleTokenOrder(user2, orders)
// we check user2 has no more DTs
expect(await dtContract.methods.balanceOf(user2).call()).to.equal('0')
expect(await dtContract2.methods.balanceOf(user2).call()).to.equal('0')
})
it('#checkDatatoken - should confirm if DT is from the factory', async () => {
assert((await nftFactory.checkDatatoken(dtAddress)) === true)
assert((await nftFactory.checkDatatoken(dtAddress2)) === true)
assert((await nftFactory.checkDatatoken(user2)) === false)
assert((await nftFactory.checkDatatoken(nftAddress)) === false)
})
it('#checkNFT - should return nftAddress if from the factory, or address(0) if not', async () => {
assert(
(await nftFactory.checkNFT(dtAddress)) ===
'0x0000000000000000000000000000000000000000'
)
assert((await nftFactory.checkNFT(nftAddress)) === nftAddress)
})
})

View File

@ -0,0 +1,300 @@
import { assert } from 'chai'
import Web3 from 'web3'
import PoolTemplate from '@oceanprotocol/contracts/artifacts/contracts/pools/balancer/BPool.sol/BPool.json'
import ERC721Factory from '@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json'
import ERC721Template from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json'
import SideStaking from '@oceanprotocol/contracts/artifacts/contracts/pools/ssContracts/SideStaking.sol/SideStaking.json'
import Router from '@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json'
import ERC20Template from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json'
import Dispenser from '@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json'
import FixedRate from '@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json'
import OPFCollector from '@oceanprotocol/contracts/artifacts/contracts/communityFee/OPFCommunityFeeCollector.sol/OPFCommunityFeeCollector.json'
import { TestContractHandler } from '../../TestContractHandler'
import { NftFactory, NftCreateData } from '../../../src/factories/NftFactory'
import { Nft } from '../../../src/tokens/NFT'
import { AbiItem } from 'web3-utils'
const web3 = new Web3('http://127.0.0.1:8545')
describe('NFT', () => {
let nftOwner: string
let user1: string
let user2: string
let user3: string
let contractHandler: TestContractHandler
let nftDatatoken: Nft
let nftFactory: NftFactory
let nftAddress: string
const nftName = 'NFTName'
const nftSymbol = 'NFTSymbol'
const publishMarketFeeAdress = '0xeE9300b7961e0a01d9f0adb863C7A227A07AaD75'
const oceanAddress = '0x967da4048cd07ab37855c090aaf366e4ce1b9f48'
it('should deploy contracts', async () => {
contractHandler = new TestContractHandler(
web3,
ERC721Template.abi as AbiItem[],
ERC20Template.abi as AbiItem[],
PoolTemplate.abi as AbiItem[],
ERC721Factory.abi as AbiItem[],
Router.abi as AbiItem[],
SideStaking.abi as AbiItem[],
FixedRate.abi as AbiItem[],
Dispenser.abi as AbiItem[],
OPFCollector.abi as AbiItem[],
ERC721Template.bytecode,
ERC20Template.bytecode,
PoolTemplate.bytecode,
ERC721Factory.bytecode,
Router.bytecode,
SideStaking.bytecode,
FixedRate.bytecode,
Dispenser.bytecode,
OPFCollector.bytecode
)
await contractHandler.getAccounts()
nftOwner = contractHandler.accounts[0]
user1 = contractHandler.accounts[1]
user2 = contractHandler.accounts[2]
user3 = contractHandler.accounts[3]
await contractHandler.deployContracts(nftOwner, Router.abi as AbiItem[])
})
it('should initialize NFTFactory instance and create a new NFT', async () => {
nftFactory = new NftFactory(
contractHandler.factory721Address,
web3,
ERC721Factory.abi as AbiItem[]
)
const nftData: NftCreateData = {
name: nftName,
symbol: nftSymbol,
templateIndex: 1,
tokenURI: 'https://oceanprotocol.com/nft/'
}
nftAddress = await nftFactory.createNFT(nftOwner, nftData)
nftDatatoken = new Nft(web3, ERC721Template.abi as AbiItem[])
})
it('#createERC20 - should create a new ERC20 DT from NFT contract', async () => {
const erc20Address = await nftDatatoken.createErc20(
nftAddress,
nftOwner,
nftOwner,
user1,
user2,
'0x0000000000000000000000000000000000000000',
'0',
'10000',
nftName,
nftSymbol,
1
)
assert(erc20Address !== null)
})
// Manager
it('#addManager - should add a new Manager', async () => {
assert((await nftDatatoken.getNftPermissions(nftAddress, user1)).manager === false)
await nftDatatoken.addManager(nftAddress, nftOwner, user1)
assert((await nftDatatoken.getNftPermissions(nftAddress, user1)).manager === true)
})
it('#addManager - should fail to add a new Manager, if NOT NFT Owner', async () => {
try {
await nftDatatoken.addManager(nftAddress, user1, user1)
} catch (e) {
assert(e.message === 'Caller is not NFT Owner')
}
})
it('#removeManager - should remove a Manager', async () => {
assert((await nftDatatoken.getNftPermissions(nftAddress, user1)).manager === true)
await nftDatatoken.removeManager(nftAddress, nftOwner, user1)
assert((await nftDatatoken.getNftPermissions(nftAddress, user1)).manager === false)
})
it('#removeManager - should fail to remove a new Manager, if NOT NFT Owner', async () => {
try {
await nftDatatoken.removeManager(nftAddress, user1, nftOwner)
} catch (e) {
assert(e.message === 'Caller is not NFT Owner')
}
})
// ERC20Deployer
it('#addERC20Deployer -should add ERC20deployer if Manager', async () => {
assert((await nftDatatoken.isErc20Deployer(nftAddress, user1)) === false)
await nftDatatoken.addErc20Deployer(nftAddress, nftOwner, user1)
assert((await nftDatatoken.isErc20Deployer(nftAddress, user1)) === true)
})
it('#addERC20Deployer - should fail to add ERC20deployer if NOT Manager', async () => {
try {
await nftDatatoken.addErc20Deployer(nftAddress, user1, user1)
} catch (e) {
assert(
e.message ===
'Returned error: VM Exception while processing transaction: revert ERC721RolesAddress: NOT MANAGER'
)
}
})
it('#removeERC20Deployer - remove ERC20deployer if Manager', async () => {
assert((await nftDatatoken.isErc20Deployer(nftAddress, user1)) === true)
await nftDatatoken.removeErc20Deployer(nftAddress, nftOwner, user1)
assert((await nftDatatoken.isErc20Deployer(nftAddress, user1)) === false)
})
it('#removeERC20Deployer - should fail and remove ERC20deployer if NOT Manager', async () => {
try {
await nftDatatoken.removeErc20Deployer(nftAddress, user1, user1)
} catch (e) {
assert(
e.message ===
'Returned error: VM Exception while processing transaction: revert ERC721RolesAddress: Not enough permissions to remove from ERC20List'
)
}
})
// MetadataUpdate
it('#addMetadataUpdate - should add to remove Metadata Updater if Manager', async () => {
assert(
(await nftDatatoken.getNftPermissions(nftAddress, user1)).updateMetadata === false
)
await nftDatatoken.addMetadataUpdater(nftAddress, nftOwner, user1)
assert(
(await nftDatatoken.getNftPermissions(nftAddress, user1)).updateMetadata === true
)
})
it('#addMetadataUpdate - should fail to add Metadata Updater if NOT Manager', async () => {
try {
await nftDatatoken.addMetadataUpdater(nftAddress, user1, user1)
} catch (e) {
assert(
e.message ===
'Returned error: VM Exception while processing transaction: revert ERC721RolesAddress: NOT MANAGER'
)
}
})
it('#removeMetadataUpdate - remove Metadata Updater if Manager', async () => {
assert(
(await nftDatatoken.getNftPermissions(nftAddress, user1)).updateMetadata === true
)
await nftDatatoken.removeMetadataUpdater(nftAddress, nftOwner, user1)
assert(
(await nftDatatoken.getNftPermissions(nftAddress, user1)).updateMetadata === false
)
})
it('#removeMetadataUpdate - should fail to remove Metadata Updater if NOT Manager', async () => {
try {
await nftDatatoken.removeMetadataUpdater(nftAddress, user1, user1)
} catch (e) {
assert(
e.message ===
'Returned error: VM Exception while processing transaction: revert ERC721RolesAddress: Not enough permissions to remove from metadata list'
)
}
})
// StoreUpdater
it('#addStoreUpdater - should add to remove Store Updater if Manager', async () => {
assert((await nftDatatoken.getNftPermissions(nftAddress, user1)).store === false)
await nftDatatoken.addStoreUpdater(nftAddress, nftOwner, user1)
assert((await nftDatatoken.getNftPermissions(nftAddress, user1)).store === true)
})
it('#addStoreUpdater - should fail to add Store Updater if NOT Manager', async () => {
try {
await nftDatatoken.addStoreUpdater(nftAddress, user1, user1)
} catch (e) {
assert(
e.message ===
'Returned error: VM Exception while processing transaction: revert ERC721RolesAddress: NOT MANAGER'
)
}
})
it('#removeStoreUpdater - remove Metadata Updater if Manager', async () => {
assert((await nftDatatoken.getNftPermissions(nftAddress, user1)).store === true)
await nftDatatoken.removeStoreUpdater(nftAddress, nftOwner, user1)
assert((await nftDatatoken.getNftPermissions(nftAddress, user1)).store === false)
})
it('#removeStoreUpdater - should fail to remove Metadata Updater if NOT Manager', async () => {
try {
await nftDatatoken.removeStoreUpdater(nftAddress, user1, user1)
} catch (e) {
assert(
e.message ===
'Returned error: VM Exception while processing transaction: revert ERC721RolesAddress: Not enough permissions to remove from 725StoreList'
)
}
})
// Transfer test
it('#transferNFT - should fail to transfer the NFT and clean all permissions, if NOT NFT Owner', async () => {
assert((await nftDatatoken.getNftOwner(nftAddress)) !== user1)
try {
await nftDatatoken.transferNft(nftAddress, user1, user1, 1)
} catch (e) {
assert(e.message === 'Caller is not NFT Owner')
}
})
it('#transferNFT - should transfer the NFT and clean all permissions, set new owner as manager', async () => {
await nftDatatoken.addManager(nftAddress, nftOwner, user2)
await nftDatatoken.addErc20Deployer(nftAddress, user2, user1)
assert((await nftDatatoken.isErc20Deployer(nftAddress, user1)) === true)
assert((await nftDatatoken.getNftOwner(nftAddress)) === nftOwner)
await nftDatatoken.transferNft(nftAddress, nftOwner, user1, 1)
assert((await nftDatatoken.getNftOwner(nftAddress)) === user1)
// console.log(await nftDatatoken.isErc20Deployer(nftAddress, user1))
// assert((await nftDatatoken.isErc20Deployer(nftAddress, user1)) === false)
})
// Clear permisions
it('#cleanPermissions - should fail to cleanPermissions if NOT NFTOwner', async () => {
try {
await nftDatatoken.cleanPermissions(nftAddress, user1)
} catch (e) {
assert(e.message === 'Caller is not NFT Owner')
}
})
it('#cleanPermissions - should cleanPermissions if NFTOwner', async () => {
await nftDatatoken.addManager(nftAddress, user1, user1)
await nftDatatoken.addErc20Deployer(nftAddress, user1, user2)
assert((await nftDatatoken.isErc20Deployer(nftAddress, user2)) === true)
await nftDatatoken.cleanPermissions(nftAddress, user1)
assert((await nftDatatoken.isErc20Deployer(nftAddress, user2)) === false)
assert((await nftDatatoken.getNftPermissions(nftAddress, nftOwner)).manager === false)
})
})