035. Getting started with Solidity——22 payable

The payable keyword is used to declare that a function or contract can receive the transfer of tokens. When the payable keyword is used in a function declaration, the function can be called by the caller with a certain amount of tokens to perform some special operations.

Sample code:


contract MyContract {
    
    // 定义一个 payable 函数,接收转账
    function myPayableFunction() public payable {
        // 在函数体内进行一些操作,例如修改数据等
    }
    
    // 定义一个函数,将代币转账到指定的地址
    function sendEther(address payable _to) public payable {
        // 检查合约余额是否充足,以及传入的 _to 地址是否有效
        require(address(this).balance >= msg.value && _to != address(0));
        // 将代币转账到指定地址
        _to.transfer(msg.value);
    }
}

Note:

myPayableFunction: The payable keyword is used in the declaration , indicating that the function can receive token transfers. The operations within the function body can be modified according to actual needs.

sendEther: The address payable type in the function represents the address that can receive tokens. require statement to ensure that the contract balance is sufficient and the incoming _to address is valid. After the conditions are met, the transfer function is used to transfer the token to the specified address.

Using the payable function will affect the gas cost of the contract. When an external account calls a payable function, gas fees need to be paid to execute the function. If there is insufficient gas charge, the function will not execute. Within the contract, tokens cannot be sent directly to ordinary addresses (addresses that do not have the ability to receive tokens), otherwise the transfer will fail and gas fees will be consumed. If you need to send tokens to a normal address, you can use the selfdestruct function.

Supongo que te gusta

Origin blog.csdn.net/qq_35369459/article/details/129103393
Recomendado
Clasificación