0

Hi I am trying to do a call between my solidity contract and js file.

I have a contract Im providing a portion of:

   struct Player {
    uint wins;
    uint losses;
}

mapping (address => Player) public players;

function gameStart(uint display, bool guess) external payable returns (bool, uint) {
  
    uint Number = numberToGuess();
    bool isWinner = whoWins(Number, display, guess);
    if (isWinner == true) {
        players[msg.sender].wins += 5;
        msg.sender.transfer(msg.value);
        return (true, Number);

    } else if (isWinner == false) {
        players[msg.sender].losses += 5;         
        return (false, Number);
    }
}

This is then contacting to my js file:

    it('Record losses', async () => {
  const initialStats = await gaming.players(player1);
  console.log('Initial Player Stats:', initialStats);

  const gameRound = await gaming.gameStart(20, true, {
    from: player1,
    value: web3.utils.toWei('0.01', 'ether')
  });

  const postStats = await gaming.players(player1);
  console.log('Post Player Stats:', postStats);

  assert.equal(postStats[1].toNumber(), 1, 'The player should lose');
});

  it('Record wins', async() => {
    const gameRound = await gaming.gameStart(20, false, {
      from: player1,
      value: web3.utils.toWei('0.01', 'ether')
    })
    const playerStats = await gaming.players(player1)
    assert.equal(playerStats[0].toNumber(), 1, 'The player should win')
  })
})

The 'Record Wins' is successful, but 'Record losses' is failing, with the 'The player should win' assert. I can see my wins are recorded but losses are not. Wondering what the issue is?

1
  • I think it should be postStats[0].toNumber(). Can you share the GitHub repo url of your codebase, so that I can try debugging on my end? Commented Aug 8 at 18:28

1 Answer 1

1

I think you're trying to access player stats using incorrect indexes.

Solution:

  • players[msg.sender].wins represents the number of wins for the player with the address msg.sender.
  • players[msg.sender].losses represents the number of losses for the player with the address msg.sender.

Corrected code:

assert.equal(postStats.losses.toNumber(), 1, 'The player should lose');
assert.equal(playerStats.wins.toNumber(), 1, 'The player should win');

Note: players[msg.sender] returns a Player struct, not an array. You can access its properties directly using dot notation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.