signTransaction
使用钱包签名一个或多个原始交易。这是一个底层 API,让你可以完全控制交易的构建和签名。
用法
ts
const { sigs } = await Turing.signTransaction({
txraws,
utxos_satoshis,
script_pubkeys,
});参数
ts
interface SignTransactionParams {
txraws: string[]; // 序列化的交易 hex 字符串数组
utxos_satoshis: number[][]; // 每笔交易中每个输入的 satoshi 值
script_pubkeys: string[][]; // 每笔交易中每个输入的 script pubkey
}| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
txraws | string[] | 是 | 未签名的交易 hex 字符串数组 |
utxos_satoshis | number[][] | 是 | 二维数组 — 每笔交易中每个输入的 satoshi 值 |
script_pubkeys | string[][] | 是 | 二维数组 — 每笔交易中每个输入的 script pubkey |
返回值
ts
interface SignTransactionResponse {
sigs: string[][]; // 二维数组 — 每笔交易中每个输入的签名
}| 字段 | 类型 | 说明 |
|---|---|---|
sigs | string[][] | 签名数组,通过 sigs[交易索引][输入索引] 访问 |
错误处理
ts
try {
const { sigs } = await Turing.signTransaction({
txraws,
utxos_satoshis,
script_pubkeys,
});
console.log("签名:", sigs);
} catch (error) {
console.error("签名失败:", error);
}示例
完整示例:构建两笔交易、签名并组装脚本。
ts
const utxosA: tbc.Transaction.IUnspentOutput[] = [];
const utxosB: tbc.Transaction.IUnspentOutput[] = [];
const utxos_satoshis: number[][] = [[], []];
const script_pubkeys: string[][] = [[], []];
const txraws: string[] = [];
const txs: tbc.Transaction[] = [];
const tx0 = new tbc.Transaction()
.from(utxosA)
.to(address, 100000)
.change(address)
.fee(80);
const tx1 = new tbc.Transaction()
.from(utxosB)
.to(address, 100000)
.change(address)
.fee(80);
txraws.push(tx0.uncheckedSerialize(), tx1.uncheckedSerialize());
for (let i = 0; i < utxosA.length; i++) {
utxos_satoshis[0].push(utxosA[i].satoshis);
script_pubkeys[0].push(utxosA[i].script);
}
for (let i = 0; i < utxosB.length; i++) {
utxos_satoshis[1].push(utxosB[i].satoshis);
script_pubkeys[1].push(utxosB[i].script);
}
const { sigs } = await Turing.signTransaction({
txraws,
utxos_satoshis,
script_pubkeys,
});
for (let i = 0; i < utxosA.length; i++) {
tx0.setInputScript({ inputIndex: i }, (tx) => {
const sig = sigs[0][i];
const sig_length = (sig.length / 2).toString(16);
const publicKey_length = (
publicKey.toBuffer().toString("hex").length / 2
).toString(16);
return new tbc.Script(
sig_length + sig + publicKey_length + publicKey.toString()
);
});
txs.push(tx0);
}
for (let i = 0; i < utxosB.length; i++) {
tx1.setInputScript({ inputIndex: i }, (tx) => {
const sig = sigs[1][i];
const sig_length = (sig.length / 2).toString(16);
const publicKey_length = (
publicKey.toBuffer().toString("hex").length / 2
).toString(16);
return new tbc.Script(
sig_length + sig + publicKey_length + publicKey.toString()
);
});
txs.push(tx1);
}
broadcastTXsraw(txs.map((tx) => ({ txraw: tx.uncheckedSerialize() })));