-
Notifications
You must be signed in to change notification settings - Fork 3
/
transfer_BCH.js
87 lines (73 loc) · 2.91 KB
/
transfer_BCH.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const btcBasic = require('./btcBasic');
const BchJsLib = require('bitcore-lib-cash')
const BigNumber = require('bignumber.js');
const coinSelect = require('coinselect')
const bitcoin = require('bitcoinjs-lib')
const _ = require('lodash')
class bchBasic extends btcBasic{
network= () => {
return BchJsLib.Networks.testnet
}
genAddressByRandom = () =>{
const pri = new BchJsLib.PrivateKey(BchJsLib.Networks.testnet)
const wif = pri.toWIF()
const address = pri.toAddress()
console.log('Private Key:', pri.toString());
console.log('wif:', wif);
console.log('Address:', address.toString(BchJsLib.Networks.testnet));
}
async sendBCH(address,amount){
const feePrice = await this.getfeeRate()
const feeRate = new BigNumber(feePrice).times(1e8).dividedBy(100).integerValue(BigNumber.ROUND_DOWN).toNumber()
const value = new BigNumber(amount).times(1e8).toNumber()
const targets = [{
address,
value
}]
//const froms
const utxos = await this.getUtxos()
const {inputs, outputs, fee} = coinSelect(utxos,targets,feeRate)
const from = []
const to = []
if (inputs && outputs){
//build tx
const filledOutputs = outputs.map(output => {
if (!output.address) {
output.address = inputs[0].address; // 在这里设置默认值
}
return output;
})
_.map(inputs, input => {
const { address, txId, vout: outputIndex, satoshis, script} = input
from.push({ address, txId, outputIndex, satoshis, script })
})
_.map(outputs, output => {
const { address, value:satoshis } = output
to.push({ address, satoshis })
})
const network = this.network()
const tx = new BchJsLib.Transaction().from(from).to(to)
//sign tx
const froms = this.config.KEYPAIR
let signer,priKey
for (let i =0;i<inputs.length;i++){
priKey = _.find(froms, function(o) { return o.ADDRESS == inputs[i].address})
signer = BchJsLib.PrivateKey.fromWIF(priKey.PRIKEY, network)
tx.sign(signer,i)
}
//send tx
const rawtx = tx.toString()
const hash = await this.sendTx(rawtx)
console.log(`Transfer ${amount} BCH to ${address}. Transaction Hash: ${hash.txid}`);
} else {
console.log(inputs, outputs, fee)
throw new Error('not enough utxos!!!')
}
}
}
const bch = new bchBasic('BCH')
//bch.genAddressByRandom()
// 从命令行参数中获取充值地址和转账金额
const address = process.argv[2];
const transferAmount = parseFloat(process.argv[3]);
bch.sendBCH(address, transferAmount)