前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >web3.js:utils包

web3.js:utils包

作者头像
孟斯特
发布2024-05-17 18:45:09
1580
发布2024-05-17 18:45:09
举报
文章被收录于专栏:code人生code人生

原文在这里[1]

介绍

在这个指南中,你将学习到web3 utils包的不同函数,它包含了如何以不同格式生成随机字节,如何在Hex值和数字之间进行转换,哈希函数,地址,打包填充的方法,最后你将看到如何比较区块号。

安装

只安装web3工具包:

代码语言:javascript
复制
$ npm i web3-utils

或者你也可以安装web3库,然后访问web3.utils

代码语言:javascript
复制
$ npm i web3

导入

有三种不同的方式来导入utils包。

导入完整的web库

代码语言:javascript
复制
// import web3 module
import { Web3 } from "web3";

// no need to initialize a provider
Web3.utils.toHex("web3");
//=> 0x77656233

// initializing  a provider
const web3 = new Web3("https:// eth.llamarpc.com");

// access the utils package
web3.utils.toHex("web3");
//=> 0x77656233

导入utils模块

代码语言:javascript
复制
// import utils module
import { utils } from "web3"; 

// access the utils package
utils.toWei("1", "ether")

导入指定方法

代码语言:javascript
复制
// import toWei and toHex functions
import { toWei, toHex } from"web3-utils";

// usage
toWei("1", "ether")
toHex("")

方法示例

随机Hex和Bytes

代码语言:javascript
复制
// Random bytes in hex format and array format

console.log(web3.utils.randomBytes(32));
/* => array format
Uint8Array(32) [
  251,  70, 124,  65, 203, 180,  92, 234,
  210, 236,  72, 154,  83, 219, 171, 223,
  212, 136, 117, 140,  67, 117,  86,  81,
  234, 245, 148, 186, 175,  83,  98,  78
]
*/

console.log(web3.utils.randomHex(32));
/* => hex string format
0x594386dc9b2e150979416f9b2a093e01f84a37c4f8db5fc1b0d9b1dc83a12c1f
*/

INFO 如果你不给出任何参数,那么这两个函数的默认值都将为32。

转换 - 以太坊面额

我们有两个不同的函数来进行以太坊面额之间的转换。

代码语言:javascript
复制
console.log(web3.utils.fromWei("1", "ether")); 
// 0.000000000000000001

console.log(web3.utils.toWei("1", "ether")); 
// 1_000_000_000_000_000_000

转换Hex变量

代码语言:javascript
复制
// most versatile one
console.log(web3.utils.toHex(10));
// 0xa

console.log(web3.utils.toHex(true));
// 0x01

console.log(web3.utils.numberToHex(10));
// 0xa

console.log(web3.utils.fromDecimal(10));
// 0xa

const arr = new Uint8Array([1, 2, 3, 4]);

console.log(web3.utils.toHex(arr));
// 0x7b2230223a312c2231223a322c2232223a332c2233223a347d

console.log(web3.utils.bytesToHex(arr));
// 0x01020304

转换UTF和ASCII

代码语言:javascript
复制
console.log(web3.utils.utf8ToHex("😊"));
// 0xf09f988a

console.log(web3.utils.fromUtf8("😊"));
// 0xf09f988a

console.log(web3.utils.asciiToHex("😊"));
// 0xd83dde0a

console.log(web3.utils.toUtf8("0xf09f988a"));
// 😊

console.log(web3.utils.hexToUtf8("0xf09f988a"));
// 😊

console.log(web3.utils.hexToString("0xf09f988a"));
// 😊

// emojis are not ASCII character, that's why it won't work
console.log(web3.utils.toAscii("0x4869"));
// Hi

console.log(web3.utils.hexToAscii("0x4869"));
// Hi

转换 - 数字和Bigint

代码语言:javascript
复制
console.log(web3.utils.toNumber("0xa"));
// 10 (number)

console.log(web3.utils.hexToNumber("0xa"));
// 10 (number)

console.log(web3.utils.toDecimal("0xa"));
// 10 (number)

console.log(web3.utils.hexToNumberString("0xa"));
// 10 (string)

console.log(web3.utils.toBigInt("0xa")); 
// 10n (bigint)

哈希函数

代码语言:javascript
复制
// both will return undefined if an empty string is passed as an argument
console.log(web3.utils.sha3("hello web3"));
// 0x6c171485a0138b7b0a49d72b570e1d9c589d42a79ae57329d90671d1ac702d74

console.log(web3.utils.soliditySha3({ type: "string", value: "hello web3" }));
// 0x6c171485a0138b7b0a49d72b570e1d9c589d42a79ae57329d90671d1ac702d74

地址

代码语言:javascript
复制
// isAddress() is deprecated so we can use toCheckSumAddress()
// to see if the hex string we are passing is a correct ethereum address

// passing an address with all characters lowercase
console.log(web3.utils.toChecksumAddress("0xa3286628134bad128faeef82f44e99aa64085c94"));
// 0xA3286628134baD128faeef82F44e99AA64085C94

// passing an wrong address
console.log(web3.utils.toChecksumAddress("0xa3286628134bad128faeef82f44e99aa64085c9"));
// InvalidAddressError: Invalid value given "0xa286628134bad128faeef82f44e99aa64085c94". Error: invalid ethereum address.

打包和填充

代码语言:javascript
复制
// same as abi.encodePacked() in solidity (must be strings)
// converts everything to hex and packs everything without padding
console.log(web3.utils.encodePacked("1", "1", "1"));
// 0x313131


// it will convert the number `10` to hex('a') and add 0s until it's 32 characters long
// the third argument will be the one that will fill/pad the whole hex string, in this case is '0'
console.log(web3.utils.padRight(10, 32, 0));
// 0xa0000000000000000000000000000000

console.log(web3.utils.rightPad(10, 32, 0));
// 0xa0000000000000000000000000000000

console.log(web3.utils.padLeft(10, 32, 0));
// 0x0000000000000000000000000000000a

console.log(web3.utils.leftPad(10, 32, 0));
// 0x0000000000000000000000000000000a

比较区块号

代码语言:javascript
复制
// accepts numbers and formats as well
console.log(web3.utils.compareBlockNumbers("pending", "latest"));
// 1

console.log(web3.utils.compareBlockNumbers("latest", "pending"));
// -1

console.log(web3.utils.compareBlockNumbers("latest", "latest"));
// 0

console.log(web3.utils.compareBlockNumbers(2, 2));
// 0

声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)[2]进行许可,使用时请注明出处。 Author: mengbin[3] blog: mengbin[4] Github: mengbin92[5] cnblogs: 恋水无意[6] 腾讯云开发者社区:孟斯特[7]

References

[1] 这里: https://docs.web3js.org/guides/web3_utils_module/mastering_web3-utils [2] 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0): https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh [3] mengbin: mengbin1992@outlook.com [4] mengbin: https://mengbin.top [5] mengbin92: https://mengbin92.github.io/ [6] 恋水无意: https://www.cnblogs.com/lianshuiwuyi/ [7] 孟斯特: https://cloud.tencent.com/developer/user/6649301

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-05-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 孟斯特 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍
  • 安装
  • 导入
    • 导入完整的web库
      • 导入utils模块
        • 导入指定方法
        • 方法示例
          • 随机Hex和Bytes
            • 转换 - 以太坊面额
              • 转换Hex变量
                • 转换UTF和ASCII
                  • 转换 - 数字和Bigint
                    • 哈希函数
                      • 地址
                        • 打包和填充
                          • 比较区块号
                            • References
                            相关产品与服务
                            云开发 CloudBase
                            云开发(Tencent CloudBase,TCB)是腾讯云提供的云原生一体化开发环境和工具平台,为200万+企业和开发者提供高可用、自动弹性扩缩的后端云服务,可用于云端一体化开发多种端应用(小程序、公众号、Web 应用等),避免了应用开发过程中繁琐的服务器搭建及运维,开发者可以专注于业务逻辑的实现,开发门槛更低,效率更高。
                            领券
                            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档