0

When I use Ganache it runs with no problem and MetaMask too. When I run my contract in my private Ethereum network (Geth). When I use a function from my contract the MetaMask gives me this error (title).

pragma solidity ^0.5.0;

contract Creation {

    int basiclife = 50;

    struct hero {
        string name;
        int life;
        int lvl;
        int xp;
        int attack;
        int winCount;
        int trophies;
        int lossCount;
    }

    hero[] public heroes; 

    struct enemy {  
        string name;
        int life;
        int lvl;
        int xp;
        int attack;
    }

    enemy[] public enemies;
    mapping (uint => address) public herotoowner;
    mapping (address => uint) public heroCount;
    mapping (uint => address) public monstertoowner;
    uint public monsterCount; 

    function createhero (string memory _name) public {
        require(heroCount[msg.sender] == 0);
        uint id= heroes.push(hero(_name, basiclife, 1, 0, 20, 0, 0, 0))-1;
        herotoowner[id] = msg.sender;
        heroCount[msg.sender]++;
    }

    function enemyRage (int _herolvl) public {
        uint id = enemies.push(enemy("Rage", 20*_herolvl, _herolvl, 7*_herolvl, 5*_herolvl)) - 1;
        monstertoowner[id] = msg.sender;
        monsterCount++;
    }

    function enemyDerpina (int _herolvl) public {
        uint id = enemies.push(enemy("Derpina", 40*_herolvl, _herolvl, 14*_herolvl, 10*_herolvl)) - 1; 
        monstertoowner[id] = msg.sender;
        monsterCount++;
    }

    function getHerosByOwner (address owner) external view returns (uint) {
        uint result = 999999;
        for (uint i = 0; i < heroes.length; i++) {
            if (herotoowner[i] == owner) {
                result = i;
                break;
            }
        }
        return result;
    }

    function getmonstersByOwner (address owner) external view returns (uint) {
        uint result = 0;
        for (uint i = enemies.length; i > 0; i--) {
            if (monstertoowner[i] == owner) {
                result = i;
                break;
            }
        }
        return result;
    }

    uint nonce=0;

    function randNum (int _num) private returns (int) {  //sinartisi gia tixaies times
        int randomnumber = int(keccak256(abi.encodePacked(now, msg.sender, nonce))) % _num;
        if (randomnumber <= 0) {
            randomnumber = (-1)*randomnumber;
        }
        nonce++;
        return randomnumber;
    }

    function attack_hero (uint _heroid, uint _monsterid, int _num) external returns (string memory, int, int, int, int ) {
        hero storage myhero = heroes[_heroid];
        enemy storage monster = enemies[_monsterid];
        int attackofhero = 0;
        if(_num == 0) { 
            attackofhero = randNum(myhero.attack);
        }

        monster.life = monster.life - attackofhero;
        int attackofmonster = randNum(monster.attack);
        myhero.life = myhero.life - attackofmonster;

        if (monster.life <= 0 && myhero.life > 0) {
            myhero.winCount++;
            myhero.xp += monster.xp;
            if (randNum(100) > 50 ){ 
                myhero.trophies++;
            }
            return("win", myhero.lvl, myhero.xp, myhero.life, myhero.trophies);
        }

        if (myhero.xp >= 10+2*myhero.lvl){ 
            myhero.lvl++;
            myhero.xp = 0; //reset you xp
            myhero.life = basiclife*myhero.lvl;  
            myhero.attack = myhero.attack*myhero.lvl;
        }

        if (myhero.life <= 0 ) { //ita 
            myhero.lossCount++; 
            return("dead", myhero.lossCount, myhero.life, myhero.lvl, myhero.trophies);
        }
        return("attack", myhero.life, attackofhero, monster.life, attackofmonster);
    }

    function resurrection (uint _heroid) public { 
        hero storage myhero = heroes[_heroid];
        myhero.life = basiclife*myhero.lvl;
    }
}

I add my app.ss code too

App = {
    web3Provider: null,
    contracts: {},
    account: '0x0',
    heros: [],
    enemies: [],
    heroId: null,
    monsterId: null,
    rand: null,
    rand2: 0,
    init: function() {

        return App.initWeb3();

    },

    initWeb3: function() {
        // TODO: refactor conditional
        if (typeof web3 !== 'undefined') {
            // If a web3 instance is already provided by Meta Mask.
            App.web3Provider = web3.currentProvider;
            web3 = new Web3(web3.currentProvider);
        } else {
            // Specify default instance if no web3 instance provided
            App.web3Provider = new Web3.providers.HttpProvider('localhost:8545');
            web3 = new Web3(App.web3Provider);
        }
        return App.initContract();
    },

    initContract: function() {
        $.getJSON("Creation.json", function(Creation) {
            // Instantiate a new truffle contract from the artifact
            App.contracts.Creation = TruffleContract(Creation);
            // Connect provider to interact with contract
            App.contracts.Creation.setProvider(App.web3Provider);

            return App.render();
        });
    },
    monsterRender: function() {
        var enemyspot = $("#enemyspot");
        enemyspot.empty();
        if (App.rand == 1) {
            App.contracts.Creation.deployed().then(function(instance) {
                creationInstance = instance;
                return creationInstance.getmonstersByOwner(App.account);
            }).then(function(getmonstersByOwner) {
                App.monsterId = getmonstersByOwner;
                console.log(App.monsterId)
                return creationInstance.enemies(getmonstersByOwner)
            }).then(function(enemies) {
                console.log("hey 1" + enemies)
                App.enemies[App.monsterId] = enemies;
                var name = enemies[0];
                var life = enemies[1];
                var lvl = enemies[2];
                var xp = enemies[3];
                var atk = enemies[4];

                var enemyTemplate = "<tr ><td colspan='2'><img src = './images/rage.jpg' width ='200px'></td></tr><tr><td> Name</td><td>: " + name + "</td></tr><tr><td>Health Points</td><td>: " + life + " HP</td></tr><tr><td>Level</td><td>: " + lvl + "</td></tr><tr><td>Experiance</td><td>: " + xp + "</td></tr><tr><td>Attack</td><td>: " + atk;
                enemyspot.append(enemyTemplate);

            }).then(function() {
                if (App.enemies[App.monsterId][1] <= 0) {
                    alert("You have won!!!");

                    enemyspot.empty();
                }
            });
        } else {
            App.contracts.Creation.deployed().then(function(instance) {
                creationInstance = instance;

                return creationInstance.getmonstersByOwner(App.account);
            }).then(function(getmonstersByOwner) {
                App.monsterId = getmonstersByOwner;
                return creationInstance.enemies(getmonstersByOwner)
            }).then(function(enemies) {
                console.log("hey 1" + enemies)

                App.enemies[App.monsterId] = enemies;
                var name = enemies[0];
                var life = enemies[1];
                var lvl = enemies[2];
                var xp = enemies[3];
                var atk = enemies[4];

                var enemyTemplate = "<tr ><td colspan='2'><img src = './images/derpina.jpg' width ='200px'></td></tr><tr><td> Name</td><td>: " + name + "</td></tr><tr><td>Health Points</td><td>: " + life + " HP</td></tr><tr><td>Level</td><td>: " + lvl + "</td></tr><tr><td>Experiance</td><td>: " + xp + "</td></tr><tr><td>Attack</td><td>: " + atk;
                enemyspot.append(enemyTemplate);
            }).then(function() {
                if (App.enemies[App.monsterId][1] <= 0) {
                    alert("You have won!!!");
                    isCreated =0;
                    var enemyspot = $("#enemyspot");
                    enemyspot.empty();
                }
            });
        }
    },


    render: function() {

        // Load account data
        web3.eth.getCoinbase(function(err, account) {
            if (err === null) {
                App.account = account;
                $("#accountAddress").html("Your Account: " + account);
            }
        });
        var herospot = $("#herospot");
        herospot.empty();
        // Load contract data
        App.contracts.Creation.deployed().then(function(instance) {
            creationInstance = instance;
            return creationInstance.getHerosByOwner(App.account);
        }).then(function(getHerosByOwner) {
            console.log("hey äóáä" + getHerosByOwner)
            App.heroId = getHerosByOwner;
            console.log(App.heroId)
            return creationInstance.heroes(getHerosByOwner);
        }).then(function(heroes) {
            $("#charform").hide();
            $("#story").hide();
            console.log(account)
            App.heroes = heroes;

            var name = heroes[0];
            var life = heroes[1];
            var lvl = heroes[2];
            var xp = heroes[3];
            var atk = heroes[4];
            var winCount = heroes[5];
            var trophies = heroes[6];
            var lossCount = heroes[7];
            var heroTemplate = "<tr ><td colspan='2'><img src = './images/happyfa.jpg' width ='200px'></td></tr><tr><td> Name</td><td>: " +
                name + "</td></tr><tr><td>Health Points</td><td>: " + life + " HP</td></tr><tr><td>Level</td><td>: " +
                lvl + "</td></tr><tr><td>Experiance</td><td>: " + xp + "</td></tr><tr><td>Attack</td><td>: " + atk + "</td></tr><tr><td>Win count</td><td>: " + winCount +
                "</td></tr><tr><td>trophies</td><td>: " + trophies + "</td></tr><tr><td>lossCount</td><td>: " + lossCount;
            herospot.append(heroTemplate);
        }).then(function() {
            console.log("hello"+App.heroes[1])
            if (App.heroes[1] <= 0) {
                console.log("sdasd" + App.heroes[1])
                alert("You have Lost!!!");
                var enemyspot = $("#enemyspot");
                enemyspot.empty();
                App.resurrection();
                isCreated =0;
            }
        }).then(App.loadMonsters());
    },
    fight: function() {
        App.contracts.Creation.deployed().then(function(instance){
            creationInstance = instance;
            return creationInstance.attack_hero(App.heroId, App.monsterId, App.rand2);
        }).then(function(attack_hero){
            App.monsterRender();
    App.render();
     App.rand2 = 0;
        })
    },
    resurrection:function() {

             App.contracts.Creation.deployed().then(function(instance){
            creationInstance = instance;
                return creationInstance.resurrection(App.heroId);
            }).then(function(resurrection){
                App.render();
            });
    },
/*
    heroSlap: function() {
        App.contracts.Creation.deployed().then(function(instance) {
            creationInstance = instance;
            return creationInstance.attack_hero(App.heroId, App.monsterId);
        }).then(function(attack_hero) {
            console.log(attack_hero)
        }).then(function(){
             console.log("h zwh tou teratos einai" +App.enemies[App.monsterId][1])
             if (App.enemies[App.monsterId][1] > 0) {
           App.monsterSlap();

        }  else if(App.enemies[App.monsterId][1] <= 0){
            isCreated =0;
            console.log("einai "+ isCreated)
        }
         App.monsterRender();
    });
    },
    monsterSlap: function() {
        App.contracts.Creation.deployed().then(function(instance) {
            creationInstance = instance;
            return creationInstance.attack_monster(App.heroId, App.monsterId);
        }).then(function(attack_monster) {
            App.render();


        })
    },
*/

    spawn: function() {
        console.log(App.heroes)
        console.log(App.account)
        var rand = Math.round(Math.random() * 1);
        App.rand = rand;
        var enemyspot = $("#enemyspot");
        enemyspot.empty();
        if (rand == 1) {
            App.contracts.Creation.deployed().then(function(instance) {
                creationInstance = instance;
                return creationInstance.enemyRage(App.heroes[2]);
            }).then(function(enemyRage) {
                console.log("hey1 " + enemyRage)
                return creationInstance.getmonstersByOwner(App.account);
            }).then(function(getmonstersByOwner) {
                App.monsterId = getmonstersByOwner;

                return creationInstance.enemies(getmonstersByOwner)
            }).then(function(enemies) {
                console.log("hey 1" + enemies)
                App.enemies.push(enemies);
                App.enemies[App.monsterId] = enemies;
                var name = enemies[0];
                var life = enemies[1];
                var lvl = enemies[2];
                var xp = enemies[3];
                var atk = enemies[4];

                var enemyTemplate = "<tr ><td colspan='2'><img src = './images/rage.jpg' width ='200px'></td></tr><tr><td> Name</td><td>: " + name + "</td></tr><tr><td>Health Points</td><td>: " + life + " HP</td></tr><tr><td>Level</td><td>: " + lvl + "</td></tr><tr><td>Experiance</td><td>: " + xp + "</td></tr><tr><td>Attack</td><td>: " + atk;
                enemyspot.append(enemyTemplate);
                isCreated = 1;
            });
        } else {
            App.contracts.Creation.deployed().then(function(instance) {
                creationInstance = instance;
                return creationInstance.enemyDerpina(App.heroes[2]);
            }).then(function(enemyDerpina) {
                console.log("hey1 " + enemyDerpina)
                return creationInstance.getmonstersByOwner(App.account);
            }).then(function(getmonstersByOwner) {
                App.monsterId = getmonstersByOwner;
                return creationInstance.enemies(getmonstersByOwner)
            }).then(function(enemies) {
                console.log("hey 1" + enemies)
                App.enemies.push(enemies);
                App.enemies[App.monsterId] = enemies;
                var name = enemies[0];
                var life = enemies[1];
                var lvl = enemies[2];
                var xp = enemies[3];
                var atk = enemies[4];

                var enemyTemplate = "<tr ><td colspan='2'><img src = './images/derpina.jpg' width ='200px'></td></tr><tr><td> Name</td><td>: " + name + "</td></tr><tr><td>Health Points</td><td>: " + life + " HP</td></tr><tr><td>Level</td><td>: " + lvl + "</td></tr><tr><td>Experiance</td><td>: " + xp + "</td></tr><tr><td>Attack</td><td>: " + atk;
                enemyspot.append(enemyTemplate);
                isCreated = 1;
            });
        }


    },

    validate: function() {
        var name = document.getElementById("name").value;

        App.contracts.Creation.deployed().then(function(instance) {
            alert("Your name is " + name);
            return instance.createhero(name, {
                from: App.account
            });
        }).then(function(result) {

            App.render();
        });
    },
    loadMonsters: function() {
        App.contracts.Creation.deployed().then(function(instance) {
            creationInstance = instance;
            return creationInstance.monsterCount();
        }).then(function(monsterCount) {
            console.log("äóöä" + monsterCount);
            for (var i = 0; i < monsterCount; i++) {

                creationInstance.enemies(i).then(function(enemies) {
                    App.enemies.push(enemies);

                });
            }
        })
    },

};
var enemyspot = $("#enemyspot");
let startFlag;
var account;
var accountInterval = setInterval(function() {
    // Check if account has changed
    if (web3.eth.accounts[0] !== account) {
        account = web3.eth.accounts[0];
        // Call some function to update the UI with the new account
        App.render();
        location.reload();
    }
}, 100);

function startAdventure() {
    $("#adventure").hide();
    var instructions = $("#advWrap");
    var heroT = "<p id='instructions'>Press W to walk <br> Press A to attack <br> Press R to run<p>";
    instructions.append(heroT);
   document.getElementById("#advWrap");
    startFlag = 1;
};
let isCreated;

console.log('fasdfas' + App.monsterId)
document.onkeyup = function(e) {
    if (e.which == 87 /*&& startFlag == 1*/ ) {
        console.log("iscreated is" + isCreated)
        let randomNum = Math.round(Math.random() * 3);
        console.log(randomNum)
        if (randomNum == 1) {

            if (isCreated == 0 || isCreated == null || isCreated == undefined  && App.heroes[1]>0) {
                alert("You have been ambushed!!!");
                App.spawn()
                isCreated =1;


            } else if (App.enemies[App.monsterId][1] <= 0  && App.heroes[1]>0) {

                App.spawn();
                isCreated =1;
            } else if (isCreated == 1) {
                alert("You must kill this monster first")
            }
        } else if(randomNum !== 1 && isCreated !==1) {
            alert("You didn't encounter any monster");
        }else if (isCreated == 1) {
                alert("You must kill this monster first")
            }
    }
    if (e.which == 65 && isCreated == 1 && App.enemies[App.monsterId][1] > 0 && App.heroes[1]>0) {
        console.log('123       ' + App.enemies[App.monsterId][1])

        App.fight()
    }
    if (e.which == 82 && isCreated == 1) {
         App.rand2 =Math.round(Math.random() * 1);
        if (App.rand2 == 0) {
            isCreated = 0;
            enemyspot.empty();
            App.rand2 = 1;
        } else if (App.rand2 ==1 ) {
            App.fight();

        }
    }
};

$(function() {
    $(window).load(function() {

        App.init();
    });
});

genesis file ...

{
"config":{
"chainId":15,
"homesteadBlock":0,
"eip155Block":0,
"eip158Block":0
},
"nonce":"0x0000000000000042",
"mixhash":"0x000000000000000000000000000000000000000000000000000000000
0000000",
"difficulty":"0x200",
"alloc": {},
"coinbase": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash":"0x0000000000000000000000000000000000000000000000000000000
000000000",
"gasLimit":"0xffffffff",
"alloc":{
}
}
}
  • Your code is formatted badly (comments are in wrong lines), it's not copypasteable (as each line includes > at the beginning) and you're not saying what you are trying to do when you get the error. – Lauri Peltonen Jun 28 at 17:48
  • sorry i edit it – Panos Kor Jun 28 at 18:35
  • I cant find which function gives the error.. i get the error when the metamask opens to do the first transaction. I bilieve the error comes from my contract code but i dont know where. I run the dapp with ganache and runs without problems – Panos Kor Jun 29 at 13:03
  • I have an error bigNumber Error: new BigNumber() not a base 16 number. After search i saw the function getHerosByOwner causes this.. I try to solve it now. I deleted the func but the error in metamask (Transaction Error. Exception thrown in contract code) still exists, – Panos Kor Jun 29 at 14:02
  • Do you configured your private network from a genesis .json file? If so, have you checked the gaslimit parameter of this file? Maybe you are running out of gas to make any transaction. – alberto Jun 29 at 16:37
0

I found it . Finally i had to let

App.web3Provider = new Web3.providers.HttpProvider('localhost:8545');

i putted instead of localhost , the ip of my node . AND I change the version of solidity . Now i have 0.4.25. In the truffle config file add

compilers: { solc: { version: '0.4.25', optimizer: { enabled: true, runs: 200 } } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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