[Solidity] 코드 구조

Alexandria·2024년 3월 4일

Solidity

목록 보기
4/11
post-thumbnail

1. 라이선스

소스 파일 내 최상단

SPDX-License-Identifier 라는 문자열로 시작하며 주석으로 달아준다.

// SPDX-License-Identifier: MIT

2. Pragma

pramga 라는 키워드로 시작하며 solidity의 버전을 명시한다.

특정 버전으로 컴파일을 하고자 한다면 "^"을 이용한다.

pragma solidity ^0.8.7;

다양한 버전을 지원하고자 한다면 비교 연산자를 이용한다.

pragma solidity >=0.4.0 <0.6.0;

3. Import

외부 소스를 불러올 필요가 존재할 수 있다.

이때, import 키워드를 이용한다.

import "path/to/HelloWorld.sol"

이름이 같을 경우 명칭을 변경하여 불러올 수 있다.

import "Hello/HelloWorld.sol" as hello;
import "World/HelloWorld.sol" as world;

contract TestContract {
    hello.HelloWorld Hello;
    world.HelloWorld World;
    
    function setHelloAddress(address _address) public {
        Hello = hello.HelloWorld(_address); // hello의 주소
    }

    function setWorldAddress(address _address) public {
        World = world.HelloWorld(_address); // world의 주소
    }

    function test1() public view returns (string memory) {
        return string(abi.encodePacked(Hello.myVariable(), World.myVariable()));
    }
}

4. Smart Contract

클래스를 사용하는 것과 같이 변수, 생성자, 함수 등을 선언할 수 있다.

contract HelloWorld {
    uint private _myVariable;

    constructor() {
        _myVariable = 99;
    }

    function setVariable(uint x) public {
        _myVariable = x;
    }

    function getVariable() public view returns (uint) {
        return _myVariable;
    }
}

5. 주석

한 줄 주석은 "//"을 사용하며 여러 줄의 경우 "/* */"를 이용한다.

contract HelloWorld {
    // 한줄 주석입니다.
    uint private _myVariable;

    /*
    여러줄의 주석은 이렇게 작성할 수 있습니다.
    */
    function getVariable() public view returns (uint) {
        return _myVariable;
    }
}

5.1. Doxygen

Doxygen 형식의 주석을 사용할 때, 한 줄 주석은 "///"을 사용하며

여러 줄의 경우 "/** */"를 이용한다.

/** @title 테스트용 컨트랙트
  * @author 2jinu
  * @notice doxygen 설명을 위한 테스트 코드입니다.
  */
contract HelloWorld {
    /// getVariable에 사용되는 변수입니다.
    uint private _myVariable;

    /** @dev myVariable에 인자를 더한 값을 반환하는 함수입니다.
      * @param x 더할 인자 값입니다.
      * @return sum 더해진 결과입니다.
      */
    function getVariable(uint x) public view returns (uint sum) {
        return _myVariable + x;
    }
}
profile
IT 도서관

0개의 댓글