bitcooo
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.
 
 
 
 

81 lines
2.3 KiB

import abi from './EthAbi.js'
const Web3 = require('web3');
var Tx = require('ethereumjs-tx');
let web3;
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"));
}
let eth = {
//获取主币eth余额
getBalance: async function(address, type) {
let balance = await web3.eth.getBalance(address);
console.log("余额:",balance)
return Number(balance) / Math.pow(10, 18);
}
,getTokenBalance: function(address,contract,resultfun){
var myContract = new web3.eth.Contract(abi, contract, {
from: address
});
console.log(myContract);
myContract.methods.decimals().call()
.then(function(decimals) {
myContract.methods.balanceOf(address).call()
.then(function(balance) {
resultfun(Number(balance) / Math.pow(10, decimals));
});
});
}
,transaction: function(fromAddress,toAddress,value,privateKey){
// 先获取当前账号交易的nonce
web3.eth.getTransactionCount(fromAddress, web3.eth.defaultBlock.pending).then(function(nonce){
// 获取交易数据
var txData = {
// nonce每次++,以免覆盖之前pending中的交易
nonce: web3.utils.toHex(nonce++),
// 设置gasLimit和gasPrice
gasLimit: web3.utils.toHex(60000),
gasPrice: web3.utils.toHex(web3.eth.getGasPrice()),
// 要转账的哪个账号
to: toAddress,
// 从哪个账号转
from: fromAddress,
// 0.001 以太币
value: web3.utils.toHex(web3.utils.toWei(value, 'ether')),
data: '0x' + Buffer.from('asd').toString('hex')
}
var tx = new Tx(txData,{'chain':'ropsten'});
// 引入私钥,并转换为16进制
// 用私钥签署交易
console.log(Buffer.from(privateKey, 'hex'))
tx.sign( new Buffer(privateKey, 'hex'));
// 序列化
var serializedTx = tx.serialize().toString('hex');
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
if (!err) {
console.log(hash);
} else {
console.error(err);
}
});
});
}
}
export default eth;