交易项
这里演示如何通过 UKey Wallet Cardano Provider 签名 CBOR 交易、确认提交交易,并配合 Lucid 或 Mesh 完成更高级的交易构建。
签交易
// transaction 需要是 CBOR 编码后的十六进制字符串
const signedTx = await api.signTx(transactionCbor, partialSign);
// partialSign flag: boolean
// - false: 对钱包拥有的所有输入都签名
// - true: 仅签那些明确归自己所有的输入(适合多签)
console.log("签名完成的交易数据:", signedTx);
确认提交交易
// 确认提交签名后的交易
const txHash = await api.submitTx(signedTransactionCbor);
console.log("交易哈希:", txHash);
完整交易流程
import {
TransactionBuilder,
TransactionBuilderConfigBuilder,
LinearFee,
BigNum,
Address,
TransactionOutput,
Value,
} from "@emurgo/cardano-serialization-lib-browser";
async function submitAdaTransfer(recipientAddress, amountLovelace) {
const api = await window.cardano.ukey.enable();
// 读取 UTxO
const utxos = await api.getUtxos();
const changeAddress = await api.getChangeAddress();
// 组装交易
const txBuilder = TransactionBuilder.new(
TransactionBuilderConfigBuilder.new()
.fee_algo(LinearFee.new(BigNum.from_str("44"), BigNum.from_str("155381")))
.pool_deposit(BigNum.from_str("500000000"))
.key_deposit(BigNum.from_str("2000000"))
.max_value_size(5000)
.max_tx_size(16384)
.coins_per_utxo_byte(BigNum.from_str("4310"))
.build(),
);
// 从 UTxO 列表里补充输入
utxos.forEach((utxo) => {
// 把 UTxO 添加为输入...
});
// 加入输出
txBuilder.add_output(
TransactionOutput.new(
Address.from_bech32(recipientAddress),
Value.new(BigNum.from_str(amountLovelace)),
),
);
// 配置找零地址
txBuilder.add_change_if_needed(Address.from_bech32(changeAddress));
// 组装交易
const tx = txBuilder.build_tx();
const txCbor = Buffer.from(tx.to_bytes()).toString("hex");
// 执行签名
const signedTxCbor = await api.signTx(txCbor, false);
// 执行确认提交
const txHash = await api.submitTx(signedTxCbor);
console.log("交易哈希:", txHash);
return txHash;
}
使用 Lucid
Lucid 可以简化交易构造和确认提交流程:
npm install lucid-cardano
import { Lucid } from "lucid-cardano";
// 通过 UKey Wallet 初始化 Lucid
const lucid = await Lucid.new(
new Blockfrost("https://cardano-mainnet.blockfrost.io/api", "demo-api-key"),
"Mainnet",
);
// 连接 UKey Wallet 设备
const api = await window.cardano.ukey.enable();
lucid.selectWallet(api);
// 发起 ADA 转账
const tx = await lucid
.newTx()
.payToAddress("addr1demoexample...", { lovelace: 5000000n })
.complete();
const signedTx = await tx.sign().complete();
const txHash = await signedTx.submit();
console.log("交易哈希:", txHash);
使用 Mesh
Mesh 也可以直接使用浏览器钱包能力:
npm install @meshsdk/core
import { BrowserWallet, Transaction } from "@meshsdk/core";
// 建立到 UKey Wallet 的连接
const wallet = await BrowserWallet.enable("ukey");
// 读取钱包信息
const balance = await wallet.getBalance();
const addresses = await wallet.getUsedAddresses();
// 组装并发送交易
const tx = new Transaction({ initiator: wallet }).sendLovelace(
"addr1demoexample...",
"5000000",
);
const unsignedTx = await tx.build();
const signedTx = await wallet.signTx(unsignedTx);
const txHash = await wallet.submitTx(signedTx);