Solidity 문법 - (23) msg.balance (사용자 잔액)

2023. 6. 4. 16:07BlockChain/Solidity 깨부수기 ( 유투브 강의 )

목차
1.msg.balance
2. msg.balance 예제코드

 

1. msg.balance

 

솔리디티에서 제공하는 msg의 속성 balance에 대해서 알아보자.

 

솔리디티에서는 다양한 변수 및 함수를 제공하는데 아래의 포스팅에 목록이 있으며, 공식문서에서도 확인이 가능하다.

 

https://char1ey.tistory.com/152

 

Ethereum - Solidity의 단위, 변수 및 함수

솔리디티 문서를 참고해서 작성하였다. https://solidity-kr.readthedocs.io/ko/latest/units-and-global-variables.html#id5 단위 및 전역 변수 — Solidity 0.5.10 documentation 이더 단위 Ether를 더 작은 단위로 변환하기 위해

char1ey.tistory.com

 

msg.balance를 사용하면 스마트 컨트랙트 사용자의 잔액을 확인할 수 있다.

 

이를 통해서 다양한 예외처리 코드를 작성할 수 있다.

 

예를 들어, 사용자의 잔액이 10 이더인데 20 이더를 보내는 일이 발생하지 않도록 해야할 경우 이를 이용한다.

 

msg.balance는 msg의 속성이므로 msg.balance라고 적어주면 손쉽게 값을 알 수 있다.

msg.balance = 스마트 컨트랙트 사용자의 잔액

 

 

 

2. msg.balance 예제 코드

 

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

contract ExConstructPayable {
    address owner;
    constructor() payable {
        owner = msg.sender;
    }

    event SendInfo(address _msgSender, uint256 _currentValue);
    event MyCurrentValue(address _msgSender, uint256 _value);
    event CurrentValueOfSomeone(address _msgSender, address _to, uint256 _value);

    function sendEther(address payable _to) public payable {
        require(msg.sender == owner, "Only Owner!");
        require(msg.sender.balance >= msg.value, "Your balance is not enough");
        _to.transfer(msg.value);
        emit SendInfo(msg.sender, (msg.sender).balance);
    }

    function checkValueNow() public {
        emit MyCurrentValue(msg.sender, msg.sender.balance);
    }

    function checkUserMoney(address _to) public {
        emit CurrentValueOfSomeone(msg.sender, _to, _to.balance);
    }
}

 

위의 컨트랙트에서는 balance 조회 뿐만 아니라 특정 사용자에게 권한을 주는 코드도 포함되어있다.

 

owner 변수에는 배포를 진행한 EOA 계정이 들어가게된다.

 

 

아래의 코드는 약 120 이더를 가진 계정에서 balance를 출력했을 때 결과를 볼 수 있다.