【问题标题】:Solidity: How to type cast string memory to address and uint type?Solidity:如何将字符串内存类型转换为地址和 uint 类型?
【发布时间】:2022-04-26 16:01:21
【问题描述】:

尝试将转换字符串内存键入地址和 uint 类型时出现以下错误。

TypeError: Explicit type conversion not allowed from "string memory" to "address".

TypeError: Explicit type conversion not allowed from "string memory" to "uint256".

下面是可靠性代码。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Test {
    struct allowedTokenDetails {
        address admin;
        uint256 price;
        uint256 balance;
        address rewardToken;
        uint256 timestampAdded;
        uint256 timestampLastUpdated;
    }
    mapping(address => allowedTokenDetails) public allowedTokensData;
    
    function setAllowedTokensData(address _token, string[][] memory _data) public {
        for (uint256 dataIndex = 0; dataIndex < _data.length; dataIndex++) {
            string memory dataKey = _data[dataIndex][0];
            string memory dataValue = _data[dataIndex][1];
            if (keccak256(abi.encodePacked(dataKey)) == keccak256(abi.encodePacked("admin"))) allowedTokensData[_token].admin = address(dataValue);
            if (keccak256(abi.encodePacked(dataKey)) == keccak256(abi.encodePacked("price"))) allowedTokensData[_token].price = uint256(dataValue);
            if (keccak256(abi.encodePacked(dataKey)) == keccak256(abi.encodePacked("balance"))) allowedTokensData[_token].balance = uint256(dataValue);
            if (keccak256(abi.encodePacked(dataKey)) == keccak256(abi.encodePacked("rewardToken"))) allowedTokensData[_token].rewardToken = address(dataValue);
            allowedTokensData[_token].timestampLastUpdated = block.timestamp;
        }
   }
}

有针对这个的解决方法吗?

【问题讨论】:

    标签: ethereum solidity smartcontracts evm


    【解决方案1】:

    无需使用一组 if 语句验证输入并根据函数逻辑对每个值进行类型转换,您已经可以在准备好的结构中以预期类型传递输入数据:

    struct inputData {
        address admin;
        uint256 price;
        uint256 balance;
        address rewardToken;
    }
    
    function setAllowedTokensData(address _token, inputData[] memory _data) public {
        for (uint256 dataIndex = 0; dataIndex < _data.length; dataIndex++) {
            allowedTokensData[_token] = allowedTokenDetails(
                _data[dataIndex].admin,
                _data[dataIndex].price,
                _data[dataIndex].balance,
                _data[dataIndex].rewardToken,
                0, // `timestampAdded` not set in your snippet
                block.timestamp
            );
        }
    }
    

    【讨论】:

    • 我知道这种方法,但我不想初始化结构中的所有变量,只初始化选定的变量。
    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 2019-12-02
    • 2019-09-10
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2022-08-18
    • 2014-03-30
    相关资源
    最近更新 更多