Transactions

萊特幣 litecore-lib 接收 UTXO 和目前餘額

  • November 5, 2018

我編寫了用於將所有餘額從地址發送到其他地址的NodeJS腳本。bitcoin現在我想為litecoin. 因為bitcoin我使用了 bitcore-libbitcore-explorers庫來做到這一點。

因為litecoin我找到了分叉並採用了 lib litecore-lib,但是我找不到UTXO像我在以下情況下那樣接收某些 LTC 地址的數據的解決方案bitcoin

var Insight = require("bitcore-explorers").Insight;
var insight = new Insight(network);
insight.getUnspentUtxos(sourceAddress, function (error, utxos) {
   // determine balance, fee and sign transaction
}

我該怎麼做litecoin?謝謝!

我使用該request庫從洞察 API 中手動檢索資訊。我還使用該litecore-lib庫來創建交易。

var Litecoin = require("litecore-lib");
var request = require("request");

//manually hit an insight api to retrieve utxos of address
function getUTXOs(address) {
 return new Promise((resolve, reject) => {
   request({
     uri: 'https://insight.litecore.io/api/addr/' + address + '/utxo',
     json: true
   },
     (error, response, body) => {
       if(error) reject(error);
       resolve(body)
     }
   )
 })
}

//manually hit an insight api to broadcast your tx
function broadcastTX(rawtx) {
 return new Promise((resolve, reject) => {
   request({
     uri: 'https://insight.litecore.io/tx/send',
     method: 'POST',
     json: {
       rawtx
     }
   },
     (error, response, body) => {
       if(error) reject(error);
       resolve(body.txid)
     }
   )
 })
}

//your private key and address here
var privateKey = PrivateKey.fromWIF('YOUR_PRIVATE_KEY_HERE');
var address = privateKey.toPublicKey().toAddress();

getUTXOs(address)
 .then((utxos) => {

   let balance = 0;
   for (var i = 0; i < utxos.length; i++) {
     balance +=utxos[i]['satoshis'];
   } //add up the balance in satoshi format from all utxos

   var fee = 1500; //fee for the tx
   var tx = new Litecoin.Transaction() //use litecore-lib to create a transaction
     .from(utxos)
     .to('TO_ADDRESS', balance - fee) //note: you are sending all your balance AKA sweeping
     .fee(fee)
     .sign(privateKey)
     .serialize();

   return broadcastTX(tx) //broadcast the serialized tx
 })
 .then((result) => {
   console.log(result) // txid
 })
 .catch((error) => {
   throw error;
 })

乾杯!

引用自:https://bitcoin.stackexchange.com/questions/61235