如何将从我的智能合约返回的地址转换为可读的字符串?

How do I convert the address returned from my smart contract into a readable string?

我有一个简单的获取函数 return 一个地址。在JS前端,我想把这个地址转换成某种可读的函数,也就是字符串。

迁移我的合约后,我使用 web3 将函数用于 return 地址。但是,我在阅读它时遇到了麻烦。我希望避免将其转换为 .sol 文件中的字符串,以避免不必要的 gas 使用。

这是智能合约中的函数

function getBookAccounts() public returns(address){
   return bookAccount;
}

这是试图控制台记录地址的JS文件

async showAccounts() {
    const contract = require('truffle-contract')
    const simpleStorage = contract(SimpleStorageContract)
    simpleStorage.setProvider(this.state.web3.currentProvider)

    var currAccount = await this.simpleStorageInstance.getBookAccounts();

    console.log('The address is ', currAccount)
}

抱歉,我无法打印此地址。我猜我需要将它转换成字符串而不是 solidity 中使用的 UTF8。

确保您的 Solidity 函数被标记为 view。否则 web3.js 的默认行为是发送交易,您可能会取回交易哈希。 (交易没有 return 个值。)

function getBookAccounts() public view returns (address) {

如果将函数更改为视图,web3.js 应该进行 调用 而不是发送交易。这更快,不需要 gas,并且可以 return 一个值。