[英]How do I see what is tr balance of a smart contract?
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?要从智能合约向智能其他钱包地址发送以太币,solidity 是否有任何特殊功能或仅发送/转移功能有效?
A contract accepting ETH needs to implement either the receive()
or the fallback()
special functions .接受 ETH 的合约需要实现receive()
或fallback()
特殊功能。
Its current balance is returned in property .balance
of address(this)
, so you can wrap it in a function to retrieve the balance.它的当前余额在address(this)
的属性.balance
中返回,因此您可以将其包装在一个函数中以检索余额。
pragma solidity ^0.8;
contract MyContract {
receive() external payable {}
function getBalance() external view returns (uint256) {
return address(this).balance;
}
}
First question answer:第一个问题答案:
contractAddress.balance
要从另一个智能合约检查智能合约的余额,您可以执行contractAddress.balance
web3.eth.getBalance(accounts[0])
要直接在链下检查,您可以直接查询 RPC 节点,或者您可以在连接到提供者(节点)后使用 web3 之类的库来包装此调用: 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):您有多种方法可以将余额从智能合约转移到另一个(我将列出其中的 5 种):
contractAddress.transfer(1 ethers)
例如: contractAddress.transfer(1 ethers)
contractAddress.send(1 ethers)
例如: contractAddress.send(1 ethers)
contractAddress.call{value: msg.value}("");
例如: 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.前 3 种方法要求,如果接收方是智能合约,则需要实现receive()
函数或fallback()
函数,两者都是明确支付的。
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.要知道为什么要检查为什么在以前的网络分叉中添加了访问列表功能。
This two last considerations are really important, because an Smart Contract can receive funds even without implement receive()
or fallback()
functions.最后两个考虑因素非常重要,因为即使没有实现receive()
或fallback()
函数,智能合约也可以接收资金。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.