@oceanprotocol/lib 7.0.0-next.4 → 7.0.0-next.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/dist/lib.cjs +1 -1
  2. package/dist/lib.module.mjs +1 -1
  3. package/dist/lib.umd.js +1 -1
  4. package/package.json +8 -5
  5. package/.mocharc.json +0 -8
  6. package/.nvmrc +0 -1
  7. package/CHANGELOG.md +0 -3256
  8. package/Cheatsheet.md +0 -326
  9. package/CodeExamples.md +0 -881
  10. package/ComputeExamples.md +0 -941
  11. package/dist/lib.cjs.map +0 -1
  12. package/dist/lib.module.mjs.map +0 -1
  13. package/dist/lib.umd.js.map +0 -1
  14. package/docs/.nojekyll +0 -1
  15. package/docs/README.md +0 -195
  16. package/docs/classes/Aquarius.md +0 -175
  17. package/docs/classes/Config.md +0 -481
  18. package/docs/classes/ConfigHelper.md +0 -66
  19. package/docs/classes/Datatoken.md +0 -1123
  20. package/docs/classes/Dispenser.md +0 -502
  21. package/docs/classes/Escrow.md +0 -285
  22. package/docs/classes/FixedRateExchange.md +0 -1068
  23. package/docs/classes/Logger.md +0 -191
  24. package/docs/classes/Nft.md +0 -970
  25. package/docs/classes/NftFactory.md +0 -861
  26. package/docs/classes/Provider.md +0 -727
  27. package/docs/classes/Router.md +0 -645
  28. package/docs/classes/SmartContract.md +0 -193
  29. package/docs/classes/SmartContractWithAddress.md +0 -268
  30. package/docs/enums/LogLevel.md +0 -63
  31. package/docs/interfaces/AbiInput.md +0 -63
  32. package/docs/interfaces/AbiItem.md +0 -107
  33. package/docs/interfaces/AbiOutput.md +0 -52
  34. package/docs/interfaces/Arweave.md +0 -32
  35. package/docs/interfaces/Asset.md +0 -227
  36. package/docs/interfaces/AssetDatatoken.md +0 -60
  37. package/docs/interfaces/AssetLastEvent.md +0 -63
  38. package/docs/interfaces/AssetNft.md +0 -105
  39. package/docs/interfaces/AssetPrice.md +0 -47
  40. package/docs/interfaces/ComputeAlgorithm.md +0 -82
  41. package/docs/interfaces/ComputeAsset.md +0 -56
  42. package/docs/interfaces/ComputeEnvFees.md +0 -30
  43. package/docs/interfaces/ComputeEnvFeesStructure.md +0 -20
  44. package/docs/interfaces/ComputeEnvironment.md +0 -177
  45. package/docs/interfaces/ComputeJob.md +0 -173
  46. package/docs/interfaces/ComputeOutput.md +0 -118
  47. package/docs/interfaces/ComputeResourcesPricingInfo.md +0 -30
  48. package/docs/interfaces/ComputeResourcesRequest.md +0 -34
  49. package/docs/interfaces/ComputeResult.md +0 -52
  50. package/docs/interfaces/ConsumeMarketFee.md +0 -41
  51. package/docs/interfaces/Credential.md +0 -30
  52. package/docs/interfaces/Credentials.md +0 -30
  53. package/docs/interfaces/DDO.md +0 -137
  54. package/docs/interfaces/DatatokenCreateParams.md +0 -107
  55. package/docs/interfaces/DatatokenRoles.md +0 -30
  56. package/docs/interfaces/DispenserCreationParams.md +0 -63
  57. package/docs/interfaces/DispenserParams.md +0 -52
  58. package/docs/interfaces/DispenserToken.md +0 -85
  59. package/docs/interfaces/DownloadResponse.md +0 -30
  60. package/docs/interfaces/Event.md +0 -73
  61. package/docs/interfaces/FeesInfo.md +0 -74
  62. package/docs/interfaces/FileInfo.md +0 -118
  63. package/docs/interfaces/Files.md +0 -41
  64. package/docs/interfaces/FixedPriceExchange.md +0 -162
  65. package/docs/interfaces/FreCreationParams.md +0 -118
  66. package/docs/interfaces/FreOrderParams.md +0 -85
  67. package/docs/interfaces/GraphqlQuery.md +0 -69
  68. package/docs/interfaces/Ipfs.md +0 -32
  69. package/docs/interfaces/Metadata.md +0 -193
  70. package/docs/interfaces/MetadataAlgorithm.md +0 -69
  71. package/docs/interfaces/MetadataAndTokenURI.md +0 -107
  72. package/docs/interfaces/MetadataProof.md +0 -52
  73. package/docs/interfaces/NftCreateData.md +0 -74
  74. package/docs/interfaces/NftRoles.md +0 -52
  75. package/docs/interfaces/Operation.md +0 -145
  76. package/docs/interfaces/OrderParams.md +0 -52
  77. package/docs/interfaces/PriceAndFees.md +0 -52
  78. package/docs/interfaces/ProviderComputeInitialize.md +0 -41
  79. package/docs/interfaces/ProviderComputeInitializeResults.md +0 -43
  80. package/docs/interfaces/ProviderFees.md +0 -96
  81. package/docs/interfaces/ProviderInitialize.md +0 -52
  82. package/docs/interfaces/PublisherTrustedAlgorithm.md +0 -47
  83. package/docs/interfaces/PublishingMarketFee.md +0 -41
  84. package/docs/interfaces/Purgatory.md +0 -34
  85. package/docs/interfaces/RunningPlatform.md +0 -30
  86. package/docs/interfaces/SearchQuery.md +0 -67
  87. package/docs/interfaces/Service.md +0 -138
  88. package/docs/interfaces/ServiceComputeOptions.md +0 -63
  89. package/docs/interfaces/ServiceEndpoint.md +0 -41
  90. package/docs/interfaces/Smartcontract-1.md +0 -58
  91. package/docs/interfaces/Stats.md +0 -47
  92. package/docs/interfaces/Template.md +0 -30
  93. package/docs/interfaces/TokenOrder.md +0 -63
  94. package/docs/interfaces/UrlFile.md +0 -71
  95. package/docs/interfaces/UserCustomParameters.md +0 -7
  96. package/docs/interfaces/ValidateMetadata.md +0 -52
  97. package/docs/modules.md +0 -850
  98. package/typedoc.json +0 -4
@@ -1,941 +0,0 @@
1
- # Compute-to-Data (C2D) Code Examples
2
-
3
- Here are the steps:
4
-
5
- 0. [Prerequisites](#0-prerequisites)
6
- 1. [Initialize services](#1-initialize-services)
7
- 2. [Create a new node.js project](#2-create-a-new-nodejs-project-with-typescript)
8
- 3. [Install dependencies](#3-install-dependencies)
9
- 4. [Import dependencies and add variables and constants](#4-import-dependencies-and-add-variables-constants-and-helper-methods)
10
- 5. [Initialize accounts and deploy contracts](#-initialize-accounts-and-deploy-contracts)
11
- 6. [Publish a dataset and an algorithm](#6-publish-assets-dataset-and-algorithm)
12
- 7. [Resolve published datasets and algorithms](#7-resolve-assets)
13
- 8. [Send datatokens to consumer](#8-send-datatokens-to-consumer)
14
- 9. [Consumer fetches compute environment](#9-get-compute-environments)
15
- 10. [Consumer starts a free compute job using a free C2D environment](#10-consumer-starts-a-compute-job)
16
- 11. [Check compute status and get download compute results url](#11-check-compute-status-and-get-download-compute-results-url)
17
- 12. [Consumer starts a paid compute job](#12-consumer-starts-a-paid-compute-job)
18
- 13. [Check paid compute job status and get download compute results URL](#13-check-paid-compute-job-status-and-get-download-compute-results-url)
19
-
20
- Let's go through each step.
21
-
22
- ## 0. Prerequisites
23
- Before we start it is important that you have all of the necessary prerequisites installed on your computer.
24
- - **A Unix based operating system (Linux or Mac)**. If you are a Windows user you can try to run linux inside a virtual machine but this is outside of the scope of this article.
25
- - **Git**. Instructions for installing Git can be found here: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
26
- - **Node.js** can be downloaded from here: https://nodejs.org/en/download/
27
- - **Docker** can be installed from here: https://docs.docker.com/get-docker/. Please note that Docker must run as a non-root user, you can set this up by following these instructions: https://docs.docker.com/engine/install/linux-postinstall/
28
-
29
- ## 1. Initialize services
30
-
31
- Ocean.js uses off-chain services for metadata (Aquarius) and consuming datasets (Provider).
32
-
33
- We start by initializing the services. To do this, we clone the Barge repository and run it. This will run the current default versions of [Aquarius](https://github.com/oceanprotocol/aquarius), [Provider](https://github.com/oceanprotocol/provider), and [Ganache](https://github.com/trufflesuite/ganache) with [our contracts](https://github.com/oceanprotocol/contracts) deployed to it.
34
-
35
- ```bash
36
- git clone https://github.com/oceanprotocol/barge.git
37
- cd barge/
38
- ./start_ocean.sh
39
- ```
40
-
41
- ## 2. Create a new Node.js project with TypeScript
42
-
43
- Start by creating a new Node.js project. Open a new terminal and enter the following commands:
44
-
45
- ```bash
46
- mkdir compute-quickstart
47
- cd compute-quickstart
48
- npm init
49
- # Answer the questions in the command line prompt
50
- touch compute.ts
51
- # On linux press CTRL + D to save
52
- ```
53
-
54
- Next, we need to setup our TypeScript compiler options. Create a new file called `tsconfig.json` in the root of the `compute-quickstart` directory.
55
-
56
- ```bash
57
- touch tsconfig.json
58
- # Copy the following json content into the file, On linux press CTRL + D to save
59
- ```
60
-
61
- ```json
62
- {
63
- "compilerOptions": {
64
- "lib": ["es6", "es7"],
65
- "module": "CommonJS",
66
- "target": "ES5",
67
- "esModuleInterop": true,
68
- "allowSyntheticDefaultImports": true,
69
- "outDir": "./dist/",
70
- "declaration": true,
71
- "declarationDir": "./dist/"
72
- },
73
- "include": [
74
- "compute.ts"
75
- ],
76
- "exclude": [ "node_modules", "dist" ]
77
- }
78
- ```
79
-
80
- Now you can compile your TypeScript project.
81
- If you have TypeScript installed use the following command:
82
-
83
- ```bash
84
- tsc
85
- ```
86
-
87
- If you don't have TypeScript installed you can install it using the command below and then compile using the above command:
88
-
89
- ```bash
90
- npm install -g typescript
91
- ```
92
-
93
- Or if you don't want to install TypeScript use the following command to compile your file:
94
- ```bash
95
- npx tsc compute.ts
96
- ```
97
-
98
- To run your script as we go along, compile the script then you can use the following command:
99
-
100
- ```bash
101
- node dist/compute.js
102
- ```
103
-
104
- ## 3. Install dependencies
105
-
106
- Install dependencies running the following command in your terminal:
107
-
108
- ```bash
109
- npm install @oceanprotocol/lib crypto-js ethers
110
- ```
111
-
112
- ## 4. Import dependencies and add variables, constants and helper methods
113
-
114
- Now open the `compute.ts` file in your text editor.
115
-
116
- ### 4.1. Dependencies
117
-
118
- Start by importing all of the necessary dependencies
119
-
120
- ```Typescript
121
- import fs from 'fs'
122
- import { homedir } from 'os'
123
-
124
- import { ethers, getAddress, JsonRpcProvider, parseEther, Signer, toBeHex } from 'ethers'
125
- import {
126
- ProviderInstance,
127
- Aquarius,
128
- NftFactory,
129
- Datatoken,
130
- Nft,
131
- ZERO_ADDRESS,
132
- transfer,
133
- sleep,
134
- approveWei,
135
- ProviderComputeInitialize,
136
- ConsumeMarketFee,
137
- ComputeAlgorithm,
138
- ComputeAsset,
139
- Config,
140
- StorageObject,
141
- NftCreateData,
142
- DatatokenCreateParams,
143
- sendTx,
144
- configHelperNetworks,
145
- ConfigHelper,
146
- getNodeEndpointConfig,
147
- getEventFromTx,
148
- amountToUnits,
149
- isDefined,
150
- ComputeResourceRequest,
151
- unitsToAmount,
152
- AssetFiles
153
- } from '../../src/index.js'
154
- import crypto from 'crypto-js'
155
- import { DDO } from '@oceanprotocol/ddo-js'
156
- import { EscrowContract } from '../../src/contracts/Escrow.js'
157
- import BigNumber from 'bignumber.js'
158
- const { SHA256 } = crypto
159
- ```
160
-
161
- ### 4.2. Constants and variables
162
-
163
- We will need two files to publish, one as dataset and one as algorithm, so here we define the files that we intend to publish.
164
- ```Typescript
165
- const DATASET_ASSET_URL: StorageObject = {
166
- type: 'url',
167
- url: 'https://raw.githubusercontent.com/oceanprotocol/testdatasets/main/shs_dataset_test.txt',
168
- method: 'GET'
169
- }
170
-
171
- const ALGORITHM_ASSET_URL: StorageObject = {
172
- type: 'url',
173
- url: 'https://raw.githubusercontent.com/oceanprotocol/testdatasets/main/shs_dataset_test.txt',
174
- method: 'GET'
175
- }
176
-
177
- ```
178
-
179
- Next, we define the metadata for the dataset and algorithm that will describe our data assets. This is what we call the DDOs
180
- ```Typescript
181
- const DATASET_DDO: DDO = {
182
- '@context': ['https://w3id.org/did/v1'],
183
- id: 'did:op:efba17455c127a885ec7830d687a8f6e64f5ba559f8506f8723c1f10f05c049c',
184
- version: '4.1.0',
185
- chainId: 8996,
186
- nftAddress: '0x0',
187
- metadata: {
188
- created: '2021-12-20T14:35:20Z',
189
- updated: '2021-12-20T14:35:20Z',
190
- type: 'dataset',
191
- name: 'dataset-name',
192
- description: 'Ocean protocol test dataset description',
193
- author: 'oceanprotocol-team',
194
- license: 'https://market.oceanprotocol.com/terms',
195
- additionalInformation: {
196
- termsAndConditions: true
197
- }
198
- },
199
- services: [
200
- {
201
- id: '1155995dda741e93afe4b1c6ced2d01734a6ec69865cc0997daf1f4db7259a36',
202
- type: 'compute',
203
- files: '',
204
- datatokenAddress: '0xa15024b732A8f2146423D14209eFd074e61964F3',
205
- serviceEndpoint: 'http://127.0.0.1:8001',
206
- timeout: 300,
207
- compute: {
208
- publisherTrustedAlgorithmPublishers: ['*'] as any,
209
- publisherTrustedAlgorithms: [
210
- {
211
- did: '*',
212
- filesChecksum: '*',
213
- containerSectionChecksum: '*'
214
- }
215
- ] as any,
216
- allowRawAlgorithm: false,
217
- allowNetworkAccess: true
218
- }
219
- }
220
- ]
221
- }
222
-
223
- const ALGORITHM_DDO: DDO = {
224
- '@context': ['https://w3id.org/did/v1'],
225
- id: 'did:op:efba17455c127a885ec7830d687a8f6e64f5ba559f8506f8723c1f10f05c049c',
226
- version: '4.1.0',
227
- chainId: 8996,
228
- nftAddress: '0x0',
229
- metadata: {
230
- created: '2021-12-20T14:35:20Z',
231
- updated: '2021-12-20T14:35:20Z',
232
- type: 'algorithm',
233
- name: 'algorithm-name',
234
- description: 'Ocean protocol test algorithm description',
235
- author: 'oceanprotocol-team',
236
- license: 'https://market.oceanprotocol.com/terms',
237
- additionalInformation: {
238
- termsAndConditions: true
239
- },
240
- algorithm: {
241
- language: 'Node.js',
242
- version: '1.0.0',
243
- container: {
244
- entrypoint: 'node $ALGO',
245
- image: 'ubuntu',
246
- tag: 'latest',
247
- checksum:
248
- 'sha256:2d7ecc9c5e08953d586a6e50c29b91479a48f69ac1ba1f9dc0420d18a728dfc5'
249
- }
250
- }
251
- },
252
- services: [
253
- {
254
- id: 'db164c1b981e4d2974e90e61bda121512e6909c1035c908d68933ae4cfaba6b0',
255
- type: 'access',
256
- files: '',
257
- datatokenAddress: '0xa15024b732A8f2146423D14209eFd074e61964F3',
258
- serviceEndpoint: 'http://127.0.0.1:8001',
259
- timeout: 300
260
- }
261
- ]
262
- }
263
- ```
264
-
265
- Now we define the variables which we will need later
266
- ```Typescript
267
- let config: Config
268
- let aquariusInstance: Aquarius
269
- let datatoken: Datatoken
270
- let providerUrl: string
271
- let publisherAccount: Signer
272
- let consumerAccount: Signer
273
- let addresses
274
- let computeEnvs
275
-
276
- let datasetId: string
277
- let algorithmId: string
278
- let resolvedDatasetDdo: DDO
279
- let resolvedAlgorithmDdo: DDO
280
-
281
- let computeJobId: string
282
- let agreementId: string
283
-
284
- ```
285
-
286
- ### 4.3 Helper methods
287
-
288
- Now we define the helper methods which we will use later to publish the dataset and algorithm, and also order them
289
-
290
- Add a `createAssetHelper()`function.
291
- ```Typescript
292
- async function createAssetHelper(
293
- name: string,
294
- symbol: string,
295
- owner: Signer,
296
- assetFiles: StorageObject[],
297
- ddo: DDO,
298
- providerUrl: string
299
- ) {
300
- const { chainId } = await owner.provider.getNetwork()
301
- const nft = new Nft(owner, Number(chainId))
302
-
303
- const nftFactory = new NftFactory(addresses.ERC721Factory, owner, Number(chainId))
304
-
305
- ddo.chainId = Number(chainId)
306
- const nftParamsAsset: NftCreateData = {
307
- name,
308
- symbol,
309
- templateIndex: 1,
310
- tokenURI: 'aaa',
311
- transferable: true,
312
- owner: await owner.getAddress()
313
- }
314
- const datatokenParams: DatatokenCreateParams = {
315
- templateIndex: 1,
316
- cap: '100000',
317
- feeAmount: '0',
318
- paymentCollector: ZERO_ADDRESS,
319
- feeToken: ZERO_ADDRESS,
320
- minter: await owner.getAddress(),
321
- mpFeeAddress: ZERO_ADDRESS
322
- }
323
-
324
- const bundleNFT = await nftFactory.createNftWithDatatoken(
325
- nftParamsAsset,
326
- datatokenParams
327
- )
328
-
329
- const trxReceipt = await bundleNFT.wait()
330
- // events have been emitted
331
- const nftCreatedEvent = getEventFromTx(trxReceipt, 'NFTCreated')
332
- const tokenCreatedEvent = getEventFromTx(trxReceipt, 'TokenCreated')
333
-
334
- const nftAddress = nftCreatedEvent.args.newTokenAddress
335
- const datatokenAddressAsset = tokenCreatedEvent.args.newTokenAddress
336
- // create the files encrypted string
337
- const assetUrl: AssetFiles = {
338
- nftAddress,
339
- datatokenAddress: datatokenAddressAsset,
340
- files: assetFiles
341
- }
342
- ddo.services[0].files = await ProviderInstance.encrypt(
343
- assetUrl,
344
- Number(chainId),
345
- providerUrl,
346
- owner
347
- )
348
- ddo.services[0].datatokenAddress = datatokenAddressAsset
349
- ddo.services[0].serviceEndpoint = providerUrl
350
-
351
- ddo.nftAddress = nftAddress
352
- ddo.id = 'did:op:' + SHA256(ethers.getAddress(nftAddress) + chainId.toString(10))
353
-
354
- const encryptedResponse = await ProviderInstance.encrypt(
355
- ddo,
356
- Number(chainId),
357
- providerUrl,
358
- owner
359
- )
360
- const validateResult = await aquariusInstance.validate(ddo, owner, providerUrl)
361
- await nft.setMetadata(
362
- nftAddress,
363
- await owner.getAddress(),
364
- 0,
365
- providerUrl,
366
- '',
367
- toBeHex(2),
368
- encryptedResponse,
369
- validateResult.hash
370
- )
371
- return ddo.id
372
- }
373
- ```
374
-
375
- Add a `handleOrder()`function.
376
- ```Typescript
377
- async function handleOrder(
378
- order: ProviderComputeInitialize,
379
- datatokenAddress: string,
380
- payerAccount: Signer,
381
- consumerAccount: string,
382
- serviceIndex: number,
383
- consumeMarkerFee?: ConsumeMarketFee
384
- ) {
385
- /* We do have 3 possible situations:
386
- - have validOrder and no providerFees -> then order is valid, providerFees are valid, just use it in startCompute
387
- - have validOrder and providerFees -> then order is valid but providerFees are not valid, we need to call reuseOrder and pay only providerFees
388
- - no validOrder -> we need to call startOrder, to pay 1 DT & providerFees
389
- */
390
- if (order.providerFee && order.providerFee.providerFeeAmount) {
391
- await approveWei(
392
- payerAccount,
393
- config,
394
- await payerAccount.getAddress(),
395
- order.providerFee.providerFeeToken,
396
- datatokenAddress,
397
- order.providerFee.providerFeeAmount
398
- )
399
- }
400
- if (order.validOrder) {
401
- if (!order.providerFee) return order.validOrder
402
- const tx = await datatoken.reuseOrder(
403
- datatokenAddress,
404
- order.validOrder,
405
- order.providerFee
406
- )
407
- const reusedTx = await tx.wait()
408
- const orderReusedTx = getEventFromTx(reusedTx, 'OrderReused')
409
- return orderReusedTx.transactionHash
410
- }
411
- const tx = await datatoken.startOrder(
412
- datatokenAddress,
413
- consumerAccount,
414
- serviceIndex,
415
- order.providerFee,
416
- consumeMarkerFee
417
- )
418
- const orderTx = await tx.wait()
419
- const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted')
420
- return orderStartedTx.transactionHash
421
- }
422
- ```
423
-
424
- At the end of your compute.ts file define `async function run(){ }`. We will use this function to add and test the following chunks of code.
425
- <!--
426
- describe('Compute-to-data example tests
427
- -->
428
-
429
- We need to load the configuration. Add the following code into your `run(){ }` function
430
- ```Typescript
431
-
432
- const provider = new JsonRpcProvider(
433
- process.env.NODE_URI || configHelperNetworks[1].nodeUri
434
- )
435
- publisherAccount = (await provider.getSigner(0)) as Signer
436
- consumerAccount = (await provider.getSigner(1)) as Signer
437
- const config = new ConfigHelper().getConfig(
438
- parseInt(String((await publisherAccount.provider.getNetwork()).chainId))
439
- )
440
- Object.assign(config, getNodeEndpointConfig())
441
- aquariusInstance = new Aquarius(config?.oceanNodeUri)
442
- providerUrl = config?.oceanNodeUri
443
- addresses = JSON.parse(
444
- // eslint-disable-next-line security/detect-non-literal-fs-filename
445
- fs.readFileSync(
446
- process.env.ADDRESS_FILE ||
447
- `${homedir}/.ocean/ocean-contracts/artifacts/address.json`,
448
- 'utf8'
449
- )
450
- ).development
451
-
452
- ```
453
- 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:
454
- ```Typescript
455
- console.log(`Indexer URL: ${config.oceanNodeUri}`)
456
- console.log(`Provider URL: ${providerUrl}`)
457
- console.log(`Deployed contracts address: ${addresses}`)
458
- console.log(`Publisher account address: ${publisherAccount}`)
459
- console.log(`Consumer account address: ${consumerAccount}`)
460
-
461
- ```
462
-
463
- 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`.
464
- If everything is working you should see the logs in the console and no errors.
465
- 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.
466
- Then compile your file with the `tsc` command and run it with `node dist/compute.js`
467
-
468
- ### 5.1 Mint OCEAN to publisher account
469
- You can skip this step if you are running your script against a remote network,
470
- you need to mint oceans to mentioned accounts only if you are using barge to test your script
471
-
472
- ```Typescript
473
- const minAbi = [
474
- {
475
- constant: false,
476
- inputs: [
477
- { name: 'to', type: 'address' },
478
- { name: 'value', type: 'uint256' }
479
- ],
480
- name: 'mint',
481
- outputs: [{ name: '', type: 'bool' }],
482
- payable: false,
483
- stateMutability: 'nonpayable',
484
- type: 'function'
485
- }
486
- ]
487
-
488
- const tokenContract = new ethers.Contract(addresses.Ocean, minAbi, publisherAccount)
489
- const estGasPublisher = await tokenContract.mint.estimateGas(
490
- await publisherAccount.getAddress(),
491
- amountToUnits(null, null, '1000', 18)
492
- )
493
- await sendTx(
494
- estGasPublisher,
495
- publisherAccount,
496
- 1,
497
- tokenContract.mint,
498
- await publisherAccount.getAddress(),
499
- amountToUnits(null, null, '1000', 18)
500
- )
501
- ```
502
- <!--
503
- }).timeout(40000) ///
504
- --->
505
-
506
- ### 5.2 Send some OCEAN to consumer account
507
- ```Typescript
508
- transfer(
509
- publisherAccount,
510
- config,
511
- addresses.Ocean,
512
- await consumerAccount.getAddress(),
513
- '100'
514
- )
515
-
516
- ```
517
-
518
- ## 6. Publish assets dataset and algorithm
519
-
520
- ### 6.1 Publish a dataset (create NFT + Datatoken) and set dataset metadata
521
- ```Typescript
522
- datasetId = await createAssetHelper(
523
- 'D1Min',
524
- 'D1M',
525
- publisherAccount,
526
- [DATASET_ASSET_URL],
527
- DATASET_DDO,
528
- providerUrl
529
- )
530
- ```
531
- Now, let's check that we successfully published a dataset (create NFT + Datatoken)
532
- ```Typescript
533
- console.log(`dataset id: ${datasetId}`)
534
- ```
535
- <!--
536
- }).timeout(40000)
537
- -->
538
-
539
- ### 6.2 Publish an algorithm (create NFT + Datatoken) and set algorithm metadata
540
- ```Typescript
541
- algorithmId = await createAssetHelper(
542
- 'D1Min',
543
- 'D1M',
544
- publisherAccount,
545
- [ALGORITHM_ASSET_URL],
546
- ALGORITHM_DDO,
547
- providerUrl
548
- )
549
- ```
550
- Now, let's check that we successfully published a algorithm (create NFT + Datatoken)
551
- ```Typescript
552
- console.log(`algorithm id: ${algorithmId}`)
553
- ```
554
- <!--
555
- }).timeout(40000)
556
- -->
557
- ## 7. Resolve assets
558
-
559
- ### 7.1 Resolve published datasets and algorithms
560
- ```Typescript
561
- resolvedDatasetDdo = await aquariusInstance.waitForIndexer(datasetId)
562
- resolvedAlgorithmDdo = await aquariusInstance.waitForIndexer(algorithmId)
563
- ```
564
- <!--
565
- assert(resolvedDatasetDdo, 'Cannot fetch DDO from Aquarius')
566
- assert(resolvedAlgorithmDdo, 'Cannot fetch DDO from Aquarius')
567
- }).timeout(80000)
568
- -->
569
-
570
- ## 8. Send datatokens to consumer
571
-
572
- ### 8.1 Mint dataset and algorithm datatokens to publisher
573
- ```Typescript
574
- const { chainId } = await publisherAccount.provider.getNetwork()
575
- const datatoken = new Datatoken(publisherAccount, Number(chainId))
576
- await datatoken.mint(
577
- resolvedDatasetDdo.services[0].datatokenAddress,
578
- await publisherAccount.getAddress(),
579
- '10',
580
- await consumerAccount.getAddress()
581
- )
582
-
583
- await datatoken.mint(
584
- resolvedAlgorithmDdo.services[0].datatokenAddress,
585
- await publisherAccount.getAddress(),
586
- '10',
587
- await consumerAccount.getAddress()
588
- )
589
- ```
590
- <!--
591
- }).timeout(40000)
592
- -->
593
-
594
- ## 9. Get compute environments
595
-
596
- ### 9.1 Fetch compute environments from provider
597
- ```Typescript
598
- computeEnvs = await ProviderInstance.getComputeEnvironments(providerUrl)
599
- ```
600
- <!--
601
- assert(computeEnvs, 'No Compute environments found')
602
- }).timeout(40000)
603
- -->
604
-
605
- ## 10. Consumer starts a free compute job
606
-
607
- ### 10.1 Start a compute job using a free C2D environment
608
- <!--
609
- const { chainId } = await consumerAccount.provider.getNetwork()
610
- datatoken = new Datatoken(consumerAccount, Number(chainId))
611
- -->
612
-
613
- let's check the free compute environment
614
- ```Typescript
615
- const computeEnv = computeEnvs.find((ce) => isDefined(ce.free))
616
- console.log('Free compute environment = ', computeEnv)
617
- ```
618
- <!--
619
- assert(computeEnv, 'Cannot find the free compute env')
620
- -->
621
-
622
- Let's have 5 minute of compute access
623
- ```Typescript
624
- const mytime = new Date()
625
- const computeMinutes = 5
626
- mytime.setMinutes(mytime.getMinutes() + computeMinutes)
627
-
628
- ```
629
- Let's prepare the dataset and algorithm assets to be used in the compute job
630
- ```Typescript
631
- const assets: ComputeAsset[] = [
632
- {
633
- documentId: resolvedDatasetDdo.id,
634
- serviceId: resolvedDatasetDdo.services[0].id
635
- }
636
- ]
637
-
638
- const algo: ComputeAlgorithm = {
639
- documentId: resolvedAlgorithmDdo.id,
640
- serviceId: resolvedAlgorithmDdo.services[0].id,
641
- meta: resolvedAlgorithmDdo.metadata.algorithm
642
- }
643
- ```
644
-
645
- Let's start the free compute job
646
- ```Typescript
647
- const computeJobs = await ProviderInstance.freeComputeStart(
648
- providerUrl,
649
- consumerAccount,
650
- computeEnv.id,
651
- assets,
652
- algo
653
- )
654
- ```
655
-
656
- <!--
657
- assert(computeJobs, 'Cannot start compute job')
658
- -->
659
-
660
- Let's save the compute job it, we re going to use later
661
- ```Typescript
662
- computeJobId = computeJobs[0].jobId
663
- // eslint-disable-next-line prefer-destructuring
664
- agreementId = computeJobs[0].agreementId
665
- ```
666
- <!--
667
- }).timeout(40000)
668
- -->
669
-
670
- ## 11. Check compute status and get download compute results URL
671
- ### 11.1 Check compute status
672
- <!--
673
-
674
- -->
675
- You can also add various delays so you see the various states of the compute job
676
- ```Typescript
677
- const jobStatus = await ProviderInstance.computeStatus(
678
- providerUrl,
679
- consumerAccount,
680
- computeJobId,
681
- agreementId
682
- )
683
- ```
684
- <!--
685
- assert(jobStatus, 'Cannot retrieve compute status!')
686
- -->
687
- Now, let's see the current status of the previously started computer job
688
- ```Typescript
689
- console.log('Current status of the compute job: ', jobStatus)
690
- ```
691
- <!--
692
- }).timeout(40000)
693
- -->
694
-
695
- ### 11.2 Get download compute results URL
696
- <!--
697
- -->
698
- ```Typescript
699
- await sleep(10000)
700
- const downloadURL = await ProviderInstance.getComputeResultUrl(
701
- providerUrl,
702
- consumerAccount,
703
- computeJobId,
704
- 0
705
- )
706
- ```
707
- <!--
708
- assert(downloadURL, 'Provider getComputeResultUrl failed!')
709
- -->
710
- Let's check the compute results url for the specified index
711
- ```Typescript
712
- console.log(`Compute results URL: ${downloadURL}`)
713
- ```
714
- <!--
715
- }).timeout(40000)
716
- -->
717
-
718
- ## 12. Consumer starts a paid compute job
719
-
720
- ### 12.1 Start a compute job using a paid C2D resources
721
- <!--
722
- const { chainId } = await consumerAccount.provider.getNetwork()
723
- datatoken = new Datatoken(consumerAccount, Number(chainId))
724
- -->
725
-
726
- let's select compute environment which have free and paid resources
727
- ```Typescript
728
- const computeEnv = computeEnvs[0]
729
- console.log('Compute environment = ', computeEnv)
730
- ```
731
- <!--
732
- assert(computeEnv, 'Cannot find the compute env')
733
- -->
734
-
735
- <!--
736
- const paymentToken = addresses.Ocean
737
-
738
- Let's have 5 minute of compute access
739
- ```Typescript
740
-
741
- const mytime = new Date()
742
- const computeMinutes = 5
743
- mytime.setMinutes(mytime.getMinutes() + computeMinutes)
744
- const computeValidUntil = Math.floor(mytime.getTime() / 1000)
745
-
746
- ```
747
-
748
- Let's prepare the dataset and algorithm assets to be used in the compute job
749
- ```Typescript
750
- const resources: ComputeResourceRequest[] = [
751
- {
752
- id: 'cpu',
753
- amount: 2
754
- },
755
- {
756
- id: 'ram',
757
- amount: 2
758
- },
759
- {
760
- id: 'disk',
761
- amount: 0
762
- }
763
- ]
764
- const assets: ComputeAsset[] = [
765
- {
766
- documentId: resolvedDatasetDdo.id,
767
- serviceId: resolvedDatasetDdo.services[0].id
768
- }
769
- ]
770
- const dtAddressArray = [resolvedDatasetDdo.services[0].datatokenAddress]
771
- const algo: ComputeAlgorithm = {
772
- documentId: resolvedAlgorithmDdo.id,
773
- serviceId: resolvedAlgorithmDdo.services[0].id,
774
- meta: resolvedAlgorithmDdo.metadata.algorithm
775
- }
776
- ```
777
-
778
- Triggering initialize compute to see payment options
779
- ```Typescript
780
- const providerInitializeComputeResults = await ProviderInstance.initializeCompute(
781
- assets,
782
- algo,
783
- computeEnv.id,
784
- paymentToken,
785
- computeValidUntil,
786
- providerUrl,
787
- await consumerAccount.getAddress(),
788
- resources,
789
- Number(chainId)
790
- )
791
-
792
- console.log(
793
- 'providerInitializeComputeResults = ',
794
- JSON.stringify(providerInitializeComputeResults)
795
- )
796
-
797
- ```
798
-
799
- <!--
800
- assert(!('error' in providerInitializeComputeResults), 'Cannot order algorithm')
801
- -->
802
-
803
- Let's check funds for escrow payment
804
- ```Typescript
805
- const escrow = new EscrowContract(
806
- getAddress(providerInitializeComputeResults.payment.escrowAddress),
807
- consumerAccount
808
- )
809
- const paymentTokenPublisher = new Datatoken(publisherAccount)
810
- const balancePublisherPaymentToken = await paymentTokenPublisher.balance(
811
- paymentToken,
812
- await publisherAccount.getAddress()
813
- )
814
- assert(
815
- new BigNumber(parseEther(balancePublisherPaymentToken)).isGreaterThan(0),
816
- 'Balance should be higher than 0'
817
- )
818
- const tx = await publisherAccount.sendTransaction({
819
- to: computeEnv.consumerAddress,
820
- value: parseEther('1.5')
821
- })
822
- await tx.wait()
823
-
824
- await paymentTokenPublisher.transfer(
825
- paymentToken,
826
- getAddress(computeEnv.consumerAddress),
827
- (Number(balancePublisherPaymentToken) / 2).toString()
828
- )
829
- const amountToDeposit = (
830
- providerInitializeComputeResults.payment.amount * 2
831
- ).toString()
832
- await escrow.verifyFundsForEscrowPayment(
833
- paymentToken,
834
- computeEnv.consumerAddress,
835
- await unitsToAmount(consumerAccount, paymentToken, amountToDeposit),
836
- providerInitializeComputeResults.payment.amount.toString(),
837
- providerInitializeComputeResults.payment.minLockSeconds.toString(),
838
- '10'
839
- )
840
- ```
841
-
842
- Let's order assets
843
- ```Typescript
844
-
845
- algo.transferTxId = await handleOrder(
846
- providerInitializeComputeResults.algorithm,
847
- resolvedAlgorithmDdo.services[0].datatokenAddress,
848
- consumerAccount,
849
- computeEnv.consumerAddress,
850
- 0
851
- )
852
- for (let i = 0; i < providerInitializeComputeResults.datasets.length; i++) {
853
- assets[i].transferTxId = await handleOrder(
854
- providerInitializeComputeResults.datasets[i],
855
- dtAddressArray[i],
856
- consumerAccount,
857
- computeEnv.consumerAddress,
858
- 0
859
- )
860
- }
861
- ```
862
-
863
- Let's start compute job
864
- ```Typescript
865
- const computeJobs = await ProviderInstance.computeStart(
866
- providerUrl,
867
- consumerAccount,
868
- computeEnv.id,
869
- assets,
870
- algo,
871
- computeValidUntil,
872
- paymentToken,
873
- resources,
874
- Number(chainId)
875
- )
876
- ```
877
-
878
- <!--
879
- assert(computeJobs, 'Cannot start compute job')
880
- -->
881
-
882
- Let's save the compute job it, we re going to use later
883
- ```Typescript
884
- computeJobId = computeJobs[0].jobId
885
- ```
886
- <!--
887
- }).timeout(40000)
888
- -->
889
-
890
- ## 13. Check paid compute job status and get download compute results URL
891
- ### 13.1 Check compute status for paid compute job
892
- <!--
893
- -->
894
- You can also add various delays so you see the various states of the compute job
895
- ```Typescript
896
- const jobStatus = await ProviderInstance.computeStatus(
897
- providerUrl,
898
- consumerAccount,
899
- computeJobId
900
- )
901
- ```
902
- <!--
903
- assert(jobStatus, 'Cannot retrieve compute status!')
904
- -->
905
- Now, let's see the current status of the previously started computer job
906
- ```Typescript
907
- console.log('Current status of the compute job: ', jobStatus)
908
- ```
909
- <!--
910
- }).timeout(40000)
911
- -->
912
-
913
- ### 13.2 Get download compute results URL
914
- <!--
915
- -->
916
-
917
- ```Typescript
918
- await sleep(10000)
919
- const downloadURL = await ProviderInstance.getComputeResultUrl(
920
- providerUrl,
921
- consumerAccount,
922
- computeJobId,
923
- 0
924
- )
925
- ```
926
- <!--
927
- assert(downloadURL, 'Provider getComputeResultUrl failed!')
928
- -->
929
- Let's check the compute results url for the specified index
930
- ```Typescript
931
- console.log(`Compute results URL: ${downloadURL}`)
932
- ```
933
- <!--
934
- }).timeout(40000)
935
- })
936
- -->
937
-
938
- ## Editing this file
939
- Please note that ComputeExamples.md is an autogenerated file, you should not edit it directly.
940
- Updates should be done in `test/integration/ComputeExamples.test.ts` and all markdown should have three forward slashes before it
941
- e.g. `/// # H1 Title`