david's daily developer note

[Solidity] 1.Basics & Language description 본문

[Blockchain]/develop

[Solidity] 1.Basics & Language description

mouse-david 2022. 8. 13. 02:45
728x90

1. 기본

솔리디티(Solidity)는 "계약 지향 프로그래밍 언어"로 스마트 컨트랙트(Smart Contract) 단위로 구성되며 실행된다. (EVM(Ethereum Virtual Machine)에서 동작하는 Curly-bracket languages)

pragma solidity ^0.4.19;
contract Example {
}

예시는 하나의 컨트랙트가 작성된 기본 예제이다.
첫 번째 라인의 pragma solidity^는 솔리디티 컴파일러 버전을 의미하며, 
레거시 코드가 새로운 컴파일러가 등장하더라도 정상 동작함을 보장한다.

솔리디티의 기본 구성 및 실행 요소는 컨트랙트이며, 
모든 변수 및 함수가 컨트랙트안에서 동작한다. 선언된 변수와 값은 실제 블록체인에 영구적으로 기록된다.

2. 변수 및 구조체 


컨트랙트내에서 다양한 형태의 상태 변수와 구조체를 사용할 수 있다.
아래는 기본 연산자 예시이다.

bool
논리 자료형

  • ! (logical negation)
  • && (logical conjunction, “and”)
  • || (logical disjunction, “or”)
  • == (equality)
  • != (inequality)

int / uint 
부호 없는 정수형

  • Comparisons: <=, <, ==, !=, >=, > (evaluate to bool)
  • Bit operators: &, |, ^ (bitwise exclusive or), ~ (bitwise negation)
  • Shift operators: << (left shift), >> (right shift)
  • Arithmetic operators: +, -, unary - (only for signed integers), *, /, % (modulo), ** (exponentiation)

adress / address payable
0.5.0 이상의 버전에서 20바이트의 이더리움 주소값을 컨트롤 하기 위하여 사용

string
UTF-8 인코딩 문자열

array
같은 타입의 연속된 배열을 만들기 위하여 사용한다. 솔리디티는 정적, 동적 배열을 선언할 수 있다.

// 2개의 원소를 담을 수 있는 고정 길이의 배열:
uint[2] fixedArray;
// 또다른 고정 배열으로 5개의 스트링을 담을 수 있다:
string[5] stringArray;
// 동적 배열은 고정된 크기가 없으며 계속 크기가 커질 수 있다:
uint[] dynamicArray;
// 동적 구조체 배열로, 원소를 계속 추가할 수 있다.
Person[] people;

배열을 public으로 선언할 수 있는데, 이는 다른 컨트랙트에서 읽을 수 있는 상태가 된다.
솔리디티는 public으로 선언한 배열에 getter 메소드를 자동으로 생성하는데, java Lombok의 @Setter 선언과 같다.
접근한정자가 사용될 수 있다는 것으로 컨트랙트가 클래스와 유사한 형태로 구조화되었음을 알 수 있다.
동적 배열은 다음과 같이 마지막 요소 뒤에 추가할 수 있다.

contract Example {
    struct User {
        string name;
        uint age;
    }
    User[] users;
    users.push(User("david",99)); // 배열 users의 마지막 요소 다음에 새로운 User 구조체를 추가
}

struct
변수의 집합으로 새로운 유형의 변수를 정의한다.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;

// Defines a new type with two fields.
// Declaring a struct outside of a contract allows
// it to be shared by multiple contracts.
// Here, this is not really needed.
struct Funder {
    address addr;
    uint amount;
}

예시의 Funder구조체는 컨트랙트 밖에 선언되었는데, 이 경우에는 여러 컨트랙트가 공유할 수 있다.

 

Reference
https://docs.soliditylang.org/en/v0.8.16/types.html

 

Types — Solidity 0.8.16 documentation

Types Solidity is a statically typed language, which means that the type of each variable (state and local) needs to be specified. Solidity provides several elementary types which can be combined to form complex types. In addition, types can interact with

docs.soliditylang.org

** 해당 자료는 솔리디티 v0.8.16을 기준으로 작성하였음

728x90

'[Blockchain] > develop' 카테고리의 다른 글

[Solidity] 5.Error handling : Assert, Require, Revert  (0) 2022.08.16
[Solidity] 4.Mapping  (0) 2022.08.15
[Solidity] 3.Event  (0) 2022.08.14
[Solidity] 2.Function  (0) 2022.08.14