@oceanprotocol/lib 7.0.0-next.0 → 7.0.0-next.10

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 (105) hide show
  1. package/dist/lib.cjs +4 -3
  2. package/dist/lib.module.mjs +4 -3
  3. package/dist/lib.umd.js +4 -3
  4. package/dist/types/@types/Compute.d.ts +21 -0
  5. package/dist/types/@types/Provider.d.ts +39 -0
  6. package/dist/types/services/providers/BaseProvider.d.ts +35 -32
  7. package/dist/types/services/providers/HttpProvider.d.ts +4 -2
  8. package/dist/types/services/providers/P2pProvider.d.ts +39 -37
  9. package/package.json +27 -21
  10. package/.mocharc.json +0 -8
  11. package/.nvmrc +0 -1
  12. package/CHANGELOG.md +0 -3228
  13. package/Cheatsheet.md +0 -326
  14. package/CodeExamples.md +0 -881
  15. package/ComputeExamples.md +0 -941
  16. package/dist/lib.cjs.map +0 -1
  17. package/dist/lib.modern.js +0 -4
  18. package/dist/lib.modern.js.map +0 -1
  19. package/dist/lib.module.mjs.map +0 -1
  20. package/dist/lib.umd.js.map +0 -1
  21. package/docs/.nojekyll +0 -1
  22. package/docs/README.md +0 -195
  23. package/docs/classes/Aquarius.md +0 -175
  24. package/docs/classes/Config.md +0 -481
  25. package/docs/classes/ConfigHelper.md +0 -66
  26. package/docs/classes/Datatoken.md +0 -1123
  27. package/docs/classes/Dispenser.md +0 -502
  28. package/docs/classes/Escrow.md +0 -285
  29. package/docs/classes/FixedRateExchange.md +0 -1068
  30. package/docs/classes/Logger.md +0 -191
  31. package/docs/classes/Nft.md +0 -970
  32. package/docs/classes/NftFactory.md +0 -861
  33. package/docs/classes/Provider.md +0 -727
  34. package/docs/classes/Router.md +0 -645
  35. package/docs/classes/SmartContract.md +0 -193
  36. package/docs/classes/SmartContractWithAddress.md +0 -268
  37. package/docs/enums/LogLevel.md +0 -63
  38. package/docs/interfaces/AbiInput.md +0 -63
  39. package/docs/interfaces/AbiItem.md +0 -107
  40. package/docs/interfaces/AbiOutput.md +0 -52
  41. package/docs/interfaces/Arweave.md +0 -32
  42. package/docs/interfaces/Asset.md +0 -227
  43. package/docs/interfaces/AssetDatatoken.md +0 -60
  44. package/docs/interfaces/AssetLastEvent.md +0 -63
  45. package/docs/interfaces/AssetNft.md +0 -105
  46. package/docs/interfaces/AssetPrice.md +0 -47
  47. package/docs/interfaces/ComputeAlgorithm.md +0 -82
  48. package/docs/interfaces/ComputeAsset.md +0 -56
  49. package/docs/interfaces/ComputeEnvFees.md +0 -30
  50. package/docs/interfaces/ComputeEnvFeesStructure.md +0 -20
  51. package/docs/interfaces/ComputeEnvironment.md +0 -177
  52. package/docs/interfaces/ComputeJob.md +0 -173
  53. package/docs/interfaces/ComputeOutput.md +0 -118
  54. package/docs/interfaces/ComputeResourcesPricingInfo.md +0 -30
  55. package/docs/interfaces/ComputeResourcesRequest.md +0 -34
  56. package/docs/interfaces/ComputeResult.md +0 -52
  57. package/docs/interfaces/ConsumeMarketFee.md +0 -41
  58. package/docs/interfaces/Credential.md +0 -30
  59. package/docs/interfaces/Credentials.md +0 -30
  60. package/docs/interfaces/DDO.md +0 -137
  61. package/docs/interfaces/DatatokenCreateParams.md +0 -107
  62. package/docs/interfaces/DatatokenRoles.md +0 -30
  63. package/docs/interfaces/DispenserCreationParams.md +0 -63
  64. package/docs/interfaces/DispenserParams.md +0 -52
  65. package/docs/interfaces/DispenserToken.md +0 -85
  66. package/docs/interfaces/DownloadResponse.md +0 -30
  67. package/docs/interfaces/Event.md +0 -73
  68. package/docs/interfaces/FeesInfo.md +0 -74
  69. package/docs/interfaces/FileInfo.md +0 -118
  70. package/docs/interfaces/Files.md +0 -41
  71. package/docs/interfaces/FixedPriceExchange.md +0 -162
  72. package/docs/interfaces/FreCreationParams.md +0 -118
  73. package/docs/interfaces/FreOrderParams.md +0 -85
  74. package/docs/interfaces/GraphqlQuery.md +0 -69
  75. package/docs/interfaces/Ipfs.md +0 -32
  76. package/docs/interfaces/Metadata.md +0 -193
  77. package/docs/interfaces/MetadataAlgorithm.md +0 -69
  78. package/docs/interfaces/MetadataAndTokenURI.md +0 -107
  79. package/docs/interfaces/MetadataProof.md +0 -52
  80. package/docs/interfaces/NftCreateData.md +0 -74
  81. package/docs/interfaces/NftRoles.md +0 -52
  82. package/docs/interfaces/Operation.md +0 -145
  83. package/docs/interfaces/OrderParams.md +0 -52
  84. package/docs/interfaces/PriceAndFees.md +0 -52
  85. package/docs/interfaces/ProviderComputeInitialize.md +0 -41
  86. package/docs/interfaces/ProviderComputeInitializeResults.md +0 -43
  87. package/docs/interfaces/ProviderFees.md +0 -96
  88. package/docs/interfaces/ProviderInitialize.md +0 -52
  89. package/docs/interfaces/PublisherTrustedAlgorithm.md +0 -47
  90. package/docs/interfaces/PublishingMarketFee.md +0 -41
  91. package/docs/interfaces/Purgatory.md +0 -34
  92. package/docs/interfaces/RunningPlatform.md +0 -30
  93. package/docs/interfaces/SearchQuery.md +0 -67
  94. package/docs/interfaces/Service.md +0 -138
  95. package/docs/interfaces/ServiceComputeOptions.md +0 -63
  96. package/docs/interfaces/ServiceEndpoint.md +0 -41
  97. package/docs/interfaces/Smartcontract-1.md +0 -58
  98. package/docs/interfaces/Stats.md +0 -47
  99. package/docs/interfaces/Template.md +0 -30
  100. package/docs/interfaces/TokenOrder.md +0 -63
  101. package/docs/interfaces/UrlFile.md +0 -71
  102. package/docs/interfaces/UserCustomParameters.md +0 -7
  103. package/docs/interfaces/ValidateMetadata.md +0 -52
  104. package/docs/modules.md +0 -850
  105. package/typedoc.json +0 -4
package/CodeExamples.md DELETED
@@ -1,881 +0,0 @@
1
- # Ocean.js Code Examples
2
-
3
- ## Introduction
4
-
5
- The following guide runs you through the process of using ocean.js to publish and then consume a dataset. The code examples below are all working and you can learn how to publish by following along.
6
- The process involves creating a Data NFT (which represents the base-IP on-chain) and a datatoken (which will be used to purchase the dataset). This guide provides all the code you need and no prior knowledge is required. It is helpful if you have some experience with javascript but it is not necessary.
7
-
8
- Selling your data over the blockchain puts you in charge of how it is used and can be a great source of passive income. There are many AI startups that have deep expertise in machine learning but need more data to improve their models. Selling your data via the blockchain gives you a level of security that you would be unable to achieve if you were selling via a centralised marketplace.
9
-
10
- In this guide we'll be making use of the Ocean.js library. Ocean Protocol provides you with everything you need to quickly get setup and start selling data over the blockchain.
11
-
12
- These examples take you through a typical user journey that focuses on the experience of a publisher, and a buyer / consumer.
13
-
14
- If you have any questions or issues at any point while following along to this article please reach out to us on [discord](https://discord.gg/TnXjkR5).
15
-
16
- Here are the steps we will be following throughout the article:
17
-
18
- Here are the steps:
19
-
20
- 0. [Prerequisites](#0-prerequisites)
21
- 1. [Initialize services](#1-initialize-services)
22
- 2. [Create a new node.js project](#2-create-a-new-nodejs-project)
23
- 3. [Install dependencies](#3-install-dependancies)
24
- 4. [Import dependencies and add variables and constants](#4-import-dependencies-and-add-variables-and-constants)
25
- 5. [Load the configuration, initialize accounts and deploy contracts](#5-load-the-configuration-initialize-accounts-and-deploy-contracts)
26
- 6. [Publish Data NFT and a Datatoken with a fixed rate exchange](#6-publish-data-nft-and-a-datatoken-with-a-fixed-rate-exchange)
27
- 7. [Consume a fixed rate asset data asset'](#7-consume-a-fixed-rate-asset-data-asset)
28
- 8. [Publish Data NFT and a Datatoken with a dispenser](#8-publish-data-nft-and-a-datatoken-with-a-dispenserr)
29
- 9. [Consume a dispenser data asset](#9-consume-a-dispenser-data-asset)
30
- 10. [Using ERC725 Key-Value Store](#10-using-erc725-key-value-store)
31
-
32
- ## 0. Prerequisites
33
- Before we start it is important that you have all of the necessary prerequisites installed on your computer.
34
- - **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.
35
- - **Git**. Instructions for installing Git can be found here: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
36
- - **Node.js** can be downloaded from here: https://nodejs.org/en/download/
37
- - **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/
38
-
39
- ## 1. Initialize services
40
-
41
- Ocean.js uses off-chain services for metadata (Aquarius) and consuming datasets (Provider).
42
-
43
- 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.
44
-
45
- ```bash
46
- git clone https://github.com/oceanprotocol/barge.git
47
- cd barge/
48
- ./start_ocean.sh
49
- ```
50
-
51
- ## 2. Create a new node.js project
52
-
53
- Start by creating a new Node.js project. Open a new terminal and enter the following commands:
54
-
55
- ```bash
56
- mkdir marketplace-quickstart
57
- cd marketplace-quickstart
58
- npm init
59
- # Answer the questions in the command line prompt
60
- cat > marketplace.js
61
- # On linux press CTRL + D to save
62
- ```
63
-
64
- ## 3. Install dependencies
65
-
66
- Install dependencies running the following command in your terminal:
67
-
68
- ```bash
69
- npm install @oceanprotocol/lib crypto-js ethers
70
- ```
71
-
72
- ## 4. Import dependencies and add variables and constants
73
-
74
- Now open the `marketplace.js` file in your text editor.
75
-
76
- Start by importing all of the necessary dependencies
77
-
78
- ```Typescript
79
- import fs from 'fs'
80
-
81
- import { ethers, formatEther, getAddress, JsonRpcProvider, Signer, toBeHex } from 'ethers'
82
- import crypto from 'crypto-js'
83
- import { homedir } from 'os'
84
- import {
85
- approve,
86
- Aquarius,
87
- balance,
88
- Config,
89
- Datatoken,
90
- Dispenser,
91
- DispenserCreationParams,
92
- downloadFile,
93
- DatatokenCreateParams,
94
- Files,
95
- FixedRateExchange,
96
- FreCreationParams,
97
- Nft,
98
- NftCreateData,
99
- NftFactory,
100
- ProviderFees,
101
- ProviderInstance,
102
- transfer,
103
- ZERO_ADDRESS,
104
- sendTx,
105
- ConfigHelper,
106
- configHelperNetworks,
107
- getNodeEndpointConfig,
108
- amountToUnits,
109
- getEventFromTx,
110
- LoggerInstance
111
- } from '../../src/index.js'
112
- import { DDO, ValidateMetadata } from '@oceanprotocol/ddo-js'
113
- ```
114
- const { SHA256 } = crypto
115
-
116
- <!--
117
- describe('Marketplace flow tests
118
- -->
119
-
120
- Now we define the variables which we will need later
121
-
122
- ```Typescript
123
- let provider: JsonRpcProvider
124
- let config: Config
125
- let aquarius: Aquarius
126
- let datatoken: Datatoken
127
- let providerUrl: any
128
- let publisherAccount: Signer
129
- let consumerAccount: Signer
130
- let stakerAccount: Signer
131
- let addresses: any
132
- let freNftAddress: string
133
- let freDatatokenAddress: string
134
- let freAddress: string
135
- let freId: string
136
- let dispenserNftAddress: string
137
- let dispenserDatatokenAddress: string
138
- let dispenserAddress: string
139
- let fixedDDO: DDO
140
- ```
141
-
142
- We also define some constants that we will use:
143
- ```Typescript
144
- const FRE_NFT_NAME = 'Datatoken 2'
145
- const FRE_NFT_SYMBOL = 'DT2'
146
- const DISP_NFT_NAME = 'Datatoken 3'
147
- const DISP_NFT_SYMBOL = 'DT3'
148
- ```
149
-
150
- We will need a file to publish, so here we define the file that we intend to publish.
151
- ```Typescript
152
- const ASSET_URL: Files = {
153
- datatokenAddress: '0x0',
154
- nftAddress: '0x0',
155
- files: [
156
- {
157
- type: 'url',
158
- url: 'https://raw.githubusercontent.com/oceanprotocol/testdatasets/main/shs_dataset_test.txt',
159
- method: 'GET'
160
- }
161
- ]
162
- }
163
- ```
164
-
165
- Next, we define the metadata that will describe our data asset. This is what we call the DDO
166
- ```Typescript
167
- const genericAsset: DDO = {
168
- '@context': ['https://w3id.org/did/v1'],
169
- id: 'did:op',
170
- version: '4.1.0',
171
- chainId: 8996,
172
- nftAddress: '0x0',
173
- metadata: {
174
- created: '2021-12-20T14:35:20Z',
175
- updated: '2021-12-20T14:35:20Z',
176
- type: 'dataset',
177
- name: 'dataset-name',
178
- description: 'Ocean protocol test dataset description',
179
- author: 'oceanprotocol-team',
180
- license: 'MIT',
181
- tags: ['white-papers'],
182
- additionalInformation: { 'test-key': 'test-value' },
183
- links: ['http://data.ceda.ac.uk/badc/ukcp09/']
184
- },
185
- services: [
186
- {
187
- id: 'db164c1b981e4d2974e90e61bda121512e6909c1035c908d68933ae4cfaba6b0',
188
- type: 'access',
189
- files: '',
190
- datatokenAddress: '0xa15024b732A8f2146423D14209eFd074e61964F3',
191
- serviceEndpoint: 'http://127.0.0.1:8001',
192
- timeout: 0
193
- }
194
- ]
195
- }
196
- ```
197
-
198
- ## 5. Load the configuration, initialize accounts and deploy contracts
199
- ```Typescript
200
-
201
- provider = new JsonRpcProvider(
202
- process.env.NODE_URI || configHelperNetworks[1].nodeUri
203
- )
204
- publisherAccount = (await provider.getSigner(0)) as Signer
205
- consumerAccount = (await provider.getSigner(1)) as Signer
206
- stakerAccount = (await provider.getSigner(2)) as Signer
207
- const config = new ConfigHelper().getConfig(
208
- parseInt(String((await publisherAccount.provider.getNetwork()).chainId))
209
- )
210
- Object.assign(config, getNodeEndpointConfig())
211
- aquarius = new Aquarius(config?.oceanNodeUri)
212
- providerUrl = config?.oceanNodeUri
213
- addresses = JSON.parse(
214
- // eslint-disable-next-line security/detect-non-literal-fs-filename
215
- fs.readFileSync(
216
- process.env.ADDRESS_FILE ||
217
- `${homedir}/.ocean/ocean-contracts/artifacts/address.json`,
218
- 'utf8'
219
- )
220
- ).development
221
- ```
222
- As we go along it's a good idea to console log the values so that you check they are right
223
- ```Typescript
224
- console.log(`Indexer URL: ${config.oceanNodeUri}`)
225
- console.log(`Provider URL: ${providerUrl}`)
226
- console.log(`Deployed contracts address: ${addresses}`)
227
- console.log(`Publisher account address: ${await publisherAccount.getAddress()}`)
228
- console.log(`Consumer account address: ${await consumerAccount.getAddress()}`)
229
- console.log(`Staker account address: ${await stakerAccount.getAddress()}`)
230
-
231
- ```
232
-
233
- ### 5.1 Mint OCEAN to publisher account
234
- You can skip this step if you are running your script against a remote network,
235
- you need to mint oceans to mentioned accounts only if you are using barge to test your script
236
-
237
- ```Typescript
238
- const minAbi = [
239
- {
240
- constant: false,
241
- inputs: [
242
- { name: 'to', type: 'address' },
243
- { name: 'value', type: 'uint256' }
244
- ],
245
- name: 'mint',
246
- outputs: [{ name: '', type: 'bool' }],
247
- payable: false,
248
- stateMutability: 'nonpayable',
249
- type: 'function'
250
- }
251
- ]
252
-
253
- const tokenContract = new ethers.Contract(addresses.Ocean, minAbi, publisherAccount)
254
- const estGasPublisher = await tokenContract.mint.estimateGas(
255
- await publisherAccount.getAddress(),
256
- amountToUnits(null, null, '1000', 18)
257
- )
258
- await sendTx(
259
- estGasPublisher,
260
- publisherAccount,
261
- 1,
262
- tokenContract.mint,
263
- await publisherAccount.getAddress(),
264
- amountToUnits(null, null, '1000', 18)
265
- )
266
-
267
- ```
268
-
269
- ### 5.3 We send some OCEAN to consumer and staker accounts
270
- ```Typescript
271
- transfer(
272
- publisherAccount,
273
- config,
274
- addresses.Ocean,
275
- await consumerAccount.getAddress(),
276
- '100'
277
- )
278
- transfer(
279
- publisherAccount,
280
- config,
281
- addresses.Ocean,
282
- await stakerAccount.getAddress(),
283
- '100'
284
- )
285
-
286
- ```
287
-
288
- ## 6. Publish Data NFT and a Datatoken with a fixed rate exchange
289
-
290
- ### 6.1 Publish a dataset (create NFT + Datatoken) with a fixed rate exchange
291
- ```Typescript
292
- const { chainId } = await publisherAccount.provider.getNetwork()
293
- const factory = new NftFactory(
294
- addresses.ERC721Factory,
295
- publisherAccount,
296
- Number(chainId)
297
- )
298
-
299
- const nftParams: NftCreateData = {
300
- name: FRE_NFT_NAME,
301
- symbol: FRE_NFT_SYMBOL,
302
- templateIndex: 1,
303
- tokenURI: '',
304
- transferable: true,
305
- owner: await publisherAccount.getAddress()
306
- }
307
-
308
- const datatokenParams: DatatokenCreateParams = {
309
- templateIndex: 1,
310
- cap: '100000',
311
- feeAmount: '0',
312
- paymentCollector: ZERO_ADDRESS,
313
- feeToken: ZERO_ADDRESS,
314
- minter: await publisherAccount.getAddress(),
315
- mpFeeAddress: ZERO_ADDRESS
316
- }
317
-
318
- const freParams: FreCreationParams = {
319
- fixedRateAddress: addresses.FixedPrice,
320
- baseTokenAddress: addresses.Ocean,
321
- owner: await publisherAccount.getAddress(),
322
- marketFeeCollector: await publisherAccount.getAddress(),
323
- baseTokenDecimals: 18,
324
- datatokenDecimals: 18,
325
- fixedRate: '1',
326
- marketFee: '0.001',
327
- allowedConsumer: ZERO_ADDRESS,
328
- withMint: true
329
- }
330
-
331
- const bundleNFT = await factory.createNftWithDatatokenWithFixedRate(
332
- nftParams,
333
- datatokenParams,
334
- freParams
335
- )
336
-
337
- const trxReceipt = await bundleNFT.wait()
338
- // events have been emitted
339
- const nftCreatedEvent = getEventFromTx(trxReceipt, 'NFTCreated')
340
- const tokenCreatedEvent = getEventFromTx(trxReceipt, 'TokenCreated')
341
- const newFreEvent = getEventFromTx(trxReceipt, 'NewFixedRate')
342
-
343
- freNftAddress = nftCreatedEvent.args.newTokenAddress
344
- freDatatokenAddress = tokenCreatedEvent.args.newTokenAddress
345
- freAddress = newFreEvent.args.exchangeContract
346
- freId = newFreEvent.args.exchangeId
347
-
348
- ```
349
- Now let's console log each of those values to check everything is working
350
- ```Typescript
351
- console.log(`Fixed rate exchange NFT address: ${freNftAddress}`)
352
- console.log(`Fixed rate exchange Datatoken address: ${freDatatokenAddress}`)
353
- console.log(`Fixed rate exchange address: ${freAddress}`)
354
- console.log(`Fixed rate exchange Id: ${freId}`)
355
-
356
- ```
357
-
358
- ### 6.2 Set metadata in the fixed rate exchange NFT
359
- ```Typescript
360
- const { chainId } = await publisherAccount.provider.getNetwork()
361
- const nft = new Nft(publisherAccount, Number(chainId))
362
-
363
- fixedDDO = { ...genericAsset }
364
-
365
- ```
366
- Now we are going to update the ddo and set the did
367
- ```Typescript
368
-
369
- fixedDDO.chainId = Number(chainId)
370
- fixedDDO.id =
371
- 'did:op:' + SHA256(getAddress(freNftAddress) + fixedDDO.chainId.toString(10))
372
- fixedDDO.nftAddress = freNftAddress
373
-
374
- ```
375
- Next, let's encrypt the file(s) using provider
376
- ```Typescript
377
- ASSET_URL.datatokenAddress = freDatatokenAddress
378
- ASSET_URL.nftAddress = freNftAddress
379
- fixedDDO.services[0].files = await ProviderInstance.encrypt(
380
- ASSET_URL,
381
- fixedDDO.chainId,
382
- providerUrl,
383
- publisherAccount
384
- )
385
- fixedDDO.services[0].datatokenAddress = freDatatokenAddress
386
-
387
- ```
388
- Now let's console log the DID to check everything is working
389
- ```Typescript
390
- console.log(`DID: ${fixedDDO.id}`)
391
-
392
- const providerResponse = await ProviderInstance.encrypt(
393
- fixedDDO,
394
- fixedDDO.chainId,
395
- providerUrl,
396
- publisherAccount
397
- )
398
- const encryptedDDO = await providerResponse
399
-
400
- const isAssetValid: ValidateMetadata = await aquarius.validate(
401
- fixedDDO,
402
- publisherAccount,
403
- providerUrl
404
- )
405
- assert(isAssetValid.valid === true, 'Published asset is not valid')
406
- await nft.setMetadata(
407
- freNftAddress,
408
- await publisherAccount.getAddress(),
409
- 0,
410
- providerUrl,
411
- '',
412
- toBeHex(2),
413
- encryptedDDO,
414
- isAssetValid.hash
415
- )
416
- })
417
- ```
418
-
419
- ### 6.3 Marketplace displays fixed rate asset for sale
420
- ```Typescript
421
- const { chainId } = await publisherAccount.provider.getNetwork()
422
- const fixedRate = new FixedRateExchange(freAddress, publisherAccount, Number(chainId))
423
- const oceanAmount = await (
424
- await fixedRate.calcBaseInGivenDatatokensOut(freId, '1')
425
- ).baseTokenAmount
426
- ```
427
- Now that the market has fetched those values it can display the asset on the front end. In our case we will just console log the results:
428
- ```Typescript
429
- console.log(`Price of 1 ${FRE_NFT_SYMBOL} is ${oceanAmount} OCEAN`)
430
-
431
- ```
432
-
433
- ## 7. Consume a fixed rate asset data asset
434
-
435
- ### 7.1 Consumer buys a fixed rate asset data asset, and downloads it
436
- ```Typescript
437
- const { chainId } = await publisherAccount.provider.getNetwork()
438
- datatoken = new Datatoken(publisherAccount, Number(chainId))
439
- const DATATOKEN_AMOUNT = '10000'
440
-
441
- await datatoken.mint(
442
- freDatatokenAddress,
443
- await publisherAccount.getAddress(),
444
- DATATOKEN_AMOUNT
445
- )
446
-
447
- const consumerBalance = await provider.getBalance(await consumerAccount.getAddress())
448
- const consumerETHBalance = formatEther(consumerBalance)
449
-
450
- ```
451
- Let's do a quick check of the consumer ETH balance before the swap
452
- ```Typescript
453
- console.log(`Consumer ETH balance: ${consumerETHBalance}`)
454
- let consumerOCEANBalance = await balance(
455
- consumerAccount,
456
- addresses.Ocean,
457
- await consumerAccount.getAddress()
458
- )
459
- console.log(`Consumer OCEAN balance before swap: ${consumerOCEANBalance}`)
460
- let consumerDTBalance = await balance(
461
- consumerAccount,
462
- freDatatokenAddress,
463
- await consumerAccount.getAddress()
464
- )
465
- console.log(`Consumer ${FRE_NFT_SYMBOL} balance before swap: ${consumerDTBalance}`)
466
-
467
- ```
468
- 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
469
- ```Typescript
470
- await approve(
471
- consumerAccount,
472
- config,
473
- await consumerAccount.getAddress(),
474
- addresses.Ocean,
475
- freAddress,
476
- '100'
477
- )
478
- await approve(
479
- publisherAccount,
480
- config,
481
- await publisherAccount.getAddress(),
482
- freDatatokenAddress,
483
- freAddress,
484
- DATATOKEN_AMOUNT
485
- )
486
-
487
- const fixedRate = new FixedRateExchange(freAddress, consumerAccount, Number(chainId))
488
-
489
- ```
490
- Now we can make the contract call
491
- ```Typescript
492
-
493
- await fixedRate.buyDatatokens(freId, '1', '2')
494
-
495
- consumerOCEANBalance = await balance(
496
- consumerAccount,
497
- addresses.Ocean,
498
- await consumerAccount.getAddress()
499
- )
500
- console.log(`Consumer OCEAN balance after swap: ${consumerOCEANBalance}`)
501
- consumerDTBalance = await balance(
502
- consumerAccount,
503
- freDatatokenAddress,
504
- await consumerAccount.getAddress()
505
- )
506
- console.log(`Consumer ${FRE_NFT_SYMBOL} balance after swap: ${consumerDTBalance}`)
507
-
508
- const resolvedDDO = await aquarius.waitForIndexer(fixedDDO.id)
509
- assert(resolvedDDO, 'Cannot fetch DDO from Aquarius')
510
-
511
- ```
512
- Next, we need to initialize the provider
513
- ```Typescript
514
- const initializeData = await ProviderInstance.initialize(
515
- resolvedDDO.id,
516
- resolvedDDO.services[0].id,
517
- 0,
518
- await consumerAccount.getAddress(),
519
- providerUrl
520
- )
521
-
522
- const providerFees: ProviderFees = {
523
- providerFeeAddress: initializeData.providerFee.providerFeeAddress,
524
- providerFeeToken: initializeData.providerFee.providerFeeToken,
525
- providerFeeAmount: initializeData.providerFee.providerFeeAmount,
526
- v: initializeData.providerFee.v,
527
- r: initializeData.providerFee.r,
528
- s: initializeData.providerFee.s,
529
- providerData: initializeData.providerFee.providerData,
530
- validUntil: initializeData.providerFee.validUntil
531
- }
532
-
533
- console.log(`Provider fee amount: ${providerFees.providerFeeAmount}`)
534
-
535
- const approveTx = await approve(
536
- consumerAccount,
537
- config,
538
- await consumerAccount.getAddress(),
539
- freDatatokenAddress,
540
- providerFees.providerFeeAddress,
541
- providerFees.providerFeeAmount
542
- )
543
-
544
- datatoken = new Datatoken(consumerAccount, Number(chainId))
545
-
546
- ```
547
- Lets now make the payment
548
- ```Typescript
549
- const tx = await datatoken.startOrder(
550
- freDatatokenAddress,
551
- await consumerAccount.getAddress(),
552
- 0,
553
- providerFees
554
- )
555
- const orderTx = await tx.wait()
556
- const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted')
557
- console.log(`Order started, tx: ${orderStartedTx.transactionHash}`)
558
-
559
- ```
560
- Now we can get the url
561
- ```Typescript
562
- const downloadURL = await ProviderInstance.getDownloadUrl(
563
- fixedDDO.id,
564
- fixedDDO.services[0].id,
565
- 0,
566
- orderStartedTx.transactionHash,
567
- providerUrl,
568
- consumerAccount
569
- )
570
-
571
- ```
572
- Lets check that the download URL was successfully received
573
- ```Typescript
574
- console.log(`Download URL: ${downloadURL}`)
575
-
576
- consumerOCEANBalance = await balance(
577
- consumerAccount,
578
- addresses.Ocean,
579
- await consumerAccount.getAddress()
580
- )
581
- console.log(`Consumer OCEAN balance after order: ${consumerOCEANBalance}`)
582
- consumerDTBalance = await balance(
583
- consumerAccount,
584
- freDatatokenAddress,
585
- await consumerAccount.getAddress()
586
- )
587
- console.log(`Consumer ${FRE_NFT_SYMBOL} balance after order: ${consumerDTBalance}`)
588
-
589
- try {
590
- const fileData = await downloadFile(downloadURL)
591
- console.log(fileData)
592
- } catch (e) {
593
- LoggerInstance.error('Download failed', e)
594
- assert.fail('Download failed')
595
- }
596
- ```
597
- <!--
598
- }).timeout(40000)
599
- -->
600
-
601
- ## 8. Publish Data NFT and a Datatoken with a dispenser
602
-
603
- ### 8.1 Publish a dataset (create NFT + Datatoken) with a dispenser
604
- ```Typescript
605
- const { chainId } = await publisherAccount.provider.getNetwork()
606
- const factory = new NftFactory(
607
- addresses.ERC721Factory,
608
- publisherAccount,
609
- Number(chainId)
610
- )
611
-
612
- const nftParams: NftCreateData = {
613
- name: DISP_NFT_NAME,
614
- symbol: DISP_NFT_SYMBOL,
615
- templateIndex: 1,
616
- tokenURI: '',
617
- transferable: true,
618
- owner: await publisherAccount.getAddress()
619
- }
620
-
621
- const datatokenParams: DatatokenCreateParams = {
622
- templateIndex: 1,
623
- cap: '100000',
624
- feeAmount: '0',
625
- paymentCollector: ZERO_ADDRESS,
626
- feeToken: ZERO_ADDRESS,
627
- minter: await publisherAccount.getAddress(),
628
- mpFeeAddress: ZERO_ADDRESS
629
- }
630
-
631
- const dispenserParams: DispenserCreationParams = {
632
- dispenserAddress: addresses.Dispenser,
633
- maxTokens: '1',
634
- maxBalance: '1',
635
- withMint: true,
636
- allowedSwapper: ZERO_ADDRESS
637
- }
638
-
639
- const bundleNFT = await factory.createNftWithDatatokenWithDispenser(
640
- nftParams,
641
- datatokenParams,
642
- dispenserParams
643
- )
644
- const trxReceipt = await bundleNFT.wait()
645
- const nftCreatedEvent = getEventFromTx(trxReceipt, 'NFTCreated')
646
- const tokenCreatedEvent = getEventFromTx(trxReceipt, 'TokenCreated')
647
- const dispenserCreatedEvent = getEventFromTx(trxReceipt, 'DispenserCreated')
648
-
649
- dispenserNftAddress = nftCreatedEvent.args.newTokenAddress
650
- dispenserDatatokenAddress = tokenCreatedEvent.args.newTokenAddress
651
- dispenserAddress = dispenserCreatedEvent.args.newTokenAddress // double check this
652
- ```
653
- Lets check that we managed to received all of those values without any problems
654
- ```Typescript
655
- console.log(`Dispenser NFT address: ${dispenserNftAddress}`)
656
- console.log(`Dispenser Datatoken address: ${dispenserDatatokenAddress}`)
657
- console.log(`Dispenser address: ${dispenserAddress}`)
658
- ```
659
- <!--
660
- }).timeout(40000)
661
- -->
662
- ### 8.2 Set metadata in the dispenser NFT
663
- ```Typescript
664
- const { chainId } = await publisherAccount.provider.getNetwork()
665
- const nft = new Nft(publisherAccount, Number(chainId))
666
-
667
- ```
668
- Lets start by updating the ddo and setting the did
669
- ```Typescript
670
- fixedDDO.chainId = Number(chainId)
671
-
672
- fixedDDO.id =
673
- 'did:op:' + SHA256(getAddress(dispenserNftAddress) + fixedDDO.chainId.toString(10))
674
- fixedDDO.nftAddress = dispenserNftAddress
675
- ```
676
- Now we need to encrypt file(s) using provider
677
- ```Typescript
678
- ASSET_URL.datatokenAddress = dispenserDatatokenAddress
679
- ASSET_URL.nftAddress = dispenserNftAddress
680
- fixedDDO.services[0].files = await ProviderInstance.encrypt(
681
- ASSET_URL,
682
- fixedDDO.chainId,
683
- providerUrl,
684
- publisherAccount
685
- )
686
- fixedDDO.services[0].datatokenAddress = dispenserDatatokenAddress
687
-
688
- console.log(`DID: ${fixedDDO.id}`)
689
-
690
- const encryptedDDO = await ProviderInstance.encrypt(
691
- fixedDDO,
692
- fixedDDO.chainId,
693
- providerUrl,
694
- publisherAccount
695
- )
696
- const isAssetValid: ValidateMetadata = await aquarius.validate(
697
- fixedDDO,
698
- publisherAccount,
699
- providerUrl
700
- )
701
- assert(isAssetValid.valid === true, 'Published asset is not valid')
702
- await nft.setMetadata(
703
- dispenserNftAddress,
704
- await publisherAccount.getAddress(),
705
- 0,
706
- providerUrl,
707
- '',
708
- toBeHex(2),
709
- encryptedDDO,
710
- isAssetValid.hash
711
- )
712
- ```
713
- <!--
714
- }).timeout(40000)
715
- -->
716
-
717
- ## 9. Consume a dispenser data asset
718
-
719
- ### 9.1 Consumer gets a dispenser data asset, and downloads it
720
- ```Typescript
721
- const { chainId } = await publisherAccount.provider.getNetwork()
722
- datatoken = new Datatoken(publisherAccount, Number(chainId))
723
- const dispenser = new Dispenser(addresses.Dispenser, consumerAccount, Number(chainId))
724
-
725
- let consumerDTBalance = await balance(
726
- consumerAccount,
727
- dispenserDatatokenAddress,
728
- await consumerAccount.getAddress()
729
- )
730
- console.log(
731
- `Consumer ${DISP_NFT_SYMBOL} balance before dispense: ${consumerDTBalance}`
732
- )
733
-
734
- await dispenser.dispense(
735
- dispenserDatatokenAddress,
736
- '1',
737
- await consumerAccount.getAddress()
738
- )
739
-
740
- consumerDTBalance = await balance(
741
- consumerAccount,
742
- dispenserDatatokenAddress,
743
- await consumerAccount.getAddress()
744
- )
745
- console.log(
746
- `Consumer ${DISP_NFT_SYMBOL} balance after dispense: ${consumerDTBalance}`
747
- )
748
-
749
- const resolvedDDO = await aquarius.waitForIndexer(fixedDDO.id)
750
- assert(resolvedDDO, 'Cannot fetch DDO from Aquarius')
751
-
752
- datatoken = new Datatoken(consumerAccount, Number(chainId))
753
-
754
- ```
755
- At this point we need to encrypt file(s) using provider
756
- ```Typescript
757
- const initializeData = await ProviderInstance.initialize(
758
- resolvedDDO.id,
759
- resolvedDDO.services[0].id,
760
- 0,
761
- await consumerAccount.getAddress(),
762
- providerUrl
763
- )
764
-
765
- const providerFees: ProviderFees = {
766
- providerFeeAddress: initializeData.providerFee.providerFeeAddress,
767
- providerFeeToken: initializeData.providerFee.providerFeeToken,
768
- providerFeeAmount: initializeData.providerFee.providerFeeAmount,
769
- v: initializeData.providerFee.v,
770
- r: initializeData.providerFee.r,
771
- s: initializeData.providerFee.s,
772
- providerData: initializeData.providerFee.providerData,
773
- validUntil: initializeData.providerFee.validUntil
774
- }
775
- ```
776
- Now we need to make the payment
777
- ```Typescript
778
- const tx = await datatoken.startOrder(
779
- dispenserDatatokenAddress,
780
- await consumerAccount.getAddress(),
781
- 0,
782
- providerFees
783
- )
784
- const orderTx = await tx.wait()
785
- const orderStartedTx = getEventFromTx(orderTx, 'OrderStarted')
786
- ```
787
- Now we can get the download URL
788
- ```Typescript
789
- const downloadURL = await ProviderInstance.getDownloadUrl(
790
- fixedDDO.id,
791
- fixedDDO.services[0].id,
792
- 0,
793
- orderStartedTx.transactionHash,
794
- providerUrl,
795
- consumerAccount
796
- )
797
- ```
798
- Let's check we received the download URL ok
799
- ```Typescript
800
- console.log(`Download URL: ${downloadURL}`)
801
-
802
- consumerDTBalance = await balance(
803
- consumerAccount,
804
- dispenserDatatokenAddress,
805
- await consumerAccount.getAddress()
806
- )
807
- console.log(`Consumer ${DISP_NFT_SYMBOL} balance after order: ${consumerDTBalance}`)
808
-
809
- try {
810
- const fileData = await downloadFile(downloadURL)
811
- console.log(fileData)
812
- } catch (e) {
813
- assert.fail('Download failed')
814
- }
815
- ```
816
- <!--
817
- }).timeout(40000)
818
- -->
819
-
820
- ## 10. Using ERC725 Key-Value Store
821
-
822
- 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).
823
-
824
- Let's see how!
825
-
826
- Here are the steps:
827
-
828
- 1. Setup (same as above)
829
- 2. Publish data NFT (same as above)
830
- 3. Add key-value pair to data NFT (use the `setData` method)
831
- 4. Retrieve value from data NFT (use the `getData` method)
832
-
833
- ### 10.1 Add key-value pair to data NFT
834
- Let's start by using the `setData` method to update the nft key value store with some data
835
- ```Typescript
836
- const { chainId } = await publisherAccount.provider.getNetwork()
837
- const nft = new Nft(publisherAccount, Number(chainId))
838
- const data = 'SomeData'
839
- try {
840
- await nft.setData(
841
- freNftAddress,
842
- await publisherAccount.getAddress(),
843
- '0x1234',
844
- data
845
- )
846
- } catch (e) {
847
- console.log('error = ', e)
848
- assert.fail('Failed to set data in NFT ERC725 key value store', e)
849
- }
850
- ```
851
-
852
- Under the hood, this uses [ERC725](https://erc725alliance.org/), which augments ERC721 with a well-defined way to set and get key-value pairs.
853
-
854
- ### 10.2 get the key-value pair data from the NFT'
855
-
856
- Use the `getData` method to get the data stored in the nft key value store
857
-
858
- ```Typescript
859
- try {
860
- const response = await nft.getData(freNftAddress, '0x1234')
861
- console.log('getData response: ', response)
862
- assert(
863
- response === data,
864
- 'Wrong data received when getting data from NFT ERC725 key value store'
865
- )
866
- } catch (e) {
867
- console.log('e = ', e)
868
- assert.fail('Failed to get data from NFT ERC725 key value store', e)
869
- }
870
- ```
871
-
872
- That's it! Note the simplicity. All data was stored and retrieved from on-chain. We don't need Ocean Provider or Ocean Aquarius for these use cases (though the latter can help for fast querying & retrieval).
873
- <!--
874
- }).timeout(40000)
875
- -->
876
-
877
-
878
- ## Editing this file
879
- Please note that CodeExamples.md is an autogenerated file, you should not edit it directly.
880
- Updates should be done in `test/integration/CodeExamples.test.ts` and all markdown should have three forward slashes before it
881
- e.g. `/// # H1 Title`