Skip to content

Instantly share code, notes, and snippets.

@martagal
Created December 29, 2020 15:33
Show Gist options
  • Save martagal/943bc9e5e41aa46730b2c8f98c574554 to your computer and use it in GitHub Desktop.
Save martagal/943bc9e5e41aa46730b2c8f98c574554 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.7.4+commit.3f05b770.js&optimize=false&runs=200&gist=
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract PetAdoption {
Adoption[16] public adoptions;
mapping(uint256 => Pet) private pet_list;
struct Adoption {
address owner;
uint256 date;
}
enum Breed {Labrador_Retriever, German_Shepherd_Dog, Golden_Retriever, French_Bulldog, Bulldog, Other}
struct Pet {
Breed breed;
bool pet_exists;
}
event Adopted(address _adopter, uint256 _petId);
//Function to give an abandoned pet to the shelter, indicating id and breed.
//The id cannot be assigned to another pet.
function giveToShelter(uint256 _petId, Breed _breed) public {
require(pet_list[_petId].pet_exists == false);
require(_petId >= 0 && _petId <=15);
pet_list[_petId].breed = _breed;
pet_list[_petId].pet_exists = true;
}
//Function to see the breed of a pet introducing its id
function seePet(uint256 _petId) public view returns (string memory){
//function to choose _petId according to the breed of the dog
require(pet_list[_petId].pet_exists == true);
return getMyEnumKeyByValue(pet_list[_petId].breed);
}
//Function to adopt a pet that has to be in the pet_list previously given with giveToShelter.
function adopt(uint256 _petId) public {
require(_petId >= 0 && _petId <=15);
require(adoptions[_petId].owner == address(0x0));
require(pet_list[_petId].pet_exists == true);
adoptions[_petId].owner = msg.sender;
adoptions[_petId].date = now;
emit Adopted(msg.sender, _petId);
}
//Function to return to Shelter a previously adopted pet.
function returnToShelter(uint256 _petId) public {
require(adoptions[_petId].owner == msg.sender);
require(now > adoptions[_petId].date + 0.1 minutes);
require(pet_list[_petId].pet_exists == true);
adoptions[_petId].owner = address(0x0);
adoptions[_petId].date = 0;
}
//Aux function to translate the enum of the Breed on seePet
function getMyEnumKeyByValue (Breed _breed) private view returns (string memory) {
if (Breed.Labrador_Retriever == _breed) return "Labrador_Retriever";
if (Breed.German_Shepherd_Dog == _breed) return "German_Shepherd_Dog";
if (Breed.Golden_Retriever == _breed) return "Golden_Retriever";
if (Breed.French_Bulldog == _breed) return "French_Bulldog";
if (Breed.Bulldog == _breed) return "Bulldog";
return "Wrong Index";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment