Programming Language/Solidity

Solidity - Calling Parent Contracts

Yongari 2023. 1. 4. 22:22

Calling Parent Contracts
부모 계약 호출 

Parent contracts can be called directly, or by using the keyword super.
부모 계약은 직접 호출하거나, super라는 키워드를 사용하여 호출할 수 있습니다.

By using the keyword super, all of the immediate parent contracts will be called.
슈퍼라는 키워드를 사용함으로써, 즉각적으로 부모 계약이 호출될 것이다.

 

 

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

/* Inheritance tree
   A
 /  \
B   C
 \ /
  D
*/

contract A {
    // This is called an event. You can emit events from your function
    // and they are logged into the transaction log.
    // In our case, this will be useful for tracing function calls.
    // 이것을 이벤트라고 합니다. 기능에서 이벤트를 내보낼 수 있습니다
    // 트랜잭션 로그에 기록됩니다.
    // 우리의 경우, 이것은 함수 호출을 추적하는 데 유용할 것이다.
    event Log(string message);

    function foo() public virtual {
        emit Log("A.foo called");
    }

    function bar() public virtual {
        emit Log("A.bar called");
    }
}

contract B is A {
    function foo() public virtual override {
        emit Log("B.foo called");
        A.foo();
    }

    function bar() public virtual override {
        emit Log("B.bar called");
        super.bar();
    }
}

contract C is A {
    function foo() public virtual override {
        emit Log("C.foo called");
        A.foo();
    }

    function bar() public virtual override {
        emit Log("C.bar called");
        super.bar();
    }
}

contract D is B, C {
    // Try:
    // - Call D.foo and check the transaction logs.
    //   Although D inherits A, B and C, it only called C and then A.
    // - Call D.bar and check the transaction logs
    //   D called C, then B, and finally A.
    //   Although super was called twice (by B and C) it only called A once.
	// try:
    // - D.foo에 call하여 거래 로그를 확인합니다.
    //   D는 A, B, C를 상속받지만 C와 A만 호출한다.
    // - D.bar으로 call 하여 거래 로그 확인
    //   D는 C, B, 그리고 마지막으로 A를 불렀다.
    //   super는 (B와 C에 의해) 두 번 호출되었지만, A는 한 번만 호출되었다.

    function foo() public override(B, C) {
        super.foo();
    }

    function bar() public override(B, C) {
        super.bar();
    }
}

Try on Remix

 

Remix - Ethereum IDE

 

remix.ethereum.org