I've been following along with the Ethereum Pet Shop tutorial, and I'm fascinated by how all of this works.
I have a few questions, though.
Before I get into it, here's the code:
pragma solidity ^0.4.17;
contract Adoption {
Pet[16] pets;
struct Pet {
address owner;
uint256 price;
}
function returnEth() public payable {
msg.sender.transfer(msg.value);
}
// Adopting a pet
function adopt(uint petId) public payable returns (uint) {
require(petId >= 0 && petId <= 15);
require(msg.value >= pets[petId]['price'] * 0.5);
pets[petId] = Pet({owner: msg.sender, price: 100});
return petId;
//return value;
}
// Retrieving the adopters
function getAdopters() public view returns (Pet[16]) {
return pets;
}
}
I understand that there are 16 total pets, with numeric IDs ranging from 0-15, inclusive. I also understand that only one person is able to "own" a pet at one time.
Is the current owner of a pet immutable? If so, how do I change this property?
Let's say that after a user "buys" a pet, I want to change the price of the pet to .5 * initialPrice, where initalPrice
does not currently exist. The remaining balance in eth in the contract is then returned to the first buyer. What would that logic look like?
I assume I'd declare some variable initialPrice
somewhere in my contract, such that initialPrice
is equal to some arbitrary value in wei, and then add something similar to the following line:
require(msg.value == initialPrice * .5);
How would I then return the remaining eth to the previous owner?
Please let me know if any of this is unclear.
Edit: I've been trying to use the code from the first, answer, but am unable to compile the contract. The error I'm getting is below:
Adoption.sol:19:17: TypeError: Type address is not implicitly convertible to expected type struct Adoption.Pet storage ref.
pets[petId] = msg.sender;
^--------^