feat: 接入天河链延时确认
This commit is contained in:
@@ -202,3 +202,4 @@
|
|||||||
- 系统设置布局微调(2026-07-06):后台 `Settings.vue` 的基础设置区改为三列卡片:左侧平台设置,中间日志设置+备份策略,右侧区块链存证;避免区块链配置夹在日志和备份之间打断阅读,同时保持保存按钮在设置卡片组右上角。
|
- 系统设置布局微调(2026-07-06):后台 `Settings.vue` 的基础设置区改为三列卡片:左侧平台设置,中间日志设置+备份策略,右侧区块链存证;避免区块链配置夹在日志和备份之间打断阅读,同时保持保存按钮在设置卡片组右上角。
|
||||||
- 天河链用户身份临时策略(2026-07-06):天河链文档中的 `userId/userKey` 属于托管链上用户身份,不是平台截图里提供的商户 API 凭证。当前设置页先只展示 `App ID/App Key`,后端仍兼容 `.env` 或历史设置中的 `TIANHE_USER_ID/TIANHE_USER_KEY`;若未配置,则使用平台级默认 `userId=artveris-platform`,`userKey=sha256(artveris:tianhe:{appId}:{appKey})` 派生。后续需再讨论是继续平台级托管用户,还是按运营账号/机构/作品批次生成链上用户。
|
- 天河链用户身份临时策略(2026-07-06):天河链文档中的 `userId/userKey` 属于托管链上用户身份,不是平台截图里提供的商户 API 凭证。当前设置页先只展示 `App ID/App Key`,后端仍兼容 `.env` 或历史设置中的 `TIANHE_USER_ID/TIANHE_USER_KEY`;若未配置,则使用平台级默认 `userId=artveris-platform`,`userKey=sha256(artveris:tianhe:{appId}:{appKey})` 派生。后续需再讨论是继续平台级托管用户,还是按运营账号/机构/作品批次生成链上用户。
|
||||||
- 天河链文档归档与字段校准(2026-07-06):新增 `docs/天河链文档.md` 作为本地对接资料。文档确认 `POST /api/v2/nfr/upload` 返回 `data.digest`(数字商品唯一哈希/文件哈希)、`data.url`(链上 URI/存证链接)、`data.transactionHash`(链上存证交易哈希);`TianheProvider` 现在优先使用 `transactionHash` 写入平台 `txHash`,使用 `url` 写入 `explorerUrl`,并把 `digest` 与 `transactionStatus=submitted` 保存在 `rawResponse`。天河链 FAQ 明确接口成功只代表交易已提交,不代表链上最终确认;后续如要严格展示“已确认”,应基于交易结果查询接口补延时确认任务。
|
- 天河链文档归档与字段校准(2026-07-06):新增 `docs/天河链文档.md` 作为本地对接资料。文档确认 `POST /api/v2/nfr/upload` 返回 `data.digest`(数字商品唯一哈希/文件哈希)、`data.url`(链上 URI/存证链接)、`data.transactionHash`(链上存证交易哈希);`TianheProvider` 现在优先使用 `transactionHash` 写入平台 `txHash`,使用 `url` 写入 `explorerUrl`,并把 `digest` 与 `transactionStatus=submitted` 保存在 `rawResponse`。天河链 FAQ 明确接口成功只代表交易已提交,不代表链上最终确认;后续如要严格展示“已确认”,应基于交易结果查询接口补延时确认任务。
|
||||||
|
- 天河链延时确认(2026-07-06):区块链凭证状态新增 `CONFIRMING`。Mock 存证仍一次完成并直接进入 `ONCHAIN`;天河链 `nfr/upload` 成功后仅标记为 `CONFIRMING`,保存交易哈希、存证链接和提交响应,然后由同一个 `ONCHAIN` 队列延时 30 秒调用 `GET /api/v2/nfr/transaction/status` 查询交易状态。查询到 `blockHash` 或 `blockNum` 后才更新为 `ONCHAIN` 并写入 `onchainAt/blockHash/blockHeight`;最多确认 20 次,仍未查到区块信息或持续失败则转 `FAILED` 并在 `rawResponse.confirmationError` 记录原因。后台状态翻译新增“确认中 / Confirming”,客户端公开页仍只展示最终 `ONCHAIN` 的凭证。
|
||||||
|
|||||||
@@ -54,6 +54,7 @@
|
|||||||
"UNBOUND": "Unbound",
|
"UNBOUND": "Unbound",
|
||||||
"INACTIVE": "Inactive",
|
"INACTIVE": "Inactive",
|
||||||
"PENDING": "Pending",
|
"PENDING": "Pending",
|
||||||
|
"CONFIRMING": "Confirming",
|
||||||
"PROCESSING": "Processing",
|
"PROCESSING": "Processing",
|
||||||
"SUCCESS": "Success",
|
"SUCCESS": "Success",
|
||||||
"PARTIAL": "Partial",
|
"PARTIAL": "Partial",
|
||||||
|
|||||||
@@ -54,6 +54,7 @@
|
|||||||
"UNBOUND": "未绑定",
|
"UNBOUND": "未绑定",
|
||||||
"INACTIVE": "未激活",
|
"INACTIVE": "未激活",
|
||||||
"PENDING": "等待中",
|
"PENDING": "等待中",
|
||||||
|
"CONFIRMING": "确认中",
|
||||||
"PROCESSING": "处理中",
|
"PROCESSING": "处理中",
|
||||||
"SUCCESS": "成功",
|
"SUCCESS": "成功",
|
||||||
"PARTIAL": "部分成功",
|
"PARTIAL": "部分成功",
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ const STATUS_TYPE: Record<string, 'default' | 'success' | 'warning' | 'error' |
|
|||||||
UNBOUND: 'default',
|
UNBOUND: 'default',
|
||||||
INACTIVE: 'info',
|
INACTIVE: 'info',
|
||||||
PENDING: 'info',
|
PENDING: 'info',
|
||||||
|
CONFIRMING: 'info',
|
||||||
PROCESSING: 'info',
|
PROCESSING: 'info',
|
||||||
GENERATING: 'info',
|
GENERATING: 'info',
|
||||||
PARTIAL: 'warning',
|
PARTIAL: 'warning',
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE `blockchain_proof`
|
||||||
|
MODIFY `status` ENUM('PENDING', 'CONFIRMING', 'ONCHAIN', 'FAILED') NOT NULL DEFAULT 'PENDING';
|
||||||
@@ -82,6 +82,7 @@ enum TraceCodeStatus {
|
|||||||
|
|
||||||
enum ProofStatus {
|
enum ProofStatus {
|
||||||
PENDING
|
PENDING
|
||||||
|
CONFIRMING
|
||||||
ONCHAIN
|
ONCHAIN
|
||||||
FAILED
|
FAILED
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,19 @@ export class AttestationService {
|
|||||||
if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404);
|
if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404);
|
||||||
await this.prisma.blockchainProof.update({
|
await this.prisma.blockchainProof.update({
|
||||||
where: { id: proofId },
|
where: { id: proofId },
|
||||||
data: { status: ProofStatus.PENDING, onchainAt: null },
|
data: {
|
||||||
|
status: ProofStatus.PENDING,
|
||||||
|
txHash: null,
|
||||||
|
blockHash: null,
|
||||||
|
blockHeight: null,
|
||||||
|
chainName: null,
|
||||||
|
explorerUrl: null,
|
||||||
|
onchainAt: null,
|
||||||
|
rawResponse: {
|
||||||
|
...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}),
|
||||||
|
retriedAt: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
await this.queue.add('onchain', { proofId });
|
await this.queue.add('onchain', { proofId });
|
||||||
return { success: true };
|
return { success: true };
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { createHash } from 'crypto';
|
import { createHash } from 'crypto';
|
||||||
import { SettingsService } from '../settings/settings.service';
|
import { SettingsService } from '../settings/settings.service';
|
||||||
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
|
import { AttestPayload, AttestResult, AttestationProvider, ConfirmTransactionResult } from './blockchain.types';
|
||||||
import { MockProvider } from './mock.provider';
|
import { MockProvider } from './mock.provider';
|
||||||
import { TianheProvider } from './tianhe.provider';
|
import { TianheProvider } from './tianhe.provider';
|
||||||
|
|
||||||
@@ -29,6 +29,14 @@ export class BlockchainService {
|
|||||||
return provider.attest(payload);
|
return provider.attest(payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async confirmTransaction(txHash: string): Promise<ConfirmTransactionResult> {
|
||||||
|
const provider = await this.buildProvider();
|
||||||
|
if (!provider.confirmTransaction) {
|
||||||
|
return { confirmed: true, txHash, raw: { provider: provider.name, transactionStatus: 'confirmed' } };
|
||||||
|
}
|
||||||
|
return provider.confirmTransaction(txHash);
|
||||||
|
}
|
||||||
|
|
||||||
private async buildProvider(): Promise<AttestationProvider> {
|
private async buildProvider(): Promise<AttestationProvider> {
|
||||||
const settings = await this.settings.getAll();
|
const settings = await this.settings.getAll();
|
||||||
const driver = (settings.blockchainDriver || this.config.get<string>('blockchain.driver') || 'mock') as 'mock' | 'tianhe';
|
const driver = (settings.blockchainDriver || this.config.get<string>('blockchain.driver') || 'mock') as 'mock' | 'tianhe';
|
||||||
|
|||||||
@@ -12,9 +12,19 @@ export interface AttestResult {
|
|||||||
explorerUrl?: string | null;
|
explorerUrl?: string | null;
|
||||||
onchainAt: Date;
|
onchainAt: Date;
|
||||||
raw: Record<string, unknown>;
|
raw: Record<string, unknown>;
|
||||||
|
confirmationRequired?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ConfirmTransactionResult {
|
||||||
|
confirmed: boolean;
|
||||||
|
txHash: string;
|
||||||
|
blockHash?: string | null;
|
||||||
|
blockHeight?: number | null;
|
||||||
|
raw: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AttestationProvider {
|
export interface AttestationProvider {
|
||||||
readonly name: string;
|
readonly name: string;
|
||||||
attest(payload: AttestPayload): Promise<AttestResult>;
|
attest(payload: AttestPayload): Promise<AttestResult>;
|
||||||
|
confirmTransaction?(txHash: string): Promise<ConfirmTransactionResult>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export class MockProvider implements AttestationProvider {
|
|||||||
message: 'success',
|
message: 'success',
|
||||||
data: { txHash, blockHash, blockHeight, dataHash: payload.dataHash },
|
data: { txHash, blockHash, blockHeight, dataHash: payload.dataHash },
|
||||||
},
|
},
|
||||||
|
confirmationRequired: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,34 @@
|
|||||||
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
import { InjectQueue, Processor, WorkerHost } from '@nestjs/bullmq';
|
||||||
import { Logger } from '@nestjs/common';
|
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 { ProofStatus, QUEUE_NAMES } from '@artveris/shared';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { BlockchainService } from './blockchain.service';
|
import { BlockchainService } from './blockchain.service';
|
||||||
|
|
||||||
interface OnchainJobData {
|
interface OnchainJobData {
|
||||||
proofId: number;
|
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 {
|
function requestMeta(raw: unknown): Record<string, unknown> | undefined {
|
||||||
if (!raw || typeof raw !== 'object') return undefined;
|
if (!raw || typeof raw !== 'object') return undefined;
|
||||||
const meta = (raw as Record<string, unknown>).requestMeta;
|
const meta = (raw as Record<string, unknown>).requestMeta;
|
||||||
return meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : undefined;
|
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)
|
@Processor(QUEUE_NAMES.ONCHAIN)
|
||||||
export class OnchainProcessor extends WorkerHost {
|
export class OnchainProcessor extends WorkerHost {
|
||||||
private readonly logger = new Logger(OnchainProcessor.name);
|
private readonly logger = new Logger(OnchainProcessor.name);
|
||||||
@@ -22,12 +36,20 @@ export class OnchainProcessor extends WorkerHost {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly blockchain: BlockchainService,
|
private readonly blockchain: BlockchainService,
|
||||||
|
@InjectQueue(QUEUE_NAMES.ONCHAIN) private readonly queue: Queue,
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
async process(job: Job<OnchainJobData>): Promise<void> {
|
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 } });
|
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
|
||||||
if (!proof) return;
|
if (!proof) return;
|
||||||
try {
|
try {
|
||||||
@@ -38,31 +60,127 @@ export class OnchainProcessor extends WorkerHost {
|
|||||||
await this.prisma.blockchainProof.update({
|
await this.prisma.blockchainProof.update({
|
||||||
where: { id: proofId },
|
where: { id: proofId },
|
||||||
data: {
|
data: {
|
||||||
status: ProofStatus.ONCHAIN,
|
status: result.confirmationRequired ? ProofStatus.CONFIRMING : ProofStatus.ONCHAIN,
|
||||||
txHash: result.txHash,
|
txHash: result.txHash,
|
||||||
blockHash: result.blockHash || null,
|
blockHash: result.blockHash || null,
|
||||||
blockHeight: result.blockHeight !== null && result.blockHeight !== undefined ? BigInt(result.blockHeight) : null,
|
blockHeight: result.blockHeight !== null && result.blockHeight !== undefined ? BigInt(result.blockHeight) : null,
|
||||||
chainName: result.chainName,
|
chainName: result.chainName,
|
||||||
explorerUrl: result.explorerUrl || null,
|
explorerUrl: result.explorerUrl || null,
|
||||||
onchainAt: result.onchainAt,
|
onchainAt: result.confirmationRequired ? null : result.onchainAt,
|
||||||
rawResponse: result.raw as object,
|
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) {
|
} catch (e) {
|
||||||
const message = (e as Error).message;
|
const message = (e as Error).message;
|
||||||
await this.prisma.blockchainProof.update({
|
await this.prisma.blockchainProof.update({
|
||||||
where: { id: proofId },
|
where: { id: proofId },
|
||||||
data: {
|
data: {
|
||||||
status: ProofStatus.FAILED,
|
status: ProofStatus.FAILED,
|
||||||
rawResponse: {
|
rawResponse: jsonObject({
|
||||||
...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}),
|
...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}),
|
||||||
error: message,
|
error: message,
|
||||||
failedAt: new Date().toISOString(),
|
failedAt: new Date().toISOString(),
|
||||||
},
|
}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
this.logger.error(`存证 ${proofId} 上链失败: ${message}`);
|
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(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,5 +37,32 @@ describe('TianheProvider', () => {
|
|||||||
expect(result.explorerUrl).toBe(response.data.url);
|
expect(result.explorerUrl).toBe(response.data.url);
|
||||||
expect(result.raw.digest).toBe(response.data.digest);
|
expect(result.raw.digest).toBe(response.data.digest);
|
||||||
expect(result.raw.transactionStatus).toBe('submitted');
|
expect(result.raw.transactionStatus).toBe('submitted');
|
||||||
|
expect(result.confirmationRequired).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('按交易状态接口确认链上区块信息', async () => {
|
||||||
|
const response = {
|
||||||
|
code: 0,
|
||||||
|
message: 'success',
|
||||||
|
data: {
|
||||||
|
status: '0x0',
|
||||||
|
blockHash: '0xblockhash',
|
||||||
|
blockNum: 12345,
|
||||||
|
transactionHash: '0x1234567890abcdef',
|
||||||
|
tokenId: -999,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
text: async () => JSON.stringify(response),
|
||||||
|
} as Response);
|
||||||
|
|
||||||
|
const result = await provider.confirmTransaction(response.data.transactionHash);
|
||||||
|
|
||||||
|
expect(result.confirmed).toBe(true);
|
||||||
|
expect(result.txHash).toBe(response.data.transactionHash);
|
||||||
|
expect(result.blockHash).toBe(response.data.blockHash);
|
||||||
|
expect(result.blockHeight).toBe(response.data.blockNum);
|
||||||
|
expect(result.raw.transactionStatus).toBe('confirmed');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
|
import { AttestPayload, AttestResult, AttestationProvider, ConfirmTransactionResult } from './blockchain.types';
|
||||||
|
|
||||||
export interface TianheOptions {
|
export interface TianheOptions {
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
@@ -125,6 +125,53 @@ export class TianheProvider implements AttestationProvider {
|
|||||||
transactionStatus: 'submitted',
|
transactionStatus: 'submitted',
|
||||||
transactionStatusNote: '天河链接口成功仅表示交易已提交;最终链上结果需通过交易查询接口确认。',
|
transactionStatusNote: '天河链接口成功仅表示交易已提交;最终链上结果需通过交易查询接口确认。',
|
||||||
},
|
},
|
||||||
|
confirmationRequired: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async confirmTransaction(txHash: string): Promise<ConfirmTransactionResult> {
|
||||||
|
const baseUrl = required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
|
||||||
|
const appId = required(this.opts.appId, 'App ID');
|
||||||
|
const appKey = required(this.opts.appKey, 'App Key');
|
||||||
|
const url = new URL(`${baseUrl}/api/v2/nfr/transaction/status`);
|
||||||
|
url.searchParams.set('appId', appId);
|
||||||
|
url.searchParams.set('appKey', appKey);
|
||||||
|
url.searchParams.set('transactionHash', required(txHash, 'Transaction Hash'));
|
||||||
|
|
||||||
|
const res = await fetch(url);
|
||||||
|
const text = await res.text();
|
||||||
|
let raw: Record<string, unknown> = { text };
|
||||||
|
try {
|
||||||
|
raw = text ? JSON.parse(text) : {};
|
||||||
|
} catch {
|
||||||
|
raw = { text };
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`天河链交易确认请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const code = pickString(raw, ['code', 'statusCode', 'errCode']);
|
||||||
|
const success = code === null || code === '0' || code.toLowerCase() === 'success' || code === '200';
|
||||||
|
if (!success) {
|
||||||
|
const msg = pickString(raw, ['message', 'msg', 'error']) || '接口返回失败';
|
||||||
|
throw new Error(`天河链交易确认失败:${msg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = responseData(raw);
|
||||||
|
const blockHash = pickString(data, ['blockHash']);
|
||||||
|
const blockHeight = pickNumber(data, ['blockNum', 'blockHeight', 'height']);
|
||||||
|
const confirmed = Boolean(blockHash || blockHeight !== null);
|
||||||
|
return {
|
||||||
|
confirmed,
|
||||||
|
txHash: pickString(data, ['transactionHash', 'txHash']) || txHash,
|
||||||
|
blockHash,
|
||||||
|
blockHeight,
|
||||||
|
raw: {
|
||||||
|
response: raw,
|
||||||
|
transactionStatus: confirmed ? 'confirmed' : 'waiting',
|
||||||
|
tokenId: pickString(data, ['tokenId']),
|
||||||
|
status: pickString(data, ['status']),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ export enum QueryResult {
|
|||||||
|
|
||||||
export enum ProofStatus {
|
export enum ProofStatus {
|
||||||
PENDING = 'PENDING',
|
PENDING = 'PENDING',
|
||||||
|
CONFIRMING = 'CONFIRMING',
|
||||||
ONCHAIN = 'ONCHAIN',
|
ONCHAIN = 'ONCHAIN',
|
||||||
FAILED = 'FAILED',
|
FAILED = 'FAILED',
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user