Skip to Content
dApp 接入
本页目录

交易

使用 dApp API 前先调用 enable()。CIP-30 返回的地址是十六进制编码的字节;交易和 value 参数是十六进制编码的 CBOR。在浏览器示例中使用 Buffer 时,需要显式导入 buffer 或使用字节转换工具。

了解如何在 Cardano 上签署和提交交易。


签署交易

// transaction should be CBOR-encoded hex string const witnessSetCbor = await api.signTx(transactionCbor, partialSign) // partialSign: boolean // - false: reject if the wallet cannot provide every required signature // - true: return the signatures the wallet can provide console.log('Witness set:', witnessSetCbor)

提交交易

// Submit signed transaction const txHash = await api.submitTx(signedTransactionCbor) console.log('Transaction hash:', txHash)

构建、签名并提交

signTx 返回 witness set,不是完整的已签名交易。使用 Cardano 交易库构建未签名交易,将返回的 witness 与原有 witness set 合并,再提交合并后的完整交易。

// `unsignedTransactionCbor` is a complete transaction built with current // protocol parameters, selected inputs, outputs, fees, and change. const witnessSetCbor = await api.signTx(unsignedTransactionCbor, false) // Merge witnessSetCbor into the original transaction using your Cardano SDK. // Preserve existing witnesses, scripts, datums, redeemers, and auxiliary data. // Submit the serialized complete transaction, never witnessSetCbor alone. const txHash = await api.submitTx(completeSignedTransactionCbor)

如果应用尚未实现交易构建和 witness 合并,可使用下方 Lucid 或 Mesh 流程。SDK 示例与版本有关,请以所安装版本的文档为准。


使用 Lucid

Lucid  提供更简单的 API:

npm install lucid-cardano
import { Lucid, Blockfrost } from 'lucid-cardano' // Initialize Lucid with OneKey const lucid = await Lucid.new( new Blockfrost('https://cardano-mainnet.blockfrost.io/api', 'your-api-key'), 'Mainnet' ) // Connect OneKey const api = await window.cardano.onekey.enable() lucid.selectWallet(api) // Send ADA const tx = await lucid .newTx() .payToAddress('addr1...', { lovelace: 5000000n }) .complete() const signedTx = await tx.sign().complete() const txHash = await signedTx.submit() console.log('TX Hash:', txHash)

使用 Mesh

Mesh  是另一个流行的 Cardano SDK:

npm install @meshsdk/core
import { BrowserWallet, Transaction } from '@meshsdk/core' // Connect to OneKey const wallet = await BrowserWallet.enable('onekey') // Get wallet info const balance = await wallet.getBalance() const addresses = await wallet.getUsedAddresses() // Build and send transaction const tx = new Transaction({ initiator: wallet }) .sendLovelace('addr1...', '5000000') const unsignedTx = await tx.build() const signedTx = await wallet.signTx(unsignedTx) const txHash = await wallet.submitTx(signedTx)
最后更新于