Simple Usage of web3.js

本文深入探讨了使用Web3.js库进行以太坊智能合约交互的方法,包括账户管理、交易发送、余额查询及单位转换等功能。通过实际代码示例,读者将学会如何连接以太坊节点、执行基本的以太坊操作,并理解SHA3哈希、ASCII与十六进制转换等关键概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const Web3=require("web3")
const web3=new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))

console.log(web3.utils.fromWei("12345678901234567890","ether"))
console.log(web3.utils.fromWei("12345678901234567890","Gwei"))
console.log(web3.utils.fromWei("12345678901234567890","Mwei"))
console.log(web3.utils.toWei("1","ether"))
console.log(web3.utils.toWei("1","Gwei"))
console.log(web3.utils.toWei("1","Mwei"))

let h1=web3.utils.sha3("asfdghjf")
console.log(h1)
let h2=web3.utils.sha3(h1,{encoding:"hex"})
console.log(h2)

console.log(web3.utils.fromAscii("xyz"))
console.log(web3.utils.toAscii("0x78797a"))

console.log(web3.utils.toHex("a"))
console.log(web3.utils.toHex(1234))
console.log(web3.utils.toHex({name:"Alice"}))
console.log(web3.utils.toHex('{"name":"Alice"}'))
console.log(web3.utils.toHex(JSON.stringify({name:"Alice"})))
console.log(web3.utils.toHex([1,2,3]))
console.log(web3.utils.toHex('[1,2,3]'))

console.log(web3.utils.isAddress("0x7b226e616d65223a22416c696365227d"))
console.log(web3.utils.isAddress("0x63c682644eb04814735F2d592A9304385F263B76"))
console.log(web3.utils.toBN(1234))
console.log(web3.utils.toDecimal(1234))

const f=async () => {
    let accounts=await web3.eth.getAccounts()
    console.log(accounts)

    let b1=await web3.eth.getBalance(accounts[1])
    console.log(b1)
    let b2=await web3.eth.getBalance(accounts[2])
    console.log(b2)

    await web3.eth.sendTransaction({
        from:accounts[1],
        to:accounts[2],
        value:web3.utils.toWei("1","ether"),
        gas:1000000
    })

    b1=await web3.eth.getBalance(accounts[1])
    console.log(b1)
    b2=await web3.eth.getBalance(accounts[2])
    console.log(b2)

    console.log(web3.eth.defaultAccount)
    web3.eth.defaultAccount=accounts[0]
    console.log(web3.eth.defaultAccount)

    console.log(web3.eth.defaultBlock)

    let b=await web3.eth.getBlock(0)
    console.log(b)

    let r=await web3.eth.estimateGas({
        to:accounts[0]
    })
    console.log(r)

    let coinbase=await web3.eth.getCoinbase()
    console.log(coinbase)
}
f()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值