feat: 接入天河链延时确认
This commit is contained in:
@@ -1,20 +1,34 @@
|
||||
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { InjectQueue, Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Job, Queue } from 'bullmq';
|
||||
import { ProofStatus, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { BlockchainService } from './blockchain.service';
|
||||
|
||||
interface OnchainJobData {
|
||||
proofId: number;
|
||||
action?: 'attest' | 'confirm';
|
||||
confirmAttempt?: number;
|
||||
}
|
||||
|
||||
const CONFIRM_DELAY_MS = 30_000;
|
||||
const MAX_CONFIRM_ATTEMPTS = 20;
|
||||
|
||||
function requestMeta(raw: unknown): Record<string, unknown> | undefined {
|
||||
if (!raw || typeof raw !== 'object') return undefined;
|
||||
const meta = (raw as Record<string, unknown>).requestMeta;
|
||||
return meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function rawObject(raw: unknown): Record<string, unknown> {
|
||||
return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
|
||||
}
|
||||
|
||||
function jsonObject(value: Record<string, unknown>): Prisma.InputJsonObject {
|
||||
return value as Prisma.InputJsonObject;
|
||||
}
|
||||
|
||||
@Processor(QUEUE_NAMES.ONCHAIN)
|
||||
export class OnchainProcessor extends WorkerHost {
|
||||
private readonly logger = new Logger(OnchainProcessor.name);
|
||||
@@ -22,12 +36,20 @@ export class OnchainProcessor extends WorkerHost {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly blockchain: BlockchainService,
|
||||
@InjectQueue(QUEUE_NAMES.ONCHAIN) private readonly queue: Queue,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async process(job: Job<OnchainJobData>): Promise<void> {
|
||||
const { proofId } = job.data;
|
||||
if (job.data.action === 'confirm') {
|
||||
await this.confirm(job.data.proofId, job.data.confirmAttempt || 1);
|
||||
return;
|
||||
}
|
||||
await this.attest(job.data.proofId);
|
||||
}
|
||||
|
||||
private async attest(proofId: number): Promise<void> {
|
||||
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
|
||||
if (!proof) return;
|
||||
try {
|
||||
@@ -38,31 +60,127 @@ export class OnchainProcessor extends WorkerHost {
|
||||
await this.prisma.blockchainProof.update({
|
||||
where: { id: proofId },
|
||||
data: {
|
||||
status: ProofStatus.ONCHAIN,
|
||||
status: result.confirmationRequired ? ProofStatus.CONFIRMING : ProofStatus.ONCHAIN,
|
||||
txHash: result.txHash,
|
||||
blockHash: result.blockHash || null,
|
||||
blockHeight: result.blockHeight !== null && result.blockHeight !== undefined ? BigInt(result.blockHeight) : null,
|
||||
chainName: result.chainName,
|
||||
explorerUrl: result.explorerUrl || null,
|
||||
onchainAt: result.onchainAt,
|
||||
rawResponse: result.raw as object,
|
||||
onchainAt: result.confirmationRequired ? null : result.onchainAt,
|
||||
rawResponse: jsonObject({
|
||||
...(result.raw as object),
|
||||
submittedAt: new Date().toISOString(),
|
||||
}),
|
||||
},
|
||||
});
|
||||
this.logger.log(`存证 ${proofId} 上链成功`);
|
||||
if (result.confirmationRequired) {
|
||||
await this.scheduleConfirm(proofId, 1);
|
||||
this.logger.log(`存证 ${proofId} 已提交链上,等待确认`);
|
||||
} else {
|
||||
this.logger.log(`存证 ${proofId} 上链成功`);
|
||||
}
|
||||
} catch (e) {
|
||||
const message = (e as Error).message;
|
||||
await this.prisma.blockchainProof.update({
|
||||
where: { id: proofId },
|
||||
data: {
|
||||
status: ProofStatus.FAILED,
|
||||
rawResponse: {
|
||||
rawResponse: jsonObject({
|
||||
...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}),
|
||||
error: message,
|
||||
failedAt: new Date().toISOString(),
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
this.logger.error(`存证 ${proofId} 上链失败: ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async confirm(proofId: number, attempt: number): Promise<void> {
|
||||
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
|
||||
if (!proof || proof.status !== ProofStatus.CONFIRMING) return;
|
||||
if (!proof.txHash) {
|
||||
await this.markConfirmFailed(proofId, proof.rawResponse, '缺少交易哈希,无法确认链上结果', attempt);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.blockchain.confirmTransaction(proof.txHash);
|
||||
if (result.confirmed) {
|
||||
await this.prisma.blockchainProof.update({
|
||||
where: { id: proofId },
|
||||
data: {
|
||||
status: ProofStatus.ONCHAIN,
|
||||
txHash: result.txHash,
|
||||
blockHash: result.blockHash || proof.blockHash || null,
|
||||
blockHeight:
|
||||
result.blockHeight !== null && result.blockHeight !== undefined
|
||||
? BigInt(result.blockHeight)
|
||||
: proof.blockHeight,
|
||||
onchainAt: new Date(),
|
||||
rawResponse: jsonObject({
|
||||
...rawObject(proof.rawResponse),
|
||||
confirmation: result.raw,
|
||||
confirmationAttempts: attempt,
|
||||
confirmedAt: new Date().toISOString(),
|
||||
}),
|
||||
},
|
||||
});
|
||||
this.logger.log(`存证 ${proofId} 链上确认成功`);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.recordWaiting(proofId, proof.rawResponse, result.raw, attempt);
|
||||
if (attempt >= MAX_CONFIRM_ATTEMPTS) {
|
||||
await this.markConfirmFailed(proofId, proof.rawResponse, '超过最大确认次数,仍未查询到链上区块信息', attempt);
|
||||
return;
|
||||
}
|
||||
await this.scheduleConfirm(proofId, attempt + 1);
|
||||
} catch (e) {
|
||||
const message = (e as Error).message;
|
||||
if (attempt >= MAX_CONFIRM_ATTEMPTS) {
|
||||
await this.markConfirmFailed(proofId, proof.rawResponse, message, attempt);
|
||||
return;
|
||||
}
|
||||
await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt);
|
||||
await this.scheduleConfirm(proofId, attempt + 1);
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleConfirm(proofId: number, confirmAttempt: number) {
|
||||
return this.queue.add(
|
||||
'confirm-onchain',
|
||||
{ proofId, action: 'confirm', confirmAttempt } satisfies OnchainJobData,
|
||||
{ delay: CONFIRM_DELAY_MS },
|
||||
);
|
||||
}
|
||||
|
||||
private recordWaiting(proofId: number, raw: unknown, confirmation: Record<string, unknown>, attempt: number) {
|
||||
return this.prisma.blockchainProof.update({
|
||||
where: { id: proofId },
|
||||
data: {
|
||||
rawResponse: jsonObject({
|
||||
...rawObject(raw),
|
||||
confirmation,
|
||||
confirmationAttempts: attempt,
|
||||
lastConfirmCheckedAt: new Date().toISOString(),
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private markConfirmFailed(proofId: number, raw: unknown, message: string, attempt: number) {
|
||||
return this.prisma.blockchainProof.update({
|
||||
where: { id: proofId },
|
||||
data: {
|
||||
status: ProofStatus.FAILED,
|
||||
rawResponse: jsonObject({
|
||||
...rawObject(raw),
|
||||
confirmationError: message,
|
||||
confirmationAttempts: attempt,
|
||||
failedAt: new Date().toISOString(),
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user