您现在的位置:kastop>> Kas信息 Kaspa网络>>正文内容

Kaspa兑换脚本示例

The redeem script


// @ts-ignore
globalThis.WebSocket = require("websocket").w3cwebsocket;
const fs = require('fs');

const {
    PrivateKey,
    Resolver,
    RpcClient,
    kaspaToSompi,
    createTransactions,
    initConsolePanicHook,
    addressFromScriptPublicKey,
    Address,
    Opcodes,
    ScriptBuilder
} = require('../../../../nodejs/kaspa');

const destinationAddressArg = 'kaspatest:qqff55t6ay54a5940jvzq2ylq8qnkazlffjqshlt70znhp48drslx9yunu0um';
const networkId = 'testnet-10';
initConsolePanicHook();

function createTimeLockedScript(lockTime) {
    const builder = new ScriptBuilder();
    return builder
        .addI64(BigInt(lockTime))
        .addOp(Opcodes.OpCheckLockTimeVerify)
        .addOp(Opcodes.OpDrop)
        .addOp(Opcodes.OpCheckSig) // This will be used for the sender's signature
        .createPayToScriptHashScript(); // This will not be used to create a new address
}

(async () => {
    const privateKey = new PrivateKey('af0aa5ddcc93ab2d60986db7cb88cae95f52b142c13d33b4d616c70106f110d4');
    const sourceAddress = privateKey.toKeypair().toAddress(networkId);
    console.info(`Source address: ${sourceAddress}`);

    const destinationAddress = new Address(destinationAddressArg);
    console.log(`Destination address: ${destinationAddress}`);

    const rpc = new RpcClient({
        resolver: new Resolver(),
        networkId
    });

    console.log(`Connecting to ${rpc.url}`);

    await rpc.connect();
    let { isSynced } = await rpc.getServerInfo();
    if (!isSynced) {
        console.error("Please wait for the node to sync");
        rpc.disconnect();
        return;
    }

    let { entries } = (await rpc.getUtxosByAddresses([sourceAddress]));

    if (!entries.length) {
        console.error("No UTXOs found for address");
    } else {
        console.info(entries);

        entries.sort((a, b) => a.amount > b.amount ? 1 : -1);

        const oneHourInSeconds = 60 * 2;
        const currentUnixTime = Math.floor(Date.now() / 1000);
        const lockTime = currentUnixTime + oneHourInSeconds;
        const timeLockedScript = createTimeLockedScript(lockTime);
        console.log(`Time-locked script: ${timeLockedScript.toString('hex')}`);
        fs.writeFileSync('timeLockedScript.json', JSON.stringify(timeLockedScript));

        // Create a P2SH address from the time-locked script
        const P2SHAddress = addressFromScriptPublicKey(timeLockedScript, networkId);
        console.log(`P2SH Address: ${P2SHAddress.toString()}`);
        
        // Use the P2SH address in the transaction outputs
        let { transactions, summary } = await createTransactions({
            entries,
            outputs: [{
                address: P2SHAddress.toString(), // Use the P2SH address here
                amount: kaspaToSompi("10") // Adjust the amount as needed
            }],
            priorityFee: 0n,
            changeAddress: sourceAddress,
            networkId: networkId
        });

        console.log("Summary:", summary);

        for (let pending of transactions) {
          // Sign the transaction
          await pending.sign([privateKey]);

          // Get the signature from the signed input
          const signature = pending.sign([privateKey]); // Assuming single input, adjust if multiple
          console.log(signature)
      
          // Set the lockTime on the transaction
          pending.transaction.lockTime = BigInt(lockTime);
      
          let txid = await pending.submit(rpc);
          console.log("Node responded with txid:", txid);
      }
    }
    await rpc.disconnect();
})();

感动 同情 无聊 愤怒 搞笑 难过 高兴 路过
【字体: 】【收藏】【打印文章】 【 打赏 】 【查看评论

相关文章

    没有相关内容