跳到主要内容

交易项

这里演示如何通过 UKey Wallet Conflux Provider 发起交易、估算 Gas、只读调用合约,并配合 js-conflux-sdk 完成更复杂的链上交互。


发交易

const txHash = await provider.request({
method: "cfx_sendTransaction",
requestParams: [
{
from: senderAddress,
to: recipientAddress,
value: "0x2386f26fc10000", // 示例 CFX 金额
gas: "0x5208", // 数值参考片段:21000
},
],
});

console.log("交易哈希:", txHash);

估算 Gas 后发送

// 第一步先估算 gas
const gasEstimate = await provider.request({
method: "cfx_estimateGasAndCollateral",
requestParams: [
{
from: senderAddress,
to: recipientAddress,
value: "0x2386f26fc10000",
},
],
});

// 按估算值发起发送
const txHash = await provider.request({
method: "cfx_sendTransaction",
requestParams: [
{
from: senderAddress,
to: recipientAddress,
value: "0x2386f26fc10000",
gas: gasEstimate.gasLimit,
storageLimit: gasEstimate.storageCollateralized,
},
],
});

调用合约

const callResult = await provider.request({
method: "cfx_call",
requestParams: [
{
to: contractAddress,
data: encodedFunctionCall,
},
"latest_state",
],
});

console.log("调用结果:", callResult);

与 js-conflux-sdk 配合使用

部署

npm install js-conflux-sdk

连接 Provider

import { Conflux } from "js-conflux-sdk";

const conflux = new Conflux({
url: "https://main.confluxrpc.com",
networkId: 1029,
});

// 调用方式如下 UKey Wallet provider 执行签名
conflux.provider = provider;

使用 SDK 发送交易

// 构建并发送交易
const tx = await conflux.cfx.sendTransaction({
from: senderAddress,
to: recipientAddress,
value: Conflux.Drip.fromCFX(1), // one CFX
});

console.log("构造出的交易:", tx);

// 等待链上确认
const receipt = await tx.executed();
console.log("交易收据:", receipt);

合约交互

const contract = conflux.Contract({
abi: contractABI,
address: contractAddress,
});

// 执行读取
const callResult = await contract.someViewFunction().call();

// 执行写入
const tx = await contract.someWriteFunction(param1, param2).sendTransaction({
from: senderAddress,
});

const receipt = await tx.executed();

处理异常

try {
const accounts = await provider.request({
method: "cfx_requestAccounts",
});
} catch (error) {
if (error.code === 4001) {
console.log("用户已拒绝本次请求");
} else if (error.code === -32603) {
console.log("Provider 内部错误");
} else {
console.error("执行报错:", error.message);
}
}