【发布时间】:2021-11-10 20:10:03
【问题描述】:
我尝试在我的智能合约中使用种子对 tokenId 进行哈希处理。为简单起见并避免其他错误,我暂时将种子放在一边。我基本上只是想在我的合同上散列一个数字并在我的 javascript 代码上散列相同的数字并接收相同的输出。 代码在 Solidity 上看起来像这样:
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
string memory currentBaseURI = _baseURI();
bytes32 hashedToken = keccak256(abi.encodePacked(tokenId));
return
bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, hashedToken, baseExtension))
: "";
}
这也会导致客户端出现错误invalid codepoint at offset。为了解决这个问题,我尝试使用这些函数将 bit32 转换为字符串
function _bytes32ToString(bytes32 _bytes32)
private
pure
returns (string memory)
{
uint8 i = 0;
bytes memory bytesArray = new bytes(64);
for (i = 0; i < bytesArray.length; i++) {
uint8 _f = uint8(_bytes32[i / 2] & 0x0f);
uint8 _l = uint8(_bytes32[i / 2] >> 4);
bytesArray[i] = _toByte(_f);
i = i + 1;
bytesArray[i] = _toByte(_l);
}
return string(bytesArray);
}
function _toByte(uint8 _uint8) private pure returns (bytes1) {
if (_uint8 < 10) {
return bytes1(_uint8 + 48);
} else {
return bytes1(_uint8 + 87);
}
}
虽然我不确定这是否等效。前端代码如下:
const hashed = web3.utils.soliditySha3(
{ type: "uint256", value: tokenId}
);
为了获得完全相同的输出,我需要进行哪些更改? invalid codepoint at offset 是什么意思?
【问题讨论】:
标签: javascript solidity web3