web3.js安装及一些基本api

本文介绍了如何通过npm安装web3.js库,并概述了一些相关的基本API使用。讲解了web3.js的同步和异步请求,以及提供了一个简单的index.html文件编辑示例。

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

npm安装web3
C:\Users> D:
D:> mkdir web3Proj
D:\> cd web3Proj
D:\web3Proj> npm init //然后一直回车即可
D:\web3Proj> npm install web3@0.19 //这里安装的是0.19版本,最新的1.*.*版本api发生了很大的变化。
一些相关API

web3.js的所有API默认是同步的,如果想要发出异步请求,可以把一个可选的回调函数作为最后的参数传送给大多数函数。所有回调函数都采用错误优先(error-first)回调方式,如示例代码所示。

在这个目录下建立一个名为index.html的文件,并编辑为下面的代码:

<html>
    <script src="./node_modules/web3/dist/web3.min.js"></script>
    <script>
        if(typeof web3 !== 'undefine'){
            web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
        }
        //sync request
        try{
            console.log(web3.eth.getBlock(48));
        }catch(e){
            console.log(e);
        }
        //async request
        //所有回调函数都采用错误优先(error-first)
        web3.eth.getBlock(148,function(error,result){
            if(!error)
                console.log(result);
            else
                console.error(error);    
        });
        //单位转换
        console.log(web3.fromWei("54995135910000000000","ether"));//wei转换为ether
        console.log(web3.toWei("13.14","ether"));//ether转换为wei
        //gas价格
        console.log(web3.eth.gasPrice.toString());
        //地址余额(参数为账户地址-16进制字符串)
        console.log(web3.eth.getBalance("0x339a7c41459c35a3FFF7E7b31B7bF14390c575AC").toString());
        //交易信息(参数为交易号)
        console.log(web3.eth.getTransactionReceipt("0xe427507227889843030fbcc2ce7aabc29af0f57e2f6a841b1cd5994f81f8a968"));
    
        //发送以太币(在geth中需要unlock账户,在Ganache中不需要)
        var txnHash = web3.eth.sendTransaction({
            from:web3.eth.accounts[1],
            to:web3.eth.accounts[0],
            value:web3.toWei("7","ether")
        });
    </script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值