solidity智能合约[23]-payable

转账

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

1
2
3
function pay() public payable{

}

this代表合约地址

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

1
2
3
4
5
function  getThis() public view returns(address){
return this;
// 0x9F4c14f487B8e4E3986467c2a2aA5bDE93052666
//0x9f4c14f487b8e4e3986467c2a2aa5bde93052666
}

获取合约账户余额

1
2
3
4
function getbalance() public view returns(uint){

return address(this).balance;
}

获取外部账户余额

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

转账

1
2
3
4
5
6
7
8
9
10
//给外部账户转账
function transfer() public payable{
address account = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c;
account.transfer(msg.value);
}

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

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

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

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

全部代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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);
}
}