1. 값 형식

1.1. INT / UINT

uint 의 줄임말입니다 부호 없는 정수, 그리고 크기를 선택할 수 있습니다 uint8 ~에 uint256

  • uint8 시작합니다 0 ~에 2 ** 8 - 1
  • uint16 시작합니다 0 ~에 2 ** 16 - 1
    ...
  • uint256 시작합니다 0 ~에 2 ** 256 - 1

uint8 public u8 = 1;
uint256 public u256 = 456;
uint public u = 123; // uint는 uint256의 축약형입니다

int 의 줄임말입니다 정수, 그리고 크기를 선택할 수 있습니다 int8 ~에 int256

  • int8 시작합니다 -2 ** 7 ~에 2 ** 7 - 1
  • int16 시작합니다 -2 ** 15 ~에 2 ** 15 - 1 ...
  • int128 시작합니다 -2 ** 127 ~에 2 ** 127 - 1
  • int256 시작합니다 -2 ** 255 ~에 2 ** 255 - 1
int8 public i8 = -1;
int256 public i256 = 456;
int public i = -123; // int는 int256의 약어입니다

int 및 uint 연산자:

  • Comparisons: <=, <, ==, !=, >=, > (returns bool)
  • 비트 연산: &, |, ^ (비트 배타적 논리합), ~ (비트 부정)
  • Shifts: << (left shift), >> (right shift)
  • 덧셈, 뺄셈 및 곱셈: +, -, 음수 - (예: 부호 있는 정수), *, /, % (모듈로 연산), ** (거듭제곱)

타입 정수 변수 X의 경우, 다음을 사용하여 type(X).min 및 type(X).max 해당 타입의 최솟값과 최댓값에 각각 접근할 수 있습니다.

// int 형의 최소값과 최대값: 
int public minInt = type(int).min;
int public maxInt = type(int).max;

// uint형의 최소값과 최대값:
uint public minUint = type(uint).min;
uint public maxUint = type(uint).max;

1.2. BOOL

bool 은 불리언(Boolean) 를 의미하며, 가질 수 있는 값은 다음 2가지입니다. true 및 false

bool public trueVar = true;
bool public falseVar = false;

1.3. 연산자:

  • ! (논리 부정)
  • && (논리곱, "and")
  • || (논리합, "or")
  • == (동등)
  • != (부등)

연산자는 || 및 && 일반적인 단락 평가(short-circuiting) 규칙을 따릅니다. 즉, 다음과 같은 표현식에서 f(x) || g(y), 만약 f(x) 의 결과가 true, g(y) 인 경우, 부수 효과(side-effect)가 발생할 수 있더라도 평가되지 않습니다.

1.4. 주소 (ADDRESS)

  • address Solidity의 특수한 데이터 유형으로, Kaia 계정의 주소(크기 20바이트)를 저장할 수 있습니다.
  • address payable 와 유사하지만 address 2개의 메서드가 추가됩니다 transfer 및 send
공개 주소 exampleAddress = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;
지급 대상 주소 public examplePayableAddress = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;

1.5. 바이트 (BYTES)

솔리디티에서 byte 데이터 타입은 바이트 시퀀스를 나타냅니다.솔리디티에는 두 가지 유형의 바이트가 있습니다:

  • 고정 크기 바이트 배열
  • 동적 크기 바이트 배열

솔리디티에서 bytes라는 단어는 바이트의 동적 배열을 의미하며, 기본적으로 byte[]를 나타냅니다.

bytes1 a = 0xb5; //  [10110101]
bytes1 b = 0x56; //  [01010110]
바이트 c = "abc"; //  [01100001, 01100010, 01100011]

1.6. 기본값

값이 할당되지 않은 선언된 변수는 기본값을 갖습니다.

bool public defaultBool; // false
uint public defaultUint; // 0
int public defaultInt; // 0
address public defaultAddr; // 0x0000000000000000000000000000000000000000
바이트1 public defaultByte; // 0x00

1.7. 계약(CONTRACT)

컨트랙트 Solidity에서 컨트랙트를 선언하는 데 사용됩니다.

contract HelloWorld {}

컨트랙트 키워드를 사용하여 다른 컨트랙트를 상속받을 수도 있습니다. 이다

contract Mercedes is Car {}

1.8. 열거형(ENUM)

열거형(Enums) 은 Solidity에서 사용자 정의 타입을 생성하는 한 방법입니다. 모든 정수 타입 상호 간에 명시적 변환이 가능하지만 암묵적 변환은 허용되지 않습니다. 정수로부터의 명시적 변환은 런타임에 값이 열거형의 범위 내에 있는지 확인하며, 그렇지 않은 경우 다음을 발생시킵니다. 패닉 오류(Panic error) 그렇지 않은 경우. 열거형(Enums) 적어도 하나의 멤버가 필요하며, 선언 시 기본값은 첫 번째 멤버입니다. 열거형은 256개 초과의 멤버를 가질 수 없습니다.

데이터 표현 방식은 다음의 열거형 C 언어와 동일합니다. 옵션은 0부터 시작하는 연속된 부호 없는 정수 값으로 표현됩니다.

사용 type(NameOfEnum).min 및 type(NameOfEnum).max 주어진 열거형의 각각 최소값과 최대값을 얻을 수 있습니다.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Enum {
    // Enum representing shipping status
    enum Status {
        Pending,
        Shipped,
        Accepted,
        Rejected,
        Canceled
    }

    // Default value is the first element listed in
    // definition of the type, in this case "Pending"
    Status public status;

    // Returns uint
    // Pending  - 0
    // Shipped  - 1
    // Accepted - 2
    // Rejected - 3
    // Canceled - 4
    function get() public view returns (Status) {
        return status;
    }

    // Update status by passing uint into input
    function set(Status _status) public {
        status = _status;
    }

    // You can update to a specific enum like this
    function cancel() public {
        status = Status.Canceled;
    }

    // delete resets the enum to its first value, 0
    function reset() public {
        delete status;
    }
}

1.9. 타입(TYPE)

사용자 정의 값 타입은 기본 값 타입에 대해 비용이 발생하지 않는 추상화를 생성할 수 있게 합니다. 이는 별칭(alias)과 유사하지만 더 엄격한 타입 요구 사항을 가집니다.

사용자 정의 값 형식은 다음과 같이 정의됩니다 type C is V, 여기서 C 는 새로 도입된 타입의 이름이고 V 은(는) 내장 값 타입이어야 합니다("기저 타입")

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.8;

// 사용자 정의 값 유형을 사용하여 18진수, 256비트 폭의 고정 소수점 유형을 나타냅니다.
type UFixed256x18 is uint256;

1.10. 함수

함수 키워드는 솔리디티에서 함수를 선언하는 데 사용됩니다.

우리는 함수 를 다음과 같이 선언할 수 있습니다:

contract Counter {
    uint public count;

    // Function to view count variable
    function get() public view returns (uint) {
        return count;
    }
}

2. 참조 타입

2.1. 데이터 스토리지 위치

데이터가 저장될 위치를 지정하기 위해 변수는 storage, memory 또는 calldata 단어와 함께 선언됩니다.

  • storage - 변수는 상태 변수입니다 (블록체인에 저장됨)
  • memory - 변수는 메모리에 있으며 함수 이(가) 실행되는 동안에만 존재합니다
  • calldata - 함수에 전달된 데이터를 포함하는 특수 데이터 저장소
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract DataLocations {
    uint storage varStorage
    uint memory varMemory
    uint calldata varCallData
}

2.2. 배열

배열 의 목록 파이썬의 배열 내부 자바스크립트.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Array {
    // Several ways to initialize an array
    uint[] public arr;
    uint[] public arr2 = [1, 2, 3];
    // Fixed sized array, all elements initialize to 0
    uint[10] public myFixedSizeArr;

    function get(uint i) public view returns (uint) {
        return arr[i];
    }

    // Solidity can return the entire array.
    // But this function should be avoided for
    // arrays that can grow indefinitely in length.
    function getArr() public view returns (uint[] memory) {
        return arr;
    }

    function push(uint i) public {
        // Append to array
        // This will increase the array length by 1.
        arr.push(i);
    }

    function pop() public {
        // Remove last element from array
        // This will decrease the array length by 1
        arr.pop();
    }

    function getLength() public view returns (uint) {
        return arr.length;
    }

    function remove(uint index) public {
        // Delete does not change the array length.
        // It resets the value at index to it's default value,
        // in this case 0
        delete arr[index];
    }

    function examples() external {
        // create array in memory, only fixed size can be created
        uint[] memory a = new uint[](5);
    }
}

‍

2.3. 구조체(Struct)

구조체 프로그래머가 다양한 형식의 여러 변수를 하나의 이름으로 묶어 쉽게 사용할 수 있도록 선언하는 데이터 형식입니다. 컨트랙트.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Todos {
    struct Todo {
        string text;
        bool completed;
    }

    // An array of 'Todo' structs
    Todo[] public todos;

    function create(string calldata _text) public {
        // 3 ways to initialize a struct
        // - calling it like a function
        todos.push(Todo(_text, false));

        // key value mapping
        todos.push(Todo({text: _text, completed: false}));

        // initialize an empty struct and then update it
        Todo memory todo;
        todo.text = _text;
        // todo.completed initialized to false

        todos.push(todo);
    }

    // Solidity automatically created a getter for 'todos' so
    // you don't actually need this function.
    function get(uint _index) public view returns (string memory text, bool completed) {
        Todo storage todo = todos[_index];
        return (todo.text, todo.completed);
    }

    // update text
    function updateText(uint _index, string calldata _text) public {
        Todo storage todo = todos[_index];
        todo.text = _text;
    }

    // update completed
    function toggleCompleted(uint _index) public {
        Todo storage todo = todos[_index];
        todo.completed = !todo.completed;
    }
}

3. 매핑 타입

매핑

매핑 을 생성하는 데 사용할 수 있습니다. 해시맵 (유사한 개념: 딕셔너리 내부 파이썬의) 사이의 타입 다른 타입.

‍

참고:
생성할 때 매핑, 모든 키 동시에 존재합니다. 즉:
예를 들어 생성하는 경우 mapping(address => uint256) addressToValue;. 아직 설정하지 않은 경우 키 및 값 그렇다면 입력하신 address 의 기본값이 반환됩니다. uint256 이는 0입니다.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Mapping {
    // Mapping from address to uint
    mapping(address => uint) public myMap;

    function get(address _addr) public view returns (uint) {
        // Mapping always returns a value.
        // If the value was never set, it will return the default value.
        return myMap[_addr];
    }

    function set(address _addr, uint _i) public {
        // Update the value at this address
        myMap[_addr] = _i;
    }

    function remove(address _addr) public {
        // Reset the value to the default value.
        delete myMap[_addr];
    }
}

contract NestedMapping {
    // Nested mapping (mapping from address to another mapping)
    mapping(address => mapping(uint => bool)) public nested;

    function get(address _addr1, uint _i) public view returns (bool) {
        // You can get values from a nested mapping
        // even when it is not initialized
        return nested[_addr1][_i];
    }

    function set(address _addr1, uint _i, bool _boo) public {
        nested[_addr1][_i] = _boo;
    }

    function remove(address _addr1, uint _i) public {
        delete nested[_addr1][_i];
    }
}

4. 단순 스토리지

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

contract SimpleStorage {

    // Declare a variable to store the name of the maintainer
    string public maintainerName = "zxstim";
    // Declare the version of the contract
    uint8 public version = 1;
    // Declare an address to receive donation
    address public donationAddress = 0xe3d25540BA6CED36a0ED5ce899b99B5963f43d3F;

    // Declare a Person type to store information of a person
    struct Person {
        string name; // name    
        uint8 age; // age
        bool overEighteen; // Over eighteen?
        address uuid; // UUID
        uint256 assetValue; // asset value
        int256 debtValue; // debt value
    }

    Person[] private listOfPeople; // this syntax means creating an array to store Person named listOfPeople
    
    mapping(address => Person) uuidToPerson; // this syntax means creating a mapping from address to Person named uuidToPerson

    //  this function will store the information of a new person with name, age, overEighteen, assetValue, debtValue
    function storePerson(string memory _name, uint8 _age, bool _overEighteen, uint256 _assetValue, int256 _debtValue) public returns (Person memory person) {
        _assetValue *= 1e18; // Convert asset value to wei unit
        _debtValue *= 1e18; // Convert debt value to wei unit
        // Add information of the new person to the listOfPeople array
        listOfPeople.push(Person({name: _name, age: _age, overEighteen: _overEighteen, uuid: msg.sender, assetValue: _assetValue, debtValue: _debtValue}));
        // Add information of the new person to the uuidToPerson mapping
        uuidToPerson[msg.sender] = Person({name: _name, age: _age, overEighteen: _overEighteen, uuid: msg.sender, assetValue: _assetValue, debtValue: _debtValue});
        return Person({name: _name, age: _age, overEighteen: _overEighteen, uuid: msg.sender, assetValue: _assetValue, debtValue: _debtValue});
    }

    // this function will retrieve the information of a person based on the address
    function retrievePerson(address _address) public view returns (Person memory person) {
        return uuidToPerson[_address];
    }
}