CryptoZombie Chapter 1

빵 반죽·2021년 9월 10일
0

Solidity: CryptoZombies

목록 보기
1/6

CryptoZombie: Making the zombie factory
try it yourself

0. Source code

pragma solidity ^0.4.25;

contract ZombieFactory {

    event NewZombie(uint zombieId, string name, uint dna);

    uint dnaDigits = 16;
    uint dnaModulus = 10 ** dnaDigits;

	//좀비 구조체
    struct Zombie {
        string name;
        uint dna;
    }

    Zombie[] public zombies;

	//좀비 배열에 새로운 좀비 추가
    function _createZombie(string _name, uint _dna) private {
        uint id = zombies.push(Zombie(_name, _dna)) - 1;
        emit NewZombie(id, _name, _dna);
    }

	//문자열을 암호화하여 랜덤 유전자 생성
    function _generateRandomDna(string _str) private view returns (uint) {
        uint rand = uint(keccak256(abi.encodePacked(_str)));
        return rand % dnaModulus;
    }

	// 위 함수들을 이용하여 이름으로 랜덤 좀비 생성
    function createRandomZombie(string _name) public {
        uint randDna = _generateRandomDna(_name);
        _createZombie(_name, randDna);
    }

}
© 2022 GitHub, Inc.
Terms
Privacy

code from here

1. Lesson Overview

Zombie DNA is a 16 digit integer that determines an unique appearance.

2. Contracts

A contract is the fundamental building block of Ethereum applications — all variables and functions belong to a contract~

Version Pragma: a declaration of the version of the Solidity compiler this code should use

pragma solidity >=0.5.0 <0.6.0;
//  any compiler version in the range of
//0.5.0 (inclusive) to 0.6.0 (exclusive)

contract ZombieFactory{
// empty contract
}

3. State Variables & Integers

State variables are permanently stored in contract storage. This means they're written to the Ethereum blockchain. Think of them like writing to a DB.

uint: 256 bit unsigned int variable. uint8, uint16, etc. also possible.

contract ZombieFactory {

    // This will be stored permanently in the blockchain
    // our zombie dna is 16 digit integer
    uint16 dnaDigits = 16;
    
}

4. Math Operations

All operations are pretty straight forward.
6 operations: x+y, x-y, x*y, x/y, x%y, x^y(x**y)

5. Structs

Allows more complex data structures.

struct Zombie {
        string name;
        uint dna;
    }

6. Arrays

2 types of arrays: fixed, dynamic
Fixed: fixed size declared
Dynamic: size not declared, size can continuously expand

Array of structs possible
Declaring an array public automatically generates getter method for it.

Zombie[] public zombies;

7. Function Declarations

memory: required for all reference types such as arrays, structs, mappings, and strings
recall 'call by value' and 'call by reference'

Check the order of keywords in this example:

// convention to put _ before a parameter
function createZombie(string memory _name, uint _dna) public {}

8. Working With Structs and Arrays

See this example:

struct Zombie {
        string name;
        uint dna;
    }

    Zombie[] public zombies;

    function createZombie (string memory _name, uint _dna) public {
        zombies.push(Zombie(_name,_dna));
    }

9. Private / Public Functions

Functions are public by default in solidity(==This means anyone can call your contract's function and execute its code.), therefore it is vulnerable to attacks. Use private habitually unless you want it to be exposed!

// conventional to put _ in front of private functions
function _createZombie(string memory _name, uint _dna) private {
        zombies.push(Zombie(_name, _dna));
    }

10. More on Functions

To return a value, it must be mentioned at declaration with type specified.
If the function does not modify any state -> view
If the function does not access any data -> pure
keyword 'returns' 'view' 'pure'

function _generateRandomDna(string memory _str) private view returns(uint){

    }

11. Keccak256 and Typecasting

Keccak256: built-in hash function based on SHA3
generates random 256 bit hex number.
expects a single byte parameter: packing needed => abi.encodePacked()

function _generateRandomDna(string memory _str) private view returns (uint) {
        uint rand = uint(keccak256(abi.encodePacked(_str)));
        return rand%dnaModulus;
    }

12. Putting It Together

function createRandomZombie(string memory _name) public {
        uint randDna = _generateRandomDna(_name);
        _createZombie(_name, randDna);
    }

13. Events

Events are a way for your contract to communicate that something happened on the blockchain to your app front-end, which can be 'listening' for certain events and take action when they happen.

event NewZombie(uint zombieId, string name, uint dna);


function _createZombie(string memory _name, uint _dna) private {
        uint id = zombies.push(Zombie(_name, _dna)) - 1;
        emit NewZombie(id, _name,_dna);
    }

14. Web3.js

Time for javascript front end for our finished contract!
Web3.js is a javascript library provided by Ethereum. Let's just have a taste of it here.

A sample from the website:

// Here's how we would access our contract:
var abi = /* abi generated by the compiler */
var ZombieFactoryContract = web3.eth.contract(abi)
var contractAddress = /* our contract address on Ethereum after deploying */
var ZombieFactory = ZombieFactoryContract.at(contractAddress)
// `ZombieFactory` has access to our contract's public functions and events

// some sort of event listener to take the text input:
$("#ourButton").click(function(e) {
  var name = $("#nameInput").val()
  // Call our contract's `createRandomZombie` function:
  ZombieFactory.createRandomZombie(name)
})

// Listen for the `NewZombie` event, and update the UI
var event = ZombieFactory.NewZombie(function(error, result) {
  if (error) return
  generateZombie(result.zombieId, result.name, result.dna)
})

// take the Zombie dna, and update our image
function generateZombie(id, name, dna) {
  let dnaStr = String(dna)
  // pad DNA with leading zeroes if it's less than 16 characters
  while (dnaStr.length < 16)
    dnaStr = "0" + dnaStr

  let zombieDetails = {
    // first 2 digits make up the head. We have 7 possible heads, so % 7
    // to get a number 0 - 6, then add 1 to make it 1 - 7. Then we have 7
    // image files named "head1.png" through "head7.png" we load based on
    // this number:
    headChoice: dnaStr.substring(0, 2) % 7 + 1,
    // 2nd 2 digits make up the eyes, 11 variations:
    eyeChoice: dnaStr.substring(2, 4) % 11 + 1,
    // 6 variations of shirts:
    shirtChoice: dnaStr.substring(4, 6) % 6 + 1,
    // last 6 digits control color. Updated using CSS filter: hue-rotate
    // which has 360 degrees:
    skinColorChoice: parseInt(dnaStr.substring(6, 8) / 100 * 360),
    eyeColorChoice: parseInt(dnaStr.substring(8, 10) / 100 * 360),
    clothesColorChoice: parseInt(dnaStr.substring(10, 12) / 100 * 360),
    zombieName: name,
    zombieDescription: "A Level 1 CryptoZombie",
  }
  return zombieDetails
}

Example with 'bob':

0개의 댓글

관련 채용 정보