Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
326 changes: 326 additions & 0 deletions Cheatsheet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,326 @@
# Ocean.js Cheatsheet

## Prerequisites
- Git, Node.js, Docker
- Install Git: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
- Node.js: https://nodejs.org/en/download/
- Docker: https://docs.docker.com/get-docker/

### Installation & Usage

```bash
npm init
npm install @oceanprotocol/lib crypto-js [email protected] typescript @types/node ts-node
```

### Configuration

```bash
export NODE_URL='https://compute1.oceanprotocol.com'
export PRIVATE_KEY=<replace_me>
export RPC=<replace_me>
```

### Publish Flow

1. Define DDO object
```javascript

const genericAsset: DDO = {
'@context': ['https://w3id.org/did/v1'],
id: 'did:op',
version: '4.1.0',
chainId: 8996,
nftAddress: '0x0',
metadata: {
created: '2021-12-20T14:35:20Z',
updated: '2021-12-20T14:35:20Z',
type: 'dataset',
name: 'dataset-name',
description: 'Ocean protocol test dataset description',
author: 'oceanprotocol-team',
license: 'MIT',
tags: ['white-papers'],
additionalInformation: { 'test-key': 'test-value' },
links: ['http://data.ceda.ac.uk/badc/ukcp09/']
},
services: [
{
id: 'db164c1b981e4d2974e90e61bda121512e6909c1035c908d68933ae4cfaba6b0',
type: 'access',
files: '',
datatokenAddress: '0xa15024b732A8f2146423D14209eFd074e61964F3',
serviceEndpoint: 'http://127.0.0.1:8001',
timeout: 0
}
]
}
```
2. Create NFT + datatoken + dispenser/FRE:

```javascript

const { chainId } = await publisherAccount.provider.getNetwork()
const factory = new NftFactory(
addresses.ERC721Factory,
publisherAccount,
Number(chainId)
)

const nftParams: NftCreateData = {
name: FRE_NFT_NAME,
symbol: FRE_NFT_SYMBOL,
templateIndex: 1,
tokenURI: '',
transferable: true,
owner: await publisherAccount.getAddress()
}

const datatokenParams: DatatokenCreateParams = {
templateIndex: 1,
cap: '100000',
feeAmount: '0',
paymentCollector: ZERO_ADDRESS,
feeToken: ZERO_ADDRESS,
minter: await publisherAccount.getAddress(),
mpFeeAddress: ZERO_ADDRESS
}

const freParams: FreCreationParams = {
fixedRateAddress: addresses.FixedPrice,
baseTokenAddress: addresses.Ocean,
owner: await publisherAccount.getAddress(),
marketFeeCollector: await publisherAccount.getAddress(),
baseTokenDecimals: 18,
datatokenDecimals: 18,
fixedRate: '1',
marketFee: '0.001',
allowedConsumer: ZERO_ADDRESS,
withMint: true
}

const bundleNFT = await factory.createNftWithDatatokenWithFixedRate(
nftParams,
datatokenParams,
freParams
)

```
### Consume Flow
As a prerequisite for this flow, publish flow needs to be executed before.
```javascript
const fixedRate = new FixedRateExchange(freAddress, consumerAccount, Number(chainId))
await fixedRate.buyDatatokens(freId, '1', '2')

const resolvedDDO = await aquarius.waitForIndexer(fixedDDO.id)
assert(resolvedDDO, 'Cannot fetch DDO from Aquarius')

// Initialize - obtain proof for ordering assets

const initializeData = await ProviderInstance.initialize(
resolvedDDO.id,
resolvedDDO.services[0].id,
0,
await consumerAccount.getAddress(),
providerUrl
)

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
}
// Starting order after retriving provider fees
const tx = await datatoken.startOrder(
freDatatokenAddress,
await consumerAccount.getAddress(),
0,
providerFees
)
const orderTx = await tx.wait()
const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted')
console.log(`Order started, tx: ${orderStartedTx.transactionHash}`)

const downloadURL = await ProviderInstance.getDownloadUrl(
fixedDDO.id,
fixedDDO.services[0].id,
0,
orderStartedTx.transactionHash,
providerUrl,
consumerAccount
)

// Lets check that the download URL was successfully received
console.log(`Download URL: ${downloadURL}`)

```
For better UX, it is recommended to have installed VSCode extension.
### Get compute environments

```javascript


// Fetch compute envrionments first
const computeEnvs = await ProviderInstance.getComputeEnvironments(providerUrl)

```
For `free start compute` it is not necessary publish flow.


### Free Start Compute

```javascript

// Let's have 5 minute of compute access
const mytime = new Date()
const computeMinutes = 5
mytime.setMinutes(mytime.getMinutes() + computeMinutes)

// Let's prepare the dataset and algorithm assets to be used in the compute job
const assets: ComputeAsset[] = [
{
documentId: resolvedDatasetDdo.id,
serviceId: resolvedDatasetDdo.services[0].id
}
]

const algo: ComputeAlgorithm = {
documentId: resolvedAlgorithmDdo.id,
serviceId: resolvedAlgorithmDdo.services[0].id,
meta: resolvedAlgorithmDdo.metadata.algorithm
}

// Let's start the free compute job
const computeJobs = await ProviderInstance.freeComputeStart(
providerUrl,
consumerAccount,
computeEnv.id,
assets,
algo
)

```

### Paid Start Compute


```javascript


const mytime = new Date()
const computeMinutes = 5
mytime.setMinutes(mytime.getMinutes() + computeMinutes)
const computeValidUntil = Math.floor(mytime.getTime() / 1000)

const resources: ComputeResourceRequest[] = [
{
id: 'cpu',
amount: 2
},
{
id: 'ram',
amount: 1000000000
},
{
id: 'disk',
amount: 0
}
]
const assets: ComputeAsset[] = [
{
documentId: resolvedDatasetDdo.id,
serviceId: resolvedDatasetDdo.services[0].id
}
]
const dtAddressArray = [resolvedDatasetDdo.services[0].datatokenAddress]
const algo: ComputeAlgorithm = {
documentId: resolvedAlgorithmDdo.id,
serviceId: resolvedAlgorithmDdo.services[0].id,
meta: resolvedAlgorithmDdo.metadata.algorithm
}

const providerInitializeComputeResults = await ProviderInstance.initializeCompute(
assets,
algo,
computeEnv.id,
paymentToken,
computeValidUntil,
providerUrl,
consumerAccount,
resources,
Number(chainId)
)
// Initialize payment contract
const escrow = new EscrowContract(
getAddress(providerInitializeComputeResults.payment.escrowAddress),
consumerAccount
)
const amountToDeposit = (providerInitializeComputeResults.payment.amount * 2).toString()
await escrow.verifyFundsForEscrowPayment(
paymentToken,
computeEnv.consumerAddress,
await unitsToAmount(consumerAccount, paymentToken, amountToDeposit),
providerInitializeComputeResults.payment.amount.toString(),
providerInitializeComputeResults.payment.minLockSeconds.toString(),
'10'
)

algo.transferTxId = await handleOrder(
providerInitializeComputeResults.algorithm,
resolvedAlgorithmDdo.services[0].datatokenAddress,
consumerAccount,
computeEnv.consumerAddress,
0
)
for (let i = 0; i < providerInitializeComputeResults.datasets.length; i++) {
assets[i].transferTxId = await handleOrder(
providerInitializeComputeResults.datasets[i],
dtAddressArray[i],
consumerAccount,
computeEnv.consumerAddress,
0
)
}

const computeJobs = await ProviderInstance.computeStart(
providerUrl,
consumerAccount,
computeEnv.id,
assets,
algo,
computeValidUntil,
paymentToken,
resources,
Number(chainId)
)
```

### Get compute job status

```javascript

const jobStatus = await ProviderInstance.computeStatus(
providerUrl,
await consumerAccount.getAddress(),
computeJobId
)
```

### Get download compute results URL

```javascript

const downloadURL = await ProviderInstance.getComputeResultUrl(
providerUrl,
consumerAccount,
computeJobId,
0
)


```
2 changes: 1 addition & 1 deletion ComputeExamples.md
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,7 @@ let's select compute environment which have free and paid resources
},
{
id: 'ram',
amount: 1000000000
amount: 2
},
{
id: 'disk',
Expand Down
2 changes: 1 addition & 1 deletion test/integration/CodeExamples.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
/// Install dependencies running the following command in your terminal:

/// ```bash
/// npm install @oceanprotocol/lib crypto-js ethers@5.7.2 typescript @types/node ts-node
/// npm install @oceanprotocol/lib crypto-js ethers
/// ```

/// ## 4. Import dependencies and add variables and constants
Expand Down Expand Up @@ -531,7 +531,7 @@

console.log(`Provider fee amount: ${providerFees.providerFeeAmount}`)

const approveTx = await approve(

Check warning on line 534 in test/integration/CodeExamples.test.ts

View workflow job for this annotation

GitHub Actions / lint

'approveTx' is assigned a value but never used
consumerAccount,
config,
await consumerAccount.getAddress(),
Expand Down
4 changes: 2 additions & 2 deletions test/integration/ComputeExamples.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
/// Install dependencies running the following command in your terminal:

/// ```bash
/// npm install @oceanprotocol/lib crypto-js ethers@5.7.2 typescript @types/node ts-node
/// npm install @oceanprotocol/lib crypto-js ethers
/// ```

/// ## 4. Import dependencies and add variables, constants and helper methods
Expand Down Expand Up @@ -792,7 +792,7 @@ describe('Compute-to-data example tests', async () => {
},
{
id: 'ram',
amount: 1000000000
amount: 2
},
{
id: 'disk',
Expand Down
6 changes: 3 additions & 3 deletions test/integration/ComputeFlow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@
let resolvedAlgoDdoWith2mTimeout
let resolvedAlgoDdoWithNoTimeout

let freeEnvDatasetTxId

Check warning on line 50 in test/integration/ComputeFlow.test.ts

View workflow job for this annotation

GitHub Actions / lint

'freeEnvDatasetTxId' is assigned a value but never used
let freeEnvAlgoTxId

Check warning on line 51 in test/integration/ComputeFlow.test.ts

View workflow job for this annotation

GitHub Actions / lint

'freeEnvAlgoTxId' is assigned a value but never used
let paidEnvDatasetTxId
let paidEnvAlgoTxId
let computeValidUntil
Expand Down Expand Up @@ -255,7 +255,7 @@
}).timeout(interval + 200)
}

async function waitTillJobEnds(): Promise<number> {

Check warning on line 258 in test/integration/ComputeFlow.test.ts

View workflow job for this annotation

GitHub Actions / lint

'waitTillJobEnds' is defined but never used
return new Promise((resolve) => {
const interval = setInterval(async () => {
const jobStatus = (await ProviderInstance.computeStatus(
Expand Down Expand Up @@ -563,7 +563,7 @@
},
{
id: 'ram',
amount: 1000000000
amount: 2
},
{
id: 'disk',
Expand Down Expand Up @@ -734,7 +734,7 @@
},
{
id: 'ram',
amount: 1000000000
amount: 2
},
{
id: 'disk',
Expand Down Expand Up @@ -823,7 +823,7 @@
},
{
id: 'ram',
amount: 1000000000
amount: 2
},
{
id: 'disk',
Expand Down
Loading