本页目录
交易
准备交易前,先连接 provider 并读取当前网络。这些示例适用于 Conflux Core Space。请替换省略的地址,并在调用 SDK 方法前初始化客户端。
了解如何在 Conflux 上发送交易。
发送交易
const txHash = await provider.request({
method: 'cfx_sendTransaction',
params: [{
from: senderAddress,
to: recipientAddress,
value: '0xDE0B6B3A7640000', // 1 CFX in Drip (hex)
gas: '0x5208', // 21000
}]
})
console.log('Transaction hash:', txHash)带 Gas 估算发送
// Estimate gas first
const gasEstimate = await provider.request({
method: 'cfx_estimateGasAndCollateral',
params: [{
from: senderAddress,
to: recipientAddress,
value: '0xDE0B6B3A7640000',
}]
})
// Send with estimated values
const txHash = await provider.request({
method: 'cfx_sendTransaction',
params: [{
from: senderAddress,
to: recipientAddress,
value: '0xDE0B6B3A7640000',
gas: gasEstimate.gasLimit,
storageLimit: gasEstimate.storageCollateralized,
}]
})调用合约
const result = await provider.request({
method: 'cfx_call',
params: [{
to: contractAddress,
data: encodedFunctionCall,
}, 'latest_state']
})
console.log('Result:', result)与 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,
})
// Use OneKey provider for signing
conflux.provider = provider使用 SDK 发送交易
// Create and send transaction
const tx = conflux.cfx.sendTransaction({
from: senderAddress,
to: recipientAddress,
value: Conflux.Drip.fromCFX(1), // 1 CFX
})
console.log('Transaction:', tx)
// Wait for confirmation
const receipt = await tx.executed()
console.log('Receipt:', receipt)合约交互
const contract = conflux.Contract({
abi: contractABI,
address: contractAddress,
})
// Read
const result = await contract.someViewFunction().call()
// Write
const tx = 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('User rejected the request')
} else if (error.code === -32603) {
console.log('Internal error')
} else {
console.error('Error:', error.message)
}
}最后更新于