solidity smart contract

Solidity is a language officially supported by Ethereum for writing smart contracts. Its syntax refers to languages ​​such as JavaScript and Java, and its syntax and concept are basically similar.

This experiment refers to

 

 

A simple experiment and study was carried out. Cryptozombies is a DAPP developed using blockchain technology. It is mainly a game for building your own zombie army to expand and upgrade. In this experiment, I refer to the tutorial to complete a simple implementation.

The main file structure of the game is as follows:

 

Introduction to the role of each file:

  1. Zombiefactory.sol This smart contract mainly includes the basic structure of zombies, the methods of creating zombies, creating random zombies, and generating random zombies.
  2. Zombiefeeding.sol This smart contract mainly includes the mutual eating of zombies and the generation of new zombies
  3. Zombieattack.sol This smart contract implements some processes and logic of two zombies fighting
  4. Zombiehelper.sol This smart contract implements the necessary conditions for setting the upgrade cost of zombies and modifying some information of zombies
  5. Zombieownership.sol This smart contract realizes the owner conversion and benefits of zombies,
  6. Interface related to Erc721.sol token transaction
  7. Ownable.sol control execution permission issue
  8. Safemath.sol provides a solution to the overflow problem
  9. Index.html is a simple web3 interface for interacting with smart contracts

The following is the specific code implementation of each agreement:

Zombiefactory.sol code implementation:

 

in this contract

pragma solidity >=0.5.0 <0.6.0;

pragma represents the version number of Solidity, the version of this contract needs to be between 0.5.0 and 0.6.0.

import "./ownable.sol";

import "./safemath.sol";

Use the import statement to bring in other Solidity files, including the Ownable contract and the SafeMath contract. The Ownable contract defines a basic permission control system, while the SafeMath contract provides mathematical calculation functions to prevent problems such as integer overflow.

Define a contract called ZombieFactory that extends the Ownable contract to use the permission control system. The library function of SafeMath is used to avoid problems such as integer overflow during mathematical calculations. Defines an event to log and notify when a new zombie is created.

A number of constants are defined, including DNA bits, DNA modulus, and cooldown time.

Define a structure called Zombie to represent the properties of a zombie.

Zombie[] public zombies: defines a dynamic array for storing all zombies.

mapping (uint => address) public zombieToOwner;

mapping (address => uint) ownerZombieCount;

Define two maps for storing zombie owners and the number of zombies each owner has.

Define an internal function called _createZombie that creates a new zombie. This function adds a new zombie to the zombies array, sets its owner as the sender of the current message, and increments the number of zombies owned by this owner. Finally, the function fires the NewZombie event to notify the outside world that a new zombie has been created.

Define a private function called _generateRandomDna for randomly generating a dna sequence.

Define a function called createRandomZombie to create a new zombie from a randomly generated DNA sequence.

The code of Zombiefeeding.sol is as follows:

 

This smart contract contains a contract called ZombieFeeding, which inherits from the previously defined ZombieFactory contract

An interface called KittyInterface is defined for interacting with external contracts. In this interface, there is a function getKitty, which is used to return information related to kitty, and is used to obtain various attributes when setting special types of zombies.

A modifier named onlyOwnerOf is declared, which requires the caller to be the owner of the zombie whose _zombieId belongs, otherwise the function will throw an exception.

The setKittyContractAddress function is used to set the kittyContract variable to the contract instance of the KittyInterface type corresponding to the specified address _address. Since this function uses the onlyOwner modifier, only the contract owner can call this function.

The _triggerCooldown function is used to reset the zombie's cooldown to cooldownTime after feeding the zombie. It accepts a parameter called _zombie with storage type whose cooldown will be modified.

The _isReady function is used to check if the zombie has finished cooling, it takes a parameter of storage type named _zombie, and returns a boolean value.

The feedAndMultiply function takes the Zombie ID, target DNA, and species string as parameters. First, it checks whether the given Zombie is ready to mate (ie its readyTime has elapsed). It then extracts the DNA modulus from the given target DNA and averages it with the given Zombie's DNA to generate new DNA. If the given kind string is equal to "kitty", set the new DNA to be the remainder of dividing by 100 plus 99. Finally, use the _createZombie function to create a new Zombie named "NoName" and set its DNA to the newly generated DNA, then call the _triggerCooldown function to set the readyTime of the given Zombie to the current time plus cooldownTime.

The feedOnKitty function receives the Zombie ID and the cat's ID as parameters, calls the KittyContract's getKitty function to get the cat's DNA, then calls the feedAndMultiply function to average the given Zombie's DNA and the cat's DNA to generate new DNA, and Create a new Zombie. This function is publicly accessible, so anyone can use it to feed their zombies.

The code for Zombieattack.sol is as follows:

 

This smart contract implements a smart contract called zombieattack, which is used to handle the process of mutual attack with zombies.

The contract imports the ZombieHelper contract, which means it has all the functions and variables defined in the ZombieHelper contract.

randNonce is the seed used to generate random numbers.

attackVictoryProbability is the probability of attack victory, initialized to 70%.

randMod is an internal function used to generate a random number and limit it to a given range. This function concatenates the current time, the address of the caller, and the randNonce value, calculates a hash value through the keccak256 hash algorithm, and converts it into a number. Finally, this number is taken modulo the given argument, returning a number between 0 and (_modulus - 1).

The attack function first obtains the zombie information of the attacker and the attacked party, and uses the randMod function to generate a random number. If the random number is less than or equal to attackVictoryProbability, the attacker wins. In this case, the number of victories and levels of the attacker is increased, the number of defeats of the attacked is increased, and the feedAndMultiply function is called to mix the DNA of the attacker and the DNA of the attacked to create a new zombie. If the attacker loses, it increments its defeat count and the attacked party's win count, and calls the _triggerCooldown function, which restarts the zombie's cooldown timer.

Zombiehelper.sol code is as follows:

 

This smart contract implements the necessary conditions for setting the upgrade cost of zombies and modifying some information of zombies.

Define a decorator named aboveLevel. The decorator requires that the level of the zombie corresponding to the second parameter (_zombieId) of the decorated function be greater than or equal to the first parameter (_level), otherwise an exception will be thrown and the function execution will be stopped.

The withdraw function is modified to be called only by the contract owner, and sends all balances from the current contract address to the contract owner.

The function of setLevelUpFee is modified so that it can only be called by the contract owner, and the value of levelUpFee is set with the parameters passed in.

The levelUp function can only be called externally, and the caller must pay an ether equal to the levelUpFee, otherwise an exception will be thrown and the function execution will stop. Increases the level of the specified zombie if the condition is met.

The changeName function can only be called externally, and the following conditions must be met: the level of the specified zombie is greater than or equal to 2, and the caller must be the owner of the zombie. Changes the specified zombie's name to the new one if the condition is met.

The changeDna function can only be called externally, and the following conditions must be met: the level of the specified zombie is greater than or equal to 20, and the caller must be the owner of the zombie. If the condition is met, the DNA of the specified zombie is changed to the new DNA.

The getZombiesByOwner function can only be called externally and returns the IDs of all zombies owned by the specified owner. It first creates a dynamic array result whose length is equal to the number of zombies owned by the specified owner, and then loops through all zombies. If the owner of a zombie is the specified owner, add the zombie's ID to result In the end, the result array is returned.

The code for Zombieownership.sol is as follows:

 

This smart contract implements a smart contract called ZombieOwnership, which is inherited from ZombieAttack and ERC721. It implements the interface defined in the ERC721 standard for managing and trading Zombies.

The balanceOf(address _owner) function returns the number of tokens owned by the specified address.

The ownerOf(uint256 _tokenId) function returns the address that owns the specified token.

_transfer(address _from, address _to, uint256 _tokenId) performs the ownership transfer of the token.

transferFrom(address _from, address _to, uint256 _tokenId): used to authorize the address to transfer the specified token to another address.

approve(address _approved, uint256 _tokenId): used to authorize the address to manage the specified token.

Erc721.sol code:

 

This contract defines RC721, erc721 is a token standard on Ethereum, which defines an interchangeable non-homogeneous token (NFT) protocol, allowing users to own and trade different tokens, each token All are unique.

The contract defines the following four functions:

The balanceOf(address _owner) function returns the amount of tokens owned by the specified address.

The ownerOf(uint256 _tokenId) function returns the owner address of the specified token ID.

The transferFrom(address _from, address _to, uint256 _tokenId) function transfers ownership of the specified token ID from one address to another.

The approve(address _approved, uint256 _tokenId) function authorizes ownership of the token ID to another address so that the address can transfer tokens.

The code of Ownable.sol is as follows:

 

This smart contract includes a smart contract called Ownable, which provides a convenient way to control who can perform sensitive operations in the contract, such as modifying the state of the contract or extracting assets in the contract. Typically, only the owner of the contract has permission to perform these operations, while other users can only perform read-only operations. By inheriting the Ownable smart contract, other contracts can obtain similar permission control functions, so as to ensure that the operations in the contract are properly authorized and authenticated.

Private variable _owner: Indicates the owner address of the contract.

OwnershipTransferred event: used to trigger a notification when the owner changes.

The constructor sets the creator of the contract as the owner, and triggers the OwnershipTransferred event, notifying that the contract has been created.

The public function owner() is used to get the owner address of the contract.

The modifier onlyOwner() is used to restrict that only the owner of the contract can call certain functions.

The public function isOwner() is used to determine whether the current caller is the owner of the contract.

Public function renounceOwnership(), only the owner of the contract can call this function to give up the ownership of the contract, trigger the OwnershipTransferred event, and set _owner to address(0).

The public function transferOwnership(address newOwner), only the owner of the contract can call this function to transfer the ownership of the contract to the new owner, and call _transferOwnership() to realize the transfer.

The internal function _transferOwnership(address newOwner) is used to transfer the ownership of the contract to the new owner, trigger the OwnershipTransferred event, and update the value of the _owner variable. Before transferring ownership, it is necessary to ensure that the new owner address is not 0.

Safemath.sol code is as follows:

 

This smart contract combines assert and related interpretations to provide a solution to the overflow security problem of uint type data.

Guess you like

Origin blog.csdn.net/qq_53633989/article/details/130514201