查询余额是否充足
app.get('/health', async function(request, response) {
let balanceInWei
let balanceInEth
const address = config.Ethereum[config.environment].account
try {
balanceInWei = await web3.eth.getBalance(address)
balanceInEth = await web3.utils.fromWei(balanceInWei, "ether")
} catch (error) {
return generateErrorResponse(response, error)
}
const resp = {
address,
balanceInWei: balanceInWei,
balanceInEth: Math.round(balanceInEth)
}
response.send(resp)
});
发送交易
async function sendPOAToRecipient(web3, receiver, response, isDebug) {
//私钥
let senderPrivateKey = config.Ethereum[config.environment].privateKey
//私钥转为16进制
const privateKeyHex = Buffer.from(senderPrivateKey, 'hex')
if (!web3.utils.isAddress(receiver)) {
return generateErrorResponse(response, {message: messages.INVALID_ADDRESS})
}
const gasPrice = web3.utils.toWei('1', 'gwei')
const gasPriceHex = web3.utils.toHex(gasPrice)
const gasLimitHex = web3.utils.toHex(config.Ethereum.gasLimit)
const nonce = await web3.eth.getTransactionCount(config.Ethereum[config.environment].account)
const nonceHex = web3.utils.toHex(nonce)
const BN = web3.utils.BN//BigInt??
//最后结果是 0.05 ether
const ethToSend = web3.utils.toWei(new BN(config.Ethereum.milliEtherToTransfer), "milliether")
const rawTx = {
nonce: nonceHex,
gasPrice: gasPriceHex,
gasLimit: gasLimitHex,
to: receiver,
value: ethToSend,
data: '0x00'
}
//"ethereumjs-tx": "2.1.2",
const tx = new EthereumTx(rawTx)
tx.sign(privateKeyHex)
const serializedTx = tx.serialize()
let txHash
web3.eth.sendSignedTransaction("0x" + serializedTx.toString('hex'))
.on('transactionHash', (_txHash) => {
txHash = _txHash
})
.on('receipt', (receipt) => {
debug(isDebug, receipt)
if (receipt.status == '0x1') {
return sendRawTransactionResponse(txHash, response)
} else {
const error = {
message: messages.TX_HAS_BEEN_MINED_WITH_FALSE_STATUS,
}
return generateErrorResponse(response, error);
}
})
.on('error', (error) => {
return generateErrorResponse(response, error)
});
}
处理交易的返回值
function sendRawTransactionResponse(txHash, response) {
const successResponse = {
code: 200,
title: 'Success',
message: messages.TX_HAS_BEEN_MINED,
txHash: txHash
}
response.send({
success: successResponse
})
}
我得到的成功结果是这样的:
{
"success":{
"code":200,
"title":"Success",
"message":"Tx has been mined",
"txHash":"0xcd7feead6851dd37ae45672b8fca1fef9d629eba3f65f33a3a044d7190126aa0"
}
}
有错误时的处理方式
function generateErrorResponse (response, err) {
const out = {
error: {
code: 500 || err.code,
title: 'Error' || err.title,
message: 'Internal server error' || err.message
}
};
console.log(err)
response.send(out)
}
module.exports = { generateErrorResponse }