david's daily developer note

[Solidity] 5.Error handling : Assert, Require, Revert 본문

[Blockchain]/develop

[Solidity] 5.Error handling : Assert, Require, Revert

mouse-david 2022. 8. 16. 00:13
728x90

솔리디티에서 에러 핸들링을 위해, revert, require, assert를 사용한다.

Require

솔리디티 함수 Require 키워드를 사용하여 문제가 되는 상황이나, 의도하지 않았던 상황에서 에러를 반환하고 함수가 수행하지 않도록 할 수 있다. Require함수는 특정 조건이 참이 아닌 경우에는 에러를 발생하고 실행을 멈춘다.

pragma solidity >=0.4.22 <0.9.0;

contract MappingExample {
	function _transfer(address sender, address recipient, uint256 amount) internal {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");
        require(_balances[sender] >= amount, "ERC20: Not enough funds.");
        
        //function do somthing
	}
}

예제함수는 sender가 recipient에게 이더리움을 전송하는 함수이다. 해당 함수가 정상적으로 수행되려면 sender와 recipient의 주소가 유효해야하며, (!= address(0)) 이더리움을 전송하려는 sender의 잔액이 충분해야한다. 3가지의 조건이 참인 경우가 아니라면 함수는 에러를 발생하고 아래 코드를 수행하지 않는다.

require는 함수 실행전에 반드시 충족해야하는 조건을 판단할 수 있기 때문에 매우 유용하다.
또한, 잘못된 코드로 실행이 되지 않았기 때문에, 이미 지불된 gas를 환불시켜준다.

Assert

require는 정상적인 코드이지만, 인자나 조건이 잘못되어서 코드를 수행할 수 없는 경우에 사용하지만, assert는 코드 자체에 문제가 있는 경우에 발생된다. 에러는 Panic(uint256) 유형으로 발생되며, 아래는 opcode와 예외 상황이다.

0x00: Used for generic compiler inserted panics.

0x01: If you call assert with an argument that evaluates to false.

0x11: If an arithmetic operation results in underflow or overflow outside of an unchecked { ... } block.

0x12; If you divide or modulo by zero (e.g. 5 / 0 or 23 % 0).

0x21: If you convert a value that is too big or negative into an enum type.

0x22: If you access a storage byte array that is incorrectly encoded.

0x31: If you call .pop() on an empty array.

0x32: If you access an array, bytesN or an array slice at an out-of-bounds or negative index (i.e. x[i] where i >= x.length or i < 0).

0x41: If you allocate too much memory or create an array that is too large.

0x51: If you call a zero-initialized variable of internal function type.

Revert

에러를 직접 발생시킨다.
에러는 선언된 사용자 오류를 수행하거나 에러 문장을 기입하여 발생시킬 수 있다. 마찬가지로 지불된 gas는 환불한다.

pragma solidity ^0.8.4;

contract VendingMachine {
    address owner;
    error Unauthorized();
    function buy(uint amount) public payable {
        if (amount > msg.value / 2 ether)
            revert("Not enough Ether provided.");
        // Alternative way to do it:
        require(
            amount <= msg.value / 2 ether,
            "Not enough Ether provided."
        );
        // Perform the purchase.
    }
    function withdraw() public {
        if (msg.sender != owner)
            revert Unauthorized();

        payable(msg.sender).transfer(address(this).balance);
    }
}

 

728x90

'[Blockchain] > develop' 카테고리의 다른 글

[Solidity] 4.Mapping  (0) 2022.08.15
[Solidity] 3.Event  (0) 2022.08.14
[Solidity] 2.Function  (0) 2022.08.14
[Solidity] 1.Basics & Language description  (0) 2022.08.13