我该如何解决这个合约问题?只有 2 个功能

how can i solve this contract problem? only 2 functions

提问人:manman 提问时间:2/2/2023 更新时间:2/2/2023 访问量:38

问:

我需要一个接收函数的合约,以将分数添加到关联钱包中已经存在的分数(如果存在)或以其他方式创建一个新分数(分数和地址),之后我需要一个函数来检索所有地址及其分数。如果可能的话,一个已经向你发送排名的函数,否则只有所有带有分数的地址都可以

contract ScoreTracker {
    mapping(address => uint) public scores;

    function addScore(address _wallet, uint _score) public {
        if (scores[_wallet] == 0) {
            scores[_wallet] = _score;
        } else {
            scores[_wallet] += _score;
        }
    }

    function getScore(address _wallet) public view returns (uint) {
        return scores[_wallet];
    }
}   

function getAllScores() public view returns (address[] memory, uint256[] memory) {
    address[] memory addresses = new address[](scores.length);
    uint256[] memory scoresList = new uint256[](scores.length);
    uint256 counter = 0;
    for (address; scores) {
        addresses[counter] = a;
        scoresList[counter] = scores[a];
        counter++;
    }
    return (addresses, scoresList);
}

我已经尽力了。但不知道我该怎么做

编译器 语法错误 solidity 智能合约 cryptojs

评论


答:

0赞 johnny 5 2/2/2023 #1

你需要一些东西。

Solidity 无法枚举映射,因此您需要创建钱包到索引的映射。您还需要将其递增 1,以便判断是否已添加钱包。

mapping(address => uint) public walletIndexIncrementedMap;
WalletScores[] scores;

struct WalletScores {
    adddress wallet;
    uint256 score;
}


function getOrAddWalletScore(address _wallet, uint256 score) public {
    uint256 incrementedIndex = walletIndexIncrementedMap[_wallet];
    if(0 == incrementedIndex) {
        WalletScore storage walletScore = scores.push();
        incrementedIndex = scores.length;
        walletIndexIncrementedMap[_wallet] = incrementedIndex;
        walletScore.wallet = _wallet;
        walletScore.score = score;
        return;
    }
    WalletScore storage walletScore = scores[incrementedIndex - 1];
    walletScore.score += score;
}

function getAllScores() public returns (WalletScores[] memory walletScores) 
{
   return scores;
}