跳转到内容

完整交易生命周期

构建、签名、广播原生 D9 转账交易,并等待区块最终确认。

前置条件: 已安装 polkadot-api@3.3.0 并生成 d9 描述文件(参见 RPC 验证),以及读取链上数据中的 src/amount.ts。

import { createClient } from "polkadot-api";
import { getWsProvider } from "polkadot-api/ws";
import { d9, getMetadata } from "@polkadot-api/descriptors";
import type { D9ConnectorAccount } from "@d9-network/dapp-connector";
import { toChainAddress } from "@d9-network/dapp-connector/protocol";
import { parseAmount } from "./amount";
import { d9Config } from "./config";
export async function executeInjectedTransfer(
account: D9ConnectorAccount,
recipientAddress: string,
d9AmountString: string,
getCurrentAccount: () => Promise<D9ConnectorAccount | undefined>,
) {
if (account.transport !== "papi" || !account.txCreator) {
throw new Error("此操作需要包含有效 txCreator 的注入式钱包账户");
}
const txCreator = account.txCreator;
const recipient = toChainAddress(recipientAddress);
const rawValue = parseAmount(d9AmountString, 12);
if (rawValue <= 0n) throw new Error("转账金额必须大于零");
const assertAuthority = async () => {
const current = await getCurrentAccount();
if (current?.transport !== "papi" || current.address !== account.address ||
current.txCreator !== txCreator) {
throw new Error("广播前账户授权状态已变更");
}
};
const client = createClient(getWsProvider(d9Config.rpcUrl), { getMetadata });
try {
const identity = await client.getChainSpecData();
if (identity.genesisHash !== d9Config.expectedGenesisHash) {
throw new Error("RPC 创世哈希与配置不匹配");
}
// 使用已生成的主网描述文件构建交易
const api = client.getTypedApi(d9);
const tx = api.tx.Balances.transfer_keep_alive({
dest: { type: "Id", value: recipient },
value: rawValue,
});
await assertAuthority();
// 由钱包完成签名并返回已签名交易字节
const signedTx = await tx.create(txCreator);
// 广播前再次核对当前账户授权状态
await assertAuthority();
const result = await client.submit(signedTx);
if (!result.ok) {
throw new Error(`链上交易执行失败: ${JSON.stringify(result.dispatchError)}`);
}
return result;
} finally {
client.destroy();
}
}
const result = await executeInjectedTransfer(account, recipientAddress, "1.25", getCurrentAccount);
  • account 须为当前活跃的注入式账户(transport: "papi")。
  • getCurrentAccount 每次调用都必须实时读取最新的已授权账户状态,切勿返回缓存副本,否则无法察觉签名期间的账户切换。

client.submit 会等待区块最终确认。返回时若 result.ok 为 true,result.block.hash 即为最终确认的区块哈希。

报错信息 处理方式
此操作需要包含有效 txCreator 的注入式钱包账户 请在 D9 钱包内置浏览器中打开页面并通过注入式提供者连接。
RPC 创世哈希与配置不匹配 将 VITE_D9_RPC_URL 指向与 VITE_D9_GENESIS_HASH 一致的网络节点。
广播前账户授权状态已变更 用户在签名期间切换或断开了账户,请提示用户重新发起操作。
链上交易执行失败: … 链上拒绝了该笔转账,请查看错误信息中的 dispatchError。