转账

如果在函数中涉及到以太币的转移,需要使用到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);
}
}

本文链接:https://dreamerjonson.com/2018/11/20/solidity-23-payable/

版权声明:本博客所有文章除特别声明外,均采用CC BY 4.0 CN协议许可协议。转载请注明出处!