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

change ercParams to dtParams

This commit is contained in:
Miquel A. Cabot 2022-06-13 12:47:18 +02:00
parent 0726051857
commit 2835304221
7 changed files with 342 additions and 342 deletions

View File

@ -1,91 +1,91 @@
# Ocean.js Code Examples
/// # Ocean.js Code Examples
## Introduction
/// ## Introduction
The following guide runs you through the process of using ocean.js to publish and then consume a dataset. The code examples below are all working and you can learn how to publish by following along.
The process involves creating a Data NFT (which represents the base-IP on-chain) and a datatoken (which will be used to purchase the dataset). This guide provides all the code you need and no prior knowledge is required. It is helpful if you have some experience with javascript but it is not necessary.
/// The following guide runs you through the process of using ocean.js to publish and then consume a dataset. The code examples below are all working and you can learn how to publish by following along.
/// The process involves creating a Data NFT (which represents the base-IP on-chain) and a datatoken (which will be used to purchase the dataset). This guide provides all the code you need and no prior knowledge is required. It is helpful if you have some experience with javascript but it is not necessary.
Selling your data over the blockchain puts you in charge of how it is used and can be a great source of passive income. There are many AI startups that have deep expertise in machine learning but need more data to improve their models. Selling your data via the blockchain gives you a level of security that you would be unable to achieve if you were selling via a centralised marketplace.
/// Selling your data over the blockchain puts you in charge of how it is used and can be a great source of passive income. There are many AI startups that have deep expertise in machine learning but need more data to improve their models. Selling your data via the blockchain gives you a level of security that you would be unable to achieve if you were selling via a centralised marketplace.
In this guide we'll be making use of the Ocean.js library. Ocean Protocol provides you with everything you need to quickly get setup and start selling data over the blockchain.
/// In this guide we'll be making use of the Ocean.js library. Ocean Protocol provides you with everything you need to quickly get setup and start selling data over the blockchain.
These examples take you through a typical user journey that focuses on the experience of a publisher, and a buyer / consumer.
/// These examples take you through a typical user journey that focuses on the experience of a publisher, and a buyer / consumer.
If you have any questions or issues at any point while following along to this article please reach out to us on [discord](https://discord.gg/TnXjkR5).
/// If you have any questions or issues at any point while following along to this article please reach out to us on [discord](https://discord.gg/TnXjkR5).
Here are the steps we will be following throughout the article:
/// Here are the steps we will be following throughout the article:
Here are the steps:
/// Here are the steps:
0. [Prerequisites](#-Prerequisites)
1. [Initialize services](#-initialize-services)
2. [Create a new node.js project](#-create-a-new-node.js-project)
3. [Install dependencies](#-install-dependencies)
4. [Initialize accounts and deploy contracts](#-initialize-accounts-and-deploy-contracts)
5. [Import dependencies and add variables and constants](#-import-dependencies-and-add-variables-and-constants)
6. [Publish Data NFT and a Datatoken with a liquidity pool](#-Publish-data-nft-and-a-datatoken-with-a-liquidity-pool)
7. [Publish Data NFT and a Datatoken with a fixed rate exchange](#-publish-data-nft-and-a-datatoken-with-a-fixed-rate-exchange)
8. [Publish Data NFT and a Datatoken with a dispenser](#-publish-data-nft-and-a-datatoken-with-a-dispenser)
/// 0. [Prerequisites](#-Prerequisites)
/// 1. [Initialize services](#-initialize-services)
/// 2. [Create a new node.js project](#-create-a-new-node.js-project)
/// 3. [Install dependencies](#-install-dependencies)
/// 4. [Initialize accounts and deploy contracts](#-initialize-accounts-and-deploy-contracts)
/// 5. [Import dependencies and add variables and constants](#-import-dependencies-and-add-variables-and-constants)
/// 6. [Publish Data NFT and a Datatoken with a liquidity pool](#-Publish-data-nft-and-a-datatoken-with-a-liquidity-pool)
/// 7. [Publish Data NFT and a Datatoken with a fixed rate exchange](#-publish-data-nft-and-a-datatoken-with-a-fixed-rate-exchange)
/// 8. [Publish Data NFT and a Datatoken with a dispenser](#-publish-data-nft-and-a-datatoken-with-a-dispenser)
## 0. Prerequisites
Before we start it is important that you have all of the necessary prerequisites installed on your computer.
- **A Unix based operating system (Linux or Mac)**. If you are a Windows user you can try to run linux inside a virtual machine but this is outside of the scope of this article.
- **Git**. Instructions for installing Git can be found here: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
- **Node.js** can be downloaded from here: https://nodejs.org/en/download/
- **Docker** can be installed from here: https://docs.docker.com/get-docker/. Please note that Docker must run as a non-root user, you can set this up by following these instructions: https://docs.docker.com/engine/install/linux-postinstall/
/// ## 0. Prerequisites
/// Before we start it is important that you have all of the necessary prerequisites installed on your computer.
/// - **A Unix based operating system (Linux or Mac)**. If you are a Windows user you can try to run linux inside a virtual machine but this is outside of the scope of this article.
/// - **Git**. Instructions for installing Git can be found here: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
/// - **Node.js** can be downloaded from here: https://nodejs.org/en/download/
/// - **Docker** can be installed from here: https://docs.docker.com/get-docker/. Please note that Docker must run as a non-root user, you can set this up by following these instructions: https://docs.docker.com/engine/install/linux-postinstall/
## 1. Initialize services
/// ## 1. Initialize services
Ocean.js uses off-chain services for metadata (Aquarius) and consuming datasets (Provider).
/// Ocean.js uses off-chain services for metadata (Aquarius) and consuming datasets (Provider).
We start by initializing the services. To do this, we clone the Barge repository and run it. This will run the current default versions of [Aquarius](https://github.com/oceanprotocol/aquarius), [Provider](https://github.com/oceanprotocol/provider), and [Ganache](https://github.com/trufflesuite/ganache) with [our contracts](https://github.com/oceanprotocol/contracts) deployed to it.
/// We start by initializing the services. To do this, we clone the Barge repository and run it. This will run the current default versions of [Aquarius](https://github.com/oceanprotocol/aquarius), [Provider](https://github.com/oceanprotocol/provider), and [Ganache](https://github.com/trufflesuite/ganache) with [our contracts](https://github.com/oceanprotocol/contracts) deployed to it.
```bash
git clone https://github.com/oceanprotocol/barge.git
cd barge/
./start_ocean.sh --with-provider2 --no-dashboard
```
/// ```bash
/// git clone https://github.com/oceanprotocol/barge.git
/// cd barge/
/// ./start_ocean.sh --with-provider2 --no-dashboard
/// ```
## 2. Create a new node.js project
/// ## 2. Create a new node.js project
Start by creating a new Node.js project. Open a new terminal and enter the following commands:
/// Start by creating a new Node.js project. Open a new terminal and enter the following commands:
```bash
mkdir marketplace-quickstart
cd marketplace-quickstart
npm init
# Answer the questions in the command line prompt
cat > marketplace.js
# On linux press CTRL + D to save
```
/// ```bash
/// mkdir marketplace-quickstart
/// cd marketplace-quickstart
/// npm init
/// # Answer the questions in the command line prompt
/// cat > marketplace.js
/// # On linux press CTRL + D to save
/// ```
## 3. Install dependancies
/// ## 3. Install dependancies
Open the package.json file in a text editor and update the dependancies to include the following:
/// Open the package.json file in a text editor and update the dependancies to include the following:
```JSON
"dependencies": {
"@oceanprotocol/contracts": "1.0.0-alpha.28",
"@oceanprotocol/lib": "1.0.0-next.37",
"crypto-js": "^4.1.1",
"web3": "^1.7.3"
}
```
/// ```JSON
/// "dependencies": {
/// "@oceanprotocol/contracts": "1.0.0-alpha.28",
/// "@oceanprotocol/lib": "1.0.0-next.37",
/// "crypto-js": "^4.1.1",
/// "web3": "^1.7.3"
/// }
/// ```
Now in your terminal run the following command:
/// Now in your terminal run the following command:
```bash
npm install
```
/// ```bash
/// npm install
/// ```
## 4. Import dependencies and add variables and constants
/// ## 4. Import dependencies and add variables and constants
Now open the `marketplace.js` file in your text editor.
/// Now open the `marketplace.js` file in your text editor.
Start by importing all of the necessary dependencies
```Typescript
/// Start by importing all of the necessary dependencies
/// ```Typescript
import { assert } from 'chai'
import { SHA256 } from 'crypto-js'
import {
AmountsOutMaxFee,
@ -113,15 +113,15 @@ import {
ZERO_ADDRESS
} from '../../src'
import { getAddresses, getTestConfig, web3 } from '../config'
```
/// ```
<!--
describe('Marketplace flow tests
-->
/// <!--
describe('Marketplace flow tests', async () => {
/// -->
Now we define the variables which we will need later
/// Now we define the variables which we will need later
```Typescript
/// ```Typescript
let config: Config
let aquarius: Aquarius
let providerUrl: any
@ -139,20 +139,20 @@ Now we define the variables which we will need later
let dispenserNftAddress: string
let dispenserDatatokenAddress: string
let dispenserAddress: string
```
/// ```
We also define some constants that we will use:
```Typescript
/// We also define some constants that we will use:
/// ```Typescript
const POOL_NFT_NAME = 'Datatoken 1'
const POOL_NFT_SYMBOL = 'DT1'
const FRE_NFT_NAME = 'Datatoken 2'
const FRE_NFT_SYMBOL = 'DT2'
const DISP_NFT_NAME = 'Datatoken 3'
const DISP_NFT_SYMBOL = 'DT3'
```
/// ```
We will need a file to publish, so here we define the file that we intend to publish.
```Typescript
/// We will need a file to publish, so here we define the file that we intend to publish.
/// ```Typescript
const ASSET_URL = [
{
type: 'url',
@ -160,10 +160,10 @@ We also define some constants that we will use:
method: 'GET'
}
]
```
/// ```
Next, we define the metadata that will describe our data asset. This is what we call the DDO
```Typescript
/// Next, we define the metadata that will describe our data asset. This is what we call the DDO
/// ```Typescript
const DDO = {
'@context': ['https://w3id.org/did/v1'],
id: '',
@ -190,57 +190,57 @@ Next, we define the metadata that will describe our data asset. This is what we
}
]
}
```
We load the configuration:
```Typescript
/// ```
/// We load the configuration:
/// ```Typescript
before(async () => {
config = await getTestConfig(web3)
aquarius = new Aquarius(config.metadataCacheUri)
providerUrl = config.providerUri
```
As we go along it's a good idea to console log the values so that you check they are right
```Typescript
/// ```
/// As we go along it's a good idea to console log the values so that you check they are right
/// ```Typescript
console.log(`Aquarius URL: ${config.metadataCacheUri}`)
console.log(`Provider URL: ${providerUrl}`)
}) ///
/// ```
```
## 5. Initialize accounts and deploy contracts
### 5.1 Initialize accounts
```Typescript
/// ## 5. Initialize accounts and deploy contracts
it('5.1 Initialize accounts', async () => {
/// ```Typescript
const accounts = await web3.eth.getAccounts()
publisherAccount = accounts[0]
consumerAccount = accounts[1]
stakerAccount = accounts[2]
```
Again, lets console log the values so that we can check that they have been saved properly
```Typescript
/// ```
/// Again, lets console log the values so that we can check that they have been saved properly
/// ```Typescript
console.log(`Publisher account address: ${publisherAccount}`)
console.log(`Consumer account address: ${consumerAccount}`)
console.log(`Staker account address: ${stakerAccount}`)
}) ///
/// ```
```
### 5.2 Next, lets get the address of the deployed contracts
```Typescript
it('5.2 Next, lets get the address of the deployed contracts', async () => {
/// ```Typescript
addresses = getAddresses()
}) ///
/// ```
```
### 5.3 We send some OCEAN to consumer and staker accounts
```Typescript
it('5.3 We send some OCEAN to consumer and staker accounts', async () => {
/// ```Typescript
transfer(web3, publisherAccount, addresses.Ocean, consumerAccount, '100')
transfer(web3, publisherAccount, addresses.Ocean, stakerAccount, '100')
}) ///
/// ```
```
/// ## 6. Publish Data NFT and a Datatoken with a liquidity pool
## 6. Publish Data NFT and a Datatoken with a liquidity pool
/// For pool creation, the OCEAN token is used as the base token. The base token can be changed into something else, such as USDC, DAI etc., but it will require an extra fee.
For pool creation, the OCEAN token is used as the base token. The base token can be changed into something else, such as USDC, DAI etc., but it will require an extra fee.
### 6.1 Publish a dataset (create NFT + Datatoken) with a liquidity pool
```Typescript
it('6.1 Publish a dataset (create NFT + Datatoken) with a liquidity pool', async () => {
/// ```Typescript
const factory = new NftFactory(addresses.ERC721Factory, web3)
const nftParams: NftCreateData = {
@ -277,9 +277,9 @@ For pool creation, the OCEAN token is used as the base token. The base token can
swapFeeLiquidityProvider: '0.001',
swapFeeMarketRunner: '0.001'
}
```
Before we call the contract we have to call `approve` so that the contract can move our tokens. This is standard when using any ERC20 tokens
```Typescript
/// ```
/// Before we call the contract we have to call `approve` so that the contract can move our tokens. This is standard when using any ERC20 Datatokens
/// ```Typescript
await approve(
web3,
publisherAccount,
@ -288,10 +288,10 @@ Before we call the contract we have to call `approve` so that the contract can m
poolParams.vestingAmount
)
```
Now we can make the contract call
```Typescript
const tx = await factory.createNftErc20WithPool(
/// ```
/// Now we can make the contract call
/// ```Typescript
const tx = await factory.createNftWithDatatokenWithPool(
publisherAccount,
nftParams,
datatokenParams,
@ -301,35 +301,35 @@ Now we can make the contract call
poolNftAddress = tx.events.NFTCreated.returnValues[0]
poolDatatokenAddress = tx.events.TokenCreated.returnValues[0]
poolAddress = tx.events.NewPool.returnValues[0]
```
Now, we did quite a few things there. Let's check that we successfully published a dataset (create NFT + Datatoken) with a liquidity pool
```Typescript
/// ```
/// Now, we did quite a few things there. Let's check that we successfully published a dataset (create NFT + Datatoken) with a liquidity pool
/// ```Typescript
console.log(`Pool NFT address: ${poolNftAddress}`)
console.log(`Pool Datatoken address: ${poolDatatokenAddress}`)
console.log(`Pool address: ${poolAddress}`)
}) ///
/// ```
```
### 6.2 Set metadata in the pool NFT
```Typescript
it('6.2 Set metadata in the pool NFT', async () => {
/// ```Typescript
const nft = new Nft(web3)
```
Now we update the ddo and set the right did
```Typescript
/// ```
/// Now we update the ddo and set the right did
/// ```Typescript
DDO.chainId = await web3.eth.getChainId()
DDO.id =
'did:op:' +
SHA256(web3.utils.toChecksumAddress(poolNftAddress) + DDO.chainId.toString(10))
DDO.nftAddress = poolNftAddress
```
Next we encrypt the file or files using Ocean Provider. The provider is an off chain proxy built specifically for this task
```Typescript
/// ```
/// Next we encrypt the file or files using Ocean Provider. The provider is an off chain proxy built specifically for this task
/// ```Typescript
const encryptedFiles = await ProviderInstance.encrypt(ASSET_URL, providerUrl)
DDO.services[0].files = await encryptedFiles
DDO.services[0].datatokenAddress = poolDatatokenAddress
```
Now let's console log the result to check everything is working
```Typescript
/// ```
/// Now let's console log the result to check everything is working
/// ```Typescript
console.log(`DID: ${DDO.id}`)
const providerResponse = await ProviderInstance.encrypt(DDO, providerUrl)
@ -345,27 +345,27 @@ Now let's console log the result to check everything is working
encryptedDDO,
'0x' + metadataHash
)
}) ///
/// ```
```
### 6.3 User should add liquidity to the pool, receiving LP tokens
```Typescript
it('6.3 User should add liquidity to the pool, receiving LP tokens', async () => {
/// ```Typescript
const pool = new Pool(web3)
```
Before we call the contract we have to call `approve` so that the contract can move our tokens. This is standard when using any ERC20 tokens
```Typescript
/// ```
/// Before we call the contract we have to call `approve` so that the contract can move our tokens. This is standard when using any ERC20 Datatokens
/// ```Typescript
await approve(web3, stakerAccount, addresses.Ocean, poolAddress, '5', true)
```
Now we can make the contract call
```Typescript
/// ```
/// Now we can make the contract call
/// ```Typescript
await pool.joinswapExternAmountIn(stakerAccount, poolAddress, '5', '0.1')
}) ///
/// ```
```
### 6.4 Marketplace displays pool asset for sale
```Typescript
it('6.4 Marketplace displays pool asset for sale', async () => {
/// ```Typescript
const pool = new Pool(web3)
const prices = await pool.getAmountInExactOut(
poolAddress,
@ -374,36 +374,36 @@ Now we can make the contract call
'1',
'0.01'
)
```
Now let's console log the result to check everything is working
```Typescript
/// ```
/// Now let's console log the result to check everything is working
/// ```Typescript
console.log(`Price of 1 ${POOL_NFT_SYMBOL} is ${prices.tokenAmount} OCEAN`)
}) ///
/// ```
```
### 6.5 Consumer buys a pool data asset, and downloads it
```Typescript
it('6.5 Consumer buys a pool data asset, and downloads it', async () => {
/// ```Typescript
const datatoken = new Datatoken(web3)
const consumerETHBalance = await web3.eth.getBalance(consumerAccount)
```
Now let's console log the result to check everything is working
```Typescript
/// ```
/// Now let's console log the result to check everything is working
/// ```Typescript
console.log(`Consumer ETH balance: ${consumerETHBalance}`)
let consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount)
```
Now let's console log consumerOCEANBalance to check everything is working
```Typescript
/// ```
/// Now let's console log consumerOCEANBalance to check everything is working
/// ```Typescript
console.log(`Consumer OCEAN balance before swap: ${consumerOCEANBalance}`)
let consumerDTBalance = await balance(web3, poolDatatokenAddress, consumerAccount)
```
Now let's console log POOL_NFT_SYMBOL and consumerDTBalance to check everything is working
```Typescript
/// ```
/// Now let's console log POOL_NFT_SYMBOL and consumerDTBalance to check everything is working
/// ```Typescript
console.log(`Consumer ${POOL_NFT_SYMBOL} balance before swap: ${consumerDTBalance}`)
```
Before we call the contract we have to call `approve` so that the contract can move our tokens. This is standard when using any ERC20 tokens
```Typescript
/// ```
/// Before we call the contract we have to call `approve` so that the contract can move our tokens. This is standard when using any ERC20 Datatokens
/// ```Typescript
await approve(web3, consumerAccount, addresses.Ocean, poolAddress, '100')
const pool = new Pool(web3)
@ -418,9 +418,9 @@ Before we call the contract we have to call `approve` so that the contract can m
swapMarketFee: '0.1'
}
```
Now we can make the contract call
```Typescript
/// ```
/// Now we can make the contract call
/// ```Typescript
await pool.swapExactAmountOut(
consumerAccount,
poolAddress,
@ -429,22 +429,22 @@ Now we can make the contract call
)
consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount)
```
Now let's console log the Consumer OCEAN balance after swap to check everything is working
```Typescript
/// ```
/// Now let's console log the Consumer OCEAN balance after swap to check everything is working
/// ```Typescript
console.log(`Consumer OCEAN balance after swap: ${consumerOCEANBalance}`)
consumerDTBalance = await balance(web3, poolDatatokenAddress, consumerAccount)
```
Next let's console log the POOL_NFT_SYMBOL and consumerDTBalance
```Typescript
/// ```
/// Next let's console log the POOL_NFT_SYMBOL and consumerDTBalance
/// ```Typescript
console.log(`Consumer ${POOL_NFT_SYMBOL} balance after swap: ${consumerDTBalance}`)
const resolvedDDO = await aquarius.waitForAqua(DDO.id)
assert(resolvedDDO, 'Cannot fetch DDO from Aquarius')
```
The next step is to initialize the provider instance
```Typescript
/// ```
/// The next step is to initialize the provider instance
/// ```Typescript
const initializeData = await ProviderInstance.initialize(
resolvedDDO.id,
resolvedDDO.services[0].id,
@ -464,9 +464,9 @@ The next step is to initialize the provider instance
validUntil: initializeData.providerFee.validUntil
}
```
Now let's make a payment
```Typescript
/// ```
/// Now let's make a payment
/// ```Typescript
const tx = await datatoken.startOrder(
poolDatatokenAddress,
consumerAccount,
@ -475,9 +475,9 @@ Now let's make a payment
providerFees
)
```
Next up, let's get the URL
```Typescript
/// ```
/// Next up, let's get the URL
/// ```Typescript
const downloadURL = await ProviderInstance.getDownloadUrl(
DDO.id,
consumerAccount,
@ -488,18 +488,18 @@ Next up, let's get the URL
web3
)
```
Now let's console log the Download URL to check everything is working
```Typescript
/// ```
/// Now let's console log the Download URL to check everything is working
/// ```Typescript
console.log(`Download URL: ${downloadURL}`)
consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount)
console.log(`Consumer OCEAN balance after order: ${consumerOCEANBalance}`)
consumerDTBalance = await balance(web3, poolDatatokenAddress, consumerAccount)
```
Now let's console log the Consumer balance after order to check everything is working
```Typescript
/// ```
/// Now let's console log the Consumer balance after order to check everything is working
/// ```Typescript
console.log(`Consumer ${POOL_NFT_SYMBOL} balance after order: ${consumerDTBalance}`)
try {
@ -508,13 +508,13 @@ Now let's console log the Consumer balance after order to check everything is wo
} catch (e) {
assert.fail('Download failed')
}
}) ///
/// ```
```
/// ## 7. Publish Data NFT and a Datatoken with a fixed rate exchange
## 7. Publish Data NFT and a Datatoken with a fixed rate exchange
### 7.1 Publish a dataset (create NFT + Datatoken) with a fixed rate exchange
```Typescript
it('7.1 Publish a dataset (create NFT + Datatoken) with a fixed rate exchange', async () => {
/// ```Typescript
const factory = new NftFactory(addresses.ERC721Factory, web3)
const nftParams: NftCreateData = {
@ -549,7 +549,7 @@ Now let's console log the Consumer balance after order to check everything is wo
withMint: false
}
const tx = await factory.createNftErc20WithFixedRate(
const tx = await factory.createNftWithDatatokenWithFixedRate(
publisherAccount,
nftParams,
datatokenParams,
@ -561,39 +561,39 @@ Now let's console log the Consumer balance after order to check everything is wo
freAddress = tx.events.NewFixedRate.returnValues.exchangeContract
freId = tx.events.NewFixedRate.returnValues.exchangeId
```
Now let's console log each of those values to check everything is working
```Typescript
/// ```
/// Now let's console log each of those values to check everything is working
/// ```Typescript
console.log(`Fixed rate exchange NFT address: ${freNftAddress}`)
console.log(`Fixed rate exchange Datatoken address: ${freDatatokenAddress}`)
console.log(`Fixed rate exchange address: ${freAddress}`)
console.log(`Fixed rate exchange Id: ${freId}`)
}) ///
/// ```
```
### 7.2 Set metadata in the fixed rate exchange NFT
```Typescript
it('7.2 Set metadata in the fixed rate exchange NFT', async () => {
/// ```Typescript
const nft = new Nft(web3)
```
Now we are going to update the ddo and set the did
```Typescript
/// ```
/// Now we are going to update the ddo and set the did
/// ```Typescript
DDO.chainId = await web3.eth.getChainId()
DDO.id =
'did:op:' +
SHA256(web3.utils.toChecksumAddress(freNftAddress) + DDO.chainId.toString(10))
DDO.nftAddress = freNftAddress
```
Next, let's encrypt the file(s) using provider
```Typescript
/// ```
/// Next, let's encrypt the file(s) using provider
/// ```Typescript
const encryptedFiles = await ProviderInstance.encrypt(ASSET_URL, providerUrl)
DDO.services[0].files = await encryptedFiles
DDO.services[0].datatokenAddress = freDatatokenAddress
```
Now let's console log the DID to check everything is working
```Typescript
/// ```
/// Now let's console log the DID to check everything is working
/// ```Typescript
console.log(`DID: ${DDO.id}`)
const providerResponse = await ProviderInstance.encrypt(DDO, providerUrl)
@ -610,23 +610,23 @@ Now let's console log the DID to check everything is working
'0x' + metadataHash
)
})
```
/// ```
### 7.3 Marketplace displays fixed rate asset for sale
```Typescript
it('7.3 Marketplace displays fixed rate asset for sale', async () => {
/// ```Typescript
const fixedRate = new FixedRateExchange(freAddress, web3)
const oceanAmount = await (
await fixedRate.calcBaseInGivenOutDT(freId, '1')
).baseTokenAmount
```
Now that the market has fetched those values it can display the asset on the front end. In our case we will just console log the results:
```Typescript
/// ```
/// Now that the market has fetched those values it can display the asset on the front end. In our case we will just console log the results:
/// ```Typescript
console.log(`Price of 1 ${FRE_NFT_SYMBOL} is ${oceanAmount} OCEAN`)
}) ///
/// ```
```
### 7.4 Consumer buys a fixed rate asset data asset, and downloads it
```Typescript
it('7.4 Consumer buys a fixed rate asset data asset, and downloads it', async () => {
/// ```Typescript
const datatoken = new Datatoken(web3)
const DATATOKEN_AMOUNT = '10000'
@ -634,18 +634,18 @@ Now that the market has fetched those values it can display the asset on the fro
const consumerETHBalance = await web3.eth.getBalance(consumerAccount)
```
Let's do a quick check of the consumer ETH balance before the swap
```Typescript
/// ```
/// Let's do a quick check of the consumer ETH balance before the swap
/// ```Typescript
console.log(`Consumer ETH balance: ${consumerETHBalance}`)
let consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount)
console.log(`Consumer OCEAN balance before swap: ${consumerOCEANBalance}`)
let consumerDTBalance = await balance(web3, freDatatokenAddress, consumerAccount)
console.log(`Consumer ${FRE_NFT_SYMBOL} balance before swap: ${consumerDTBalance}`)
```
Before we call the contract we have to call `approve` so that the contract can move our tokens. This is standard when using any ERC20 tokens
```Typescript
/// ```
/// Before we call the contract we have to call `approve` so that the contract can move our tokens. This is standard when using any ERC20 Datatokens
/// ```Typescript
await approve(web3, consumerAccount, addresses.Ocean, freAddress, '100')
await approve(
web3,
@ -656,9 +656,9 @@ Before we call the contract we have to call `approve` so that the contract can m
)
const fixedRate = new FixedRateExchange(freAddress, web3)
```
Now we can make the contract call
```Typescript
/// ```
/// Now we can make the contract call
/// ```Typescript
await fixedRate.buyDT(consumerAccount, freId, '1', '2')
consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount)
@ -669,9 +669,9 @@ Now we can make the contract call
const resolvedDDO = await aquarius.waitForAqua(DDO.id)
assert(resolvedDDO, 'Cannot fetch DDO from Aquarius')
```
Next, we need to initialize the provider
```Typescript
/// ```
/// Next, we need to initialize the provider
/// ```Typescript
const initializeData = await ProviderInstance.initialize(
resolvedDDO.id,
resolvedDDO.services[0].id,
@ -691,9 +691,9 @@ Next, we need to initialize the provider
validUntil: initializeData.providerFee.validUntil
}
```
Lets now make the payment
```Typescript
/// ```
/// Lets now make the payment
/// ```Typescript
const tx = await datatoken.startOrder(
freDatatokenAddress,
consumerAccount,
@ -701,9 +701,9 @@ Lets now make the payment
0,
providerFees
)
```
Now we can get the url
```Typescript
/// ```
/// Now we can get the url
/// ```Typescript
const downloadURL = await ProviderInstance.getDownloadUrl(
DDO.id,
consumerAccount,
@ -714,9 +714,9 @@ Now we can get the url
web3
)
```
Lets check that the download URL was successfully received
```Typescript
/// ```
/// Lets check that the download URL was successfully received
/// ```Typescript
console.log(`Download URL: ${downloadURL}`)
consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount)
@ -730,13 +730,13 @@ Lets check that the download URL was successfully received
} catch (e) {
assert.fail('Download failed')
}
}) ///
/// ```
```
/// ## 8. Publish Data NFT and a Datatoken with a dispenser
## 8. Publish Data NFT and a Datatoken with a dispenser
### 8.1 Publish a dataset (create NFT + Datatoken) with a dispenser
```Typescript
it('8.1 Publish a dataset (create NFT + Datatoken) with a dispenser', async () => {
/// ```Typescript
const factory = new NftFactory(addresses.ERC721Factory, web3)
const nftParams: NftCreateData = {
@ -766,7 +766,7 @@ Lets check that the download URL was successfully received
allowedSwapper: ZERO_ADDRESS
}
const tx = await factory.createNftErc20WithDispenser(
const tx = await factory.createNftWithDatatokenWithDispenser(
publisherAccount,
nftParams,
datatokenParams,
@ -776,31 +776,31 @@ Lets check that the download URL was successfully received
dispenserNftAddress = tx.events.NFTCreated.returnValues[0]
dispenserDatatokenAddress = tx.events.TokenCreated.returnValues[0]
dispenserAddress = tx.events.DispenserCreated.returnValues[0]
```
Lets check that we managed to received all of those values without any problems
```Typescript
/// ```
/// Lets check that we managed to received all of those values without any problems
/// ```Typescript
console.log(`Dispenser NFT address: ${dispenserNftAddress}`)
console.log(`Dispenser Datatoken address: ${dispenserDatatokenAddress}`)
console.log(`Dispenser address: ${dispenserAddress}`)
}) ///
/// ```
```
### 8.2 Set metadata in the dispenser NFT
```Typescript
it('8.2 Set metadata in the dispenser NFT', async () => {
/// ```Typescript
const nft = new Nft(web3)
```
Lets start by updating the ddo and setting the did
```Typescript
/// ```
/// Lets start by updating the ddo and setting the did
/// ```Typescript
DDO.chainId = await web3.eth.getChainId()
DDO.id =
'did:op:' +
SHA256(web3.utils.toChecksumAddress(dispenserNftAddress) + DDO.chainId.toString(10))
DDO.nftAddress = dispenserNftAddress
```
Now we need to encrypt file(s) using provider
```Typescript
/// ```
/// Now we need to encrypt file(s) using provider
/// ```Typescript
const encryptedFiles = await ProviderInstance.encrypt(ASSET_URL, providerUrl)
DDO.services[0].files = await encryptedFiles
DDO.services[0].datatokenAddress = dispenserDatatokenAddress
@ -820,11 +820,11 @@ Now we need to encrypt file(s) using provider
encryptedDDO,
'0x' + metadataHash
)
}) ///
/// ```
```
### 8.3 Consumer gets a dispenser data asset, and downloads it
```Typescript
it('8.3 Consumer gets a dispenser data asset, and downloads it', async () => {
/// ```Typescript
const datatoken = new Datatoken(web3)
const dispenser = new Dispenser(addresses.Dispenser, web3)
@ -851,9 +851,9 @@ Now we need to encrypt file(s) using provider
const resolvedDDO = await aquarius.waitForAqua(DDO.id)
assert(resolvedDDO, 'Cannot fetch DDO from Aquarius')
```
At this point we need to encrypt file(s) using provider
```Typescript
/// ```
/// At this point we need to encrypt file(s) using provider
/// ```Typescript
const initializeData = await ProviderInstance.initialize(
resolvedDDO.id,
resolvedDDO.services[0].id,
@ -872,9 +872,9 @@ At this point we need to encrypt file(s) using provider
providerData: initializeData.providerFee.providerData,
validUntil: initializeData.providerFee.validUntil
}
```
Now we need to make the payment
```Typescript
/// ```
/// Now we need to make the payment
/// ```Typescript
const tx = await datatoken.startOrder(
dispenserDatatokenAddress,
consumerAccount,
@ -882,9 +882,9 @@ Now we need to make the payment
0,
providerFees
)
```
Now we can get the download URL
```Typescript
/// ```
/// Now we can get the download URL
/// ```Typescript
const downloadURL = await ProviderInstance.getDownloadUrl(
DDO.id,
consumerAccount,
@ -894,9 +894,9 @@ Now we can get the download URL
providerUrl,
web3
)
```
Let's check we received the download URL ok
```Typescript
/// ```
/// Let's check we received the download URL ok
/// ```Typescript
console.log(`Download URL: ${downloadURL}`)
consumerDTBalance = await balance(web3, dispenserDatatokenAddress, consumerAccount)
@ -908,11 +908,11 @@ Let's check we received the download URL ok
} catch (e) {
assert.fail('Download failed')
}
}) ///
/// ```
}) ///
```
## Editing this file
Please note that CodeExamples.md is an autogenerated file, you should not edit it directly.
Updates should be done in `test/integration/CodeExamples.test.ts` and all markdown should have three forward slashes before it
e.g. `/// # H1 Title`
/// ## Editing this file
/// Please note that CodeExamples.md is an autogenerated file, you should not edit it directly.
/// Updates should be done in `test/integration/CodeExamples.test.ts` and all markdown should have three forward slashes before it
/// e.g. `/// # H1 Title`

View File

@ -573,9 +573,9 @@ export class NftFactory extends SmartContractWithAddress {
public async estGasCreateNftWithDatatoken(
address: string,
nftCreateData: NftCreateData,
ercParams: DatatokenCreateParams
dtParams: DatatokenCreateParams
): Promise<any> {
const ercCreateData = this.getErcCreationParams(ercParams)
const ercCreateData = this.getErcCreationParams(dtParams)
return estimateGas(
address,
this.contract.methods.createNftWithErc20,
@ -596,9 +596,9 @@ export class NftFactory extends SmartContractWithAddress {
public async createNftWithDatatoken(
address: string,
nftCreateData: NftCreateData,
ercParams: DatatokenCreateParams
dtParams: DatatokenCreateParams
): Promise<TransactionReceipt> {
const ercCreateData = this.getErcCreationParams(ercParams)
const ercCreateData = this.getErcCreationParams(dtParams)
const estGas = await estimateGas(
address,
@ -623,17 +623,17 @@ export class NftFactory extends SmartContractWithAddress {
* Estimate gas cost for createNftWithDatatokenWithPool method
* @param address Caller address
* @param nftCreateData input data for NFT Creation
* @param ercParams input data for Datatoken Creation
* @param dtParams input data for Datatoken Creation
* @param poolParams input data for Pool Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async estGasCreateNftWithDatatokenWithPool(
address: string,
nftCreateData: NftCreateData,
ercParams: DatatokenCreateParams,
dtParams: DatatokenCreateParams,
poolParams: PoolCreationParams
): Promise<any> {
const ercCreateData = this.getErcCreationParams(ercParams)
const ercCreateData = this.getErcCreationParams(dtParams)
const poolData = await this.getPoolCreationParams(poolParams)
return estimateGas(
address,
@ -650,17 +650,17 @@ export class NftFactory extends SmartContractWithAddress {
* 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 Datatoken Creation
* @param dtParams input data for Datatoken Creation
* @param poolParams input data for Pool Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async createNftWithDatatokenWithPool(
address: string,
nftCreateData: NftCreateData,
ercParams: DatatokenCreateParams,
dtParams: DatatokenCreateParams,
poolParams: PoolCreationParams
): Promise<TransactionReceipt> {
const ercCreateData = this.getErcCreationParams(ercParams)
const ercCreateData = this.getErcCreationParams(dtParams)
const poolData = await this.getPoolCreationParams(poolParams)
const estGas = await estimateGas(
@ -686,17 +686,17 @@ export class NftFactory extends SmartContractWithAddress {
/** Estimate gas cost for createNftWithDatatokenWithFixedRate method
* @param address Caller address
* @param nftCreateData input data for NFT Creation
* @param ercParams input data for Datatoken Creation
* @param dtParams input data for Datatoken Creation
* @param freParams input data for FixedRate Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async estGasCreateNftWithDatatokenWithFixedRate(
address: string,
nftCreateData: NftCreateData,
ercParams: DatatokenCreateParams,
dtParams: DatatokenCreateParams,
freParams: FreCreationParams
): Promise<any> {
const ercCreateData = this.getErcCreationParams(ercParams)
const ercCreateData = this.getErcCreationParams(dtParams)
const fixedData = await this.getFreCreationParams(freParams)
return estimateGas(
address,
@ -713,17 +713,17 @@ export class NftFactory extends SmartContractWithAddress {
* 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 Datatoken Creation
* @param dtParams input data for Datatoken Creation
* @param freParams input data for FixedRate Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async createNftWithDatatokenWithFixedRate(
address: string,
nftCreateData: NftCreateData,
ercParams: DatatokenCreateParams,
dtParams: DatatokenCreateParams,
freParams: FreCreationParams
): Promise<TransactionReceipt> {
const ercCreateData = this.getErcCreationParams(ercParams)
const ercCreateData = this.getErcCreationParams(dtParams)
const fixedData = this.getFreCreationParams(freParams)
const estGas = await estimateGas(
@ -749,17 +749,17 @@ export class NftFactory extends SmartContractWithAddress {
/** Estimate gas cost for estGasCreateNftWithDatatokenWithDispenser method
* @param address Caller address
* @param nftCreateData input data for NFT Creation
* @param ercParams input data for Datatoken Creation
* @param dtParams input data for Datatoken Creation
* @param dispenserParams input data for Dispenser Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async estGasCreateNftWithDatatokenWithDispenser(
address: string,
nftCreateData: NftCreateData,
ercParams: DatatokenCreateParams,
dtParams: DatatokenCreateParams,
dispenserParams: DispenserCreationParams
): Promise<any> {
const ercCreateData = this.getErcCreationParams(ercParams)
const ercCreateData = this.getErcCreationParams(dtParams)
return estimateGas(
address,
this.contract.methods.createNftWithErc20WithDispenser,
@ -775,17 +775,17 @@ export class NftFactory extends SmartContractWithAddress {
* Use this carefully, because if Dispenser 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 Datatoken Creation
* @param dtParams input data for Datatoken Creation
* @param dispenserParams input data for Dispenser Creation
* @return {Promise<TransactionReceipt>} transaction receipt
*/
public async createNftWithDatatokenWithDispenser(
address: string,
nftCreateData: NftCreateData,
ercParams: DatatokenCreateParams,
dtParams: DatatokenCreateParams,
dispenserParams: DispenserCreationParams
): Promise<TransactionReceipt> {
const ercCreateData = this.getErcCreationParams(ercParams)
const ercCreateData = this.getErcCreationParams(dtParams)
dispenserParams.maxBalance = Web3.utils.toWei(dispenserParams.maxBalance)
dispenserParams.maxTokens = Web3.utils.toWei(dispenserParams.maxTokens)
@ -810,22 +810,22 @@ export class NftFactory extends SmartContractWithAddress {
return trxReceipt
}
private getErcCreationParams(ercParams: DatatokenCreateParams): any {
private getErcCreationParams(dtParams: DatatokenCreateParams): any {
let name: string, symbol: string
// Generate name & symbol if not present
if (!ercParams.name || !ercParams.symbol) {
if (!dtParams.name || !dtParams.symbol) {
;({ name, symbol } = generateDtName())
}
return {
templateIndex: ercParams.templateIndex,
strings: [ercParams.name || name, ercParams.symbol || symbol],
templateIndex: dtParams.templateIndex,
strings: [dtParams.name || name, dtParams.symbol || symbol],
addresses: [
ercParams.minter,
ercParams.paymentCollector,
ercParams.mpFeeAddress,
ercParams.feeToken
dtParams.minter,
dtParams.paymentCollector,
dtParams.mpFeeAddress,
dtParams.feeToken
],
uints: [Web3.utils.toWei(ercParams.cap), Web3.utils.toWei(ercParams.feeAmount)],
uints: [Web3.utils.toWei(dtParams.cap), Web3.utils.toWei(dtParams.feeAmount)],
bytess: []
}
}

View File

@ -43,7 +43,7 @@ describe('Nft Factory test', () => {
owner: factoryOwner
}
const ercParams: DatatokenCreateParams = {
const dtParams: DatatokenCreateParams = {
templateIndex: 1,
minter: nftOwner,
paymentCollector: user2,
@ -63,9 +63,9 @@ describe('Nft Factory test', () => {
user2 = accounts[3]
nftData.owner = factoryOwner
ercParams.minter = nftOwner
ercParams.paymentCollector = user2
ercParams.mpFeeAddress = user1
dtParams.minter = nftOwner
dtParams.paymentCollector = user2
dtParams.mpFeeAddress = user1
})
it('should deploy contracts', async () => {
@ -108,7 +108,7 @@ describe('Nft Factory test', () => {
const txReceipt = await nftFactory.createNftWithDatatoken(
nftOwner,
nftData,
ercParams
dtParams
)
// events have been emitted
@ -124,7 +124,7 @@ describe('Nft Factory test', () => {
const currentNFTCount = await nftFactory.getCurrentNFTCount()
const currentTokenCount = await nftFactory.getCurrentTokenCount()
await nftFactory.createNftWithDatatoken(nftOwner, nftData, ercParams)
await nftFactory.createNftWithDatatoken(nftOwner, nftData, dtParams)
expect((await nftFactory.getCurrentNFTCount()) === currentNFTCount + 1)
expect((await nftFactory.getCurrentTokenCount()) === currentTokenCount + 1)
@ -167,7 +167,7 @@ describe('Nft Factory test', () => {
const txReceipt = await nftFactory.createNftWithDatatokenWithPool(
nftOwner,
nftData,
ercParams,
dtParams,
poolParams
)
@ -195,7 +195,7 @@ describe('Nft Factory test', () => {
const txReceipt = await nftFactory.createNftWithDatatokenWithFixedRate(
nftOwner,
nftData,
ercParams,
dtParams,
freParams
)
@ -221,7 +221,7 @@ describe('Nft Factory test', () => {
const txReceipt = await nftFactory.createNftWithDatatokenWithDispenser(
nftOwner,
nftData,
ercParams,
dtParams,
dispenserParams
)

View File

@ -30,7 +30,7 @@ describe('Pool unit test', () => {
let pool: Pool
let poolAddress: string
let datatoken: string
let ercParams: DatatokenCreateParams
let dtParams: DatatokenCreateParams
const nftData: NftCreateData = {
name: '72120Bundle',
@ -49,7 +49,7 @@ describe('Pool unit test', () => {
nftData.owner = factoryOwner
ercParams = {
dtParams = {
templateIndex: 1,
minter: factoryOwner,
paymentCollector: user2,
@ -133,7 +133,7 @@ describe('Pool unit test', () => {
const txReceipt = await nftFactory.createNftWithDatatokenWithPool(
factoryOwner,
nftData,
ercParams,
dtParams,
poolParams
)
@ -520,7 +520,7 @@ describe('Pool unit test', () => {
const txReceipt = await nftFactory.createNftWithDatatokenWithPool(
factoryOwner,
nftData,
ercParams,
dtParams,
poolParams
)

View File

@ -30,7 +30,7 @@ describe('Dispenser flow', () => {
owner: null
}
const ercParams: DatatokenCreateParams = {
const dtParams: DatatokenCreateParams = {
templateIndex: 1,
minter: null,
paymentCollector: null,
@ -49,9 +49,9 @@ describe('Dispenser flow', () => {
user2 = accounts[4]
nftData.owner = factoryOwner
ercParams.minter = factoryOwner
ercParams.paymentCollector = user2
ercParams.mpFeeAddress = user1
dtParams.minter = factoryOwner
dtParams.paymentCollector = user2
dtParams.mpFeeAddress = user1
})
it('should deploy contracts', async () => {
@ -69,7 +69,7 @@ describe('Dispenser flow', () => {
const txReceipt = await nftFactory.createNftWithDatatoken(
factoryOwner,
nftData,
ercParams
dtParams
)
expect(txReceipt.events.NFTCreated.event === 'NFTCreated')

View File

@ -37,7 +37,7 @@ describe('Fixed Rate unit test', () => {
owner: null
}
const ercParams: DatatokenCreateParams = {
const dtParams: DatatokenCreateParams = {
templateIndex: 1,
minter: null,
paymentCollector: null,
@ -57,9 +57,9 @@ describe('Fixed Rate unit test', () => {
exchangeOwner = accounts[0]
nftData.owner = factoryOwner
ercParams.minter = factoryOwner
ercParams.paymentCollector = user2
ercParams.mpFeeAddress = factoryOwner
dtParams.minter = factoryOwner
dtParams.paymentCollector = user2
dtParams.mpFeeAddress = factoryOwner
})
it('should deploy contracts', async () => {
@ -89,7 +89,7 @@ describe('Fixed Rate unit test', () => {
const txReceipt = await nftFactory.createNftWithDatatokenWithFixedRate(
exchangeOwner,
nftData,
ercParams,
dtParams,
freParams
)
@ -398,7 +398,7 @@ describe('Fixed Rate unit test', () => {
const txReceipt = await nftFactory.createNftWithDatatokenWithFixedRate(
exchangeOwner,
nftData,
ercParams,
dtParams,
freParams
)

View File

@ -52,7 +52,7 @@ describe('SideStaking unit test', () => {
owner: null
}
const ercParams: DatatokenCreateParams = {
const dtParams: DatatokenCreateParams = {
templateIndex: 1,
minter: null,
paymentCollector: null,
@ -71,9 +71,9 @@ describe('SideStaking unit test', () => {
user2 = accounts[2]
nftData.owner = factoryOwner
ercParams.minter = factoryOwner
ercParams.paymentCollector = user2
ercParams.mpFeeAddress = factoryOwner
dtParams.minter = factoryOwner
dtParams.paymentCollector = user2
dtParams.mpFeeAddress = factoryOwner
})
it('should deploy contracts', async () => {
@ -156,7 +156,7 @@ describe('SideStaking unit test', () => {
const txReceipt = await nftFactory.createNftWithDatatokenWithPool(
factoryOwner,
nftData,
ercParams,
dtParams,
poolParams
)
@ -378,7 +378,7 @@ describe('SideStaking unit test', () => {
const txReceipt = await nftFactory.createNftWithDatatokenWithPool(
factoryOwner,
nftData,
ercParams,
dtParams,
poolParams
)