【转载】solidity智能合约[23]-payable

solidity

#1

转账

如果在函数中涉及到以太币的转移,需要使用到payable关键词。意味着可以在调用这笔函数的消息中附带以太币。

function pay() public payable{

 }

this代表合约地址

this 代表当前部署的合约地址

function  getThis() public view returns(address){
     return this;
     // 0x9F4c14f487B8e4E3986467c2a2aA5bDE93052666
      //0x9f4c14f487b8e4e3986467c2a2aa5bde93052666
 }

获取合约账户余额

function getbalance() public view returns(uint){

     return address(this).balance;
 }

获取外部账户余额

function getExternalBalance(address account) public view returns(uint){
       return account.balance;
   }

转账

//给外部账户转账
function transfer() public payable{
     address account = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c;
     account.transfer(msg.value);
 }

//给合约地址转账
 function transfer2() public payable{
    address(this).transfer(msg.value);
}

给合约地址与外部地址同时转账

在下面的例子中,如果在调用此函数时,附带了20Ether,那么就会给account账户转移10ether,给合约账户转移10ether

function transfer3() public payable{
    address account = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c;
    account.transfer(10*10**18);
}

全部代码

pragma solidity ^0.4.23;


contract  payableTest{

    function pay() public payable{

    }

     function getbalance() public view returns(uint){

        return address(this).balance;
    }

    function  getThis() public view returns(address){
        return this;
        // 0x9F4c14f487B8e4E3986467c2a2aA5bDE93052666
         //0x9f4c14f487b8e4e3986467c2a2aa5bde93052666
    }


    function getExternalBalance(address account) public view returns(uint){
        return account.balance;
    }


    function transfer() public payable{
        address account = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c;
        account.transfer(msg.value);
    }


     function transfer2() public payable{
        address(this).transfer(msg.value);
    }

    function ()  public payable{

    }

    function transfer3() public payable{
        address account = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c;
        account.transfer(10*10**18);
    }
}
  • 本文链接: <https ://dreamerjonson.com/2018/11/20/solidity-23-payable/>