블록체인 개발 - Solidity

김성진·2021년 10월 5일
0
post-thumbnail

Solidity란..?

솔리디티는 계약 지향 프로그래밍 언어로 다양한 블록체인 플렛폼의 스마트계약(smart contract) 작성 및 구현에 사용된다.
앞서 공부한 스마트컨트랙트라는 것을 실제 프로그래밍 언어로 개발해보며 좀 더 블록체인 개발에 한걸음 다가가보자!

솔리디티의 가장 기본:

pragma solidity ^0.4.19; //모든 솔리디티는 "version pragma"로 시작한다 

contract ZombieFactory { //컨트랙트 선언

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

    uint dnaDigits = 16; //부호 없는 정수 uint (변수의 종류)
    uint dnaModulus = 10 ** dnaDigits;

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

    Zombie[] public zombies; //public으로 배열 선언. getter메소드 자동 생성

    // 여기서 매핑 선언

    function _createZombie(string _name, uint _dna) private {
        uint id = zombies.push(Zombie(_name, _dna)) - 1; //push는 배열에 넣는 함수
        NewZombie(id, _name, _dna);
    } 

    function _generateRandomDna(string _str) private view returns (uint) {
        uint rand = uint(keccak256(_str)); // 이더리움 SHA3의 한버전인 keccak256
        return rand % dnaModulus;
    }

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

}

솔리디티 function을 작성할때 public과 private으로 구분해서 작성할 수가 있는데, 여기서 public은 모두에게 공개함으로서 내 함수를 호출 및 실행도 가능캐한다, 반면 private으로 선언하면 공개가 되지 않는다. 잘 고민해서 public으로 선언할지, private으로 선언할지 결정하자.

profile
multi-national communicator with programming (back-end)

0개의 댓글