본문 바로가기

Ethereum

솔리디티 문법 2

Solidity v0.8.14 기준 문법

Solidity 컨트랙트 상속

// SPDX-License-Identifier:GPL-30
// Constructor가 없는 컨트랙트
pragma solidity >= 0.7.0 < 0.9.0;

contract Father{
    string public familyName = "Kim";
    string public givenName = "Jung";
    uint256 public money = 100; 
    
    function getFamilyName() view public  returns(string memory){
        return familyName;
    } 
    
    function getGivenName() view public  returns(string memory){
        return givenName;
    } 
    
    function getMoney() view public returns(uint256){
        return money;
    }
    

}

contract Son is Father{
    
}
// SPDX-License-Identifier:GPL-30
// Constructor가 있는 컨트랙트
pragma solidity >= 0.7.0 < 0.9.0;

contract Father{
    string public familyName = "Kim";
    string public givenName = "Jung";
    uint256 public money = 100; 
    
    constructor(string memory _givenName) public {
        givenName = _givenName;
    }
    
    
    function getFamilyName() view public  returns(string memory){
        return familyName;
    } 
    
    function getGivenName() view public  returns(string memory){
        return givenName;
    } 
    
    function getMoney() view public returns(uint256){
        return money;
    }
    

}

contract Son is Father("James"){

}

 

 

Solidity overriding (오버라이딩)

// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;

contract Father{
    
    string public familyName = "Kim";
    string public givenName = "Jung";
    uint256 public money = 100; 
    
    constructor(string memory _givenName) public {
        givenName = _givenName;
    }
    
    
    function getFamilyName() view public  returns(string memory){
        return familyName;
    } 
    
    function getGivenName() view public  returns(string memory){
        return givenName;
    } 
    
    function getMoney() view  public virtual returns(uint256){
        return money;
    }
    
    
}

contract Son is Father("James"){
    
    
    uint256 public earning = 0;
    function work() public {
        earning += 100;
    }
    
     function getMoney() view  public override returns(uint256){
        return money+earning;
    }

}

위의 예제에서 getMoney() 함수를 오버라이딩하기 위해서 오버라이딩할 함수에 virtual을 명시해주어야 한다. 상속받은 Son 컨트랙트는 오버라이딩한 getMoney() 함수에 override를 명시해 주어야 한다.

 

// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;


contract Father{
    uint256 public fatherMoney = 100;
    function getFatherName() public pure returns(string memory){
        return "KimJung";
    }
    
    function getMoney() public view virtual returns(uint256){
        return fatherMoney;
    }
    
}

contract Mother{
    uint256 public motherMoney = 500;
    function getMotherName() public  pure returns(string memory){
        return "Leesol";
    }
    function getMoney() public view virtual returns(uint256){
        return motherMoney;
    }
}


contract Son is Father, Mother {

    function getMoney() public view override(Father,Mother) returns(uint256){
        return fatherMoney+motherMoney;
    }
}

다중 상속일 경우 오버라이딩할시 오버라이딩을 하는 컨트랙트 명을 명시해줘야 한다.

 

Solidity Event

event라는 것은 블록체인 네트워크의 블록에 특정값을 기록하는 것을 말한다. 예를들어 누군가 송금을 한다면 송금한 살마의 계좌와 금액이 이벤트로 출력이 되어서 블록체인 네트워크 안에 기록이 된다.

 

// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0 <0.9.0;

contract lec13 {
   
    event info(string name, uint256 money);
    
    function sendMoney() public {
        emit info("KimDaeJin", 1000);
    }
}

sendMoney 함수를 보면 emit을 통해서 이벤트를 출력한다. 

 

event 를 생성할때 파라미터에 indexed 라는 키워드를 입력하게되면 나중에 event를 쿼리할때 indexed된 특정 값만 쿼리할 수 있다. 즉 indexed를 써줌으로써 블록들안에 출력된 이벤트들을 필터하여 원하는 이벤트만을 가지고 올 수 잇다.

// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0 <0.9.0;

contract Lec14 {
    event numberTracker(uint256 indexed num, string str);

    uint256 num =0;
    function PushEvent(string memory _str) public {
        emit numberTracker(num,_str);
        num ++;
    }
}

 

Solidity에서의 super 메소드는 부모 컨트랙트의 함수를 들고 올 수 있다.

// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;

contract Father {
    event FatherName(string name);
    function who() public virtual{
        emit FatherName("KimDaeho");
    }
}

contract Mother {
    event MotherName(string name);
    function who() public virtual{
        emit MotherName("leeSol");
    }
}

contract Son is Father{
    event sonName(string name);
    function who() public override{
        super.who();
        emit sonName("KimJin");
    }
}

 

Solidity mapping

// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;

contract lec17{
    mapping(uint256=>uint256) private ageList;
    
    
    function setAgeList(uint256 _index,uint256 _age) public {
        ageList[_index] = _age;
    }
    
    function getAge(uint256 _index) public view returns(uint256){
        return ageList[_index];
    }
  
    
}

Solidity에서 mapping은 파이썬의 dictionary 형태와 비슷한 해시 테이블 변수이다. mapping의 키 밸류 쌍도 타입을 지정해줘야 한다.

// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;


contract lec17 {
    mapping(string=>uint256) private priceList;
    mapping(uint256=>string) private nameList;
    mapping(uint256=>uint256) private ageList;
    
    
    function setAgeList(uint256 _key,uint256 _age) public {
        ageList[_key] = _age;
    }
    
    function getAge(uint256 _key) public view returns(uint256){
        return ageList[_key];
    }
    
    function setNameList(uint256 _key,string memory _name) public {
        nameList[_key] = _name;
    }
    
    function getName(uint256 _key) public view returns(string memory){
        return nameList[_key];
    }
    
    function setPriceList(string memory _itemName,uint256 _price) public {
        priceList[_itemName] = _price;
    }
    
    function getPriceList(string memory _key) public view returns(uint256){
        return priceList[_key];
    }
    
}

 

Solidity Array

The type of an array of fixed size k and element type T is written as T[k], and an array of dynamic size as T[ ].

 

An array of 5 dynamic arrays of uint is written as uint[ ][5].

 

In Solidity, X[3] is always an array containing three elements of type X, even if X is itself an array.

 

Variables of type bytes and string are special arrays.

 

length:

Arrays have a length member that contains their number of elements. The length of memory arrays is fixed (but dynamic, i.e. it can depend on runtime parameters) once they are created.

 

push():

Dynamic storage arrays and bytes (not string) have a member function called push() that you can use to append a zero-initialised element at the end of the array. It returns a reference to the element, so that it can be used like x.push().t = 2 or x.push() = b.

 

push(x):

Dynamic storage arrays and bytes (not string) have a member function called push(x) that you can use to append a given element at the end of the array. The function returns nothing.

 

pop():

Dynamic storage arrays and bytes (not string) have a member function called pop() that you can use to remove an element from the end of the array. This also implicitly calls delete on the removed element. The function returns nothing.

// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;
 
contract lec18{
    
    
    uint256[] public ageArray;
    uint256[10] public ageFixedSizeArray;
    string[] public nameArray= ["Kal","Jhon","Kerri"];
  
    function AgeLength()public view returns(uint256) {
        return ageArray.length;
    }
    
    function AgePush(uint256 _age)public{
        ageArray.push(_age);
    }
    function AgeChange(uint256 _index, uint256 _age)public{
        ageArray[_index] = _age;
    }
    function AgeGet(uint256 _index)public view returns(uint256){
        return ageArray[_index];
    }
    function AgePop()public {
        ageArray.pop();
    }
    
    function AgePop(uint256 _index)public {
        delete ageArray[_index];
    }


}

 

Solidity Struct

// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;

contract lec20{
    struct Character{
        uint256 age;
        string name;
        string job;
    }
    
    mapping(uint256=>Character) public CharacterMapping;
    Character[] public CharacterArray;
    
    function createCharacter(uint256 _age,string memory _name,string memory _job) pure public returns(Character memory) {
        return Character(_age,_name,_job);
    }
    
    function createChracterMapping(uint256 _key, uint256 _age,string memory _name,string memory _job )  public {
       CharacterMapping[_key] = Character(_age,_name,_job);
    }
    
    function getChracterMapping(uint256 _key)  public view returns(Character memory){
       return CharacterMapping[_key];
    }
    
    function createChracterArray(uint256 _age,string memory _name,string memory _job )  public {
       CharacterArray.push(Character(_age,_name,_job));
    }
    
    function getChracterArray(uint256 _index)  public view returns(Character memory){
       return CharacterMapping[_index];
    }
}

 

Solidity Data Location and Assignment Rules

  1. Variables declared as state variables are always stored within the storage data location.
  2. Varibles declared as function parameters are always stored within the memory data location.
  3. Variables declared within functions, by default, are stored in memory data location.
    • The location for value type variables is memory within a function while the default for a reference type variable is storage. By overriding the default location, reference types variables are often located at the memory data location. The reference types referred are arrays, structs, and strings. Value type variables declared during a function can’t be overridden and can’t be stored at the storage location.
    • Mappings are always declared at the storage location. this suggests that they can’t be declared within a function. they can’t be declared as memory types. However, mappings during a function can ask mappings declared as state variables.
  4. Arguments supplied by callers to function parameters are always stored as calldata data location.
  5. Assignments to state variables from another state variable always create a replacement copy.
  6. Assignments to storage variables from another memory variable always create a replacement copy.
  7. Assignments to memory variable from another state variable always create a replacement copy.
  8. Assignments to a memory variable from another memory variable create a reference.

'Ethereum' 카테고리의 다른 글

솔리디티 Contract 구조  (0) 2022.05.18
이더리움 개발 문서  (0) 2022.05.16