-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCredits.e2e.test.ts
413 lines (346 loc) Β· 14.9 KB
/
Credits.e2e.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
import chai, { assert } from 'chai'
import chaiAsPromised from 'chai-as-promised'
import { decodeJwt, JWTPayload } from 'jose'
import { DDO } from '../../src/ddo/DDO'
import { NvmAccount } from '../../src/models/NvmAccount'
import { Nevermined } from '../../src/nevermined/Nevermined'
import { MetaData } from '../../src/types/DDOTypes'
import config from '../../test/config'
import { jsonReplacer } from '../../src/common/helpers'
import { EscrowPaymentCondition, TransferNFTCondition } from '../../src/keeper/contracts/conditions'
import { Token } from '../../src/keeper/contracts/Token'
import { AssetPrice } from '../../src/models/AssetPrice'
import { NFTAttributes } from '../../src/models/NFTAttributes'
import { NFT1155Api, SubscriptionCreditsNFTApi } from '../../src/nevermined/api'
import { getRoyaltyAttributes, RoyaltyAttributes } from '../../src/nevermined/api/AssetsApi'
import { getChecksumAddress } from '../../src/nevermined/utils/BlockchainViemUtils'
import { EventOptions } from '../../src/types/EventTypes'
import { RoyaltyKind } from '../../src/types/MetadataTypes'
import { didZeroX } from '../../src/utils/ConversionTypeHelpers'
import TestContractHandler from '../../test/keeper/TestContractHandler'
import { getMetadata } from '../utils/ddo-metadata-generator'
import { sleep } from '../utils/utils'
chai.use(chaiAsPromised)
describe('Credit Subscriptions using NFT ERC-1155 End-to-End', () => {
let editor: NvmAccount
let subscriber: NvmAccount
let reseller: NvmAccount
let nevermined: Nevermined
let token: Token
let escrowPaymentCondition: EscrowPaymentCondition
let transferNftCondition: TransferNFTCondition
let subscriptionDDO: DDO
let assetDDO: DDO
let agreementId: string
// Configuration of First Sale:
// Editor -> Subscriber, the Reseller get a cut (25%)
let subscriptionPrice = 20n
let amounts = [15n, 5n]
let receivers: string[]
let assetPrice1: AssetPrice
let royaltyAttributes: RoyaltyAttributes
let subscriptionMetadata: MetaData
let assetMetadata: MetaData
let subsSalesService
const preMint = false
const royalties = 0
const nftTransfer = false
const subscriptionDuration = 1000 // in blocks
// 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 subscriptionCredits = 5n
// 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 accessCostInCredits = 2n
let initialBalances: any
let scale: bigint
let subscriptionNFT: NFT1155Api
let neverminedNodeAddress
let payload: JWTPayload
before(async () => {
TestContractHandler.setConfig(config)
nevermined = await Nevermined.getInstance(config)
;[, editor, subscriber, , reseller] = nevermined.accounts.list()
const clientAssertion = await nevermined.utils.jwt.generateClientAssertion(editor)
await nevermined.services.marketplace.login(clientAssertion)
payload = decodeJwt(config.marketplaceAuthToken)
assetMetadata = getMetadata()
subscriptionMetadata = getMetadata(undefined, 'Subscription NFT1155')
subscriptionMetadata.main.type = 'subscription'
assetMetadata.userId = payload.sub
neverminedNodeAddress = await nevermined.services.node.getProviderAddress()
// conditions
;({ escrowPaymentCondition, transferNftCondition } = nevermined.keeper.conditions)
// components
;({ token } = nevermined.keeper)
scale = 10n ** BigInt(await token.decimals())
subscriptionPrice = subscriptionPrice * scale
amounts = amounts.map((v) => v * scale)
receivers = [editor.getId(), reseller.getId()]
assetPrice1 = new AssetPrice(
new Map([
[receivers[0], amounts[0]],
[receivers[1], amounts[1]],
]),
).setTokenAddress(token.address)
royaltyAttributes = getRoyaltyAttributes(nevermined, RoyaltyKind.Standard, royalties)
initialBalances = {
editor: await token.balanceOf(editor.getId()),
subscriber: await token.balanceOf(subscriber.getId()),
reseller: await token.balanceOf(reseller.getId()),
escrowPaymentCondition: Number(await token.balanceOf(escrowPaymentCondition.address)),
}
})
describe('As an editor I want to register new content and provide a subscriptions to my content', () => {
it('I want to register a subscriptions NFT that gives access to exclusive contents to the holders', async () => {
console.log(`Running first test`)
// Deploy NFT
TestContractHandler.setConfig(config)
const networkName = await nevermined.keeper.getNetworkName()
const contractABI = await TestContractHandler.getABIArtifact(
'NFT1155SubscriptionUpgradeable',
config.artifactsFolder,
networkName,
)
subscriptionNFT = await SubscriptionCreditsNFTApi.deployInstance(
config,
contractABI,
editor,
[
editor.getId(),
nevermined.keeper.didRegistry.address,
'Credits Subscription NFT',
'CRED',
'',
nevermined.keeper.nvmConfig.address,
] as any,
)
console.debug(`Deployed ERC-1155 Subscription NFT on address: ${subscriptionNFT.address}`)
await nevermined.contracts.loadNft1155Api(subscriptionNFT)
await subscriptionNFT.grantOperatorRole(transferNftCondition.address, editor)
console.debug(`Granting operator role to Nevermined Node Address: ${neverminedNodeAddress}`)
await subscriptionNFT.grantOperatorRole(neverminedNodeAddress, editor)
assert.equal(nevermined.nfts1155.getContract.address, subscriptionNFT.address)
const nftAttributes = NFTAttributes.getCreditsSubscriptionInstance({
metadata: subscriptionMetadata,
services: [
{
serviceType: 'nft-sales',
price: assetPrice1,
nft: { duration: subscriptionDuration, amount: subscriptionCredits, nftTransfer },
},
],
providers: [neverminedNodeAddress],
nftContractAddress: subscriptionNFT.address,
preMint,
royaltyAttributes: royaltyAttributes,
})
subscriptionDDO = await nevermined.nfts1155.create(nftAttributes, editor)
assert.equal(await subscriptionNFT.balance(subscriptionDDO.id, editor.getId()), 0n)
assert.isDefined(subscriptionDDO)
console.log(`Subscription DID: ${subscriptionDDO.id}`)
})
it('should grant Nevermined the operator role', async () => {
assert.isTrue(
await nevermined.nfts1155.isOperatorOfDID(
subscriptionDDO.id,
nevermined.keeper.conditions.transferNftCondition.address,
),
)
})
it('I want to register a new asset and tokenize (via NFT)', async () => {
const nftAttributes = NFTAttributes.getCreditsSubscriptionInstance({
metadata: assetMetadata,
services: [
{
serviceType: 'nft-access',
nft: {
tokenId: subscriptionDDO.shortId(),
duration: subscriptionDuration,
amount: accessCostInCredits,
nftTransfer,
},
},
],
providers: [neverminedNodeAddress],
nftContractAddress: subscriptionNFT.address,
preMint,
royaltyAttributes: royaltyAttributes,
})
assetDDO = await nevermined.nfts1155.create(nftAttributes, editor)
assert.isDefined(assetDDO)
console.log(`Asset DID: ${assetDDO.id}`)
const accessService = assetDDO.findServiceByType('nft-access')
const tokenId = DDO.getTokenIdFromService(accessService)
assert.equal(tokenId, subscriptionDDO.shortId())
})
})
describe('As a subscriber I want to get access to some contents', () => {
it('I check the details of the subscription NFT', async () => {
const details = await nevermined.nfts1155.details(subscriptionDDO.id)
assert.equal(details.owner, editor.getId())
})
it('I am ordering the subscription NFT', async () => {
await nevermined.accounts.requestTokens(subscriber, subscriptionPrice / scale)
const subscriberBalanceBefore = await token.balanceOf(subscriber.getId())
assert.equal(subscriberBalanceBefore, initialBalances.subscriber + subscriptionPrice)
subsSalesService = subscriptionDDO.findServiceByType('nft-sales')
console.debug(`Ordering service with index ${subsSalesService.index}`)
agreementId = await nevermined.nfts1155.order(
subscriptionDDO.id,
subscriptionCredits,
subscriber,
subsSalesService.index,
)
assert.isDefined(agreementId)
console.debug(`Agreement ID: ${agreementId}`)
const subscriberBalanceAfter = await token.balanceOf(subscriber.getId())
assert.equal(subscriberBalanceAfter, initialBalances.subscriber)
})
it('The credits seller can check the payment and transfer the NFT to the subscriber', async () => {
// Let's use the Node to mint the subscription and release the payments
const balanceBefore = await subscriptionNFT.balance(subscriptionDDO.id, subscriber.getId())
console.log(`Balance Before: ${balanceBefore}`)
console.log(`Balance Before (JSON): ${JSON.stringify(balanceBefore.toString())}`)
assert.isTrue(balanceBefore === 0n)
try {
const receipt = await nevermined.nfts1155.claim(
agreementId,
editor.getId(),
subscriber.getId(),
subscriptionCredits,
subscriptionDDO.id,
subsSalesService.index,
)
assert.isTrue(receipt)
} catch (e) {
console.error(e.message)
assert.fail(e.message)
}
console.log(`Got the receipt`)
const minted = await subscriptionNFT.getContract.getMintedEntries(
subscriber.getId(),
subscriptionDDO.shortId(),
)
console.log(`Minted: ${minted.length}`)
})
it('the editor and reseller can receive their payment', async () => {
const receiver0Balance = await token.balanceOf(assetPrice1.getReceivers()[0])
const receiver1Balance = await token.balanceOf(assetPrice1.getReceivers()[1])
assert.isTrue(receiver0Balance === initialBalances.editor + assetPrice1.getAmounts()[0])
assert.isTrue(receiver1Balance === initialBalances.reseller + assetPrice1.getAmounts()[1])
})
it('the subscription can be checked on chain', async () => {
const eventOptions: EventOptions = {
eventName: 'Fulfilled',
filterSubgraph: {
where: {
_did: didZeroX(subscriptionDDO.id),
_receiver: subscriber.getId(),
},
},
filterJsonRpc: {
_did: didZeroX(subscriptionDDO.id),
_receiver: subscriber.getId(),
},
result: {
_agreementId: true,
_did: true,
_receiver: true,
},
}
// wait for the event to be picked by the subgraph
await nevermined.keeper.conditions.transferNftCondition.events.once((e) => e, eventOptions)
const [event] = await nevermined.keeper.conditions.transferNftCondition.events.getPastEvents(
eventOptions,
)
// subgraph event or json-rpc event?
const eventValues = event.args || event
console.debug(`EVENTS: ${JSON.stringify(eventValues, jsonReplacer)}`)
assert.equal(eventValues._agreementId, agreementId)
assert.equal(eventValues._did, didZeroX(subscriptionDDO.id))
// thegraph stores the addresses in lower case
assert.equal(getChecksumAddress(eventValues._receiver), subscriber.getId())
})
it('the subscriber can check the balance with the new NFTs received', async () => {
console.log(
`Checking the balance of DID [${
subscriptionDDO.id
}] of the subscriber ${subscriber.getId()}`,
)
const balanceAfter = await subscriptionNFT.balance(subscriptionDDO.id, subscriber.getId())
console.log(`Balance After Purchase is completed: ${balanceAfter}`)
assert.isTrue(balanceAfter === subscriptionCredits)
})
})
describe('As subscriber I want to get access to assets include as part of my subscription', () => {
it('The collector access the files', async () => {
const result = await nevermined.nfts1155.access(
assetDDO.id,
subscriber,
'/tmp/',
undefined,
agreementId,
)
assert.isTrue(result)
})
it('The balance of the subscriber should be lower because credits got used', async () => {
const balanceAfter = await subscriptionNFT.balance(subscriptionDDO.id, subscriber.getId())
console.log(`Balance After Burn: ${balanceAfter}`)
assert.isTrue(balanceAfter === subscriptionCredits - accessCostInCredits)
})
it('The tokens are burned and the subscriber cant get access anymore', async () => {
let balance
try {
for (let i = 0; i < 5; i++) {
await nevermined.nfts1155.access(assetDDO.id, subscriber, '/tmp/', undefined, agreementId)
await sleep(1000)
balance = await subscriptionNFT.balance(subscriptionDDO.id, subscriber.getId())
console.log(`Balance After Access: ${balance}`)
}
assert.fail('Should not get here')
} catch (error) {
console.log(`User cant get access anymore: ${error.message}`)
}
const balanceAfter = await subscriptionNFT.balance(subscriptionDDO.id, subscriber.getId())
console.log(`Balance After Burn: ${balanceAfter}`)
assert.isTrue(balanceAfter < accessCostInCredits)
})
it('The subscriber can top-up', async () => {
await nevermined.accounts.requestTokens(subscriber, subscriptionPrice / scale)
agreementId = await nevermined.nfts1155.order(
subscriptionDDO.id,
subscriptionCredits,
subscriber,
subsSalesService.index,
)
assert.isDefined(agreementId)
const receipt = await nevermined.nfts1155.claim(
agreementId,
editor.getId(),
subscriber.getId(),
subscriptionCredits,
subscriptionDDO.id,
subsSalesService.index,
)
assert.isTrue(receipt)
const balanceAfterTopUp = await subscriptionNFT.balance(
subscriptionDDO.id,
subscriber.getId(),
)
console.log(`Balance After TopUp: ${balanceAfterTopUp}`)
assert.isTrue(balanceAfterTopUp > accessCostInCredits)
})
it('Should be able to burn in batch', async () => {
const beforeBalance = await subscriptionNFT.balance(subscriptionDDO.id, subscriber.getId())
await nevermined.nfts1155.burnBatchFromHolders(
[subscriber.getId(), subscriber.getId()],
[subscriptionDDO.id, subscriptionDDO.id],
[1n, 2n],
editor,
)
const afterBalance = await subscriptionNFT.balance(subscriptionDDO.id, subscriber.getId())
assert.equal(beforeBalance - 3n, afterBalance)
})
})
})