티스토리 뷰

블록체인 개발/Solidity

call

투자유v 2022. 1. 2. 00:40
728x90
  • 송금
  • 외부 컨트랙트의 함수 호출
  • 가변 gas(send, transfer는 2300 gas로 고정(가스비 상승으로 트랜잭션 성공 보장 못함))
  • re-entrancy(재진입) 공격의 위험 있음, 따라서 Checks Effects Interactions Pattern 사용
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.11;

contract Adder {
   function add(uint _num1, uint _num2) public pure returns (uint) {
      return _num1 + _num2;
   }

   event received(string _str);
   event fallbacked(string _str);

   receive() external payable {
      emit received("Received");
   }

   fallback() external payable {
      emit fallbacked("Fallbacked");
   }
}

contract Caller {
   // 1. 송금
   function callEther(address payable _CA) public payable {
      (bool _sent, ) = _CA.call{value: msg.value}("");
      require(_sent, "Failed");
   }

   // 2. 외부 컨트랙트 함수 호출
   event calledFunction(bool _success, bytes _output);

   function callFunction(address payable _CA, uint _num1, uint _num2) public payable {
      (bool _sent, bytes memory _output) = _CA.call{value: msg.value}(abi.encodeWithSignature("add(uint, uint)", _num1, _num2));
      require(_sent, "Failed");
      emit calledFunction(_sent, _output);
   }

   // 2-2. 존재하지 않는 함수 호출
   function calledFunction2(address payable _CA) public payable {
      (bool _sent, bytes memory _output) = _CA.call{value: msg.value}(abi.encodeWithSignature("subtract(uint, uint)"));
      require(_sent, "Failed");
      emit calledFunction(_sent, _output);
   }
}

'블록체인 개발 > Solidity' 카테고리의 다른 글

mapping 타입에서 겪었던 에러  (0) 2022.01.02
interface  (0) 2022.01.02
fallback, receive  (0) 2022.01.02
send, transfer, call  (0) 2022.01.02
에러 핸들링(require, revert, assert)  (0) 2022.01.01
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함