|
| 1 | +import { Client } from '@hashgraph/sdk'; |
| 2 | + |
| 3 | +import { Hcs1FileBuilder } from '@/shared/hol/hcs1-file-builder'; |
| 4 | +import { Hcs2RegistryBuilder } from '@/shared/hol/hcs2-registry-builder'; |
| 5 | +import { HCS2_REGISTRY_TYPE } from '@/shared/hol/constants'; |
| 6 | +import type { AuditEntry } from '../audit-entry'; |
| 7 | +import type { SessionAwareWriter } from './types'; |
| 8 | + |
| 9 | +export class HolAuditWriter implements SessionAwareWriter { |
| 10 | + private client: Client; |
| 11 | + private sessionId!: string; |
| 12 | + |
| 13 | + constructor(client: Client) { |
| 14 | + this.client = client; |
| 15 | + } |
| 16 | + |
| 17 | + setSessionId(sessionId: string): void { |
| 18 | + this.sessionId = sessionId; |
| 19 | + } |
| 20 | + |
| 21 | + async initialize(): Promise<string> { |
| 22 | + const tx = Hcs2RegistryBuilder.createRegistry({ |
| 23 | + autoRenewAccountId: this.client.operatorAccountId!.toString(), |
| 24 | + submitKey: this.client.operatorPublicKey!, |
| 25 | + registryType: HCS2_REGISTRY_TYPE.INDEXED, |
| 26 | + ttl: 0, |
| 27 | + }); |
| 28 | + |
| 29 | + const response = await tx.execute(this.client); |
| 30 | + const receipt = await response.getReceipt(this.client); |
| 31 | + if (!receipt.topicId) { |
| 32 | + throw new Error('Failed to create session topic'); |
| 33 | + } |
| 34 | + |
| 35 | + return receipt.topicId.toString(); |
| 36 | + } |
| 37 | + |
| 38 | + async write(entry: AuditEntry): Promise<void> { |
| 39 | + const { topicTransaction, buildMessageTransactions } = Hcs1FileBuilder.createFile({ |
| 40 | + autoRenewAccountId: this.client.operatorAccountId!.toString(), |
| 41 | + submitKey: this.client.operatorPublicKey!, |
| 42 | + content: JSON.stringify(entry), |
| 43 | + }); |
| 44 | + |
| 45 | + const topicResponse = await topicTransaction.execute(this.client); |
| 46 | + const topicReceipt = await topicResponse.getReceipt(this.client); |
| 47 | + if (!topicReceipt.topicId) { |
| 48 | + throw new Error('Failed to create HCS-1 topic for audit entry'); |
| 49 | + } |
| 50 | + const entryTopicId = topicReceipt.topicId.toString(); |
| 51 | + |
| 52 | + const messageTxs = buildMessageTransactions(entryTopicId); |
| 53 | + for (const messageTx of messageTxs) { |
| 54 | + await messageTx.execute(this.client); |
| 55 | + } |
| 56 | + |
| 57 | + const registerTx = Hcs2RegistryBuilder.registerEntry({ |
| 58 | + registryTopicId: this.sessionId, |
| 59 | + targetTopicId: entryTopicId, |
| 60 | + }); |
| 61 | + |
| 62 | + await registerTx.execute(this.client); |
| 63 | + } |
| 64 | +} |
0 commit comments