4

If you are creating a game where your character receives xp after every time they play, how can you prevent people from just calling the "addXP()" function from the contract and giving their player infinite xp?

Thank you for the help!

connorvo
  • 201
  • 1
  • 3

1 Answers1

3

You can make that function internal in solidity, so it can only be called from within the contract.

Ex.

function addXp(uint8 amt) internal {}

This will disallow any external calls.

Alternatively, if you want to call it from outside the contract but only want a specific address to be able to call it, you can do something like:

modifier OnlyOwner { require(msg.sender == owner); _; } 

and the function be like

function addXp(uint8 amt) OnlyOwner { }

Keep in mind that modifier syntax is probably off and you should make sure I was right, but the idea is still there.

Achala Dissanayake
  • 5,819
  • 15
  • 28
  • 38
DaJuukes
  • 31
  • 3
  • But if you are building an HTML5 game, you need to be able to increase XP based on certain actions (say finishing a level). So it needs to be called from outside the contract (from the game) but not from other people. – connorvo Feb 25 '18 at 22:17
  • In that case you can have a game server which the HTML communicates with which interacts with the contract. – Meriadoc Feb 23 '22 at 15:52
  • Designing a trustless application, which is writing finishLevel() that calls internal addXp() without a server/owner, is hard. You probably need to use randomness. If you come up with something that does not rely on a trusted server, then you will have written a game that cannot be copied by web2 methods. It is possible and good luck :) – eth Feb 25 '22 at 13:42