튼튼한 기초

개발자 여러분 안녕하세요.👋
본문에서 우리는 견고한 기초 지식을 배울 것이다.Solidity는 새로운 고급 프로그래밍 언어로 이더리움 블록체인에서 스마트 계약을 실시하는 데 전문적으로 사용된다.

카탈로그


  • Features of Solidity
  • Access Modifiers
  • memory vs storage
  • Basic Types
  • Variables
  • Data Structures
  • Conditionals and Loops
  • Functions
  • Error handling
  • Inheritance
  • 견고성 특징

  • C++나 자바와 같은 대상 프로그래밍 언어.
  • Typescript와 같은 정적 유형 언어는 개발 과정의 초기 단계에서 버그를 포획하는 데 도움이 된다.
  • Javascript, Python, C++ 등 다른 프로그래밍 언어의 영향을 많이 받았다.
  • 은 계약 상속을 지원하고 이더리움 가상 기기(EVM)에서 운행한다.

  • 액세스 수정 함수


    There are four basic access modifiers used by variables and functions

  • Public: 변수와 함수의 값은 계약, 하위 계약과 외부 함수에 접근할 수 있습니다.
  • contract MyContract {
        uint256 public myPublicVar;
        function getVar() public view returns(uint) { 
            return myPublicVar;
        }
    }
    
  • 외부: 외부 함수에서만 변수와 함수의 값에 접근할 수 있습니다.
  • contract MyContract {
        uint256 external externalVar; 
        function getVar() external view returns(uint) { 
            return externalVar;
        }
    }
    
  • 내부: 변수와 함수의 값은 계약과 하위 계약에서 접근할 수 있다.
  • contract MyContract  {
        uint256 internal internalVar; 
        function getVar() internal view returns(uint) { 
            return internalVar;
        }
    }
    
  • Private: 변수와 함수의 값은 동일한 계약에서만 액세스할 수 있습니다.
  • contract MyContract { 
        uint256 private privateVar; 
        function getVar() private view returns(uint) { 
            return privateVar;
        }
    }
    

    메모리 및 스토리지


    우리는 메모리를 램으로, 메모리를 하드디스크로 볼 수 있다.메모리 변수에 저장된 모든 값은 임시적이며 실행이 중지되면 지워지고 저장 변수의 값은 블록체인에 영구적으로 저장되며 새로 실행된 후에도 변수는 이전에 저장된 값을 가지게 됩니다.계약이 체결된 후 스토리지 구조는 영원히 바꿀 수 없지만 그 가치는 바꿀 수 있다.

  • 메모리가 소모되는 기체는 상대적으로 적다.

  • 메모리는 방법에서만 사용할 수 있고 계약 단계(상태 변수)에서는 사용할 수 없습니다.
  • memory 키워드를 사용하지 않으면 Solidity에서 메모리에 변수를 설명하려고 시도합니다.

  • 메모리는 변수의 새 복사본을 만들고 저장은 같은 위치를 가리키며 원시 변수의 값을 변경할 수 있습니다.
  • Example

    pragma solidity >=0.8.7;
    
    // Creating a contract
    contract MemoryContract
    { 
        // state variable (always in storage)
        uint[] public numbers;
    
        function addNumbers() public  {
            numbers.push(1);
            numbers.push(2);  
            // numbers = [1, 2]
    
            //1. Creating a new memory instance 
            uint[] memory myMemoryNumbers = numbers;
            myMemoryNumbers[0] = 10;
            // myMemoryNumber = [10, 2]
            // numbers = [1, 2]  
    
    
            //2. Creating a new storage instance
            uint[] storage myStorageNumbers = numbers;
            myStorageNumbers[0] = 10;
            // myStorageNumbers = [10, 2]
            // numbers = [10, 2] 
        } 
    }
    
    

    기본 유형


    Example

    // specify the version of solidity
    pragma solidity >=0.8.7;   
    
    // Creating a contract
    contract BasicTypes {   
    
        // Boolean value
        bool public myBoolean = false;
    
        // Integer variable
        int32 public myInt = -60313;
        // unsigned Integer
        uint public myUInt = 60313; // alias for uint256
    
        // String variable
        string public myStr = "Saurabh";
        // Byte string (uses less gas)
        bytes32 public myByteString = "Bomble";
    
        // Byte variable
        bytes1 public b = "a";
    
        // Defining an enumerator
        enum myEnum { ACCEPTED, PENDING, REJECTED }  
    }
    

    변량


    구문


    <type> <access modifier> <variable name>; 
    

    변수 유형

  • 상태 변수 - 이러한 변수는 블록체인 계약 저장소에 영구적으로 저장되는 변수이다.
  • 국부 변수 - 이러한 변수는 블록체인에 저장되지 않고 하나의 역할 영역(예를 들어 함수)에 만들어져 업무 논리를 작성하는 데 도움을 준다.
  • 전역 변수 - 전역 명칭 공간에 존재하며 계약의 어느 곳에서든 호출할 수 있다.글로벌 변수에는 다양한 거래 및 블록체인 속성에 대한 정보가 포함됩니다.예를 들어 Block, msg 및 tx
  • Example

    pragma solidity >=0.8.7;
    
    contract VariableType {
        // State variables => stored on blockchain  
        uint myUint = 1;  
        //160-bit ethereum address 
        address public myAddress = 0xE9Bc4d002161aA50E15728ba19aDC3aA34a91D98; 
    
        constructor() {
            // msg is global variable
            myAddress = msg.sender  // address of user who deployed the contract
        }
    
        function getValue() public pure returns(uint) {
            myAddress = msg.sender  // address of current caller
            uint value = 1; // local variable
            return value;
        }
    }
    

    데이터 구조

  • 수조 - 우리는 한 수조에 같은 유형의 원소 집합을 저장할 수 있다.우리는 수조에서 원소를 접근하고, 전송하고, 팝업할 수 있으며, 수조의 길이를 계산할 수 있다.엔티티 배열의 인덱스는 0입니다.
  • Struct-Struct를 사용하면 사용자가 정의한 데이터 유형을 만들 수 있습니다.
  • 맵 - C++의 무질서한 맵이나python의 사전처럼 튼튼한 맵입니다.키 값 쌍을 저장하는 데 사용됩니다.여기서 키는 사용자가 정의한 형식을 포함하여 모든 내장 데이터 형식이 될 수 있습니다.
  • Example

    pragma solidity >=0.8.7;
    
    contract DataStructure {
        // Array
        uint[] public myIntArray = [1, 2, 3];
        string[] public myStringArray = ["apple", "banana"];
        uint[][] public array2D = [ [1,2,3], [4,5,6] ];
    
        function addValue(string memory _value) public {
            myStringArray.push(_value);
        }
    
        function valueCount() public view returns(uint) {
            return myStringArray.length;
        } 
    
        // Mapping (key-value store)
        mapping(uint => string) public names;
    
        constructor() {
            names[1] = "Saurabh";
            names[2] = "John";
            names[3] = "Doe"; 
        }
    
        struct Book {
            string title;
            string author;
        }
    
    
        mapping(uint => Book) books; // key = id of book(unit), value = Book
        // Nested mapping
        mapping(address => mapping(uint => Book)) public myBooks; 
    
        function addBook(uint _id, string memory _title, string memory _author) public {
            books[_id] = Book(_title, _author);
        }
    
        function getBook(uint _id) public view returns(string memory, string memory){
            string memory _title = books[_id].title;
            string memory _author = books[_id].author; 
            return (_title, _author);
        }
    
        function addMyBook(uint _id, string memory _title, string memory _author) public {
            myBooks[msg.sender][_id] = Book(_title, _author);
        } 
    }
    

    조건문과 순환

  • 조건문-조건문은if-else,삼원연산자
  • 포함
  • For 루프 - c++ 루프와 유사합니다.세개의 번호로 구분된 매개 변수를 받아들이다.위즈.초기화, 조건, 교체.
  • While loop - 조건이 진실이면 한 문장이나 문장 블록을 반복해서 실행하고 조건이 가짜가 되면 순환이 종료됩니다.
  • Do while - while 순환과 유사하지만 조건 검사는 순환
  • 의 말미에 발생한다
    Example

    pragma solidity >=0.8.7;
    
    contract ConditionalsLoops {
        // Loop
        uint[] public numbers = [1,2,3,4,5];
        address public owner;
    
        constructor() {
            owner = msg.sender;
        }
    
        function countEven() public view returns(uint count) {
            count = 0;
            for(uint i = 0; i < numbers.length; i++) {
                count += isEven(numbers[i]) ? 1 : 0;
            } 
        }
    
        // Conditionals (just like js)
        function isEven(uint _value) public pure returns(bool) {
            return _value % 2 == 0; 
        }
    
        function isOwner() public view returns(bool) {
            if(msg.sender == owner) return true;
            return false;
        }
    }
    

    기능

  • 함수 보기 - 이 함수는 상태 변수만 읽을 수 있습니다.
  • 순수 함수 - 이 함수는 읽거나 상태 변수를 수정할 수 없습니다.
  • returns(type) - 함수의 반환 형식을 나타낸다.
  • Example

    pragma solidity >=0.8.7;
    
    contract FunctionContract {  
        uint myUint = 1;
    
        function getValue() public pure returns(uint) {
            uint value = 1; 
            return value;
        }
    
        function getMyUint() public view returns(uint) { 
            return myUint;
        }
    }
    

    오류 처리

  • revert(문자열 메모리 메시지) - 상태 변경 사항의 실행을 중지하고 복원합니다.메시지를 반환합니다.
  • Example

    if(currentStatus == Status.VACANT) {
         revert("Currently occupied");
    } 
    
  • 필요(부울 조건, 문자열 저장 메시지)− 조건이 충족되지 않으면, 이 방법은 원본 상태로 복원되고, 사용자 정의 메시지를 던집니다.
  • Example

    require(currentStatus == Status.VACANT, "Currently occupied");
    

    상속권


    계승은 대상을 대상으로 프로그래밍하는 언어의 가장 중요한 특성 중의 하나다.그것은 코드를 신축성, 중용성, 조직성을 가지게 한다.부계약을 기본계약이라고 하고, 기본계약 상속 방법과 속성의 계약을 파생계약이라고 한다.
  • 파생 계약은 기초 계약의 모든 공공과 내부 기능에 접근할 수 있다.
  • 함수 서명이 변하지 않으면 함수를 다시 쓸 수 있습니다.
  • 서브계약 중의 슈퍼 키워드는 부계약의 구조 함수를 호출하는 데 도움이 된다.
  • 계약은 is 키워드를 사용하여 다른 계약을 계승할 수 있다.
  • 하위 계약이 덮어쓰는 함수는 가상으로 성명해야 한다.
  • pragma solidity >=0.8.7; 
    
    contract BaseContract {  
        uint public a;   
        uint public b;    
    
        // Wrong defination to be corrected in derived 
        function getDiff() public view virtual returns(uint) {
            return(a*b);
        }
    } 
    
    // Defining child contract 
    contract DerivedContract is BaseContract{   
        constructor(uint _a, uint _b) {
            a = _a;
            b = _b;
            super;
        }
    
        // Correct defination with same signature
        function getDiff() public view virtual override returns(uint) {
            return(a-b);
        }
    } 
    
    // Defining calling contract
    contract CallerContract {
        DerivedContract derivedContract;
        constructor(uint _val1, uint _val2) {
            derivedContract = new DerivedContract(_val1, _val2); 
        }
    
        function getDiffAandB() public view returns(uint) { 
            return derivedContract.getDiff();
        }
    }
    

    결론


    읽어주셔서 감사합니다.🙏. 이 장은 여기까지입니다.우리는solidity의 대부분 기본 개념을 배워서 스마트 계약을 작성하기 시작했다.
    dev.to에서 따라오세요.
  • 곧 발표될 블록체인 기술에 관한 글입니다.
  • 웹 개발(React.js+Nest.js)
  • 응용 프로그램 개발(떨림, 반응 원생)
  • 좋은 웹페이지 즐겨찾기