交易项
这里演示如何通过 UKey Wallet Algorand Provider 签名 ARC-0001 交易、广播交易、处理分组交易和兼容传统交易 API。
签名交易(ARC-0001)
下面这段参考代码构造一笔支付交易,编码后交给钱包签名:
import algosdk from "algosdk";
// 构建交易
const suggestedParams = await algodClient.getTransactionParams().do();
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
from: senderAddress,
to: recipientAddress,
amount: 1000000, // one ALGO (microAlgos)
suggestedParams,
});
// 准备进行签名
const walletTxns = [
{
txn: Buffer.from(algosdk.encodeUnsignedTransaction(txn)).toString("base64"),
},
];
// 执行签名
const signedTxns = await provider.signTxns(walletTxns);
console.log("签名完成的交易数据:", signedTxns);
签名多个交易
// 这是一组交易
const txns = [txn1, txn2, txn3];
algosdk.assignGroupID(txns);
// 准备进行签名
const walletTxns = txns.map((txn) => ({
txn: Buffer.from(algosdk.encodeUnsignedTransaction(txn)).toString("base64"),
}));
// 对整组全部签名
const signedTxns = await provider.signTxns(walletTxns);
部分签名(多签)
// 只对组里指定交易签名
const walletTxns = [
{ txn: encodedTxn1 },
{ txn: encodedTxn2, signers: [] }, // 这一笔跳过签名
{ txn: encodedTxn3 },
];
const signedTxns = await provider.signTxns(walletTxns);
// signedTxns[1] 会是 null
确认提交交易
广播已签名的交易:
const callResult = await provider.postTxns(signedTxns);
console.log("交易 ID 返回值:", callResult.txIDs);
签名并确认提交
一步完成签名和广播:
const callResult = await provider.signAndPostTxns(walletTxns);
console.log("交易 ID 返回值:", callResult.txIDs);
传统交易 API
签名交易(传统)
// 将交易构造成 Uint8Array
const txnBytes = algosdk.encodeUnsignedTransaction(txn);
// 执行签名
const signedTxnBytes = await provider.signTransaction([txnBytes]);
// 确认提交发送
const { txId } = await algodClient.sendRawTransaction(signedTxnBytes[0]).do();
签名并发送(传统)
const callResult = await provider.signAndSendTransaction([txnBytes]);
console.log("交易 ID 返回值:", callResult.txId);
整例
import algosdk from "algosdk";
async function submitAlgoTransfer() {
// 建立连接
const provider = window.$ukey?.algo;
const { address } = await provider.connect();
// 配置客户端
const algodClient = new algosdk.Algodv2(
"",
"https://mainnet-api.algonode.cloud",
"",
);
// 读取参数
const suggestedParams = await algodClient.getTransactionParams().do();
// 构建交易
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
from: address,
to: "TARGET_ACCOUNT_ADDRESS",
amount: 1000000, // one ALGO
suggestedParams,
});
// 执行签名
const walletTxns = [
{
txn: Buffer.from(algosdk.encodeUnsignedTransaction(txn)).toString(
"base64",
),
},
];
const signedTxns = await provider.signTxns(walletTxns);
// 确认提交发送
const { txId } = await algodClient
.sendRawTransaction(Buffer.from(signedTxns[0], "base64"))
.do();
console.log("交易 ID 返回值:", txId);
// 等待链上确认
await algosdk.waitForConfirmation(algodClient, txId, 4);
console.log("已收到确认!");
}