본문 바로가기
블록체인

[Solidity] Solidity 문법 정리 (1)

by 테크케찰 2022. 6. 11.

https://docs.soliditylang.org/en/v0.8.14/

 

Solidity — Solidity 0.8.14 documentation

1. Understand the Smart Contract Basics If you are new to the concept of smart contracts we recommend you to get started by digging into the “Introduction to Smart Contracts” section, which covers: 2. Get to Know Solidity Once you are accustomed to the

docs.soliditylang.org

https://cryptozombies.io/ko/

 

#1 Solidity Tutorial & Ethereum Blockchain Programming Course | CryptoZombies

CryptoZombies is The Most Popular, Interactive Solidity Tutorial That Will Help You Learn Blockchain Programming on Ethereum by Building Your Own Fun Game with Zombies — Master Blockchain Development with Web3, Infura, Metamask & Ethereum Smart Contracts

cryptozombies.io

 

오늘 포스트에서는 solidity의 기본 문법에 대해서 알아보겠습니다. 

저는 일단 crypto zombies라는 사이트를 이용해 학습을 진행해보았는데요, 게임을 만들면서 이더리움 댑 코딩을 배울 수 있는 사이트입니다.

해당 포스트는 크립토 좀비의 첫 번째 course를 따라가면서 제작되었습니다.

선언

pragma solidity ^0.4.19; // solidity 버전 명시

// 컨트랙트 정의
contract ZombieFactory { 
    // 여기에 코드 작성
}

위 코드는 간단하게 ZombieFactory라는 contract를 정의한 코드입니다. 최상단에 solidity 버전을 명시해주면 되는데, solidity 공식 홈페이지 들어가보니 최신 버전은 0.8.14 버전으로 되어 있는데 현재 course에서는 0.4.19를 기반으로 작성되어 있어서 위와 같이 명시해주었습니다.

변수

solidity type을 선언자로 선언해서 사용할 수 있습니다.

uint var1 = 1;

구조체

javascript의 object와 비슷한 역할을 하는 친구로 보입니다.

struct Person {
  uint age;
  string name;
}

배열

타입을 이용해서 배열 선언 가능
구조체로도 배열 선언이 가능합니다.

// 고정 길이의 배열
uint[2] fixedArray;
// 동적 길이의 배열
uint[] dynamicArray;

함수

cryptoZombie 사이트에 따르면 함수 인자명에 prefix로 _(안더스코어)를 붙여주는 것이 관례라고 합니다.

function myFunction(string _arg1, uint _arg2){

}

private과 public

디폴트는 public
public: 외부에서 자유롭게 컨트랙트의 함수를 호출 및 코드 실해 가능
private: 컨트랙트 내의 다른 함수들만이 이 함수를 호출 가능

이외에도 external, internal이라는 친구도 있음

https://docs.soliditylang.org/en/v0.8.14/cheatsheet.html#function-visibility-specifiers

function myFunction(string _arg1, uint _arg2) private {

}

반환값, 함수 제어자(Modifier)

아래 예문에서는 view와 pure만 다루고 있는데 공식 문서에서는 payable, constant 등의 더 많은 제어자가 존재합니다.

https://docs.soliditylang.org/en/v0.8.14/cheatsheet.html#modifiers

string var1 = "hi!";

// return 뒤에 리턴값 선언
function myFunction() public returns (string){
    return var1;
}

// solidity에서 상태를 변화시키지 않는 경우 view 함수로 선언
function myFunction2() public view returns (string){
    return var1;
}

// pure: 함수가 앱에서 어떤 데이터도 접근하지 않는 경우
function addNumber(uint _a, uint _b) private pure returns (uint){
    return a+b;
}

형반환

uint a = 1;
uint8(a) // uint -> uint8로 형변환

이벤트

컨트랙트의 블록체인 상에서 사용자 단의 액션이 발생했을 떄 호출됩니다.

event 선언자를 사용해서 선언하고,  emit을 이용해서 실행시킵니다.

크립토좀비에서는 emit을 사용하지 않았는데 아래 글을 확인해 보면 emit을 사용해주는 것이 맞는 것 같습니다. (솔리디티 0.4.21부터 emit이 추가되었다고 합니다 :) )

https://www.tutorialspoint.com/solidity/solidity_events.htm

 

Solidity - Events

Solidity - Events Event is an inheritable member of a contract. An event is emitted, it stores the arguments passed in transaction logs. These logs are stored on blockchain and are accessible using address of the contract till the contract is present on th

www.tutorialspoint.com

이벤트는 로그를 남기는 역할을 하는데 아래 글을 참고해보면 너무 자주 사용할 시 사용자에게 가스 부담이 갈 수 있기 떄문에 필요할 때에 사용해야 된다고 나와 있습니다.

https://hichoco.tistory.com/entry/Solidity%EC%86%94%EB%A6%AC%EB%94%94%ED%8B%B0-%EC%9D%B4%EB%B2%A4%ED%8A%B8event-%EB%B0%A9%EC%B6%9Cemit-%ED%95%98%EA%B3%A0-%EC%95%88%ED%95%98%EA%B3%A0-%EC%B0%A8%EC%9D%B4

 

Solidity(솔리디티): 이벤트(event) 방출(emit) 하고 안하고 차이?

Solidity 개발을 처음 시작할 때 궁금한 것들 중 하나는 이벤트(event)에 대한 것일 텐데요. 이벤트가 왜 있는지, 이벤트를 발생시키면 어떤 차이가 발생하는지를 간단한 예제로 알아보도록 하겠습

hichoco.tistory.com

// 이벤트 선언
event MyEvent(uint x, uint y);

function myEvent(uint _x, uint _y){
    // 이벤트 호출
    emit MyEvent(_x, _y);
}

이벤트는 아래 세가지 케이스에서 유용하다고 합니다. 

1. 트랜잭션의 결과값을 확인하는 경우

2. 이더 송금 등의 트랜잭션 기록을 저장할 때 (상태 변수에 트랜잭션 기록을 하게 되면 storage 영역에 기록이 되어 높은 비용이 들 수 있음)

3. dapp에서 이벤트를 모니터링해 이벤트 발생 시 특정 함수를 실행시키는 경우