You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.5 KiB
87 lines
2.5 KiB
import systemConfiguration from 'utils/SystemConfiguration.js'
|
|
const bitcoin = require('bitcoinjs-lib')
|
|
|
|
let BtcUtil = {
|
|
getBalance:async function(address,success) {
|
|
let balance=0;
|
|
try{
|
|
let res= await uni.request({
|
|
url: 'http://scan.weirui0755.com/btc/api/address/balancetrend/btc/' + address, //请求接口
|
|
header: {
|
|
'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
|
|
}
|
|
});
|
|
if (res.data.code === 1) {
|
|
if(res.data.data.length>0){
|
|
var data=res.data.data[0];
|
|
console.log(data,11111)
|
|
for(let b in data){
|
|
balance=data[b];
|
|
}
|
|
}
|
|
}
|
|
}catch(e){
|
|
//TODO handle the exception
|
|
}
|
|
return balance;
|
|
},
|
|
btcToSatoshi:function(btcAmount){
|
|
return Math.ceil(btcAmount * 1e8);
|
|
},
|
|
sendTransaction:async function(fromAddress, toAddress, value, privateKey){
|
|
const utxo = await fetch(systemConfiguration.constant.btcUtxo+fromAddress);
|
|
const utxoData=await utxo.json();
|
|
const txs=utxoData.data.txs;
|
|
let txsList=[];
|
|
let remainingValue=value;
|
|
let balanceSatoshis=0;
|
|
|
|
for(let i=0;i<txs.length;i++){
|
|
txsList.push(txs[i]);
|
|
balanceSatoshis=Number(balanceSatoshis)+Number(txs[i].value);
|
|
if(txs[i].value>remainingValue){
|
|
break;
|
|
}
|
|
remainingValue=remainingValue-txs[i].value;
|
|
}
|
|
if(balanceSatoshis<=value){
|
|
throw new Error("Insufficient balance");
|
|
}
|
|
console.log(balanceSatoshis,value)
|
|
const feeSatoshis=this.btcToSatoshi(0.0001);
|
|
|
|
balanceSatoshis=this.btcToSatoshi(balanceSatoshis);
|
|
value=this.btcToSatoshi(value);
|
|
let change = balanceSatoshis - feeSatoshis - value;
|
|
|
|
let bob = new bitcoin.ECPair.fromWIF(privateKey,systemConfiguration.constant.btcNetwork);
|
|
let txb = new bitcoin.TransactionBuilder(systemConfiguration.constant.btcNetwork);
|
|
for(let i=0;i<txsList.length;i++){
|
|
|
|
txb.addInput(txsList[i].txid, txsList[i].output_no);
|
|
|
|
}
|
|
console.log(change)
|
|
txb.addOutput(fromAddress, change);
|
|
console.log(txsList[0].txid,txsList[0].output_no)
|
|
txb.addOutput(toAddress, value);
|
|
|
|
for(let i=0;i<txsList.length;i++){
|
|
txb.sign(i, bob);
|
|
}
|
|
// 签名交易,0代表索引,输入排序,这里只有一个输入,所以是第0位。
|
|
|
|
|
|
// 序列化成一串字符
|
|
const txid = txb.build().toHex();
|
|
const network="BTCTEST"
|
|
const result = await fetch(systemConfiguration.constant.btcSendTransaction,{
|
|
method:'post',
|
|
headers:{'Content-Type':'application/json'},
|
|
body:JSON.stringify({txid,network})
|
|
});
|
|
|
|
return txid;
|
|
}
|
|
}
|
|
export default BtcUtil
|