2

If I send some ether to a samrt contract address, what function can I use to check the total balance of the smart contract?

To send ether to smart other wallet address from smart contract, is there any special function in solidity or mere send/transafer function works?

Blockchain Kid
  • 315
  • 2
  • 9

2 Answers2

3

A contract accepting ETH needs to implement either the receive() or the fallback() special functions.

Its current balance is returned in property .balance of address(this), so you can wrap it in a function to retrieve the balance.

pragma solidity ^0.8;

contract MyContract {
    receive() external payable {}

    function getBalance() external view returns (uint256) {
        return address(this).balance;
    }
}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
1

First question answer:

  • To check the balance of an Smart Contract from another Smart contract you can do contractAddress.balance
  • To check directly off-chain you can query an RPC Node directly, or you can use a library like web3 to wrap this call after connecting to a Provider (the Node): web3.eth.getBalance(accounts[0])

Second question answer:

You have multiple ways for transferring balance from a Smart Contract to Another (I'm going to list 5 of them):

  • Using transfer function. Ex: contractAddress.transfer(1 ethers)
  • Using send function. Ex: contractAddress.send(1 ethers)
  • Using call function. Ex: contractAddress.call{value: msg.value}("");

To check the differences among this methods, check this article.

This first 3 approaches required that, if the receiver is an Smart Contract, this needs to implement the receive() function, or the fallback() function, both explicitly payable.

The recommended approach is using call (not transfer or send). To know why check why Access List feature was added in a previous network fork.

  • You can also send balance from one contract to other account by using the SELFDESTRUCT opcode.
  • And also is important to know that you can transfer balance to an Smart Contract before its creation, because Smart Contract addresses are deterministic over the address and the nonce of the deployer.

This two last considerations are really important, because an Smart Contract can receive funds even without implement receive() or fallback() functions.