-
Notifications
You must be signed in to change notification settings - Fork 1
/
NVMAppFlows.test.ts
637 lines (552 loc) Β· 21.7 KB
/
NVMAppFlows.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// @ts-nocheck
import chai, { assert } from 'chai'
import chaiAsPromised from 'chai-as-promised'
import { decodeJwt, JWTPayload } from 'jose'
import config from '../../test/config'
import TestContractHandler from '../../test/keeper/TestContractHandler'
import { Nevermined } from '../../src/nevermined/Nevermined'
import { NvmAccount } from '../../src/models/NvmAccount'
import { AssetPrice } from '../../src/models/AssetPrice'
import { SubscriptionCreditsNFTApi } from '../../src/nevermined/api/nfts/SubscriptionCreditsNFTApi'
import { Token } from '../../src/keeper/contracts/Token'
import { DDO } from '../../src/ddo/DDO'
import { TransferNFTCondition } from '../../src/keeper/contracts/conditions/NFTs/TransferNFTCondition'
import { getRoyaltyAttributes, RoyaltyAttributes } from '../../src/nevermined/api/AssetsApi'
import { MetaData } from '../../src/types/DDOTypes'
import { generateSubscriptionMetadata, getMetadata } from '../utils/ddo-metadata-generator'
import {
PublishMetadataOptions,
PublishOnChainOptions,
RoyaltyKind,
} from '../../src/types/MetadataTypes'
import { NFTAttributes } from '../../src/models/NFTAttributes'
import { mineBlocks, sleep } from '../utils/utils'
chai.use(chaiAsPromised)
describe('NVM App main flows using Credit NFTs (ERC-1155)', () => {
let publisher: NvmAccount
let subscriber: NvmAccount
let reseller: NvmAccount
let nevermined: Nevermined
let token: Token
let transferNftCondition: TransferNFTCondition
let creditSubscriptionDDO: DDO
let timeSubscriptionDDO: DDO
let datasetDDO: DDO
let agreementId: string
const amounts1 = [15n, 5n]
const amounts2 = [30n, 10n]
let receivers: string[]
let subsBronzePrice: AssetPrice
let subsSilverPrice: AssetPrice
let subsGoldPrice: AssetPrice
let royaltyAttributes: RoyaltyAttributes
let subscriptionMetadata: MetaData
let timeSubscriptionMetadata: MetaData
let datasetMetadata: MetaData
const preMint = false
const royalties = 0
const nftTransfer = false
const subscriptionBronzeDuration = 9 // in blocks
const subscriptionSilverDuration = 20 // in blocks
const subscriptionGoldDuration = 50 // in blocks
const subscriptionBronzePrice = 15n
const subscriptionSilverPrice = 20n
const subscriptionGoldPrice = 40n
// This is the number of credits that the subscriber will get when purchase the subscription
// In the DDO this will be added in the `_numberNFTs` value of the `nft-sales` service of the subscription
const subscriptionBronzeCredits = 1n
const subscriptionSilverCredits = 15n
const subscriptionGoldCredits = 50n
// This is the number of credits that cost get access to the service attached to the subscription
// In the DDO this will be added in the `_numberNFTs` value of the `nft-access` service of the asset associated to the subscription
const accessCostInCreditsDataset = 2n
let salesServices
let accessServices
let subscriptionNFT: SubscriptionCreditsNFTApi
let neverminedNodeAddress
let payload: JWTPayload
before(async () => {
TestContractHandler.setConfig(config)
nevermined = await Nevermined.getInstance(config, {
loadCore: true,
loadServiceAgreements: true,
loadNFTs1155: true,
loadNFTs721: false,
loadDispenser: true,
loadERC20Token: true,
loadAccessFlow: false,
loadDIDTransferFlow: false,
loadRewards: false,
loadRoyalties: true,
loadCompute: false,
})
;[, publisher, subscriber, , reseller] = nevermined.accounts.list()
const clientAssertion = await nevermined.utils.jwt.generateClientAssertion(publisher)
await nevermined.services.marketplace.login(clientAssertion)
payload = decodeJwt(config.marketplaceAuthToken)
datasetMetadata = getMetadata()
timeSubscriptionMetadata = generateSubscriptionMetadata('NVM App Time only Subscription')
subscriptionMetadata = generateSubscriptionMetadata('NVM App Credits Subscription')
datasetMetadata.userId = payload.sub
neverminedNodeAddress = await nevermined.services.node.getProviderAddress()
// conditions
;({ transferNftCondition } = nevermined.keeper.conditions)
// components
;({ token } = nevermined.keeper)
// scale = 10n ** BigInt(await token.decimals())
receivers = [publisher.getId(), reseller.getId()]
subsBronzePrice = new AssetPrice(
new Map([
[receivers[0], amounts1[0]],
[receivers[1], amounts1[1]],
]),
).setTokenAddress(token.address)
subsSilverPrice = new AssetPrice(
new Map([
[receivers[0], amounts1[0]],
[receivers[1], amounts1[1]],
]),
).setTokenAddress(token.address)
subsGoldPrice = new AssetPrice(
new Map([
[receivers[0], amounts2[0]],
[receivers[1], amounts2[1]],
]),
).setTokenAddress(token.address)
royaltyAttributes = getRoyaltyAttributes(nevermined, RoyaltyKind.Standard, royalties)
})
describe('As NVM Admin I want to setup a factory contract for subscriptions', () => {
it('As NVM admin I can deploy a `NFT1155SubscriptionUpgradeable` contract (NFT1155)', async () => {
console.log(`Running first test`)
// Deploy NFT
TestContractHandler.setConfig(config)
const contractABI = await TestContractHandler.getABIArtifact(
`NFT1155SubscriptionUpgradeable.${await nevermined.keeper.getNetworkName()}`,
'./artifacts/',
)
subscriptionNFT = await SubscriptionCreditsNFTApi.deployInstance(
config,
contractABI,
publisher,
[
publisher.getId(),
nevermined.keeper.didRegistry.address,
'App Subscription NFT',
'CRED',
'',
nevermined.keeper.nvmConfig.address,
],
)
console.debug(`Deployed ERC-1155 Subscription NFT on address: ${subscriptionNFT.address}`)
await nevermined.contracts.loadNft1155Api(subscriptionNFT)
await subscriptionNFT.grantOperatorRole(transferNftCondition.address, publisher)
console.debug(`Granting operator role to Nevermined Node Address: ${neverminedNodeAddress}`)
await subscriptionNFT.grantOperatorRole(neverminedNodeAddress, publisher)
assert.equal(nevermined.nfts1155.getContract.address, subscriptionNFT.address)
})
it('I should grant Nevermined the operator role', async () => {
assert.isTrue(
await nevermined.nfts1155.isOperator(
subscriptionNFT.address,
nevermined.keeper.conditions.transferNftCondition.address,
1155,
),
)
})
})
describe('As publisher I can register a TIME ONLY Smart Subscription', () => {
it('As publisher I can register a time based Smart Subscription as part of the NFT1155', async () => {
const nftAttributes = NFTAttributes.getCreditsSubscriptionInstance({
metadata: timeSubscriptionMetadata,
services: [
{
serviceType: 'nft-sales',
price: subsBronzePrice,
nft: {
duration: subscriptionBronzeDuration,
amount: subscriptionBronzeCredits,
nftTransfer,
},
},
],
providers: [neverminedNodeAddress],
nftContractAddress: subscriptionNFT.address,
preMint,
royaltyAttributes: royaltyAttributes,
})
timeSubscriptionDDO = await nevermined.nfts1155.create(nftAttributes, publisher)
assert.equal(await subscriptionNFT.balance(timeSubscriptionDDO.id, publisher.getId()), 0n)
assert.isDefined(timeSubscriptionDDO)
console.log(`Subscription DID: ${timeSubscriptionDDO.id}`)
salesServices = timeSubscriptionDDO.getServicesByType('nft-sales')
assert.equal(salesServices.length, 1)
})
it('As publisher I can register an off-chain dataset associated to a TIME ONLY subscription', async () => {
const nftAttributes = NFTAttributes.getCreditsSubscriptionInstance({
metadata: getMetadata(),
services: [
{
serviceType: 'nft-access',
nft: {
tokenId: timeSubscriptionDDO.shortId(),
duration: subscriptionBronzeDuration,
amount: 0n,
nftTransfer,
},
},
],
providers: [neverminedNodeAddress],
nftContractAddress: subscriptionNFT.address,
preMint,
royaltyAttributes: royaltyAttributes,
})
datasetDDO = await nevermined.nfts1155.create(nftAttributes, publisher, {
metadata: PublishMetadataOptions.OnlyMetadataAPI,
did: PublishOnChainOptions.OnlyOffchain,
})
assert.isDefined(datasetDDO)
console.log(`Asset DID: ${datasetDDO.id}`)
accessServices = datasetDDO.getServicesByType('nft-access')
assert.equal(accessServices.length, 1)
const tokenId = DDO.getTokenIdFromService(accessServices[0])
assert.equal(tokenId, timeSubscriptionDDO.shortId())
const amount = DDO.getNftAmountFromService(accessServices[0])
assert.equal(amount, 0n)
})
})
describe('As a subscriber I can purchase a TIME based Smart Subscription based on NFT1155', () => {
let agreementId: string
it('I can order and claim the subscription', async () => {
await nevermined.accounts.requestTokens(subscriber, subscriptionBronzePrice)
const bronzeSalesService = timeSubscriptionDDO.getServicesByType('nft-sales')[0]
console.log(
`Bronze Sales Service with index ${bronzeSalesService.index} and Price ${bronzeSalesService.attributes.main.price}`,
)
agreementId = await nevermined.nfts1155.order(
timeSubscriptionDDO.id,
subscriptionBronzeCredits,
subscriber,
bronzeSalesService.index,
)
assert.isDefined(agreementId)
try {
const receipt = await nevermined.nfts1155.claim(
agreementId,
publisher.getId(),
subscriber.getId(),
subscriptionBronzeCredits,
timeSubscriptionDDO.id,
bronzeSalesService.index,
)
assert.isTrue(receipt)
} catch (e) {
console.error(e.message)
assert.fail(e.message)
}
})
it('I can download a dataset using my subscription', async () => {
const balanceBefore = await subscriptionNFT.balance(
timeSubscriptionDDO.id,
subscriber.getId(),
)
console.log(`Balance Before: ${balanceBefore}`)
console.log(`Time based AgreementId: ${agreementId}`)
for (let i = 0; i < 3; i++) {
const result = await nevermined.nfts1155.access(
datasetDDO.id,
subscriber,
'/tmp/.nevermined-downloads/0/',
undefined,
agreementId,
)
await sleep(1000)
assert.isTrue(result)
console.log(`Asset downloaded ${i} time/s`)
}
const minted = await subscriptionNFT.getContract.getMintedEntries(
subscriber.getId(),
timeSubscriptionDDO.shortId(),
)
console.log(`Current Block Number: ${await nevermined.client.public.getBlockNumber()}`)
console.log(`Minted entries: ${minted.length}`)
minted.map((m) =>
console.log(
`Minted ${m.amountMinted} tokens on block ${m.mintBlock} and expiring on ${m.expirationBlock} block`,
),
)
const balanceAfter = await subscriptionNFT.balance(timeSubscriptionDDO.id, subscriber.getId())
console.log(`Balance After: ${balanceAfter}`)
})
})
describe('Subscriptions expires', () => {
it('When subscription expires my balance is back to 0', async () => {
await mineBlocks(nevermined, subscriber, subscriptionBronzeDuration + 1)
const balanceAfter = await subscriptionNFT.balance(timeSubscriptionDDO.id, subscriber.getId())
console.log(`Balance After Expiring duration: ${balanceAfter}`)
assert.isTrue(balanceAfter === 0n)
})
it('As a subscriber I can not access to the dataset using my expired subscription', async () => {
try {
await nevermined.nfts1155.access(
datasetDDO.id,
subscriber,
'/tmp/.nevermined-downloads/0/',
undefined,
agreementId,
)
assert.fail('Should not be able to access the dataset')
} catch (e) {
assert.isTrue(true)
}
})
})
describe('As publisher I can register a TIME & CREDITS based Smart Subscription', () => {
it('As publisher I can register a time based Smart Subscription as part of the NFT1155', async () => {
const nftAttributes = NFTAttributes.getCreditsSubscriptionInstance({
metadata: subscriptionMetadata,
services: [
{
serviceType: 'nft-sales',
price: subsSilverPrice,
nft: {
duration: subscriptionSilverDuration,
amount: subscriptionSilverCredits,
nftTransfer,
},
},
{
serviceType: 'nft-sales',
price: subsGoldPrice,
nft: {
duration: subscriptionGoldDuration,
amount: subscriptionGoldCredits,
nftTransfer,
},
},
],
providers: [neverminedNodeAddress],
nftContractAddress: subscriptionNFT.address,
preMint,
royaltyAttributes: royaltyAttributes,
})
creditSubscriptionDDO = await nevermined.nfts1155.create(nftAttributes, publisher)
assert.equal(await subscriptionNFT.balance(creditSubscriptionDDO.id, publisher.getId()), 0n)
assert.isDefined(creditSubscriptionDDO)
console.log(`Subscription DID: ${creditSubscriptionDDO.id}`)
salesServices = creditSubscriptionDDO.getServicesByType('nft-sales')
assert.equal(salesServices.length, 2)
assert.equal(
salesServices[0].attributes.main.price.toString(),
subsSilverPrice.getTotalPrice().toString(),
)
assert.equal(
salesServices[1].attributes.main.price.toString(),
subsGoldPrice.getTotalPrice().toString(),
)
})
it('As publisher I can register an off-chain dataset associated to a time and credits subscription', async () => {
const nftAttributes = NFTAttributes.getCreditsSubscriptionInstance({
metadata: datasetMetadata,
services: [
{
serviceType: 'nft-access',
nft: {
tokenId: creditSubscriptionDDO.shortId(),
duration: subscriptionSilverDuration,
amount: accessCostInCreditsDataset,
nftTransfer,
maxCreditsToCharge: 100n,
minCreditsToCharge: 1n,
},
},
],
providers: [neverminedNodeAddress],
nftContractAddress: subscriptionNFT.address,
preMint,
royaltyAttributes: royaltyAttributes,
})
datasetDDO = await nevermined.nfts1155.create(nftAttributes, publisher, {
metadata: PublishMetadataOptions.OnlyMetadataAPI,
did: PublishOnChainOptions.OnlyOffchain,
})
assert.isDefined(datasetDDO)
console.log(`Asset DID: ${datasetDDO.id}`)
accessServices = datasetDDO.getServicesByType('nft-access')
assert.equal(accessServices.length, 1)
const tokenId = DDO.getTokenIdFromService(accessServices[0])
assert.equal(tokenId, creditSubscriptionDDO.shortId())
})
it.skip('As a publisher I can register an off-chain webservice associated to a time subscription', async () => {})
})
describe('As a subscriber I can purchase a time and credits based Smart Subscription based on NFT1155', () => {
let agreementId: string
it('I can order and claim the subscription', async () => {
await nevermined.accounts.requestTokens(subscriber, subscriptionSilverPrice)
const silverSalesService = creditSubscriptionDDO.getServicesByType('nft-sales')[0]
console.log(
`Silver Sales Service with index ${silverSalesService.index} and Price ${silverSalesService.attributes.main.price}`,
)
agreementId = await nevermined.nfts1155.order(
creditSubscriptionDDO.id,
subscriptionSilverCredits,
subscriber,
silverSalesService.index,
)
assert.isDefined(agreementId)
try {
const receipt = await nevermined.nfts1155.claim(
agreementId,
publisher.getId(),
subscriber.getId(),
subscriptionSilverCredits,
creditSubscriptionDDO.id,
silverSalesService.index,
)
assert.isTrue(receipt)
} catch (e) {
console.error(e.message)
assert.fail(e.message)
}
})
it('I can download a dataset using my subscription', async () => {
const balanceBefore = await subscriptionNFT.balance(
creditSubscriptionDDO.id,
subscriber.getId(),
)
console.log(`Balance Before: ${balanceBefore}`)
console.log(`First AgreementId: ${agreementId}`)
const result = await nevermined.nfts1155.access(
datasetDDO.id,
subscriber,
'/tmp/.nevermined-downloads/1/',
undefined,
agreementId,
)
assert.isTrue(result)
const balanceAfter = await subscriptionNFT.balance(
creditSubscriptionDDO.id,
subscriber.getId(),
)
console.log(`Balance After: ${balanceAfter}`)
assert.equal(balanceBefore - accessCostInCreditsDataset, balanceAfter)
})
it.skip('I can access a service using my subscription ', async () => {})
})
describe('Subscriptions expires', () => {
it('When subscription expires my balance is back to 0', async () => {
await mineBlocks(nevermined, subscriber, subscriptionSilverDuration + 1)
const balanceAfter = await subscriptionNFT.balance(
creditSubscriptionDDO.id,
subscriber.getId(),
)
console.log(`Balance After Expiring duration: ${balanceAfter}`)
assert.isTrue(balanceAfter === 0n)
})
it('As a subscriber I can not access to the dataset using my expired subscription', async () => {
try {
await nevermined.nfts1155.access(
datasetDDO.id,
subscriber,
'/tmp/.nevermined-downloads/1/',
undefined,
agreementId,
)
assert.fail('Should not be able to access the dataset')
} catch (e) {
assert.isTrue(true)
}
})
it.skip('As a subscriber I can not access to the service using my expired subscription ', async () => {})
})
describe('As a subscriber I want to topup my subscription purchasing a GOLD plan', () => {
it('I check the details of the subscription NFT', async () => {
const details = await nevermined.nfts1155.details(creditSubscriptionDDO.id)
assert.equal(details.owner, publisher.getId())
})
it('I am ordering the GOLD plan associated to the subscription NFT', async () => {
const balanceBeforeTopup = await subscriptionNFT.balance(
creditSubscriptionDDO.id,
subscriber.getId(),
)
console.log(`Balance Before Topup: ${balanceBeforeTopup}`)
await nevermined.accounts.requestTokens(subscriber, subscriptionGoldPrice)
const goldSalesService = creditSubscriptionDDO.getServicesByType('nft-sales')[1]
console.log(
`Gold Sales Service with index ${goldSalesService.index} and Price ${goldSalesService.attributes.main.price}`,
)
agreementId = await nevermined.nfts1155.order(
creditSubscriptionDDO.id,
subscriptionGoldCredits,
subscriber,
goldSalesService.index,
)
assert.isDefined(agreementId)
console.log(`Ordered Agreement Id ${agreementId}`)
try {
const receipt = await nevermined.nfts1155.claim(
agreementId,
publisher.getId(),
subscriber.getId(),
subscriptionGoldCredits,
creditSubscriptionDDO.id,
goldSalesService.index,
)
assert.isTrue(receipt)
} catch (e) {
console.error(e.message)
assert.fail(e.message)
}
const balanceAfterTopup = await subscriptionNFT.balance(
creditSubscriptionDDO.id,
subscriber.getId(),
)
console.log(`Balance After Topup: ${balanceAfterTopup}`)
const minted = await subscriptionNFT.getContract.getMintedEntries(
subscriber.getId(),
creditSubscriptionDDO.shortId(),
)
console.log(`Current Block Number: ${await nevermined.client.public.getBlockNumber()}`)
console.log(`Minted entries: ${minted.length}`)
minted.map((m) =>
console.log(
`Minted ${m.amountMinted} tokens on block ${m.mintBlock} and expiring on ${m.expirationBlock} block`,
),
)
assert.equal(balanceBeforeTopup + subscriptionGoldCredits, balanceAfterTopup)
})
it('I can download again using my toped up subscription', async () => {
await mineBlocks(nevermined, subscriber, 1)
const balanceBefore = await subscriptionNFT.balance(
creditSubscriptionDDO.id,
subscriber.getId(),
)
console.log(`Balance Before: ${balanceBefore}`)
console.log(`Using Agreement Id ${agreementId}`)
const result = await nevermined.nfts1155.access(
datasetDDO.id,
subscriber,
'/tmp/.nevermined-downloads/2/',
undefined,
agreementId,
)
assert.isTrue(result)
const balanceAfter = await subscriptionNFT.balance(
creditSubscriptionDDO.id,
subscriber.getId(),
)
console.log(`Balance After: ${balanceAfter}`)
const minted = await subscriptionNFT.getContract.getMintedEntries(
subscriber.getId(),
creditSubscriptionDDO.shortId(),
)
console.log(`Current Block Number: ${await nevermined.client.public.getBlockNumber()}`)
console.log(`Minted entries: ${minted.length}`)
minted.map((m) =>
console.log(
`Minted ${m.amountMinted} tokens on block ${m.mintBlock} and expiring on ${m.expirationBlock} block`,
),
)
assert.equal(balanceBefore - accessCostInCreditsDataset, balanceAfter)
})
})
})