1
0
mirror of https://github.com/oceanprotocol/docs.git synced 2024-11-26 19:49:26 +01:00

update consume and configuration code example

This commit is contained in:
Bogdan Fazakas 2023-08-17 16:16:01 +03:00
parent 501d17d055
commit 862f0b0291
2 changed files with 136 additions and 117 deletions

View File

@ -26,6 +26,7 @@ The below tabs show partially filled `.env` file content for some of the support
{% tabs %} {% tabs %}
{% tab title="Mainnet" %} {% tab title="Mainnet" %}
{% code title=".env" %} {% code title=".env" %}
```bash ```bash
# Mandatory environment variables # Mandatory environment variables
@ -38,11 +39,13 @@ PRIVATE_KEY=<secret>
AQUARIUS_URL=https://v4.aquarius.oceanprotocol.com/ AQUARIUS_URL=https://v4.aquarius.oceanprotocol.com/
PROVIDER_URL=https://v4.provider.oceanprotocol.com PROVIDER_URL=https://v4.provider.oceanprotocol.com
``` ```
{% endcode %} {% endcode %}
{% endtab %} {% endtab %}
{% tab title="Polygon" %} {% tab title="Polygon" %}
{% code title=".env" %} {% code title=".env" %}
```bash ```bash
# Mandatory environment variables # Mandatory environment variables
@ -55,11 +58,13 @@ PRIVATE_KEY=<secret>
AQUARIUS_URL=https://v4.aquarius.oceanprotocol.com/ AQUARIUS_URL=https://v4.aquarius.oceanprotocol.com/
PROVIDER_URL=https://v4.provider.oceanprotocol.com PROVIDER_URL=https://v4.provider.oceanprotocol.com
``` ```
{% endcode %} {% endcode %}
{% endtab %} {% endtab %}
{% tab title="Local (using Barge)" %} {% tab title="Local (using Barge)" %}
{% code title=".env" %} {% code title=".env" %}
```bash ```bash
# Mandatory environment variables # Mandatory environment variables
OCEAN_NETWORK=development OCEAN_NETWORK=development
@ -70,6 +75,7 @@ PROVIDER_URL=http://172.15.0.4:8030
# Replace PRIVATE_KEY if needed # Replace PRIVATE_KEY if needed
PRIVATE_KEY=0xc594c6e5def4bab63ac29eed19a134c130388f74f019bc74b8f4389df2837a58 PRIVATE_KEY=0xc594c6e5def4bab63ac29eed19a134c130388f74f019bc74b8f4389df2837a58
``` ```
{% endcode %} {% endcode %}
{% endtab %} {% endtab %}
{% endtabs %} {% endtabs %}
@ -87,10 +93,12 @@ Let's install Ocean.js library into your current project by running:
{% tabs %} {% tabs %}
{% tab title="Terminal" %} {% tab title="Terminal" %}
{% code overflow="wrap" %} {% code overflow="wrap" %}
```bash ```bash
npm init npm init
npm i @oceanprotocol/lib@latest dotenv crypto-js ethers@5.7.4 @truffle/hdwallet-provider npm i @oceanprotocol/lib@latest dotenv crypto-js ethers@5.7.4 @truffle/hdwallet-provider
``` ```
{% endcode %} {% endcode %}
{% endtab %} {% endtab %}
{% endtabs %} {% endtabs %}
@ -104,69 +112,66 @@ Create the configuration file in the working directory i.e. at the same path whe
{% tabs %} {% tabs %}
{% tab title="config.js" %} {% tab title="config.js" %}
{% code title="config.js" %} {% code title="config.js" %}
```javascript ```javascript
require('dotenv').config(); require("dotenv").config();
const { Aquarius, ZERO_ADDRESS, ConfigHelper, configHelperNetworks } = require('@oceanprotocol/lib'); const {
const { providers } = require('ethers') Aquarius,
const ethers = require('ethers'); ConfigHelper,
async function oceanConfig(){ configHelperNetworks,
} = require("@oceanprotocol/lib");
const ethers = require("ethers");
import fs from "fs";
import { homedir } from "os";
// Get configuration for the given network async function oceanConfig() {
const provider = new providers.JsonRpcProvider( const provider = new ethers.providers.JsonRpcProvider(
process.env.OCEAN_NETWORK_URL || configHelperNetworks[1].nodeUri process.env.OCEAN_NETWORK_URL || configHelperNetworks[1].nodeUri
) );
const publisherAccount = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
const ethersProvider = new ethers.Wallet( let oceanConfig = new ConfigHelper().getConfig(
process.env.PRIVATE_KEY, parseInt(String((await publisherAccount.provider.getNetwork()).chainId))
provider );
); const aquarius = new Aquarius(oceanConfig?.metadataCacheUri);
const publisherAccount = wallet.connect(provider);
let oceanConfig = new ConfigHelper().getConfig( // If using local development environment, read the addresses from local file.
parseInt(String((await publisherAccount.provider.getNetwork()).chainId)) // The local deployment address file can be generated using barge.
) if (process.env.OCEAN_NETWORK === "development") {
const aquarius = new Aquarius(oceanConfig?.metadataCacheUri) const addresses = JSON.parse(
// eslint-disable-next-line security/detect-non-literal-fs-filename
fs.readFileSync(
process.env.ADDRESS_FILE ||
`${homedir}/.ocean/ocean-contracts/artifacts/address.json`,
"utf8"
)
).development;
// If using local development environment, read the addresses from local file. oceanConfig = {
// The local deployment address file can be generated using barge. ...oceanConfig,
if (process.env.OCEAN_NETWORK === 'development') { oceanTokenAddress: addresses.Ocean,
const addresses = JSON.parse( fixedRateExchangeAddress: addresses.FixedPrice,
// eslint-disable-next-line security/detect-non-literal-fs-filename dispenserAddress: addresses.Dispenser,
fs.readFileSync( nftFactoryAddress: addresses.ERC721Factory,
process.env.ADDRESS_FILE || opfCommunityFeeCollector: addresses.OPFCommunityFeeCollector,
`${homedir}/.ocean/ocean-contracts/artifacts/address.json`, };
'utf8' }
)
).development
oceanConfig = { oceanConfig = {
...oceanConfig, ...oceanConfig,
oceanTokenAddress: addresses.Ocean, publisherAccount: publisherAccount,
poolTemplateAddress: addresses.poolTemplate, consumerAccount: publisherAccount,
fixedRateExchangeAddress: addresses.FixedPrice, aquarius: aquarius,
dispenserAddress: addresses.Dispenser, };
nftFactoryAddress: addresses.ERC721Factory,
sideStakingAddress: addresses.Staking,
opfCommunityFeeCollector: addresses.OPFCommunityFeeCollector
};
}
oceanConfig = { return oceanConfig;
...oceanConfig, }
publisherAccount: publisherAccount,
consumerAccount: consumerAccount,
stakerAccount: stakerAccount,
aquarius: aquarius
};
return oceanConfig
};
module.exports = { module.exports = {
oceanConfig oceanConfig,
} };
``` ```
{% endcode %} {% endcode %}
{% endtab %} {% endtab %}
{% endtabs %} {% endtabs %}

View File

@ -18,13 +18,13 @@ Later on, when working with the ocean.js library, you can use this order transac
#### Prerequisites #### Prerequisites
* [Obtain an API key](../get-api-keys-for-blockchain-access.md) - [Obtain an API key](../get-api-keys-for-blockchain-access.md)
* [Set up the .env file](configuration.md#create-a-env-file) - [Set up the .env file](configuration.md#create-a-env-file)
* [Install the dependencies](configuration.md#setup-dependencies) - [Install the dependencies](configuration.md#setup-dependencies)
* [Create a configuration file](configuration.md#create-a-configuration-file) - [Create a configuration file](configuration.md#create-a-configuration-file)
{% hint style="info" %} {% hint style="info" %}
The variables **AQUARIUS\_URL** and **PROVIDER\_URL** should be set correctly in `.env` file The variables **AQUARIUS_URL** and **PROVIDER_URL** should be set correctly in `.env` file
{% endhint %} {% endhint %}
#### Create a script to consume an asset #### Create a script to consume an asset
@ -32,76 +32,90 @@ The variables **AQUARIUS\_URL** and **PROVIDER\_URL** should be set correctly in
Create a new file in the same working directory where the configuration file (`config.js`) and `.env` files are present, and copy the code as listed below. Create a new file in the same working directory where the configuration file (`config.js`) and `.env` files are present, and copy the code as listed below.
<pre class="language-javascript" data-overflow="wrap"><code class="lang-javascript">// Note: Make sure .env file and config.js are created and setup correctly <pre class="language-javascript" data-overflow="wrap"><code class="lang-javascript">// Note: Make sure .env file and config.js are created and setup correctly
const { oceanConfig } = require('./config.js'); const { oceanConfig } = require("./config.js");
const { ZERO_ADDRESS, NftFactory, getHash, Nft } = require ('@oceanprotocol/lib'); const {
ZERO_ADDRESS,
NftFactory,
getHash,
ProviderFees,
Datatoken,
ProviderInstance,
Nft,
FixedRateExchange,
approve
} = require("@oceanprotocol/lib");
// replace the did here // replace the did here
const did = "did:op:a419f07306d71f3357f8df74807d5d12bddd6bcd738eb0b461470c64859d6f0f"; const did = "did:op:a419f07306d71f3357f8df74807d5d12bddd6bcd738eb0b461470c64859d6f0f";
// This function takes did as a parameter and updates the data NFT information // This function takes did as a parameter and updates the data NFT information
const consumeAsset = async (did) => { const consumeAsset = async (did) => {
const consumer = await oceanConfig.consumerAccount.getAddress();
const consumer = await oceanConfig.consumerAccount.getAddress();
// Fetch ddo from Aquarius
const asset = await await oceanConfig.aquarius.resolve(did);
const nft = new Nft(oceanConfig.consumerAccount); // Fetch ddo from Aquarius
const asset = await await oceanConfig.aquarius.resolve(did);
await approve(
consumerAccount,
config,
await consumerAccount.getAddress(),
addresses.Ocean,
freAddress,
'1'
)
const fixedRate = new FixedRateExchange(fixedRateExchangeAddress, consumerAccount)
const tx = await fixedRate.buyDatatokens(fixedRateId, '1', '2')
<strong> const initializeData = await ProviderInstance.initialize(
</strong> resolvedDDO.id,
resolvedDDO.services[0].id,
0,
await consumerAccount.getAddress(),
providerUrl
)
const providerFees: ProviderFees = { const nft = new Nft(consumer);
providerFeeAddress: initializeData.providerFee.providerFeeAddress,
providerFeeToken: initializeData.providerFee.providerFeeToken,
providerFeeAmount: initializeData.providerFee.providerFeeAmount,
v: initializeData.providerFee.v,
r: initializeData.providerFee.r,
s: initializeData.providerFee.s,
providerData: initializeData.providerFee.providerData,
validUntil: initializeData.providerFee.validUntil
}
datatoken = new Datatoken(consumerAccount) await approve(
Error,
const tx = await datatoken.startOrder( oceanConfig,
freDatatokenAddress, await consumer.getAddress(),
await consumerAccount.getAddress(), oceanConfig.Ocean,
0, oceanConfig.fixedRateExchangeAddress,
providerFees "1"
) );
const orderTx = await tx.wait()
const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted')
const downloadURL = await ProviderInstance.getDownloadUrl( const fixedRate = new FixedRateExchange(
fixedDDO.id, oceanConfig.fixedRateExchangeAddress,
fixedDDO.services[0].id, consumer
0, );
orderStartedTx.transactionHash,
providerUrl,
consumerAccount
<strong> )
</strong> console.log(`Resolved asset did [${updatedAsset.id}]from aquarius.`);
console.log(`Updated asset state: [${updatedAsset.nft.state}].`);
const txBuyDt = await fixedRate.buyDatatokens(
oceanConfig.fixedRateId,
"1",
"2"
);
const initializeData = await ProviderInstance.initialize(
asset.id,
asset.services[0].id,
0,
await consumer.getAddress(),
oceanConfig.providerUri
);
const providerFees: ProviderFees = {
providerFeeAddress: initializeData.providerFee.providerFeeAddress,
providerFeeToken: initializeData.providerFee.providerFeeToken,
providerFeeAmount: initializeData.providerFee.providerFeeAmount,
v: initializeData.providerFee.v,
r: initializeData.providerFee.r,
s: initializeData.providerFee.s,
providerData: initializeData.providerFee.providerData,
validUntil: initializeData.providerFee.validUntil,
};
const datatoken = new Datatoken(consumer);
const tx = await datatoken.startOrder(
oceanConfig.fixedRateExchangeAddress,
await consumer.getAddress(),
0,
providerFees
);
const orderTx = await tx.wait();
const orderStartedTx = getEventFromTx(orderTx, "OrderStarted");
const downloadURL = await ProviderInstance.getDownloadUrl(
asset.id,
asset.services[0].id,
0,
orderTx.transactionHash,
oceanConfig.providerUri,
consumer
);
}; };
// Call setMetadata(...) function defined above // Call setMetadata(...) function defined above