使用web3通过私钥解锁账号

API

  • web3.eth.accounts.privateKeyToAccount(privateKey)

参数

  • privateKey- String:要解锁账号的私钥

返回值

  • Object:一个帐户对象。
web3.eth.accounts.privateKeyToAccount('0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709');
> {
    address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01',
    privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
    signTransaction: function(tx){...},
    sign: function(data){...},
    encrypt: function(password){...}
}
2. 使用web3获取以太币余额

API

  • web3.eth.getBalance(address [, defaultBlock] [, callback])

参数

  • address-String:获取以太币余额的账号地址。
  • defaultBlock-Number|String:(可选)如果传递此参数,则不会使用web3.eth.defaultBlock设置的默认块。
  • callback-Function:(可选)回调函数,将错误对象作为第一个参数返回,结果作为第二个参数返回。

返回

  • Promise:返回String:给定地址的当前余额,以wei为单位。

示例

web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1")
.then(console.log);
> "1000000000000"
3. 将wei为单位的余额数据转换为ether

在代码中的计算都是以最小单位(wei)进行计算,在需要显示余额数据时才将它进行转换为单位ether.

API

  • web3.utils.fromWei(number [, unit])

参数

  • wei: ‘1’
  • kwei: ‘1000’
  • mwei: ‘1000000’
  • gwei: ‘1000000000’
  • micro: ‘1000000000000’
  • finney: ‘1000000000000000’
  • ether: ‘1000000000000000000’
  • kether: ‘1000000000000000000000’
  • mether: ‘1000000000000000000000000’
  • gether: ‘1000000000000000000000000000’
  • tether: ‘1000000000000000000000000000000’
  • unit- String(可选):默认为"ether"。

返回值

  • String|BN:如果传入一个数字或字符串,则返回一个数字字符串,否则返回一个BN.js实例。

示例

web3.utils.fromWei('1', 'ether');
> "0.000000000000000001"

web3.utils.fromWei('1', 'finney');
> "0.000000000000001"

demo

let { success, fail } = require("../utils/myUtils")
let web3 = require("../utils/myUtils").getweb3()

//获取以太币余额
async function getAccountBalance(address) {
    let balance = await web3.eth.getBalance(address)
    return web3.utils.fromWei(balance, "ether")
}

//配置返回给前端的数据,包含以太币的数据,还会有Token的数据
async function setResponseData(account) {
    //获取账户余额
    let balance = await getAccountBalance(account.address)
    console.log(balance)

    let resData = success({
        balance: balance,
        address: account.address,
        privatekey: account.privateKey
    })

    //返回相应数据给前端
    return resData
}

module.exports = {
    unlockAccountWithPrivate: async (ctx) => {
        //1.获取私钥
        let privatekey = ctx.request.body.privatekey
        console.log(privatekey)
        //2.通过私钥解锁账户
        let account = web3.eth.accounts.privateKeyToAccount(privatekey)
        console.log(account)
        //3.将账户信息返回给前端
        ctx.body = await setResponseData(account)
    },
}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐