diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c48c551..1b83a729 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -213,3 +213,28 @@ jobs: - name: Create Guide & Commit if there are changes run: npm run commit:guides + + update_docs: + runs-on: ubuntu-latest + needs: [test_unit, test_integration] + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v2 + with: + node-version: '16' + + - name: checkout ocean.js repo + uses: actions/checkout@v3 + with: + repository: 'oceanprotocol/ocean.js' + path: 'ocean.js' + ref: ${{ github.event.pull_request.head.sha }} + + - name: setup git config + run: | + # setup the username and email. I tend to use 'GitHub Actions Bot' with no email by default + git config user.name "GitHub Actions Bot" + git config user.email "<>" + + - name: Create updated docs & commit changes + run: npm run commit:docs diff --git a/CHANGELOG.md b/CHANGELOG.md index 110f0091..e79978be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,50 @@ All notable changes to this project will be documented in this file. Dates are d Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). +#### [v3.0.0-next.2](https://github.com/oceanprotocol/ocean.js/compare/v3.0.0-next.1...v3.0.0-next.2) + +- Adding docs with Typedoc [`#1724`](https://github.com/oceanprotocol/ocean.js/pull/1724) +- update get compute env return type [`#1721`](https://github.com/oceanprotocol/ocean.js/pull/1721) +- Bump @truffle/hdwallet-provider from 2.1.5 to 2.1.10 [`#1725`](https://github.com/oceanprotocol/ocean.js/pull/1725) +- Bump vm2 from 3.9.11 to 3.9.17 [`#1722`](https://github.com/oceanprotocol/ocean.js/pull/1722) +- Bump chai from 4.3.6 to 4.3.7 [`#1726`](https://github.com/oceanprotocol/ocean.js/pull/1726) +- Fix c2d restart job with valid fees and order [`#1729`](https://github.com/oceanprotocol/ocean.js/pull/1729) +- Make FRE withMint = True [`#1719`](https://github.com/oceanprotocol/ocean.js/pull/1719) +- Bump @types/node from 18.11.18 to 18.15.11 [`#1712`](https://github.com/oceanprotocol/ocean.js/pull/1712) +- Bump bignumber.js from 9.1.0 to 9.1.1 [`#1713`](https://github.com/oceanprotocol/ocean.js/pull/1713) +- Bump @typescript-eslint/eslint-plugin from 5.54.0 to 5.57.0 [`#1711`](https://github.com/oceanprotocol/ocean.js/pull/1711) +- Bump @oceanprotocol/contracts from 1.1.8 to 1.1.12 [`#1709`](https://github.com/oceanprotocol/ocean.js/pull/1709) +- merge main fix conflicts [`a038f24`](https://github.com/oceanprotocol/ocean.js/commit/a038f24af4ff10adaab38cf2973febabc199aadb) +- adding Typedoc to ethers branch [`bc1f537`](https://github.com/oceanprotocol/ocean.js/commit/bc1f537d09855b84f96514f02e651db7e4fa8559) +- adding Typedoc to ethers branch [`66c6a73`](https://github.com/oceanprotocol/ocean.js/commit/66c6a730f055e601e848b67950e99ef30366d140) + +#### [v3.0.0-next.1](https://github.com/oceanprotocol/ocean.js/compare/v3.0.0-next.0...v3.0.0-next.1) + +> 28 April 2023 + +- update provider signature message [`05c4030`](https://github.com/oceanprotocol/ocean.js/commit/05c4030afdf7756307cf65483222bbeb3ac53712) +- Release 3.0.0-next.1 [`eb67d4c`](https://github.com/oceanprotocol/ocean.js/commit/eb67d4c7f070fb17fb0dc151b22cf223ee7f60f4) +- fix lint [`304b53a`](https://github.com/oceanprotocol/ocean.js/commit/304b53ad16067ede69e5274acfcb2ff205f591a6) + +#### [v3.0.0-next.0](https://github.com/oceanprotocol/ocean.js/compare/v2.7.0...v3.0.0-next.0) + +> 18 April 2023 + +- Cover all storage type support [`#1685`](https://github.com/oceanprotocol/ocean.js/pull/1685) +- fix compute flow integration test [`0750d98`](https://github.com/oceanprotocol/ocean.js/commit/0750d98b986bad063dff0dd1e14458010665fcca) +- more cleanup and jsdoc updates [`967f664`](https://github.com/oceanprotocol/ocean.js/commit/967f6642fb1a0cf9c20d4f4fa28d36527d8e43ba) +- Updating CodeExamples.md [`815ee37`](https://github.com/oceanprotocol/ocean.js/commit/815ee37c52f9aa64f2cac4948fb137f447d1c6b4) + #### [v2.7.0](https://github.com/oceanprotocol/ocean.js/compare/v2.7.0-next.2...v2.7.0) +> 20 March 2023 + - Multichain Provider [`#1698`](https://github.com/oceanprotocol/ocean.js/pull/1698) - Bump release-it from 15.6.0 to 15.6.1 [`#1704`](https://github.com/oceanprotocol/ocean.js/pull/1704) - Bump prettier from 2.8.1 to 2.8.4 [`#1703`](https://github.com/oceanprotocol/ocean.js/pull/1703) - Bump @typescript-eslint/eslint-plugin from 5.47.1 to 5.54.0 [`#1702`](https://github.com/oceanprotocol/ocean.js/pull/1702) - Updated copyright year. [`#1700`](https://github.com/oceanprotocol/ocean.js/pull/1700) +- Release 2.7.0 [`a2e9901`](https://github.com/oceanprotocol/ocean.js/commit/a2e9901697b32c6aaaa489c3bec1a19fcfa185ab) #### [v2.7.0-next.2](https://github.com/oceanprotocol/ocean.js/compare/v2.7.0-next.1...v2.7.0-next.2) diff --git a/CodeExamples.md b/CodeExamples.md index c5645119..2741d3ca 100644 --- a/CodeExamples.md +++ b/CodeExamples.md @@ -17,14 +17,17 @@ Here are the steps we will be following throughout the article: 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 fixed rate exchange](#-publish-data-nft-and-a-datatoken-with-a-fixed-rate-exchange) -7. [Publish Data NFT and a Datatoken with a dispenser](#-publish-data-nft-and-a-datatoken-with-a-dispenser) +0. [Prerequisites](#0-prerequisites) +1. [Initialize services](#1-initialize-services) +2. [Create a new node.js project](#2-create-a-new-nodejs-project) +3. [Install dependencies](#3-install-dependancies) +4. [Import dependencies and add variables and constants](#4-import-dependencies-and-add-variables-and-constants) +5. [Load the configuration, initialize accounts and deploy contracts](#5-load-the-configuration-initialize-accounts-and-deploy-contracts) +6. [Publish Data NFT and a Datatoken with a fixed rate exchange](#6-publish-data-nft-and-a-datatoken-with-a-fixed-rate-exchange) +7. [Consume a fixed rate asset data asset'](#7-consume-a-fixed-rate-asset-data-asset) +8. [Publish Data NFT and a Datatoken with a dispenser](#8-publish-data-nft-and-a-datatoken-with-a-dispenserr) +9. [Consume a dispenser data asset](#9-consume-a-dispenser-data-asset) +10. [Using ERC725 Key-Value Store](#10-using-erc725-key-value-store) ## 0. Prerequisites Before we start it is important that you have all of the necessary prerequisites installed on your computer. @@ -67,7 +70,7 @@ Open the package.json file in a text editor and update the dependancies to inclu "@oceanprotocol/contracts": "1.0.0-alpha.28", "@oceanprotocol/lib": "1.0.0-next.37", "crypto-js": "^4.1.1", - "web3": "^1.7.3" + "ethers": "^5.7.2" } ``` @@ -84,9 +87,11 @@ Now open the `marketplace.js` file in your text editor. Start by importing all of the necessary dependencies ```Typescript +import fs from 'fs' -import { AbiItem } from 'web3-utils' +import { ethers, providers, Signer } from 'ethers' import { SHA256 } from 'crypto-js' +import { homedir } from 'os' import { approve, Aquarius, @@ -108,10 +113,14 @@ import { ProviderInstance, transfer, ZERO_ADDRESS, - calculateEstimatedGas, - sendTx + sendTx, + ConfigHelper, + configHelperNetworks, + amountToUnits, + ValidateMetadata, + getEventFromTx, + DDO } from '@oceanprotocol/lib' -import { getAddresses, getTestConfig, web3 } from '../config' ``` - -``` - - ### 5.2 Next, lets get the address of the deployed contracts -```Typescript - addresses = getAddresses() ``` ### 5.3 We send some OCEAN to consumer and staker accounts ```Typescript - transfer(web3, config, publisherAccount, addresses.Ocean, consumerAccount, '100') - transfer(web3, config, publisherAccount, addresses.Ocean, stakerAccount, '100') + transfer( + publisherAccount, + config, + addresses.Ocean, + await consumerAccount.getAddress(), + '100' + ) + transfer( + publisherAccount, + config, + addresses.Ocean, + await stakerAccount.getAddress(), + '100' + ) ``` @@ -276,7 +300,7 @@ Again, lets console log the values so that we can check that they have been save ### 6.1 Publish a dataset (create NFT + Datatoken) with a fixed rate exchange ```Typescript - const factory = new NftFactory(addresses.ERC721Factory, web3) + const factory = new NftFactory(addresses.ERC721Factory, publisherAccount) const nftParams: NftCreateData = { name: FRE_NFT_NAME, @@ -284,7 +308,7 @@ Again, lets console log the values so that we can check that they have been save templateIndex: 1, tokenURI: '', transferable: true, - owner: publisherAccount + owner: await publisherAccount.getAddress() } const datatokenParams: DatatokenCreateParams = { @@ -293,15 +317,15 @@ Again, lets console log the values so that we can check that they have been save feeAmount: '0', paymentCollector: ZERO_ADDRESS, feeToken: ZERO_ADDRESS, - minter: publisherAccount, + minter: await publisherAccount.getAddress(), mpFeeAddress: ZERO_ADDRESS } const freParams: FreCreationParams = { fixedRateAddress: addresses.FixedPrice, baseTokenAddress: addresses.Ocean, - owner: publisherAccount, - marketFeeCollector: publisherAccount, + owner: await publisherAccount.getAddress(), + marketFeeCollector: await publisherAccount.getAddress(), baseTokenDecimals: 18, datatokenDecimals: 18, fixedRate: '1', @@ -310,17 +334,22 @@ Again, lets console log the values so that we can check that they have been save withMint: true } - const tx = await factory.createNftWithDatatokenWithFixedRate( - publisherAccount, + const bundleNFT = await factory.createNftWithDatatokenWithFixedRate( nftParams, datatokenParams, freParams ) - freNftAddress = tx.events.NFTCreated.returnValues[0] - freDatatokenAddress = tx.events.TokenCreated.returnValues[0] - freAddress = tx.events.NewFixedRate.returnValues.exchangeContract - freId = tx.events.NewFixedRate.returnValues.exchangeId + const trxReceipt = await bundleNFT.wait() + // events have been emitted + const nftCreatedEvent = getEventFromTx(trxReceipt, 'NFTCreated') + const tokenCreatedEvent = getEventFromTx(trxReceipt, 'TokenCreated') + const newFreEvent = getEventFromTx(trxReceipt, 'NewFixedRate') + + freNftAddress = nftCreatedEvent.args.newTokenAddress + freDatatokenAddress = tokenCreatedEvent.args.newTokenAddress + freAddress = newFreEvent.args.exchangeContract + freId = newFreEvent.args.exchangeId ``` Now let's console log each of those values to check everything is working @@ -334,54 +363,64 @@ Now let's console log each of those values to check everything is working ### 6.2 Set metadata in the fixed rate exchange NFT ```Typescript - const nft = new Nft(web3) + const nft = new Nft( + publisherAccount, + (await publisherAccount.provider.getNetwork()).chainId + ) + + fixedDDO = { ...genericAsset } ``` Now we are going to update the ddo and set the did ```Typescript - DDO.chainId = await web3.eth.getChainId() - DDO.id = + + fixedDDO.chainId = (await publisherAccount.provider.getNetwork()).chainId + fixedDDO.id = 'did:op:' + - SHA256(web3.utils.toChecksumAddress(freNftAddress) + DDO.chainId.toString(10)) - DDO.nftAddress = freNftAddress + SHA256(ethers.utils.getAddress(freNftAddress) + fixedDDO.chainId.toString(10)) + fixedDDO.nftAddress = freNftAddress ``` Next, let's encrypt the file(s) using provider ```Typescript ASSET_URL.datatokenAddress = freDatatokenAddress ASSET_URL.nftAddress = freNftAddress - const encryptedFiles = await ProviderInstance.encrypt( + fixedDDO.services[0].files = await ProviderInstance.encrypt( ASSET_URL, - DDO.chainId, + fixedDDO.chainId, providerUrl ) - DDO.services[0].files = await encryptedFiles - DDO.services[0].datatokenAddress = freDatatokenAddress + fixedDDO.services[0].datatokenAddress = freDatatokenAddress ``` Now let's console log the DID to check everything is working ```Typescript - console.log(`DID: ${DDO.id}`) + console.log(`DID: ${fixedDDO.id}`) - const providerResponse = await ProviderInstance.encrypt(DDO, DDO.chainId, providerUrl) + const providerResponse = await ProviderInstance.encrypt( + fixedDDO, + fixedDDO.chainId, + providerUrl + ) const encryptedDDO = await providerResponse - const metadataHash = getHash(JSON.stringify(DDO)) + const isAssetValid: ValidateMetadata = await aquarius.validate(fixedDDO) + assert(isAssetValid.valid === true, 'Published asset is not valid') await nft.setMetadata( freNftAddress, - publisherAccount, + await publisherAccount.getAddress(), 0, providerUrl, '', - '0x2', + ethers.utils.hexlify(2), encryptedDDO, - '0x' + metadataHash + isAssetValid.hash ) }) ``` ### 6.3 Marketplace displays fixed rate asset for sale ```Typescript - const fixedRate = new FixedRateExchange(freAddress, web3) + const fixedRate = new FixedRateExchange(freAddress, publisherAccount) const oceanAmount = await ( await fixedRate.calcBaseInGivenDatatokensOut(freId, '1') ).baseTokenAmount @@ -392,49 +431,79 @@ Now that the market has fetched those values it can display the asset on the fro ``` - ### 6.4 Consumer buys a fixed rate asset data asset, and downloads it +## 7. Consume a fixed rate asset data asset + + ### 7.1 Consumer buys a fixed rate asset data asset, and downloads it ```Typescript - const datatoken = new Datatoken(web3) + datatoken = new Datatoken(publisherAccount) const DATATOKEN_AMOUNT = '10000' - await datatoken.mint(freDatatokenAddress, publisherAccount, DATATOKEN_AMOUNT) + await datatoken.mint( + freDatatokenAddress, + await publisherAccount.getAddress(), + DATATOKEN_AMOUNT + ) - const consumerETHBalance = await web3.eth.getBalance(consumerAccount) + const consumerBalance = await provider.getBalance(await consumerAccount.getAddress()) + const consumerETHBalance = ethers.utils.formatEther(consumerBalance) ``` 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) + let consumerOCEANBalance = await balance( + consumerAccount, + addresses.Ocean, + await consumerAccount.getAddress() + ) console.log(`Consumer OCEAN balance before swap: ${consumerOCEANBalance}`) - let consumerDTBalance = await balance(web3, freDatatokenAddress, consumerAccount) + let consumerDTBalance = await balance( + consumerAccount, + freDatatokenAddress, + await consumerAccount.getAddress() + ) 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 ```Typescript - await approve(web3, config, consumerAccount, addresses.Ocean, freAddress, '100') await approve( - web3, + consumerAccount, config, + await consumerAccount.getAddress(), + addresses.Ocean, + freAddress, + '100' + ) + await approve( publisherAccount, + config, + await publisherAccount.getAddress(), freDatatokenAddress, freAddress, DATATOKEN_AMOUNT ) - const fixedRate = new FixedRateExchange(freAddress, web3) + const fixedRate = new FixedRateExchange(freAddress, consumerAccount) ``` Now we can make the contract call ```Typescript - await fixedRate.buyDatatokens(consumerAccount, freId, '1', '2') + await fixedRate.buyDatatokens(freId, '1', '2') - consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount) + consumerOCEANBalance = await balance( + consumerAccount, + addresses.Ocean, + await consumerAccount.getAddress() + ) console.log(`Consumer OCEAN balance after swap: ${consumerOCEANBalance}`) - consumerDTBalance = await balance(web3, freDatatokenAddress, consumerAccount) + consumerDTBalance = await balance( + consumerAccount, + freDatatokenAddress, + await consumerAccount.getAddress() + ) console.log(`Consumer ${FRE_NFT_SYMBOL} balance after swap: ${consumerDTBalance}`) - const resolvedDDO = await aquarius.waitForAqua(DDO.id) + const resolvedDDO = await aquarius.waitForAqua(fixedDDO.id) assert(resolvedDDO, 'Cannot fetch DDO from Aquarius') ``` @@ -444,7 +513,7 @@ Next, we need to initialize the provider resolvedDDO.id, resolvedDDO.services[0].id, 0, - consumerAccount, + await consumerAccount.getAddress(), providerUrl ) @@ -459,27 +528,29 @@ Next, we need to initialize the provider validUntil: initializeData.providerFee.validUntil } + datatoken = new Datatoken(consumerAccount) + ``` Lets now make the payment ```Typescript const tx = await datatoken.startOrder( freDatatokenAddress, - consumerAccount, - consumerAccount, + await consumerAccount.getAddress(), 0, providerFees ) + const orderTx = await tx.wait() + const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted') ``` Now we can get the url ```Typescript const downloadURL = await ProviderInstance.getDownloadUrl( - DDO.id, - consumerAccount, - DDO.services[0].id, + fixedDDO.id, + fixedDDO.services[0].id, 0, - tx.transactionHash, + orderStartedTx.transactionHash, providerUrl, - web3 + consumerAccount ) ``` @@ -487,9 +558,17 @@ Lets check that the download URL was successfully received ```Typescript console.log(`Download URL: ${downloadURL}`) - consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount) + consumerOCEANBalance = await balance( + consumerAccount, + addresses.Ocean, + await consumerAccount.getAddress() + ) console.log(`Consumer OCEAN balance after order: ${consumerOCEANBalance}`) - consumerDTBalance = await balance(web3, freDatatokenAddress, consumerAccount) + consumerDTBalance = await balance( + consumerAccount, + freDatatokenAddress, + await consumerAccount.getAddress() + ) console.log(`Consumer ${FRE_NFT_SYMBOL} balance after order: ${consumerDTBalance}`) try { @@ -501,11 +580,11 @@ Lets check that the download URL was successfully received ``` -## 7. Publish Data NFT and a Datatoken with a dispenser +## 8. Publish Data NFT and a Datatoken with a dispenser - ### 7.1 Publish a dataset (create NFT + Datatoken) with a dispenser + ### 8.1 Publish a dataset (create NFT + Datatoken) with a dispenser ```Typescript - const factory = new NftFactory(addresses.ERC721Factory, web3) + const factory = new NftFactory(addresses.ERC721Factory, publisherAccount) const nftParams: NftCreateData = { name: DISP_NFT_NAME, @@ -513,7 +592,7 @@ Lets check that the download URL was successfully received templateIndex: 1, tokenURI: '', transferable: true, - owner: publisherAccount + owner: await publisherAccount.getAddress() } const datatokenParams: DatatokenCreateParams = { @@ -522,7 +601,7 @@ Lets check that the download URL was successfully received feeAmount: '0', paymentCollector: ZERO_ADDRESS, feeToken: ZERO_ADDRESS, - minter: publisherAccount, + minter: await publisherAccount.getAddress(), mpFeeAddress: ZERO_ADDRESS } @@ -534,16 +613,19 @@ Lets check that the download URL was successfully received allowedSwapper: ZERO_ADDRESS } - const tx = await factory.createNftWithDatatokenWithDispenser( - publisherAccount, + const bundleNFT = await factory.createNftWithDatatokenWithDispenser( nftParams, datatokenParams, dispenserParams ) + const trxReceipt = await bundleNFT.wait() + const nftCreatedEvent = getEventFromTx(trxReceipt, 'NFTCreated') + const tokenCreatedEvent = getEventFromTx(trxReceipt, 'TokenCreated') + const dispenserCreatedEvent = getEventFromTx(trxReceipt, 'DispenserCreated') - dispenserNftAddress = tx.events.NFTCreated.returnValues[0] - dispenserDatatokenAddress = tx.events.TokenCreated.returnValues[0] - dispenserAddress = tx.events.DispenserCreated.returnValues[0] + dispenserNftAddress = nftCreatedEvent.args.newTokenAddress + dispenserDatatokenAddress = tokenCreatedEvent.args.newTokenAddress + dispenserAddress = dispenserCreatedEvent.args.newTokenAddress // double check this ``` Lets check that we managed to received all of those values without any problems ```Typescript @@ -553,59 +635,67 @@ Lets check that we managed to received all of those values without any problems ``` - ### 7.2 Set metadata in the dispenser NFT + ### 8.2 Set metadata in the dispenser NFT ```Typescript - const nft = new Nft(web3) + const nft = new Nft( + publisherAccount, + (await publisherAccount.provider.getNetwork()).chainId + ) ``` 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 + fixedDDO.chainId = (await publisherAccount.provider.getNetwork()).chainId + fixedDDO.id = + 'did:op:' + + SHA256(ethers.utils.getAddress(dispenserNftAddress) + fixedDDO.chainId.toString(10)) + fixedDDO.nftAddress = dispenserNftAddress ``` Now we need to encrypt file(s) using provider ```Typescript ASSET_URL.datatokenAddress = dispenserDatatokenAddress ASSET_URL.nftAddress = dispenserNftAddress - const encryptedFiles = await ProviderInstance.encrypt( + fixedDDO.services[0].files = await ProviderInstance.encrypt( ASSET_URL, - DDO.chainId, + fixedDDO.chainId, providerUrl ) - DDO.services[0].files = await encryptedFiles - DDO.services[0].datatokenAddress = dispenserDatatokenAddress + fixedDDO.services[0].datatokenAddress = dispenserDatatokenAddress - console.log(`DID: ${DDO.id}`) + console.log(`DID: ${fixedDDO.id}`) - const providerResponse = await ProviderInstance.encrypt(DDO, DDO.chainId, providerUrl) - const encryptedDDO = await providerResponse - const metadataHash = getHash(JSON.stringify(DDO)) + const encryptedDDO = await ProviderInstance.encrypt( + fixedDDO, + fixedDDO.chainId, + providerUrl + ) + const isAssetValid: ValidateMetadata = await aquarius.validate(fixedDDO) + assert(isAssetValid.valid === true, 'Published asset is not valid') await nft.setMetadata( dispenserNftAddress, - publisherAccount, + await publisherAccount.getAddress(), 0, providerUrl, '', - '0x2', + ethers.utils.hexlify(2), encryptedDDO, - '0x' + metadataHash + isAssetValid.hash ) ``` - ### 7.3 Consumer gets a dispenser data asset, and downloads it +## 9. Consume a dispenser data asset + + ### 9.1 Consumer gets a dispenser data asset, and downloads it ```Typescript - const datatoken = new Datatoken(web3) - const dispenser = new Dispenser(addresses.Dispenser, web3) + datatoken = new Datatoken(publisherAccount) + const dispenser = new Dispenser(addresses.Dispenser, consumerAccount) let consumerDTBalance = await balance( - web3, + consumerAccount, dispenserDatatokenAddress, - consumerAccount + await consumerAccount.getAddress() ) console.log( `Consumer ${DISP_NFT_SYMBOL} balance before dispense: ${consumerDTBalance}` @@ -613,18 +703,24 @@ Now we need to encrypt file(s) using provider await dispenser.dispense( dispenserDatatokenAddress, - consumerAccount, '1', - consumerAccount + await consumerAccount.getAddress() ) - consumerDTBalance = await balance(web3, dispenserDatatokenAddress, consumerAccount) + consumerDTBalance = await balance( + consumerAccount, + dispenserDatatokenAddress, + await consumerAccount.getAddress() + ) console.log( `Consumer ${DISP_NFT_SYMBOL} balance after dispense: ${consumerDTBalance}` ) - const resolvedDDO = await aquarius.waitForAqua(DDO.id) + const resolvedDDO = await aquarius.waitForAqua(fixedDDO.id) assert(resolvedDDO, 'Cannot fetch DDO from Aquarius') + + datatoken = new Datatoken(consumerAccount) + ``` At this point we need to encrypt file(s) using provider ```Typescript @@ -632,7 +728,7 @@ At this point we need to encrypt file(s) using provider resolvedDDO.id, resolvedDDO.services[0].id, 0, - consumerAccount, + await consumerAccount.getAddress(), providerUrl ) @@ -651,29 +747,33 @@ Now we need to make the payment ```Typescript const tx = await datatoken.startOrder( dispenserDatatokenAddress, - consumerAccount, - consumerAccount, + await consumerAccount.getAddress(), 0, providerFees ) + const orderTx = await tx.wait() + const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted') ``` Now we can get the download URL ```Typescript const downloadURL = await ProviderInstance.getDownloadUrl( - DDO.id, - consumerAccount, - DDO.services[0].id, + fixedDDO.id, + fixedDDO.services[0].id, 0, - tx.transactionHash, + orderStartedTx.transactionHash, providerUrl, - web3 + consumerAccount ) ``` Let's check we received the download URL ok ```Typescript console.log(`Download URL: ${downloadURL}`) - consumerDTBalance = await balance(web3, dispenserDatatokenAddress, consumerAccount) + consumerDTBalance = await balance( + consumerAccount, + dispenserDatatokenAddress, + await consumerAccount.getAddress() + ) console.log(`Consumer ${DISP_NFT_SYMBOL} balance after order: ${consumerDTBalance}`) try { @@ -685,7 +785,7 @@ Let's check we received the download URL ok ``` -## 8. Using ERC725 Key-Value Store +## 10. 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). @@ -698,33 +798,40 @@ Here are the steps: 3. Add key-value pair to data NFT (use the `setData` method) 4. Retrieve value from data NFT (use the `getData` method) - ### 8.1 Add key-value pair to data NFT + ### 10.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 ```Typescript - const nft = new Nft(web3) + const nft = new Nft(publisherAccount) const data = 'SomeData' try { - await nft.setData(freNftAddress, publisherAccount, '1', data) + await nft.setData( + freNftAddress, + await publisherAccount.getAddress(), + '0x1234', + data + ) } catch (e) { + console.log('e = ', 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. -### 8.2 get the key-value pair data from the NFT' +### 10.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 try { - const response = await nft.getData(freNftAddress, '1') + const response = await nft.getData(freNftAddress, '0x1234') console.log('getData response: ', response) assert( response === data, 'Wrong data received when getting data from NFT ERC725 key value store' ) } catch (e) { + console.log('e = ', e) assert.fail('Failed to get data from NFT ERC725 key value store', e) } ``` diff --git a/ComputeExamples.md b/ComputeExamples.md index 21991c3b..b0aa8d1f 100644 --- a/ComputeExamples.md +++ b/ComputeExamples.md @@ -2,18 +2,18 @@ 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. [Import dependencies and add variables and constants](#-import-dependencies-and-add-variables-and-constants) +0. [Prerequisites](#0-prerequisites) +1. [Initialize services](#1-initialize-services) +2. [Create a new node.js project](#2-create-a-new-nodejs-project-with-typescript) +3. [Install dependencies](#3-install-dependencies) +4. [Import dependencies and add variables and constants](#4-import-dependencies-and-add-variables-constants-and-helper-methods) 5. [Initialize accounts and deploy contracts](#-initialize-accounts-and-deploy-contracts) -6. [Publish a dataset and an algorithm](#-publish-a-dataset-data-nft-and-datatoken) -7. [Resolve published datasets and algorithms](#-resolve-published-datasets-and-algorithms) -8. [Send datatokens to consumer](#-send-datatokens-to-consumer) -9. [Consumer fetches compute environment](#-consumer-starts-a-compute-job-using-a-free-c2D-environment) -10. [Consumer starts a compute job using a free C2D environment](#-consumer-starts-a-compute-job-using-a-free-c2D-environment) -11. [Check compute status and get download compute results url](#-check-compute-status-and-get-download-compute-results-url) +6. [Publish a dataset and an algorithm](#6-publish-assets-dataset-and-algorithm) +7. [Resolve published datasets and algorithms](#7-resolve-assets) +8. [Send datatokens to consumer](#8-send-datatokens-to-consumer) +9. [Consumer fetches compute environment](#9-get-compute-environments) +10. [Consumer starts a compute job using a free C2D environment](#10-consumer-starts-a-compute-job) +11. [Check compute status and get download compute results url](#11-check-compute-status-and-get-download-compute-results-url) Let's go through each step. @@ -104,7 +104,7 @@ node dist/compute.js Install dependencies running the following command in your terminal: ```bash -npm install @oceanprotocol/lib crypto-js web3 web3-utils typescript @types/node ts-node +npm install @oceanprotocol/lib crypto-js ethers typescript @types/node ts-node ``` ## 4. Import dependencies and add variables, constants and helper methods @@ -120,8 +120,7 @@ import fs from 'fs' import { homedir } from 'os' import { SHA256 } from 'crypto-js' -import Web3 from 'web3' -import { AbiItem } from 'web3-utils' +import { ethers, providers, Signer } from 'ethers' import { ProviderInstance, Aquarius, @@ -141,12 +140,12 @@ import { DDO, NftCreateData, DatatokenCreateParams, - calculateEstimatedGas, sendTx, configHelperNetworks, - ConfigHelper + ConfigHelper, + getEventFromTx, + amountToUnits } from '@oceanprotocol/lib' - ``` ### 4.2. Constants and variables @@ -260,13 +259,12 @@ const ALGORITHM_DDO: DDO = { Now we define the variables which we will need later ```Typescript -let web3: Web3 let config: Config -let aquarius: Aquarius +let aquariusInstance: Aquarius let datatoken: Datatoken let providerUrl: string -let publisherAccount: string -let consumerAccount: string +let publisherAccount: Signer +let consumerAccount: Signer let addresses let computeEnvs @@ -287,16 +285,17 @@ Add a `createAsset()`function. async function createAsset( name: string, symbol: string, - owner: string, + owner: Signer, assetUrl: Files, ddo: DDO, providerUrl: string ) { - const nft = new Nft(web3) - const Factory = new NftFactory(addresses.ERC721Factory, web3) + const nft = new Nft(owner, (await owner.provider.getNetwork()).chainId) + + const nftFactory = new NftFactory(addresses.ERC721Factory, owner) + + const chain = (await owner.provider.getNetwork()).chainId - // Now we update the DDO and set the right did - const chain = await web3.eth.getChainId() ddo.chainId = parseInt(chain.toString(10)) const nftParamsAsset: NftCreateData = { name, @@ -304,7 +303,7 @@ async function createAsset( templateIndex: 1, tokenURI: 'aaa', transferable: true, - owner + owner: await owner.getAddress() } const datatokenParams: DatatokenCreateParams = { templateIndex: 1, @@ -312,45 +311,41 @@ async function createAsset( feeAmount: '0', paymentCollector: ZERO_ADDRESS, feeToken: ZERO_ADDRESS, - minter: owner, + minter: await owner.getAddress(), mpFeeAddress: ZERO_ADDRESS } - // Now we can make the contract call createNftWithDatatoken - const result = await Factory.createNftWithDatatoken( - owner, + + const bundleNFT = await nftFactory.createNftWithDatatoken( nftParamsAsset, datatokenParams ) - const nftAddress = result.events.NFTCreated.returnValues[0] - const datatokenAddressAsset = result.events.TokenCreated.returnValues[0] - ddo.nftAddress = web3.utils.toChecksumAddress(nftAddress) + const trxReceipt = await bundleNFT.wait() + // events have been emitted + const nftCreatedEvent = getEventFromTx(trxReceipt, 'NFTCreated') + const tokenCreatedEvent = getEventFromTx(trxReceipt, 'TokenCreated') - // Next we encrypt the file or files using Ocean Provider. The provider is an off chain proxy built specifically for this task + const nftAddress = nftCreatedEvent.args.newTokenAddress + const datatokenAddressAsset = tokenCreatedEvent.args.newTokenAddress + // create the files encrypted string assetUrl.datatokenAddress = datatokenAddressAsset - assetUrl.nftAddress = ddo.nftAddress - let providerResponse = await ProviderInstance.encrypt(assetUrl, chain, providerUrl) - ddo.services[0].files = await providerResponse + assetUrl.nftAddress = nftAddress + ddo.services[0].files = await ProviderInstance.encrypt(assetUrl, chain, providerUrl) ddo.services[0].datatokenAddress = datatokenAddressAsset - ddo.services[0].serviceEndpoint = providerUrl + ddo.services[0].serviceEndpoint = 'http://172.15.0.4:8030' // put back proviederUrl - // Next we update ddo and set the right did - ddo.nftAddress = web3.utils.toChecksumAddress(nftAddress) - ddo.id = - 'did:op:' + SHA256(web3.utils.toChecksumAddress(nftAddress) + chain.toString(10)) - providerResponse = await ProviderInstance.encrypt(ddo, chain, providerUrl) - const encryptedResponse = await providerResponse - const validateResult = await aquarius.validate(ddo) - - // Next you can check if if the ddo is valid by checking if validateResult.valid returned true + ddo.nftAddress = nftAddress + ddo.id = 'did:op:' + SHA256(ethers.utils.getAddress(nftAddress) + chain.toString(10)) + const encryptedResponse = await ProviderInstance.encrypt(ddo, chain, providerUrl) + const validateResult = await aquariusInstance.validate(ddo) await nft.setMetadata( nftAddress, - owner, + await owner.getAddress(), 0, - providerUrl, + 'http://172.15.0.4:8030', // put back proviederUrl '', - '0x2', + ethers.utils.hexlify(2), encryptedResponse, validateResult.hash ) @@ -363,7 +358,7 @@ Add a `handleOrder()`function. async function handleOrder( order: ProviderComputeInitialize, datatokenAddress: string, - payerAccount: string, + payerAccount: Signer, consumerAccount: string, serviceIndex: number, consumeMarkerFee?: ConsumeMarketFee @@ -375,9 +370,9 @@ async function handleOrder( */ if (order.providerFee && order.providerFee.providerFeeAmount) { await approveWei( - web3, - config, payerAccount, + config, + await payerAccount.getAddress(), order.providerFee.providerFeeToken, datatokenAddress, order.providerFee.providerFeeAmount @@ -387,21 +382,23 @@ async function handleOrder( if (!order.providerFee) return order.validOrder const tx = await datatoken.reuseOrder( datatokenAddress, - payerAccount, order.validOrder, order.providerFee ) - return tx.transactionHash + const reusedTx = await tx.wait() + const orderReusedTx = getEventFromTx(reusedTx, 'OrderReused') + return orderReusedTx.transactionHash } const tx = await datatoken.startOrder( datatokenAddress, - payerAccount, consumerAccount, serviceIndex, order.providerFee, consumeMarkerFee ) - return tx.transactionHash + const orderTx = await tx.wait() + const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted') + return orderStartedTx.transactionHash } ``` @@ -413,9 +410,17 @@ describe('Compute-to-data example tests We need to load the configuration. Add the following code into your `run(){ }` function ```Typescript - web3 = new Web3(process.env.NODE_URI || configHelperNetworks[1].nodeUri) - config = new ConfigHelper().getConfig(await web3.eth.getChainId()) + const provider = new providers.JsonRpcProvider( + process.env.NODE_URI || configHelperNetworks[1].nodeUri + ) + publisherAccount = (await provider.getSigner(0)) as Signer + consumerAccount = (await provider.getSigner(1)) as Signer + const config = new ConfigHelper().getConfig( + parseInt(String((await publisherAccount.provider.getNetwork()).chainId)) + ) config.providerUri = process.env.PROVIDER_URL || config.providerUri + aquariusInstance = new Aquarius(config?.metadataCacheUri) + providerUrl = config?.providerUri addresses = JSON.parse( // eslint-disable-next-line security/detect-non-literal-fs-filename fs.readFileSync( @@ -424,37 +429,24 @@ We need to load the configuration. Add the following code into your `run(){ }` f 'utf8' ) ).development - aquarius = new Aquarius(config.metadataCacheUri) - providerUrl = config.providerUri - datatoken = new Datatoken(web3) + ``` As we go along it's a good idea to console log the values so that you check they are right. At the end of your `run(){ ... }` function add the following logs: ```Typescript console.log(`Aquarius URL: ${config.metadataCacheUri}`) console.log(`Provider URL: ${providerUrl}`) console.log(`Deployed contracts address: ${addresses}`) - -``` - -Now at the end of your compute.ts file call you `run()` function. Next, let's compile the file with the `tsc` command in the console and run `node dist/compute.js`. -If everything is working you should see the logs in the console and no errors. -## 5. Initialize accounts - ### 5.1 Initialize accounts -We will use all of the following code snippets in the same way. Add the code snippet and the logs to the end of your `run(){ ... }` function as well as the logs. -Then compile your file with the `tsc` command and run it with `node dist/compute.js` -```Typescript - const accounts = await web3.eth.getAccounts() - publisherAccount = accounts[0] - consumerAccount = accounts[1] -``` -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}`) ``` - ### 5.2 Mint OCEAN to publisher account +Now at the end of your compute.ts file call you `run()` function. Next, let's compile the file with the `tsc` command in the console and run `node dist/compute.js`. +If everything is working you should see the logs in the console and no errors. +We will use all of the following code snippets in the same way. Add the code snippet and the logs to the end of your `run(){ ... }` function as well as the logs. +Then compile your file with the `tsc` command and run it with `node dist/compute.js` + + ### 5.1 Mint OCEAN to publisher account You can skip this step if you are running your script against a remote network, you need to mint oceans to mentioned accounts only if you are using barge to test your script @@ -472,29 +464,33 @@ you need to mint oceans to mentioned accounts only if you are using barge to tes stateMutability: 'nonpayable', type: 'function' } - ] as AbiItem[] - const tokenContract = new web3.eth.Contract(minAbi, addresses.Ocean) - const estGas = await calculateEstimatedGas( - publisherAccount, - tokenContract.methods.mint, - publisherAccount, - web3.utils.toWei('1000') + ] + + const tokenContract = new ethers.Contract(addresses.Ocean, minAbi, publisherAccount) + const estGasPublisher = await tokenContract.estimateGas.mint( + await publisherAccount.getAddress(), + amountToUnits(null, null, '1000', 18) ) await sendTx( + estGasPublisher, publisherAccount, - estGas, - web3, 1, - tokenContract.methods.mint, - publisherAccount, - web3.utils.toWei('1000') + tokenContract.mint, + await publisherAccount.getAddress(), + amountToUnits(null, null, '1000', 18) ) ``` - ### 5.3 Send some OCEAN to consumer account + ### 5.2 Send some OCEAN to consumer account ```Typescript - transfer(web3, config, publisherAccount, addresses.Ocean, consumerAccount, '100') + transfer( + publisherAccount, + config, + addresses.Ocean, + await consumerAccount.getAddress(), + '100' + ) ``` @@ -538,8 +534,8 @@ Now, let's check that we successfully published a algorithm (create NFT + Datato ### 7.1 Resolve published datasets and algorithms ```Typescript - resolvedDatasetDdo = await aquarius.waitForAqua(datasetId) - resolvedAlgorithmDdo = await aquarius.waitForAqua(algorithmId) + resolvedDatasetDdo = await aquariusInstance.waitForAqua(datasetId) + resolvedAlgorithmDdo = await aquariusInstance.waitForAqua(algorithmId) ``` - }) /// - /// ``` - - it('5.2 Next, lets get the address of the deployed contracts', async () => { - /// ```Typescript - addresses = getAddresses() }) /// /// ``` it('5.3 We send some OCEAN to consumer and staker accounts', async () => { /// ```Typescript - transfer(web3, config, publisherAccount, addresses.Ocean, consumerAccount, '100') - transfer(web3, config, publisherAccount, addresses.Ocean, stakerAccount, '100') + transfer( + publisherAccount, + config, + addresses.Ocean, + await consumerAccount.getAddress(), + '100' + ) + transfer( + publisherAccount, + config, + addresses.Ocean, + await stakerAccount.getAddress(), + '100' + ) }) /// /// ``` @@ -276,7 +300,7 @@ describe('Marketplace flow tests', async () => { it('6.1 Publish a dataset (create NFT + Datatoken) with a fixed rate exchange', async () => { /// ```Typescript - const factory = new NftFactory(addresses.ERC721Factory, web3) + const factory = new NftFactory(addresses.ERC721Factory, publisherAccount) const nftParams: NftCreateData = { name: FRE_NFT_NAME, @@ -284,7 +308,7 @@ describe('Marketplace flow tests', async () => { templateIndex: 1, tokenURI: '', transferable: true, - owner: publisherAccount + owner: await publisherAccount.getAddress() } const datatokenParams: DatatokenCreateParams = { @@ -293,15 +317,15 @@ describe('Marketplace flow tests', async () => { feeAmount: '0', paymentCollector: ZERO_ADDRESS, feeToken: ZERO_ADDRESS, - minter: publisherAccount, + minter: await publisherAccount.getAddress(), mpFeeAddress: ZERO_ADDRESS } const freParams: FreCreationParams = { fixedRateAddress: addresses.FixedPrice, baseTokenAddress: addresses.Ocean, - owner: publisherAccount, - marketFeeCollector: publisherAccount, + owner: await publisherAccount.getAddress(), + marketFeeCollector: await publisherAccount.getAddress(), baseTokenDecimals: 18, datatokenDecimals: 18, fixedRate: '1', @@ -310,17 +334,22 @@ describe('Marketplace flow tests', async () => { withMint: true } - const tx = await factory.createNftWithDatatokenWithFixedRate( - publisherAccount, + const bundleNFT = await factory.createNftWithDatatokenWithFixedRate( nftParams, datatokenParams, freParams ) - freNftAddress = tx.events.NFTCreated.returnValues[0] - freDatatokenAddress = tx.events.TokenCreated.returnValues[0] - freAddress = tx.events.NewFixedRate.returnValues.exchangeContract - freId = tx.events.NewFixedRate.returnValues.exchangeId + const trxReceipt = await bundleNFT.wait() + // events have been emitted + const nftCreatedEvent = getEventFromTx(trxReceipt, 'NFTCreated') + const tokenCreatedEvent = getEventFromTx(trxReceipt, 'TokenCreated') + const newFreEvent = getEventFromTx(trxReceipt, 'NewFixedRate') + + freNftAddress = nftCreatedEvent.args.newTokenAddress + freDatatokenAddress = tokenCreatedEvent.args.newTokenAddress + freAddress = newFreEvent.args.exchangeContract + freId = newFreEvent.args.exchangeId /// ``` /// Now let's console log each of those values to check everything is working @@ -334,54 +363,64 @@ describe('Marketplace flow tests', async () => { it('6.2 Set metadata in the fixed rate exchange NFT', async () => { /// ```Typescript - const nft = new Nft(web3) + const nft = new Nft( + publisherAccount, + (await publisherAccount.provider.getNetwork()).chainId + ) + + fixedDDO = { ...genericAsset } /// ``` /// Now we are going to update the ddo and set the did /// ```Typescript - DDO.chainId = await web3.eth.getChainId() - DDO.id = + + fixedDDO.chainId = (await publisherAccount.provider.getNetwork()).chainId + fixedDDO.id = 'did:op:' + - SHA256(web3.utils.toChecksumAddress(freNftAddress) + DDO.chainId.toString(10)) - DDO.nftAddress = freNftAddress + SHA256(ethers.utils.getAddress(freNftAddress) + fixedDDO.chainId.toString(10)) + fixedDDO.nftAddress = freNftAddress /// ``` /// Next, let's encrypt the file(s) using provider /// ```Typescript ASSET_URL.datatokenAddress = freDatatokenAddress ASSET_URL.nftAddress = freNftAddress - const encryptedFiles = await ProviderInstance.encrypt( + fixedDDO.services[0].files = await ProviderInstance.encrypt( ASSET_URL, - DDO.chainId, + fixedDDO.chainId, providerUrl ) - DDO.services[0].files = await encryptedFiles - DDO.services[0].datatokenAddress = freDatatokenAddress + fixedDDO.services[0].datatokenAddress = freDatatokenAddress /// ``` /// Now let's console log the DID to check everything is working /// ```Typescript - console.log(`DID: ${DDO.id}`) + console.log(`DID: ${fixedDDO.id}`) - const providerResponse = await ProviderInstance.encrypt(DDO, DDO.chainId, providerUrl) + const providerResponse = await ProviderInstance.encrypt( + fixedDDO, + fixedDDO.chainId, + providerUrl + ) const encryptedDDO = await providerResponse - const metadataHash = getHash(JSON.stringify(DDO)) + const isAssetValid: ValidateMetadata = await aquarius.validate(fixedDDO) + assert(isAssetValid.valid === true, 'Published asset is not valid') await nft.setMetadata( freNftAddress, - publisherAccount, + await publisherAccount.getAddress(), 0, providerUrl, '', - '0x2', + ethers.utils.hexlify(2), encryptedDDO, - '0x' + metadataHash + isAssetValid.hash ) }) /// ``` it('6.3 Marketplace displays fixed rate asset for sale', async () => { /// ```Typescript - const fixedRate = new FixedRateExchange(freAddress, web3) + const fixedRate = new FixedRateExchange(freAddress, publisherAccount) const oceanAmount = await ( await fixedRate.calcBaseInGivenDatatokensOut(freId, '1') ).baseTokenAmount @@ -392,49 +431,79 @@ describe('Marketplace flow tests', async () => { }) /// /// ``` - it('6.4 Consumer buys a fixed rate asset data asset, and downloads it', async () => { + /// ## 7. Consume a fixed rate asset data asset + + it('7.1 Consumer buys a fixed rate asset data asset, and downloads it', async () => { /// ```Typescript - const datatoken = new Datatoken(web3) + datatoken = new Datatoken(publisherAccount) const DATATOKEN_AMOUNT = '10000' - await datatoken.mint(freDatatokenAddress, publisherAccount, DATATOKEN_AMOUNT) + await datatoken.mint( + freDatatokenAddress, + await publisherAccount.getAddress(), + DATATOKEN_AMOUNT + ) - const consumerETHBalance = await web3.eth.getBalance(consumerAccount) + const consumerBalance = await provider.getBalance(await consumerAccount.getAddress()) + const consumerETHBalance = ethers.utils.formatEther(consumerBalance) /// ``` /// 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) + let consumerOCEANBalance = await balance( + consumerAccount, + addresses.Ocean, + await consumerAccount.getAddress() + ) console.log(`Consumer OCEAN balance before swap: ${consumerOCEANBalance}`) - let consumerDTBalance = await balance(web3, freDatatokenAddress, consumerAccount) + let consumerDTBalance = await balance( + consumerAccount, + freDatatokenAddress, + await consumerAccount.getAddress() + ) 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 /// ```Typescript - await approve(web3, config, consumerAccount, addresses.Ocean, freAddress, '100') await approve( - web3, + consumerAccount, config, + await consumerAccount.getAddress(), + addresses.Ocean, + freAddress, + '100' + ) + await approve( publisherAccount, + config, + await publisherAccount.getAddress(), freDatatokenAddress, freAddress, DATATOKEN_AMOUNT ) - const fixedRate = new FixedRateExchange(freAddress, web3) + const fixedRate = new FixedRateExchange(freAddress, consumerAccount) /// ``` /// Now we can make the contract call /// ```Typescript - await fixedRate.buyDatatokens(consumerAccount, freId, '1', '2') + await fixedRate.buyDatatokens(freId, '1', '2') - consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount) + consumerOCEANBalance = await balance( + consumerAccount, + addresses.Ocean, + await consumerAccount.getAddress() + ) console.log(`Consumer OCEAN balance after swap: ${consumerOCEANBalance}`) - consumerDTBalance = await balance(web3, freDatatokenAddress, consumerAccount) + consumerDTBalance = await balance( + consumerAccount, + freDatatokenAddress, + await consumerAccount.getAddress() + ) console.log(`Consumer ${FRE_NFT_SYMBOL} balance after swap: ${consumerDTBalance}`) - const resolvedDDO = await aquarius.waitForAqua(DDO.id) + const resolvedDDO = await aquarius.waitForAqua(fixedDDO.id) assert(resolvedDDO, 'Cannot fetch DDO from Aquarius') /// ``` @@ -444,7 +513,7 @@ describe('Marketplace flow tests', async () => { resolvedDDO.id, resolvedDDO.services[0].id, 0, - consumerAccount, + await consumerAccount.getAddress(), providerUrl ) @@ -459,27 +528,29 @@ describe('Marketplace flow tests', async () => { validUntil: initializeData.providerFee.validUntil } + datatoken = new Datatoken(consumerAccount) + /// ``` /// Lets now make the payment /// ```Typescript const tx = await datatoken.startOrder( freDatatokenAddress, - consumerAccount, - consumerAccount, + await consumerAccount.getAddress(), 0, providerFees ) + const orderTx = await tx.wait() + const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted') /// ``` /// Now we can get the url /// ```Typescript const downloadURL = await ProviderInstance.getDownloadUrl( - DDO.id, - consumerAccount, - DDO.services[0].id, + fixedDDO.id, + fixedDDO.services[0].id, 0, - tx.transactionHash, + orderStartedTx.transactionHash, providerUrl, - web3 + consumerAccount ) /// ``` @@ -487,9 +558,17 @@ describe('Marketplace flow tests', async () => { /// ```Typescript console.log(`Download URL: ${downloadURL}`) - consumerOCEANBalance = await balance(web3, addresses.Ocean, consumerAccount) + consumerOCEANBalance = await balance( + consumerAccount, + addresses.Ocean, + await consumerAccount.getAddress() + ) console.log(`Consumer OCEAN balance after order: ${consumerOCEANBalance}`) - consumerDTBalance = await balance(web3, freDatatokenAddress, consumerAccount) + consumerDTBalance = await balance( + consumerAccount, + freDatatokenAddress, + await consumerAccount.getAddress() + ) console.log(`Consumer ${FRE_NFT_SYMBOL} balance after order: ${consumerDTBalance}`) try { @@ -501,11 +580,11 @@ describe('Marketplace flow tests', async () => { }) /// /// ``` - /// ## 7. Publish Data NFT and a Datatoken with a dispenser + /// ## 8. Publish Data NFT and a Datatoken with a dispenser - it('7.1 Publish a dataset (create NFT + Datatoken) with a dispenser', async () => { + it('8.1 Publish a dataset (create NFT + Datatoken) with a dispenser', async () => { /// ```Typescript - const factory = new NftFactory(addresses.ERC721Factory, web3) + const factory = new NftFactory(addresses.ERC721Factory, publisherAccount) const nftParams: NftCreateData = { name: DISP_NFT_NAME, @@ -513,7 +592,7 @@ describe('Marketplace flow tests', async () => { templateIndex: 1, tokenURI: '', transferable: true, - owner: publisherAccount + owner: await publisherAccount.getAddress() } const datatokenParams: DatatokenCreateParams = { @@ -522,7 +601,7 @@ describe('Marketplace flow tests', async () => { feeAmount: '0', paymentCollector: ZERO_ADDRESS, feeToken: ZERO_ADDRESS, - minter: publisherAccount, + minter: await publisherAccount.getAddress(), mpFeeAddress: ZERO_ADDRESS } @@ -534,16 +613,19 @@ describe('Marketplace flow tests', async () => { allowedSwapper: ZERO_ADDRESS } - const tx = await factory.createNftWithDatatokenWithDispenser( - publisherAccount, + const bundleNFT = await factory.createNftWithDatatokenWithDispenser( nftParams, datatokenParams, dispenserParams ) + const trxReceipt = await bundleNFT.wait() + const nftCreatedEvent = getEventFromTx(trxReceipt, 'NFTCreated') + const tokenCreatedEvent = getEventFromTx(trxReceipt, 'TokenCreated') + const dispenserCreatedEvent = getEventFromTx(trxReceipt, 'DispenserCreated') - dispenserNftAddress = tx.events.NFTCreated.returnValues[0] - dispenserDatatokenAddress = tx.events.TokenCreated.returnValues[0] - dispenserAddress = tx.events.DispenserCreated.returnValues[0] + dispenserNftAddress = nftCreatedEvent.args.newTokenAddress + dispenserDatatokenAddress = tokenCreatedEvent.args.newTokenAddress + dispenserAddress = dispenserCreatedEvent.args.newTokenAddress // double check this /// ``` /// Lets check that we managed to received all of those values without any problems /// ```Typescript @@ -553,59 +635,67 @@ describe('Marketplace flow tests', async () => { }) /// /// ``` - it('7.2 Set metadata in the dispenser NFT', async () => { + it('8.2 Set metadata in the dispenser NFT', async () => { /// ```Typescript - const nft = new Nft(web3) + const nft = new Nft( + publisherAccount, + (await publisherAccount.provider.getNetwork()).chainId + ) /// ``` /// 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 + fixedDDO.chainId = (await publisherAccount.provider.getNetwork()).chainId + fixedDDO.id = + 'did:op:' + + SHA256(ethers.utils.getAddress(dispenserNftAddress) + fixedDDO.chainId.toString(10)) + fixedDDO.nftAddress = dispenserNftAddress /// ``` /// Now we need to encrypt file(s) using provider /// ```Typescript ASSET_URL.datatokenAddress = dispenserDatatokenAddress ASSET_URL.nftAddress = dispenserNftAddress - const encryptedFiles = await ProviderInstance.encrypt( + fixedDDO.services[0].files = await ProviderInstance.encrypt( ASSET_URL, - DDO.chainId, + fixedDDO.chainId, providerUrl ) - DDO.services[0].files = await encryptedFiles - DDO.services[0].datatokenAddress = dispenserDatatokenAddress + fixedDDO.services[0].datatokenAddress = dispenserDatatokenAddress - console.log(`DID: ${DDO.id}`) + console.log(`DID: ${fixedDDO.id}`) - const providerResponse = await ProviderInstance.encrypt(DDO, DDO.chainId, providerUrl) - const encryptedDDO = await providerResponse - const metadataHash = getHash(JSON.stringify(DDO)) + const encryptedDDO = await ProviderInstance.encrypt( + fixedDDO, + fixedDDO.chainId, + providerUrl + ) + const isAssetValid: ValidateMetadata = await aquarius.validate(fixedDDO) + assert(isAssetValid.valid === true, 'Published asset is not valid') await nft.setMetadata( dispenserNftAddress, - publisherAccount, + await publisherAccount.getAddress(), 0, providerUrl, '', - '0x2', + ethers.utils.hexlify(2), encryptedDDO, - '0x' + metadataHash + isAssetValid.hash ) }) /// /// ``` - it('7.3 Consumer gets a dispenser data asset, and downloads it', async () => { + /// ## 9. Consume a dispenser data asset + + it('9.1 Consumer gets a dispenser data asset, and downloads it', async () => { /// ```Typescript - const datatoken = new Datatoken(web3) - const dispenser = new Dispenser(addresses.Dispenser, web3) + datatoken = new Datatoken(publisherAccount) + const dispenser = new Dispenser(addresses.Dispenser, consumerAccount) let consumerDTBalance = await balance( - web3, + consumerAccount, dispenserDatatokenAddress, - consumerAccount + await consumerAccount.getAddress() ) console.log( `Consumer ${DISP_NFT_SYMBOL} balance before dispense: ${consumerDTBalance}` @@ -613,18 +703,24 @@ describe('Marketplace flow tests', async () => { await dispenser.dispense( dispenserDatatokenAddress, - consumerAccount, '1', - consumerAccount + await consumerAccount.getAddress() ) - consumerDTBalance = await balance(web3, dispenserDatatokenAddress, consumerAccount) + consumerDTBalance = await balance( + consumerAccount, + dispenserDatatokenAddress, + await consumerAccount.getAddress() + ) console.log( `Consumer ${DISP_NFT_SYMBOL} balance after dispense: ${consumerDTBalance}` ) - const resolvedDDO = await aquarius.waitForAqua(DDO.id) + const resolvedDDO = await aquarius.waitForAqua(fixedDDO.id) assert(resolvedDDO, 'Cannot fetch DDO from Aquarius') + + datatoken = new Datatoken(consumerAccount) + /// ``` /// At this point we need to encrypt file(s) using provider /// ```Typescript @@ -632,7 +728,7 @@ describe('Marketplace flow tests', async () => { resolvedDDO.id, resolvedDDO.services[0].id, 0, - consumerAccount, + await consumerAccount.getAddress(), providerUrl ) @@ -651,29 +747,33 @@ describe('Marketplace flow tests', async () => { /// ```Typescript const tx = await datatoken.startOrder( dispenserDatatokenAddress, - consumerAccount, - consumerAccount, + await consumerAccount.getAddress(), 0, providerFees ) + const orderTx = await tx.wait() + const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted') /// ``` /// Now we can get the download URL /// ```Typescript const downloadURL = await ProviderInstance.getDownloadUrl( - DDO.id, - consumerAccount, - DDO.services[0].id, + fixedDDO.id, + fixedDDO.services[0].id, 0, - tx.transactionHash, + orderStartedTx.transactionHash, providerUrl, - web3 + consumerAccount ) /// ``` /// Let's check we received the download URL ok /// ```Typescript console.log(`Download URL: ${downloadURL}`) - consumerDTBalance = await balance(web3, dispenserDatatokenAddress, consumerAccount) + consumerDTBalance = await balance( + consumerAccount, + dispenserDatatokenAddress, + await consumerAccount.getAddress() + ) console.log(`Consumer ${DISP_NFT_SYMBOL} balance after order: ${consumerDTBalance}`) try { @@ -685,7 +785,7 @@ describe('Marketplace flow tests', async () => { }) /// /// ``` - /// ## 8. Using ERC725 Key-Value Store + /// ## 10. 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). @@ -698,33 +798,40 @@ describe('Marketplace flow tests', async () => { /// 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('10.1 Add key-value pair to data NFT', async () => { /// Let's start by using the `setData` method to update the nft key value store with some data /// ```Typescript - const nft = new Nft(web3) + const nft = new Nft(publisherAccount) const data = 'SomeData' try { - await nft.setData(freNftAddress, publisherAccount, '1', data) + await nft.setData( + freNftAddress, + await publisherAccount.getAddress(), + '0x1234', + data + ) } catch (e) { + console.log('e = ', 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. - /// ### 8.2 get the key-value pair data from the NFT' + /// ### 10.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 try { - const response = await nft.getData(freNftAddress, '1') + const response = await nft.getData(freNftAddress, '0x1234') console.log('getData response: ', response) assert( response === data, 'Wrong data received when getting data from NFT ERC725 key value store' ) } catch (e) { + console.log('e = ', e) assert.fail('Failed to get data from NFT ERC725 key value store', e) } /// ``` diff --git a/test/integration/ComputeExamples.test.ts b/test/integration/ComputeExamples.test.ts index eb303d83..bbe8c033 100644 --- a/test/integration/ComputeExamples.test.ts +++ b/test/integration/ComputeExamples.test.ts @@ -2,18 +2,18 @@ /// 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. [Import dependencies and add variables and constants](#-import-dependencies-and-add-variables-and-constants) +/// 0. [Prerequisites](#0-prerequisites) +/// 1. [Initialize services](#1-initialize-services) +/// 2. [Create a new node.js project](#2-create-a-new-nodejs-project-with-typescript) +/// 3. [Install dependencies](#3-install-dependencies) +/// 4. [Import dependencies and add variables and constants](#4-import-dependencies-and-add-variables-constants-and-helper-methods) /// 5. [Initialize accounts and deploy contracts](#-initialize-accounts-and-deploy-contracts) -/// 6. [Publish a dataset and an algorithm](#-publish-a-dataset-data-nft-and-datatoken) -/// 7. [Resolve published datasets and algorithms](#-resolve-published-datasets-and-algorithms) -/// 8. [Send datatokens to consumer](#-send-datatokens-to-consumer) -/// 9. [Consumer fetches compute environment](#-consumer-starts-a-compute-job-using-a-free-c2D-environment) -/// 10. [Consumer starts a compute job using a free C2D environment](#-consumer-starts-a-compute-job-using-a-free-c2D-environment) -/// 11. [Check compute status and get download compute results url](#-check-compute-status-and-get-download-compute-results-url) +/// 6. [Publish a dataset and an algorithm](#6-publish-assets-dataset-and-algorithm) +/// 7. [Resolve published datasets and algorithms](#7-resolve-assets) +/// 8. [Send datatokens to consumer](#8-send-datatokens-to-consumer) +/// 9. [Consumer fetches compute environment](#9-get-compute-environments) +/// 10. [Consumer starts a compute job using a free C2D environment](#10-consumer-starts-a-compute-job) +/// 11. [Check compute status and get download compute results url](#11-check-compute-status-and-get-download-compute-results-url) /// Let's go through each step. @@ -104,7 +104,7 @@ /// Install dependencies running the following command in your terminal: /// ```bash -/// npm install @oceanprotocol/lib crypto-js web3 web3-utils typescript @types/node ts-node +/// npm install @oceanprotocol/lib crypto-js ethers typescript @types/node ts-node /// ``` /// ## 4. Import dependencies and add variables, constants and helper methods @@ -120,8 +120,7 @@ import fs from 'fs' import { homedir } from 'os' import { assert } from 'chai' import { SHA256 } from 'crypto-js' -import Web3 from 'web3' -import { AbiItem } from 'web3-utils' +import { ethers, providers, Signer } from 'ethers' import { ProviderInstance, Aquarius, @@ -141,12 +140,12 @@ import { DDO, NftCreateData, DatatokenCreateParams, - calculateEstimatedGas, sendTx, configHelperNetworks, - ConfigHelper + ConfigHelper, + getEventFromTx, + amountToUnits } from '../../src' - /// ``` /// ### 4.2. Constants and variables @@ -260,13 +259,12 @@ const ALGORITHM_DDO: DDO = { /// Now we define the variables which we will need later /// ```Typescript -let web3: Web3 let config: Config -let aquarius: Aquarius +let aquariusInstance: Aquarius let datatoken: Datatoken let providerUrl: string -let publisherAccount: string -let consumerAccount: string +let publisherAccount: Signer +let consumerAccount: Signer let addresses let computeEnvs @@ -287,16 +285,17 @@ let computeJobId: string async function createAsset( name: string, symbol: string, - owner: string, + owner: Signer, assetUrl: Files, ddo: DDO, providerUrl: string ) { - const nft = new Nft(web3) - const Factory = new NftFactory(addresses.ERC721Factory, web3) + const nft = new Nft(owner, (await owner.provider.getNetwork()).chainId) + + const nftFactory = new NftFactory(addresses.ERC721Factory, owner) + + const chain = (await owner.provider.getNetwork()).chainId - // Now we update the DDO and set the right did - const chain = await web3.eth.getChainId() ddo.chainId = parseInt(chain.toString(10)) const nftParamsAsset: NftCreateData = { name, @@ -304,7 +303,7 @@ async function createAsset( templateIndex: 1, tokenURI: 'aaa', transferable: true, - owner + owner: await owner.getAddress() } const datatokenParams: DatatokenCreateParams = { templateIndex: 1, @@ -312,45 +311,41 @@ async function createAsset( feeAmount: '0', paymentCollector: ZERO_ADDRESS, feeToken: ZERO_ADDRESS, - minter: owner, + minter: await owner.getAddress(), mpFeeAddress: ZERO_ADDRESS } - // Now we can make the contract call createNftWithDatatoken - const result = await Factory.createNftWithDatatoken( - owner, + + const bundleNFT = await nftFactory.createNftWithDatatoken( nftParamsAsset, datatokenParams ) - const nftAddress = result.events.NFTCreated.returnValues[0] - const datatokenAddressAsset = result.events.TokenCreated.returnValues[0] - ddo.nftAddress = web3.utils.toChecksumAddress(nftAddress) + const trxReceipt = await bundleNFT.wait() + // events have been emitted + const nftCreatedEvent = getEventFromTx(trxReceipt, 'NFTCreated') + const tokenCreatedEvent = getEventFromTx(trxReceipt, 'TokenCreated') - // Next we encrypt the file or files using Ocean Provider. The provider is an off chain proxy built specifically for this task + const nftAddress = nftCreatedEvent.args.newTokenAddress + const datatokenAddressAsset = tokenCreatedEvent.args.newTokenAddress + // create the files encrypted string assetUrl.datatokenAddress = datatokenAddressAsset - assetUrl.nftAddress = ddo.nftAddress - let providerResponse = await ProviderInstance.encrypt(assetUrl, chain, providerUrl) - ddo.services[0].files = await providerResponse + assetUrl.nftAddress = nftAddress + ddo.services[0].files = await ProviderInstance.encrypt(assetUrl, chain, providerUrl) ddo.services[0].datatokenAddress = datatokenAddressAsset - ddo.services[0].serviceEndpoint = providerUrl + ddo.services[0].serviceEndpoint = 'http://172.15.0.4:8030' // put back proviederUrl - // Next we update ddo and set the right did - ddo.nftAddress = web3.utils.toChecksumAddress(nftAddress) - ddo.id = - 'did:op:' + SHA256(web3.utils.toChecksumAddress(nftAddress) + chain.toString(10)) - providerResponse = await ProviderInstance.encrypt(ddo, chain, providerUrl) - const encryptedResponse = await providerResponse - const validateResult = await aquarius.validate(ddo) - - // Next you can check if if the ddo is valid by checking if validateResult.valid returned true + ddo.nftAddress = nftAddress + ddo.id = 'did:op:' + SHA256(ethers.utils.getAddress(nftAddress) + chain.toString(10)) + const encryptedResponse = await ProviderInstance.encrypt(ddo, chain, providerUrl) + const validateResult = await aquariusInstance.validate(ddo) await nft.setMetadata( nftAddress, - owner, + await owner.getAddress(), 0, - providerUrl, + 'http://172.15.0.4:8030', // put back proviederUrl '', - '0x2', + ethers.utils.hexlify(2), encryptedResponse, validateResult.hash ) @@ -363,7 +358,7 @@ async function createAsset( async function handleOrder( order: ProviderComputeInitialize, datatokenAddress: string, - payerAccount: string, + payerAccount: Signer, consumerAccount: string, serviceIndex: number, consumeMarkerFee?: ConsumeMarketFee @@ -375,9 +370,9 @@ async function handleOrder( */ if (order.providerFee && order.providerFee.providerFeeAmount) { await approveWei( - web3, - config, payerAccount, + config, + await payerAccount.getAddress(), order.providerFee.providerFeeToken, datatokenAddress, order.providerFee.providerFeeAmount @@ -387,21 +382,23 @@ async function handleOrder( if (!order.providerFee) return order.validOrder const tx = await datatoken.reuseOrder( datatokenAddress, - payerAccount, order.validOrder, order.providerFee ) - return tx.transactionHash + const reusedTx = await tx.wait() + const orderReusedTx = getEventFromTx(reusedTx, 'OrderReused') + return orderReusedTx.transactionHash } const tx = await datatoken.startOrder( datatokenAddress, - payerAccount, consumerAccount, serviceIndex, order.providerFee, consumeMarkerFee ) - return tx.transactionHash + const orderTx = await tx.wait() + const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted') + return orderStartedTx.transactionHash } /// ``` @@ -413,9 +410,17 @@ describe('Compute-to-data example tests', async () => { /// We need to load the configuration. Add the following code into your `run(){ }` function /// ```Typescript before(async () => { - web3 = new Web3(process.env.NODE_URI || configHelperNetworks[1].nodeUri) - config = new ConfigHelper().getConfig(await web3.eth.getChainId()) + const provider = new providers.JsonRpcProvider( + process.env.NODE_URI || configHelperNetworks[1].nodeUri + ) + publisherAccount = (await provider.getSigner(0)) as Signer + consumerAccount = (await provider.getSigner(1)) as Signer + const config = new ConfigHelper().getConfig( + parseInt(String((await publisherAccount.provider.getNetwork()).chainId)) + ) config.providerUri = process.env.PROVIDER_URL || config.providerUri + aquariusInstance = new Aquarius(config?.metadataCacheUri) + providerUrl = config?.providerUri addresses = JSON.parse( // eslint-disable-next-line security/detect-non-literal-fs-filename fs.readFileSync( @@ -424,37 +429,24 @@ describe('Compute-to-data example tests', async () => { 'utf8' ) ).development - aquarius = new Aquarius(config.metadataCacheUri) - providerUrl = config.providerUri - datatoken = new Datatoken(web3) + /// ``` /// As we go along it's a good idea to console log the values so that you check they are right. At the end of your `run(){ ... }` function add the following logs: /// ```Typescript console.log(`Aquarius URL: ${config.metadataCacheUri}`) console.log(`Provider URL: ${providerUrl}`) console.log(`Deployed contracts address: ${addresses}`) - }) /// - /// ``` - - /// Now at the end of your compute.ts file call you `run()` function. Next, let's compile the file with the `tsc` command in the console and run `node dist/compute.js`. - /// If everything is working you should see the logs in the console and no errors. - /// ## 5. Initialize accounts - it('5.1 Initialize accounts', async () => { - /// We will use all of the following code snippets in the same way. Add the code snippet and the logs to the end of your `run(){ ... }` function as well as the logs. - /// Then compile your file with the `tsc` command and run it with `node dist/compute.js` - /// ```Typescript - const accounts = await web3.eth.getAccounts() - publisherAccount = accounts[0] - consumerAccount = accounts[1] - /// ``` - /// 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}`) }) /// /// ``` - it('5.2 Mint OCEAN to publisher account', async () => { + /// Now at the end of your compute.ts file call you `run()` function. Next, let's compile the file with the `tsc` command in the console and run `node dist/compute.js`. + /// If everything is working you should see the logs in the console and no errors. + /// We will use all of the following code snippets in the same way. Add the code snippet and the logs to the end of your `run(){ ... }` function as well as the logs. + /// Then compile your file with the `tsc` command and run it with `node dist/compute.js` + + it('5.1 Mint OCEAN to publisher account', async () => { /// You can skip this step if you are running your script against a remote network, /// you need to mint oceans to mentioned accounts only if you are using barge to test your script @@ -472,29 +464,33 @@ describe('Compute-to-data example tests', async () => { stateMutability: 'nonpayable', type: 'function' } - ] as AbiItem[] - const tokenContract = new web3.eth.Contract(minAbi, addresses.Ocean) - const estGas = await calculateEstimatedGas( - publisherAccount, - tokenContract.methods.mint, - publisherAccount, - web3.utils.toWei('1000') + ] + + const tokenContract = new ethers.Contract(addresses.Ocean, minAbi, publisherAccount) + const estGasPublisher = await tokenContract.estimateGas.mint( + await publisherAccount.getAddress(), + amountToUnits(null, null, '1000', 18) ) await sendTx( + estGasPublisher, publisherAccount, - estGas, - web3, 1, - tokenContract.methods.mint, - publisherAccount, - web3.utils.toWei('1000') + tokenContract.mint, + await publisherAccount.getAddress(), + amountToUnits(null, null, '1000', 18) ) }) /// /// ``` - it('5.3 Send some OCEAN to consumer account', async () => { + it('5.2 Send some OCEAN to consumer account', async () => { /// ```Typescript - transfer(web3, config, publisherAccount, addresses.Ocean, consumerAccount, '100') + transfer( + publisherAccount, + config, + addresses.Ocean, + await consumerAccount.getAddress(), + '100' + ) }) /// /// ``` @@ -538,8 +534,8 @@ describe('Compute-to-data example tests', async () => { it('7.1 Resolve published datasets and algorithms', async () => { /// ```Typescript - resolvedDatasetDdo = await aquarius.waitForAqua(datasetId) - resolvedAlgorithmDdo = await aquarius.waitForAqua(algorithmId) + resolvedDatasetDdo = await aquariusInstance.waitForAqua(datasetId) + resolvedAlgorithmDdo = await aquariusInstance.waitForAqua(algorithmId) /// ``` ///