-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathprocessor.ts
More file actions
1545 lines (1475 loc) · 50.9 KB
/
processor.ts
File metadata and controls
1545 lines (1475 loc) · 50.9 KB
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Interface,
JsonRpcApiProvider,
Signer,
ZeroAddress,
ethers,
getAddress,
getBytes,
hexlify,
toUtf8Bytes,
toUtf8String
} from 'ethers'
import { createHash } from 'crypto'
import { Readable } from 'node:stream'
import axios from 'axios'
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
import { LOG_LEVELS_STR } from '../../utils/logging/Logger.js'
import ERC721Template from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json' assert { type: 'json' }
import ERC20Template from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json' assert { type: 'json' }
import Dispenser from '@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json' assert { type: 'json' }
import FixedRateExchange from '@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json' assert { type: 'json' }
import { getDatabase } from '../../utils/database.js'
import {
PROTOCOL_COMMANDS,
EVENTS,
MetadataStates,
EVENT_HASHES,
ENVIRONMENT_VARIABLES
} from '../../utils/constants.js'
import {
findServiceIdByDatatoken,
getDtContract,
getPricingStatsForDddo,
wasNFTDeployedByOurFactory,
getPricesByDt,
doesDispenserAlreadyExist,
doesFreAlreadyExist
} from './utils.js'
import { INDEXER_LOGGER } from '../../utils/logging/common.js'
import { Purgatory } from './purgatory.js'
import {
deleteIndexedMetadataIfExists,
getConfiguration,
timestampToDateTime
} from '../../utils/index.js'
import { OceanNode } from '../../OceanNode.js'
import { asyncCallWithTimeout, streamToString } from '../../utils/util.js'
import { DecryptDDOCommand } from '../../@types/commands.js'
import { create256Hash } from '../../utils/crypt.js'
import { URLUtils } from '../../utils/url.js'
import { makeDid } from '../core/utils/validateDdoHandler.js'
import { PolicyServer } from '../policyServer/index.js'
import { checkCredentialOnAccessList } from '../../utils/credentials.js'
class BaseEventProcessor {
protected networkId: number
constructor(chainId: number) {
this.networkId = chainId
}
protected isValidDtAddressFromServices(services: any[]): boolean {
for (const service of services) {
if (
service.datatokenAddress === '0x0' ||
service.datatokenAddress === ZeroAddress
) {
return false
}
}
return true
}
protected async getTokenInfo(services: any[], signer: Signer): Promise<any[]> {
const datatokens: any[] = []
for (const service of services) {
const datatoken = new ethers.Contract(
service.datatokenAddress,
ERC20Template.abi,
signer
)
let name: string
let symbol: string
if (
service.datatokenAddress === '0x0' ||
service.datatokenAddress === ZeroAddress
) {
name = `Datatoken${services.indexOf(service)}`
symbol = `DT${services.indexOf(service)}`
} else {
name = await datatoken.name()
INDEXER_LOGGER.logMessage(`name.datatoken: ${name}`)
symbol = await datatoken.symbol()
INDEXER_LOGGER.logMessage(`symbol.datatoken: ${symbol}`)
}
datatokens.push({
address: service.datatokenAddress,
name,
symbol,
serviceId: service.id
})
}
return datatokens
}
protected async getEventData(
provider: JsonRpcApiProvider,
transactionHash: string,
abi: any,
eventType: string
): Promise<ethers.LogDescription> {
const iface = new Interface(abi)
const receipt = await provider.getTransactionReceipt(transactionHash)
let eventHash: string
for (const [key, value] of Object.entries(EVENT_HASHES)) {
if (value.type === eventType) {
eventHash = key
break
}
}
if (eventHash === '') {
INDEXER_LOGGER.error(`Event hash couldn't be found!`)
return null
}
let eventObj: any
for (const log of receipt.logs) {
if (log.topics[0] === eventHash) {
eventObj = {
topics: log.topics,
data: log.data
}
break
}
}
if (!eventObj) {
INDEXER_LOGGER.error(
`Event object couldn't be retrieved! Event hash not present in logs topics`
)
return null
}
return iface.parseLog(eventObj)
}
protected async getNFTInfo(
nftAddress: string,
signer: Signer,
owner: string,
timestamp: number
): Promise<any> {
const nftContract = new ethers.Contract(nftAddress, ERC721Template.abi, signer)
const state = parseInt((await nftContract.getMetaData())[2])
const id = parseInt(await nftContract.getId())
const tokenURI = await nftContract.tokenURI(id)
return {
state,
address: nftAddress,
name: await nftContract.name(),
symbol: await nftContract.symbol(),
owner,
created: timestampToDateTime(timestamp),
tokenURI
}
}
protected async createOrUpdateDDO(ddo: any, method: string): Promise<any> {
try {
const { ddo: ddoDatabase, ddoState } = await getDatabase()
const saveDDO = await ddoDatabase.update({ ...ddo })
await ddoState.update(
this.networkId,
saveDDO.id,
saveDDO.nftAddress,
saveDDO.indexedMetadata?.event?.tx,
true
)
INDEXER_LOGGER.logMessage(
`Saved or updated DDO : ${saveDDO.id} from network: ${this.networkId} triggered by: ${method}`
)
return saveDDO
} catch (err) {
const { ddoState } = await getDatabase()
await ddoState.update(
this.networkId,
ddo.id,
ddo.nftAddress,
ddo.indexedMetadata?.event?.tx,
true,
err.message
)
INDEXER_LOGGER.log(
LOG_LEVELS_STR.LEVEL_ERROR,
`Error found on ${this.networkId} triggered by: ${method} while creating or updating DDO: ${err}`,
true
)
}
}
protected checkDdoHash(decryptedDocument: any, documentHashFromContract: any): boolean {
const utf8Bytes = toUtf8Bytes(JSON.stringify(decryptedDocument))
const expectedMetadata = hexlify(utf8Bytes)
if (create256Hash(expectedMetadata.toString()) !== documentHashFromContract) {
INDEXER_LOGGER.error(`DDO checksum does not match.`)
return false
}
return true
}
protected async decryptDDO(
decryptorURL: string,
flag: string,
eventCreator: string,
contractAddress: string,
chainId: number,
txId: string,
metadataHash: string,
metadata: any
): Promise<any> {
let ddo
if (parseInt(flag) === 2) {
INDEXER_LOGGER.logMessage(
`Decrypting DDO from network: ${this.networkId} created by: ${eventCreator} encrypted by: ${decryptorURL}`
)
const nonce = Math.floor(Date.now() / 1000).toString()
const { keys } = await getConfiguration()
const nodeId = keys.peerId.toString()
const wallet: ethers.Wallet = new ethers.Wallet(process.env.PRIVATE_KEY as string)
const message = String(
txId + contractAddress + keys.ethAddress + chainId.toString() + nonce
)
const consumerMessage = ethers.solidityPackedKeccak256(
['bytes'],
[ethers.hexlify(ethers.toUtf8Bytes(message))]
)
const signature = await wallet.signMessage(consumerMessage)
if (URLUtils.isValidUrl(decryptorURL)) {
try {
const payload = {
transactionId: txId,
chainId,
decrypterAddress: keys.ethAddress,
dataNftAddress: contractAddress,
signature,
nonce
}
const response = await axios({
method: 'post',
url: `${decryptorURL}/api/services/decrypt`,
data: payload
})
if (response.status !== 200) {
const message = `bProvider exception on decrypt DDO. Status: ${response.status}, ${response.statusText}`
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_ERROR, message)
throw new Error(message)
}
let responseHash
if (response.data instanceof Object) {
responseHash = create256Hash(JSON.stringify(response.data))
ddo = response.data
} else {
ddo = JSON.parse(response.data)
responseHash = create256Hash(ddo)
}
if (responseHash !== metadataHash) {
const msg = `Hash check failed: response=${ddo}, decrypted ddo hash=${responseHash}\n metadata hash=${metadataHash}`
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_ERROR, msg)
throw new Error(msg)
}
} catch (err) {
const message = `Provider exception on decrypt DDO. Status: ${err.message}`
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_ERROR, message)
throw new Error(message)
}
} else {
const node = OceanNode.getInstance(await getDatabase())
if (nodeId === decryptorURL) {
const decryptDDOTask: DecryptDDOCommand = {
command: PROTOCOL_COMMANDS.DECRYPT_DDO,
transactionId: txId,
decrypterAddress: keys.ethAddress,
chainId,
encryptedDocument: metadata,
documentHash: metadataHash,
dataNftAddress: contractAddress,
signature,
nonce
}
try {
const response = await node
.getCoreHandlers()
.getHandler(PROTOCOL_COMMANDS.DECRYPT_DDO)
.handle(decryptDDOTask)
ddo = JSON.parse(await streamToString(response.stream as Readable))
} catch (error) {
const message = `Node exception on decrypt DDO. Status: ${error.message}`
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_ERROR, message)
throw new Error(message)
}
} else {
try {
const p2pNode = await node.getP2PNode()
let isBinaryContent = false
const sink = async function (source: any) {
let first = true
for await (const chunk of source) {
if (first) {
first = false
try {
const str = uint8ArrayToString(chunk.subarray()) // Obs: we need to specify the length of the subarrays
const decoded = JSON.parse(str)
if ('headers' in decoded) {
if (str?.toLowerCase().includes('application/octet-stream')) {
isBinaryContent = true
}
}
if (decoded.httpStatus !== 200) {
INDEXER_LOGGER.logMessage(
`Error in sink method : ${decoded.httpStatus} errro: ${decoded.error}`
)
throw new Error('Error in sink method', decoded.error)
}
} catch (e) {
INDEXER_LOGGER.logMessage(
`Error in sink method } error: ${e.message}`
)
throw new Error(`Error in sink method ${e.message}`)
}
} else {
if (isBinaryContent) {
return chunk.subarray()
} else {
const str = uint8ArrayToString(chunk.subarray())
return str
}
}
}
}
const message = {
command: PROTOCOL_COMMANDS.DECRYPT_DDO,
transactionId: txId,
decrypterAddress: keys.ethAddress,
chainId,
encryptedDocument: metadata,
documentHash: metadataHash,
dataNftAddress: contractAddress,
signature,
nonce
}
const response = await p2pNode.sendTo(
decryptorURL,
JSON.stringify(message),
sink
)
ddo = JSON.parse(await streamToString(response.stream as Readable))
} catch (error) {
const message = `Node exception on decrypt DDO. Status: ${error.message}`
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_ERROR, message)
throw new Error(message)
}
}
}
} else {
INDEXER_LOGGER.logMessage(
`Decompressing DDO from network: ${this.networkId} created by: ${eventCreator} ecnrypted by: ${decryptorURL}`
)
const byteArray = getBytes(metadata)
const utf8String = toUtf8String(byteArray)
ddo = JSON.parse(utf8String)
}
return ddo
}
}
export class MetadataEventProcessor extends BaseEventProcessor {
async processEvent(
event: ethers.Log,
chainId: number,
signer: Signer,
provider: JsonRpcApiProvider,
eventName: string
): Promise<any> {
let did = 'did:op'
try {
const { ddo: ddoDatabase, ddoState } = await getDatabase()
const wasDeployedByUs = await wasNFTDeployedByOurFactory(
chainId,
signer,
getAddress(event.address)
)
if (!wasDeployedByUs) {
INDEXER_LOGGER.log(
LOG_LEVELS_STR.LEVEL_ERROR,
`NFT not deployed by OPF factory`,
true
)
return
}
const decodedEventData = await this.getEventData(
provider,
event.transactionHash,
ERC721Template.abi,
eventName
)
const metadata = decodedEventData.args[4]
const metadataHash = decodedEventData.args[5]
const flag = decodedEventData.args[3]
const owner = decodedEventData.args[0]
const ddo = await this.decryptDDO(
decodedEventData.args[2],
flag,
owner,
event.address,
chainId,
event.transactionHash,
metadataHash,
metadata
)
const clonedDdo = structuredClone(ddo)
INDEXER_LOGGER.logMessage(`clonedDdo: ${JSON.stringify(clonedDdo)}`)
const updatedDdo = deleteIndexedMetadataIfExists(clonedDdo)
if (updatedDdo.id !== makeDid(event.address, chainId.toString(10))) {
INDEXER_LOGGER.error(
`Decrypted DDO ID is not matching the generated hash for DID.`
)
return
}
// for unencrypted DDOs
if (parseInt(flag) !== 2 && !this.checkDdoHash(updatedDdo, metadataHash)) {
return
}
// check authorized publishers
const { authorizedPublishers, authorizedPublishersList } = await getConfiguration()
if (authorizedPublishers.length > 0) {
// if is not there, do not index
const authorized: string[] = authorizedPublishers.filter((address) =>
// do a case insensitive search
address.toLowerCase().includes(owner.toLowerCase())
)
if (!authorized.length) {
INDEXER_LOGGER.error(
`DDO owner ${owner} is NOT part of the ${ENVIRONMENT_VARIABLES.AUTHORIZED_PUBLISHERS.name} group.`
)
return
}
}
if (authorizedPublishersList) {
// check accessList
const isAuthorized = await checkCredentialOnAccessList(
authorizedPublishersList,
String(chainId),
owner,
signer
)
if (!isAuthorized) {
INDEXER_LOGGER.error(
`DDO owner ${owner} is NOT part of the ${ENVIRONMENT_VARIABLES.AUTHORIZED_PUBLISHERS_LIST.name} access group.`
)
return
}
}
did = ddo.id
// stuff that we overwrite
ddo.chainId = chainId
ddo.nftAddress = event.address
ddo.datatokens = await this.getTokenInfo(ddo.services, signer)
INDEXER_LOGGER.logMessage(
`Processed new DDO data ${ddo.id} with txHash ${event.transactionHash} from block ${event.blockNumber}`,
true
)
const previousDdo = await ddoDatabase.retrieve(ddo.id)
if (eventName === EVENTS.METADATA_CREATED) {
if (previousDdo && previousDdo.nft.state === MetadataStates.ACTIVE) {
INDEXER_LOGGER.logMessage(`DDO ${ddo.id} is already registered as active`, true)
await ddoState.update(
this.networkId,
did,
event.address,
event.transactionHash,
false,
`DDO ${ddo.id} is already registered as active`
)
return
}
}
if (eventName === EVENTS.METADATA_UPDATED) {
if (!previousDdo) {
INDEXER_LOGGER.logMessage(
`Previous DDO with did ${ddo.id} was not found the database. Maybe it was deleted/hidden to some violation issues`,
true
)
await ddoState.update(
this.networkId,
did,
event.address,
event.transactionHash,
false,
`Previous DDO with did ${ddo.id} was not found the database. Maybe it was deleted/hidden to some violation issues`
)
return
}
const [isUpdateable, error] = this.isUpdateable(
previousDdo,
event.transactionHash,
event.blockNumber
)
if (!isUpdateable) {
INDEXER_LOGGER.error(
`Error encountered when checking if the asset is eligiable for update: ${error}`
)
await ddoState.update(
this.networkId,
did,
event.address,
event.transactionHash,
false,
error
)
return
}
}
const from = decodedEventData.args[0].toString()
let ddoUpdatedWithPricing = {}
// we need to store the event data (either metadata created or update and is updatable)
if (
[EVENTS.METADATA_CREATED, EVENTS.METADATA_UPDATED].includes(eventName) &&
this.isValidDtAddressFromServices(ddo.services)
) {
const ddoWithPricing = await getPricingStatsForDddo(ddo, signer)
ddoWithPricing.indexedMetadata.nft = await this.getNFTInfo(
ddoWithPricing.nftAddress,
signer,
owner,
parseInt(decodedEventData.args[6])
)
if (!ddoWithPricing.indexedMetadata.event) {
ddoWithPricing.indexedMetadata.event = {}
}
ddoWithPricing.indexedMetadata.event.tx = event.transactionHash
ddoWithPricing.indexedMetadata.event.from = from
ddoWithPricing.indexedMetadata.event.contract = event.address
if (event.blockNumber) {
ddoWithPricing.indexedMetadata.event.block = event.blockNumber
// try get block & timestamp from block (only wait 2.5 secs maximum)
const promiseFn = provider.getBlock(event.blockNumber)
const result = await asyncCallWithTimeout(promiseFn, 2500)
if (result.data !== null && !result.timeout) {
ddoWithPricing.indexedMetadata.event.datetime = new Date(
result.data.timestamp * 1000
).toJSON()
}
} else {
ddoWithPricing.indexedMetadata.event.block = -1
}
// policyServer check
const policyServer = new PolicyServer()
let policyStatus
if (eventName === EVENTS.METADATA_UPDATED)
policyStatus = await policyServer.checkUpdateDDO(
ddoWithPricing,
this.networkId,
event.transactionHash,
event
)
else
policyStatus = await policyServer.checknewDDO(
ddoWithPricing,
this.networkId,
event.transactionHash,
event
)
if (!policyStatus.success) {
await ddoState.update(
this.networkId,
did,
event.address,
event.transactionHash,
false,
policyStatus.message
)
return
}
ddoUpdatedWithPricing = structuredClone(ddoWithPricing)
}
// always call, but only create instance once
const purgatory = await Purgatory.getInstance()
// if purgatory is disabled just return false
const updatedDDO = await this.updatePurgatoryStateDdo(
ddoUpdatedWithPricing,
from,
purgatory
)
if (updatedDDO.indexedMetadata.purgatory.state === false) {
// TODO: insert in a different collection for purgatory DDOs
const saveDDO = await this.createOrUpdateDDO(ddoUpdatedWithPricing, eventName)
INDEXER_LOGGER.logMessage(`saved DDO: ${JSON.stringify(saveDDO)}`)
return saveDDO
}
} catch (error) {
const { ddoState } = await getDatabase()
await ddoState.update(
this.networkId,
did,
event.address,
event.transactionHash,
false,
error.message
)
INDEXER_LOGGER.log(
LOG_LEVELS_STR.LEVEL_ERROR,
`Error processMetadataEvents: ${error}`,
true
)
}
}
async updatePurgatoryStateDdo(
ddo: any,
owner: string,
purgatory: Purgatory
): Promise<any> {
if (purgatory.isEnabled()) {
const state: boolean =
(await purgatory.isBannedAsset(ddo.id)) ||
(await purgatory.isBannedAccount(owner))
ddo.indexedMetadata.purgatory = {
state
}
} else {
ddo.indexedMetadata.purgatory = {
state: false
}
}
return ddo
}
isUpdateable(previousDdo: any, txHash: string, block: number): [boolean, string] {
let errorMsg: string
const ddoTxId = previousDdo.indexedMetadata.event.tx
// do not update if we have the same txid
if (txHash === ddoTxId) {
errorMsg = `Previous DDO has the same tx id, no need to update: event-txid=${txHash} <> asset-event-txid=${ddoTxId}`
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_DEBUG, errorMsg, true)
return [false, errorMsg]
}
const ddoBlock = previousDdo.indexedMetadata.event.block
// do not update if we have the same block
if (block === ddoBlock) {
errorMsg = `Asset was updated later (block: ${ddoBlock}) vs transaction block: ${block}`
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_DEBUG, errorMsg, true)
return [false, errorMsg]
}
return [true, '']
}
}
export class MetadataStateEventProcessor extends BaseEventProcessor {
async processEvent(
event: ethers.Log,
chainId: number,
provider: JsonRpcApiProvider
): Promise<any> {
INDEXER_LOGGER.logMessage(`Processing metadata state event...`, true)
const decodedEventData = await this.getEventData(
provider,
event.transactionHash,
ERC721Template.abi,
EVENTS.METADATA_STATE
)
const metadataState = parseInt(decodedEventData.args[1].toString())
INDEXER_LOGGER.logMessage(`Processed new metadata state ${metadataState} `, true)
INDEXER_LOGGER.logMessage(
`NFT address in processing MetadataState: ${event.address} `,
true
)
const did =
'did:op:' +
createHash('sha256')
.update(getAddress(event.address) + chainId.toString(10))
.digest('hex')
try {
const { ddo: ddoDatabase } = await getDatabase()
let ddo = await ddoDatabase.retrieve(did)
if (!ddo) {
INDEXER_LOGGER.logMessage(
`Detected MetadataState changed for ${did}, but it does not exists.`
)
return
}
INDEXER_LOGGER.logMessage(`Found did ${did} on network ${chainId}`)
if (
'nft' in ddo.indexedMetadata &&
ddo.indexedMetadata.nft.state !== metadataState
) {
let shortVersion = null
if (
ddo.indexedMetadata.nft.state === MetadataStates.ACTIVE &&
[MetadataStates.REVOKED, MetadataStates.DEPRECATED].includes(metadataState)
) {
INDEXER_LOGGER.logMessage(
`DDO became non-visible from ${ddo.indexedMetadata.nft.state} to ${metadataState}`
)
shortVersion = {
id: ddo.id,
chainId,
nftAddress: ddo.nftAddress,
indexedMetadata: {
nft: {
state: metadataState
}
}
}
}
// We should keep it here, because in further development we'll store
// the previous structure of the non-visible DDOs (full version)
// in case their state changes back to active.
ddo.indexedMetadata.nft.state = metadataState
if (shortVersion) {
ddo = shortVersion
}
} else {
// Still update until we validate and polish schemas for DDO.
// But it should update ONLY if the first condition is met.
// Check https://github.com/oceanprotocol/aquarius/blob/84a560ea972485e46dd3c2cfc3cdb298b65d18fa/aquarius/events/processors.py#L663
ddo.indexedMetadata.nft = {
state: metadataState
}
}
INDEXER_LOGGER.logMessage(
`Found did ${did} for state updating on network ${chainId}`
)
const savedDDO = await this.createOrUpdateDDO(ddo, EVENTS.METADATA_STATE)
return savedDDO
} catch (err) {
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_ERROR, `Error retrieving DDO: ${err}`, true)
}
}
}
export class OrderStartedEventProcessor extends BaseEventProcessor {
async processEvent(
event: ethers.Log,
chainId: number,
signer: Signer,
provider: JsonRpcApiProvider
): Promise<any> {
const decodedEventData = await this.getEventData(
provider,
event.transactionHash,
ERC20Template.abi,
EVENTS.ORDER_STARTED
)
const serviceIndex = parseInt(decodedEventData.args[3].toString())
const timestamp = parseInt(decodedEventData.args[4].toString())
const consumer = decodedEventData.args[0].toString()
const payer = decodedEventData.args[1].toString()
INDEXER_LOGGER.logMessage(
`Processed new order for service index ${serviceIndex} at ${timestamp}`,
true
)
const datatokenContract = getDtContract(signer, event.address)
const nftAddress = await datatokenContract.getERC721Address()
const did =
'did:op:' +
createHash('sha256')
.update(getAddress(nftAddress) + chainId.toString(10))
.digest('hex')
try {
const { ddo: ddoDatabase, order: orderDatabase } = await getDatabase()
const ddo = await ddoDatabase.retrieve(did)
if (!ddo) {
INDEXER_LOGGER.logMessage(
`Detected OrderStarted changed for ${did}, but it does not exists.`
)
return
}
if (!ddo.indexedMetadata) {
ddo.indexedMetadata = {}
}
if (!Array.isArray(ddo.indexedMetadata.stats)) {
ddo.indexedMetadata.stats = []
}
if (
ddo.indexedMetadata.stats.length !== 0 &&
ddo.services[serviceIndex].datatokenAddress?.toLowerCase() ===
event.address?.toLowerCase()
) {
for (const stat of ddo.indexedMetadata.stats) {
if (stat.datatokenAddress.toLowerCase() === event.address?.toLowerCase()) {
stat.orders += 1
break
}
}
} else if (ddo.indexedMetadata.stats.length === 0) {
ddo.indexedMetadata.stats.push({
datatokenAddress: event.address,
name: await datatokenContract.name(),
serviceId: ddo.services[serviceIndex].id,
orders: 1,
prices: await getPricesByDt(datatokenContract, signer)
})
}
await orderDatabase.create(
event.transactionHash,
'startOrder',
timestamp,
consumer,
payer,
ddo.services[serviceIndex].datatokenAddress,
nftAddress,
did
)
INDEXER_LOGGER.logMessage(
`Found did ${did} for order starting on network ${chainId}`
)
const savedDDO = await this.createOrUpdateDDO(ddo, EVENTS.ORDER_STARTED)
return savedDDO
} catch (err) {
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_ERROR, `Error retrieving DDO: ${err}`, true)
}
}
}
export class OrderReusedEventProcessor extends BaseEventProcessor {
async processEvent(
event: ethers.Log,
chainId: number,
signer: Signer,
provider: JsonRpcApiProvider
): Promise<any> {
const decodedEventData = await this.getEventData(
provider,
event.transactionHash,
ERC20Template.abi,
EVENTS.ORDER_REUSED
)
const startOrderId = decodedEventData.args[0].toString()
const timestamp = parseInt(decodedEventData.args[2].toString())
const payer = decodedEventData.args[1].toString()
INDEXER_LOGGER.logMessage(`Processed reused order at ${timestamp}`, true)
const datatokenContract = getDtContract(signer, event.address)
const nftAddress = await datatokenContract.getERC721Address()
const did =
'did:op:' +
createHash('sha256')
.update(getAddress(nftAddress) + chainId.toString(10))
.digest('hex')
try {
const { ddo: ddoDatabase, order: orderDatabase } = await getDatabase()
const ddo = await ddoDatabase.retrieve(did)
if (!ddo) {
INDEXER_LOGGER.logMessage(
`Detected OrderReused changed for ${did}, but it does not exists.`
)
return
}
if (!ddo.indexedMetadata) {
ddo.indexedMetadata = {}
}
if (!Array.isArray(ddo.indexedMetadata.stats)) {
ddo.indexedMetadata.stats = []
}
if (ddo.indexedMetadata.stats.length !== 0) {
for (const stat of ddo.indexedMetadata.stats) {
if (stat.datatokenAddress.toLowerCase() === event.address?.toLowerCase()) {
stat.orders += 1
break
}
}
} else {
INDEXER_LOGGER.logMessage(`[OrderReused] - No stats were found on the ddo`)
const serviceIdToFind = findServiceIdByDatatoken(ddo, event.address)
if (!serviceIdToFind) {
INDEXER_LOGGER.logMessage(
`[OrderReused] - This datatoken does not contain this service. Invalid service id!`
)
return
}
ddo.indexedMetadata.stats.push({
datatokenAddress: event.address,
name: await datatokenContract.name(),
serviceId: serviceIdToFind,
orders: 1,
prices: await getPricesByDt(datatokenContract, signer)
})
}
try {
const startOrder = await orderDatabase.retrieve(startOrderId)
if (!startOrder) {
INDEXER_LOGGER.logMessage(
`Detected OrderReused changed for order ${startOrderId}, but it does not exists.`
)
return
}
await orderDatabase.create(
event.transactionHash,
'reuseOrder',
timestamp,
startOrder.consumer,
payer,
event.address,
nftAddress,
did,
startOrderId
)
} catch (error) {
INDEXER_LOGGER.log(
LOG_LEVELS_STR.LEVEL_ERROR,
`Error retrieving startOrder for reuseOrder: ${error}`,
true
)
}
const savedDDO = await this.createOrUpdateDDO(ddo, EVENTS.ORDER_REUSED)
return savedDDO
} catch (err) {
INDEXER_LOGGER.log(LOG_LEVELS_STR.LEVEL_ERROR, `Error retrieving DDO: ${err}`, true)
}
}
}
export class DispenserCreatedEventProcessor extends BaseEventProcessor {
async processEvent(
event: ethers.Log,
chainId: number,
signer: Signer,
provider: JsonRpcApiProvider
): Promise<any> {
const decodedEventData = await this.getEventData(
provider,
event.transactionHash,
Dispenser.abi,
EVENTS.DISPENSER_CREATED
)
const datatokenAddress = decodedEventData.args[0].toString()
const datatokenContract = getDtContract(signer, datatokenAddress)
const nftAddress = await datatokenContract.getERC721Address()
const did =
'did:op:' +
createHash('sha256')
.update(getAddress(nftAddress) + chainId.toString(10))
.digest('hex')
try {
const { ddo: ddoDatabase } = await getDatabase()
const ddo = await ddoDatabase.retrieve(did)
if (!ddo) {
INDEXER_LOGGER.logMessage(
`Detected DispenserCreated changed for ${did}, but it does not exists.`
)
return
}
if (!ddo.indexedMetadata) {
ddo.indexedMetadata = {}
}
if (!Array.isArray(ddo.indexedMetadata.stats)) {
ddo.indexedMetadata.stats = []
}
if (ddo.indexedMetadata.stats.length !== 0) {
for (const stat of ddo.indexedMetadata.stats) {
if (
stat.datatokenAddress.toLowerCase() === datatokenAddress.toLowerCase() &&
!doesDispenserAlreadyExist(event.address, stat.prices)[0]
) {
const price = {
type: 'dispenser',
price: '0',
contract: event.address,
token: datatokenAddress
}