web3.utils.soliditySha3 - solidity方式计算sha3哈希

优质
小牛编辑
127浏览
2023-12-01

采用和solidity同样的方式计算给定参数的sha3哈希值,也就是说, 在计算哈希之前,需要首先对参数进行ABI编码,并进行字节紧凑化处理。

调用:

web3.utils.soliditySha3(param1 [, param2, ...])

参数:

paramX - Mixed: 任意类型,或是一个具有如下结构的对象:{type: 'uint', value: '123456'} 或 {t: 'bytes', v: '0xfff456'}。 可以自动识别基本数据类型并解析为对应的solidity类型:

  • String 非数值的UTF-8字符串将解释为string
  • String|Number|BN|HEX 正数将解释为uint256
  • String|Number|BN 负数将解释为int256
  • Boolean 解释为bool.
  • String HEX 具有前缀0x的字符串将解释为bytes
  • HEX 16进制表示的数值将解释为uint256.

返回值:

String: 结果哈希值

示例代码:

web3.utils.soliditySha3('234564535', '0xfff23243', true, -10);
// 自动检测:        uint256,      bytes,     bool,   int256
> "0x3e27a893dc40ef8a7f0841d96639de2f58a132be5ae466d40087a2cfa83b7179"


web3.utils.soliditySha3('Hello!%'); // 自动检测: string
> "0x661136a4267dba9ccdf6bfddb7c00e714de936674c4bdb065a531cf1cb15c7fc"


web3.utils.soliditySha3('234'); // 自动检测: uint256
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"

web3.utils.soliditySha3(0xea); // 同上
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"

web3.utils.soliditySha3(new BN('234')); // 同上
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"

web3.utils.soliditySha3({type: 'uint256', value: '234'})); // 同上
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"

web3.utils.soliditySha3({t: 'uint', v: new BN('234')})); // 同上
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"


web3.utils.soliditySha3('0x407D73d8a49eeb85D32Cf465507dd71d507100c1');
> "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b"

web3.utils.soliditySha3({t: 'bytes', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'});
> "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b" // 结果同上


web3.utils.soliditySha3({t: 'address', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'});
> "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b" // 同上,但首先会检查校验和


web3.utils.soliditySha3({t: 'bytes32', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'});
> "0x3c69a194aaf415ba5d6afca734660d0a3d45acdc05d54cd1ca89a8988e7625b4" // 不同的类型得到不同的哈希值


web3.utils.soliditySha3({t: 'string', v: 'Hello!%'}, {t: 'int8', v:-23}, {t: 'address', v: '0x85F43D8a49eeB85d32Cf465507DD71d507100C1d'});
> "0xa13b31627c1ed7aaded5aecec71baf02fe123797fffd45e662eac8e06fbe4955"