From d75432de76bb383186857be45f0dd1a5ff3744f4 Mon Sep 17 00:00:00 2001 From: UchihaCFC Date: Tue, 26 Jul 2022 09:51:20 +0200 Subject: [PATCH] Challenges #2 and #3 are solved --- PokemonFactory.sol | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/PokemonFactory.sol b/PokemonFactory.sol index 35ffda8a..ef633ad2 100644 --- a/PokemonFactory.sol +++ b/PokemonFactory.sol @@ -7,22 +7,57 @@ contract PokemonFactory { struct Pokemon { uint id; string name; + Ability[] abilities; + } + + struct Ability{ + string name; + string description; } Pokemon[] private pokemons; + Ability[] private abilities; mapping (uint => address) public pokemonToOwner; mapping (address => uint) ownerPokemonCount; + mapping(uint8 => uint) globalId; event eventNewPokemon( uint id, string name ); - function createPokemon (string memory _name, uint _id) public { - pokemons.push(Pokemon(_id, _name)); + event eventNewPokemonAbility( + string name, + string description + ); + + modifier checkPokemonData(string memory _name, uint _id){ + require(_id > 0, "The id must be bigger than 0!"); + require(bytes(_name).length > 2 || bytes(_name).length == 0, "The name must be bigger than 2 characters!"); + _; + } + + modifier checkPokemonAbilityData(string memory name, string memory description, uint256 id){ + require(id > 0, "The id must be bigger than 0!"); + require(bytes(name).length > 2 || bytes(name).length == 0, "The name must be bigger than 2 characters!"); + require(bytes(description).length > 10, "The description must be bigger than 10 characters!"); + _; + } + + modifier checkPokemonExist(uint8 id) { + require(globalId[id] > 0, "The pokemon with this id doesn't exist, please check that it is correct and try again"); + _; + } + + function createPokemon (string memory _name, uint8 _id) public checkPokemonData(_name, _id) { + pokemons.push(); + uint pokemonId = pokemons.length - 1; + pokemons[pokemonId].id = _id; + pokemons[pokemonId].name = _name; pokemonToOwner[_id] = msg.sender; ownerPokemonCount[msg.sender]++; + globalId[_id] = pokemonId + 1; emit eventNewPokemon(_id, _name); } @@ -30,6 +65,11 @@ contract PokemonFactory { return pokemons; } + function addPokemonAbility(string memory name, string memory description, uint8 id) public checkPokemonAbilityData(name, description, id) checkPokemonExist(id){ + uint idx = globalId[id]; + pokemons[idx - 1].abilities.push(Ability(name, description)); + emit eventNewPokemonAbility(name, description); + } function getResult() public pure returns(uint product, uint sum){ uint a = 1;