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

Combining tests and checking that the data received is correct

This commit is contained in:
Jamie Hewitt 2022-12-22 14:25:01 +00:00
parent 2bb4f751a2
commit 39ac4a4046
2 changed files with 60 additions and 113 deletions

View File

@ -27,9 +27,7 @@ Here are the steps:
7. [Publish Data NFT and a Datatoken with a dispenser](#-publish-data-nft-and-a-datatoken-with-a-dispenser) 7. [Publish Data NFT and a Datatoken with a dispenser](#-publish-data-nft-and-a-datatoken-with-a-dispenser)
## 0. Prerequisites ## 0. Prerequisites
Before we start it is important that you have all of the necessary prerequisites installed on your computer. 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. - **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 - **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/ - **Node.js** can be downloaded from here: https://nodejs.org/en/download/
@ -140,7 +138,6 @@ Now we define the variables which we will need later
``` ```
We also define some constants that we will use: We also define some constants that we will use:
```Typescript ```Typescript
const FRE_NFT_NAME = 'Datatoken 2' const FRE_NFT_NAME = 'Datatoken 2'
const FRE_NFT_SYMBOL = 'DT2' const FRE_NFT_SYMBOL = 'DT2'
@ -148,8 +145,7 @@ We also define some constants that we will use:
const DISP_NFT_SYMBOL = 'DT3' const DISP_NFT_SYMBOL = 'DT3'
``` ```
We will need a file to publish, so here we define the file that we intend to publish. We will need a file to publish, so here we define the file that we intend to publish.
```Typescript ```Typescript
const ASSET_URL: Files = { const ASSET_URL: Files = {
datatokenAddress: '0x0', datatokenAddress: '0x0',
@ -165,7 +161,6 @@ We will need a file to publish, so here we define the file that we intend to pub
``` ```
Next, we define the metadata that will describe our data asset. This is what we call the DDO Next, we define the metadata that will describe our data asset. This is what we call the DDO
```Typescript ```Typescript
const DDO = { const DDO = {
'@context': ['https://w3id.org/did/v1'], '@context': ['https://w3id.org/did/v1'],
@ -196,16 +191,13 @@ Next, we define the metadata that will describe our data asset. This is what we
``` ```
We load the configuration: We load the configuration:
```Typescript ```Typescript
config = await getTestConfig(web3) config = await getTestConfig(web3)
aquarius = new Aquarius(config.metadataCacheUri) aquarius = new Aquarius(config.metadataCacheUri)
providerUrl = config.providerUri providerUrl = config.providerUri
``` ```
As we go along it's a good idea to console log the values so that you check they are right As we go along it's a good idea to console log the values so that you check they are right
```Typescript ```Typescript
console.log(`Aquarius URL: ${config.metadataCacheUri}`) console.log(`Aquarius URL: ${config.metadataCacheUri}`)
console.log(`Provider URL: ${providerUrl}`) console.log(`Provider URL: ${providerUrl}`)
@ -213,25 +205,20 @@ As we go along it's a good idea to console log the values so that you check they
``` ```
## 5. Initialize accounts and deploy contracts ## 5. Initialize accounts and deploy contracts
### 5.1 Next, lets get the address of the deployed contracts
### 5.1 Next, lets get the address of the deployed contracts
```Typescript ```Typescript
addresses = getAddresses() addresses = getAddresses()
``` ```
### 5.2 Initialize accounts ### 5.2 Initialize accounts
```Typescript ```Typescript
const accounts = await web3.eth.getAccounts() const accounts = await web3.eth.getAccounts()
publisherAccount = accounts[0] publisherAccount = accounts[0]
consumerAccount = accounts[1] consumerAccount = accounts[1]
stakerAccount = accounts[2] stakerAccount = accounts[2]
``` ```
Again, lets console log the values so that we can check that they have been saved properly Again, lets console log the values so that we can check that they have been saved properly
```Typescript ```Typescript
console.log(`Publisher account address: ${publisherAccount}`) console.log(`Publisher account address: ${publisherAccount}`)
console.log(`Consumer account address: ${consumerAccount}`) console.log(`Consumer account address: ${consumerAccount}`)
@ -272,15 +259,13 @@ Again, lets console log the values so that we can check that they have been save
``` ```
### 5.2 Next, lets get the address of the deployed contracts ### 5.2 Next, lets get the address of the deployed contracts
```Typescript ```Typescript
addresses = getAddresses() addresses = getAddresses()
``` ```
### 5.3 We send some OCEAN to consumer and staker accounts ### 5.3 We send some OCEAN to consumer and staker accounts
```Typescript ```Typescript
transfer(web3, config, publisherAccount, addresses.Ocean, consumerAccount, '100') transfer(web3, config, publisherAccount, addresses.Ocean, consumerAccount, '100')
transfer(web3, config, publisherAccount, addresses.Ocean, stakerAccount, '100') transfer(web3, config, publisherAccount, addresses.Ocean, stakerAccount, '100')
@ -289,8 +274,7 @@ Again, lets console log the values so that we can check that they have been save
## 6. Publish Data NFT and a Datatoken with a fixed rate exchange ## 6. Publish Data NFT and a Datatoken with a fixed rate exchange
### 6.1 Publish a dataset (create NFT + Datatoken) with a fixed rate exchange ### 6.1 Publish a dataset (create NFT + Datatoken) with a fixed rate exchange
```Typescript ```Typescript
const factory = new NftFactory(addresses.ERC721Factory, web3) const factory = new NftFactory(addresses.ERC721Factory, web3)
@ -339,9 +323,7 @@ Again, lets console log the values so that we can check that they have been save
freId = tx.events.NewFixedRate.returnValues.exchangeId freId = tx.events.NewFixedRate.returnValues.exchangeId
``` ```
Now let's console log each of those values to check everything is working Now let's console log each of those values to check everything is working
```Typescript ```Typescript
console.log(`Fixed rate exchange NFT address: ${freNftAddress}`) console.log(`Fixed rate exchange NFT address: ${freNftAddress}`)
console.log(`Fixed rate exchange Datatoken address: ${freDatatokenAddress}`) console.log(`Fixed rate exchange Datatoken address: ${freDatatokenAddress}`)
@ -350,15 +332,12 @@ Now let's console log each of those values to check everything is working
``` ```
### 6.2 Set metadata in the fixed rate exchange NFT ### 6.2 Set metadata in the fixed rate exchange NFT
```Typescript ```Typescript
const nft = new Nft(web3) const nft = new Nft(web3)
``` ```
Now we are going to update the ddo and set the did Now we are going to update the ddo and set the did
```Typescript ```Typescript
DDO.chainId = await web3.eth.getChainId() DDO.chainId = await web3.eth.getChainId()
DDO.id = DDO.id =
@ -367,9 +346,7 @@ Now we are going to update the ddo and set the did
DDO.nftAddress = freNftAddress DDO.nftAddress = freNftAddress
``` ```
Next, let's encrypt the file(s) using provider Next, let's encrypt the file(s) using provider
```Typescript ```Typescript
ASSET_URL.datatokenAddress = freDatatokenAddress ASSET_URL.datatokenAddress = freDatatokenAddress
ASSET_URL.nftAddress = freNftAddress ASSET_URL.nftAddress = freNftAddress
@ -378,9 +355,7 @@ Next, let's encrypt the file(s) using provider
DDO.services[0].datatokenAddress = freDatatokenAddress DDO.services[0].datatokenAddress = freDatatokenAddress
``` ```
Now let's console log the DID to check everything is working Now let's console log the DID to check everything is working
```Typescript ```Typescript
console.log(`DID: ${DDO.id}`) console.log(`DID: ${DDO.id}`)
@ -400,24 +375,20 @@ Now let's console log the DID to check everything is working
}) })
``` ```
### 6.3 Marketplace displays fixed rate asset for sale ### 6.3 Marketplace displays fixed rate asset for sale
```Typescript ```Typescript
const fixedRate = new FixedRateExchange(freAddress, web3) const fixedRate = new FixedRateExchange(freAddress, web3)
const oceanAmount = await ( const oceanAmount = await (
await fixedRate.calcBaseInGivenDatatokensOut(freId, '1') await fixedRate.calcBaseInGivenDatatokensOut(freId, '1')
).baseTokenAmount ).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: 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 ```Typescript
console.log(`Price of 1 ${FRE_NFT_SYMBOL} is ${oceanAmount} OCEAN`) console.log(`Price of 1 ${FRE_NFT_SYMBOL} is ${oceanAmount} OCEAN`)
``` ```
### 6.4 Consumer buys a fixed rate asset data asset, and downloads it ### 6.4 Consumer buys a fixed rate asset data asset, and downloads it
```Typescript ```Typescript
const datatoken = new Datatoken(web3) const datatoken = new Datatoken(web3)
const DATATOKEN_AMOUNT = '10000' const DATATOKEN_AMOUNT = '10000'
@ -427,9 +398,7 @@ Now that the market has fetched those values it can display the asset on the fro
const consumerETHBalance = await web3.eth.getBalance(consumerAccount) const consumerETHBalance = await web3.eth.getBalance(consumerAccount)
``` ```
Let's do a quick check of the consumer ETH balance before the swap Let's do a quick check of the consumer ETH balance before the swap
```Typescript ```Typescript
console.log(`Consumer ETH balance: ${consumerETHBalance}`) console.log(`Consumer ETH balance: ${consumerETHBalance}`)
let consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount) let consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount)
@ -438,9 +407,7 @@ Let's do a quick check of the consumer ETH balance before the swap
console.log(`Consumer ${FRE_NFT_SYMBOL} balance before swap: ${consumerDTBalance}`) 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 Datatokens 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 ```Typescript
await approve(web3, config, consumerAccount, addresses.Ocean, freAddress, '100') await approve(web3, config, consumerAccount, addresses.Ocean, freAddress, '100')
await approve( await approve(
@ -454,9 +421,7 @@ Before we call the contract we have to call `approve` so that the contract can m
const fixedRate = new FixedRateExchange(freAddress, web3) const fixedRate = new FixedRateExchange(freAddress, web3)
``` ```
Now we can make the contract call Now we can make the contract call
```Typescript ```Typescript
await fixedRate.buyDatatokens(consumerAccount, freId, '1', '2') await fixedRate.buyDatatokens(consumerAccount, freId, '1', '2')
@ -469,9 +434,7 @@ Now we can make the contract call
assert(resolvedDDO, 'Cannot fetch DDO from Aquarius') assert(resolvedDDO, 'Cannot fetch DDO from Aquarius')
``` ```
Next, we need to initialize the provider Next, we need to initialize the provider
```Typescript ```Typescript
const initializeData = await ProviderInstance.initialize( const initializeData = await ProviderInstance.initialize(
resolvedDDO.id, resolvedDDO.id,
@ -493,9 +456,7 @@ Next, we need to initialize the provider
} }
``` ```
Lets now make the payment Lets now make the payment
```Typescript ```Typescript
const tx = await datatoken.startOrder( const tx = await datatoken.startOrder(
freDatatokenAddress, freDatatokenAddress,
@ -505,9 +466,7 @@ Lets now make the payment
providerFees providerFees
) )
``` ```
Now we can get the url Now we can get the url
```Typescript ```Typescript
const downloadURL = await ProviderInstance.getDownloadUrl( const downloadURL = await ProviderInstance.getDownloadUrl(
DDO.id, DDO.id,
@ -520,9 +479,7 @@ Now we can get the url
) )
``` ```
Lets check that the download URL was successfully received Lets check that the download URL was successfully received
```Typescript ```Typescript
console.log(`Download URL: ${downloadURL}`) console.log(`Download URL: ${downloadURL}`)
@ -542,8 +499,7 @@ Lets check that the download URL was successfully received
## 7. Publish Data NFT and a Datatoken with a dispenser ## 7. Publish Data NFT and a Datatoken with a dispenser
### 7.1 Publish a dataset (create NFT + Datatoken) with a dispenser ### 7.1 Publish a dataset (create NFT + Datatoken) with a dispenser
```Typescript ```Typescript
const factory = new NftFactory(addresses.ERC721Factory, web3) const factory = new NftFactory(addresses.ERC721Factory, web3)
@ -585,9 +541,7 @@ Lets check that the download URL was successfully received
dispenserDatatokenAddress = tx.events.TokenCreated.returnValues[0] dispenserDatatokenAddress = tx.events.TokenCreated.returnValues[0]
dispenserAddress = tx.events.DispenserCreated.returnValues[0] dispenserAddress = tx.events.DispenserCreated.returnValues[0]
``` ```
Lets check that we managed to received all of those values without any problems Lets check that we managed to received all of those values without any problems
```Typescript ```Typescript
console.log(`Dispenser NFT address: ${dispenserNftAddress}`) console.log(`Dispenser NFT address: ${dispenserNftAddress}`)
console.log(`Dispenser Datatoken address: ${dispenserDatatokenAddress}`) console.log(`Dispenser Datatoken address: ${dispenserDatatokenAddress}`)
@ -595,15 +549,12 @@ Lets check that we managed to received all of those values without any problems
``` ```
### 7.2 Set metadata in the dispenser NFT ### 7.2 Set metadata in the dispenser NFT
```Typescript ```Typescript
const nft = new Nft(web3) const nft = new Nft(web3)
``` ```
Lets start by updating the ddo and setting the did Lets start by updating the ddo and setting the did
```Typescript ```Typescript
DDO.chainId = await web3.eth.getChainId() DDO.chainId = await web3.eth.getChainId()
DDO.id = DDO.id =
@ -612,9 +563,7 @@ Lets start by updating the ddo and setting the did
DDO.nftAddress = dispenserNftAddress DDO.nftAddress = dispenserNftAddress
``` ```
Now we need to encrypt file(s) using provider Now we need to encrypt file(s) using provider
```Typescript ```Typescript
ASSET_URL.datatokenAddress = dispenserDatatokenAddress ASSET_URL.datatokenAddress = dispenserDatatokenAddress
ASSET_URL.nftAddress = dispenserNftAddress ASSET_URL.nftAddress = dispenserNftAddress
@ -640,8 +589,7 @@ Now we need to encrypt file(s) using provider
``` ```
### 7.3 Consumer gets a dispenser data asset, and downloads it ### 7.3 Consumer gets a dispenser data asset, and downloads it
```Typescript ```Typescript
const datatoken = new Datatoken(web3) const datatoken = new Datatoken(web3)
const dispenser = new Dispenser(addresses.Dispenser, web3) const dispenser = new Dispenser(addresses.Dispenser, web3)
@ -670,9 +618,7 @@ Now we need to encrypt file(s) using provider
const resolvedDDO = await aquarius.waitForAqua(DDO.id) const resolvedDDO = await aquarius.waitForAqua(DDO.id)
assert(resolvedDDO, 'Cannot fetch DDO from Aquarius') assert(resolvedDDO, 'Cannot fetch DDO from Aquarius')
``` ```
At this point we need to encrypt file(s) using provider At this point we need to encrypt file(s) using provider
```Typescript ```Typescript
const initializeData = await ProviderInstance.initialize( const initializeData = await ProviderInstance.initialize(
resolvedDDO.id, resolvedDDO.id,
@ -693,9 +639,7 @@ At this point we need to encrypt file(s) using provider
validUntil: initializeData.providerFee.validUntil validUntil: initializeData.providerFee.validUntil
} }
``` ```
Now we need to make the payment Now we need to make the payment
```Typescript ```Typescript
const tx = await datatoken.startOrder( const tx = await datatoken.startOrder(
dispenserDatatokenAddress, dispenserDatatokenAddress,
@ -705,9 +649,7 @@ Now we need to make the payment
providerFees providerFees
) )
``` ```
Now we can get the download URL Now we can get the download URL
```Typescript ```Typescript
const downloadURL = await ProviderInstance.getDownloadUrl( const downloadURL = await ProviderInstance.getDownloadUrl(
DDO.id, DDO.id,
@ -719,9 +661,7 @@ Now we can get the download URL
web3 web3
) )
``` ```
Let's check we received the download URL ok Let's check we received the download URL ok
```Typescript ```Typescript
console.log(`Download URL: ${downloadURL}`) console.log(`Download URL: ${downloadURL}`)
@ -737,7 +677,7 @@ Let's check we received the download URL ok
``` ```
### 8.1 Add key-value pair to data NFT ## 8. Using ERC725 Key-Value Store
Data NFTs can store arbitrary key-value pairs on-chain. This opens up their usage for a broad variety of applications, such as comments & ratings, attestations, and privately sharing data (when the value is encrypted). Data NFTs can store arbitrary key-value pairs on-chain. This opens up their usage for a broad variety of applications, such as comments & ratings, attestations, and privately sharing data (when the value is encrypted).
@ -750,39 +690,42 @@ Here are the steps:
3. Add key-value pair to data NFT (use the `setData` method) 3. Add key-value pair to data NFT (use the `setData` method)
4. Retrieve value from data NFT (use the `getData` method) 4. Retrieve value from data NFT (use the `getData` method)
### 8.1 Add key-value pair to data NFT
Let's start by using the `setData` method to update the nft key value store with some data Let's start by using the `setData` method to update the nft key value store with some data
```Typescript ```Typescript
const nft = new Nft(web3) const nft = new Nft(web3)
const data = 'SomeData' const data = 'SomeData'
try { try {
await nft.setData(freNftAddress, publisherAccount, '1', data) await nft.setData(freNftAddress, publisherAccount, '1', data)
} catch (e) { } catch (e) {
console.error(e)
assert.fail('Failed to set data in NFT ERC725 key value store', e) assert.fail('Failed to set data in NFT ERC725 key value store', e)
} }
``` ```
Under the hood, this uses [ERC725](https://erc725alliance.org/), which augments ERC721 with a well-defined way to set and get key-value pairs. Under the hood, this uses [ERC725](https://erc725alliance.org/), which augments ERC721 with a well-defined way to set and get key-value pairs.
### 8.2 get the key-value pair data from the NFT ### 8.2 get the key-value pair data from the NFT'
Use the `getData` method to get the data stored in the nft key value store
```Typescript ```Typescript
const nft = new Nft(web3)
try { try {
Use the `getData` method to get the data stored in the nft key value store const response = await nft.getData(freNftAddress, '1')
const data = await nft.getData(freNftAddress, '1') console.log('getData response: ', response)
console.log('Data: ', data) assert(
response === data,
'Wrong data received when getting data from NFT ERC725 key value store'
)
} catch (e) { } catch (e) {
console.error(e)
assert.fail('Failed to get data from NFT ERC725 key value store', e) assert.fail('Failed to get data from NFT ERC725 key value store', e)
} }
``` ```
That's it! Note the simplicity. All data was stored and retrieved from on-chain. We don't need Ocean Provider or Ocean Aquarius for these use cases (though the latter can help for fast querying & retrieval). That's it! Note the simplicity. All data was stored and retrieved from on-chain. We don't need Ocean Provider or Ocean Aquarius for these use cases (though the latter can help for fast querying & retrieval).
## Editing this file
## Editing this file
Please note that CodeExamples.md is an autogenerated file, you should not edit it directly. 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 Updates should be done in `test/integration/CodeExamples.test.ts` and all markdown should have three forward slashes before it
e.g. `/// # H1 Title` e.g. `/// # H1 Title`

View File

@ -677,18 +677,20 @@ describe('Marketplace flow tests', async () => {
}) /// }) ///
/// ``` /// ```
/// ## 8. Using ERC725 Key-Value Store
/// Data NFTs can store arbitrary key-value pairs on-chain. This opens up their usage for a broad variety of applications, such as comments & ratings, attestations, and privately sharing data (when the value is encrypted).
/// Let's see how!
/// Here are the steps:
/// 1. Setup (same as above)
/// 2. Publish data NFT (same as above)
/// 3. Add key-value pair to data NFT (use the `setData` method)
/// 4. Retrieve value from data NFT (use the `getData` method)
it('8.1 Add key-value pair to data NFT', async () => { it('8.1 Add key-value pair to data NFT', async () => {
/// Data NFTs can store arbitrary key-value pairs on-chain. This opens up their usage for a broad variety of applications, such as comments & ratings, attestations, and privately sharing data (when the value is encrypted).
/// Let's see how!
/// Here are the steps:
/// 1. Setup (same as above)
/// 2. Publish data NFT (same as above)
/// 3. Add key-value pair to data NFT (use the `setData` method)
/// 4. Retrieve value from data NFT (use the `getData` method)
/// Let's start by using the `setData` method to update the nft key value store with some data /// Let's start by using the `setData` method to update the nft key value store with some data
/// ```Typescript /// ```Typescript
const nft = new Nft(web3) const nft = new Nft(web3)
@ -696,23 +698,25 @@ describe('Marketplace flow tests', async () => {
try { try {
await nft.setData(freNftAddress, publisherAccount, '1', data) await nft.setData(freNftAddress, publisherAccount, '1', data)
} catch (e) { } catch (e) {
console.error(e)
assert.fail('Failed to set data in NFT ERC725 key value store', e) assert.fail('Failed to set data in NFT ERC725 key value store', e)
} }
/// ``` /// ```
/// Under the hood, this uses [ERC725](https://erc725alliance.org/), which augments ERC721 with a well-defined way to set and get key-value pairs. /// Under the hood, this uses [ERC725](https://erc725alliance.org/), which augments ERC721 with a well-defined way to set and get key-value pairs.
}) ///
it('8.2 get the key-value pair data from the NFT', async () => { /// ### 8.2 get the key-value pair data from the NFT'
/// Use the `getData` method to get the data stored in the nft key value store
/// ```Typescript /// ```Typescript
const nft = new Nft(web3)
try { try {
/// Use the `getData` method to get the data stored in the nft key value store const response = await nft.getData(freNftAddress, '1')
const data = await nft.getData(freNftAddress, '1') console.log('getData response: ', response)
console.log('Data: ', data) assert(
response === data,
'Wrong data received when getting data from NFT ERC725 key value store'
)
} catch (e) { } catch (e) {
console.error(e)
assert.fail('Failed to get data from NFT ERC725 key value store', e) assert.fail('Failed to get data from NFT ERC725 key value store', e)
} }
/// ``` /// ```