宠物商店领养系统智能合约示例 - Solidity 代码及功能介绍
"宠物商店领养系统智能合约示例 - Solidity 代码及功能介绍"\n\n"下面是一个简单的宠物商店领养系统的智能合约的示例:\n\nsolidity\npragma solidity ^0.8.0;\n\ncontract PetShopAdoption {\n struct Pet {\n uint id;\n string name;\n uint age;\n bool adopted;\n }\n\n address public shopOwner;\n mapping(uint => Pet) public pets;\n\n event PetAdopted(uint petId, address adopter);\n\n constructor() {\n shopOwner = msg.sender;\n }\n\n modifier onlyOwner() {\n require(msg.sender == shopOwner, \"Only shop owner can call this function.\");\n _;\n }\n\n function addPet(uint id, string memory name, uint age) public onlyOwner {\n require(pets[id].id != id, \"Pet with this ID already exists.\");\n pets[id] = Pet(id, name, age, false);\n }\n\n function adoptPet(uint petId) public payable {\n require(pets[petId].id == petId, \"Pet with this ID does not exist.\");\n require(!pets[petId].adopted, \"This pet has already been adopted.\");\n require(msg.value >= 0.1 ether, \"Insufficient adoption fee.\");\n\n pets[petId].adopted = true;\n emit PetAdopted(petId, msg.sender);\n }\n\n function getPet(uint petId) public view returns (uint, string memory, uint, bool) {\n require(pets[petId].id == petId, \"Pet with this ID does not exist.\");\n\n Pet memory pet = pets[petId];\n return (pet.id, pet.name, pet.age, pet.adopted);\n }\n\n function withdraw() public onlyOwner {\n require(address(this).balance > 0, \"No balance to withdraw.\");\n payable(shopOwner).transfer(address(this).balance);\n }\n}\n\n\n这个智能合约包含了以下功能:\n\n- addPet:商店所有者可以添加宠物到商店中。\n- adoptPet:用户可以支付领养费用来领养一只宠物。\n- getPet:用户可以查询宠物的信息。\n- withdraw:商店所有者可以提取合约中的余额。\n\n需要注意的是,在这个示例中,以太币的单位是ether,领养费用被设置为0.1 ether。你可以根据实际需求进行调整。\n\n"\n
原文地址: https://www.cveoy.top/t/topic/p3pM 著作权归作者所有。请勿转载和采集!