如果在函数中涉及到以太币的转移,需要使用到payable关键词。意味着可以在调用这笔函数的消息中附带以太币。
123 | function pay() public payable{ } |
this 代表当前部署的合约地址
12345 | function getThis() public view returns(address){ return this; // 0x9F4c14f487B8e4E3986467c2a2aA5bDE93052666 //0x9f4c14f487b8e4e3986467c2a2aa5bde93052666 } |
1234 | function getbalance() public view returns(uint){ return address(this).balance; } |
123 | function getExternalBalance(address account) public view returns(uint){ return account.balance; } |
12345678910 | //给外部账户转账function transfer() public payable{ address account = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c; account.transfer(msg.value); }//给合约地址转账 function transfer2() public payable{ address(this).transfer(msg.value);} |
在下面的例子中,如果在调用此函数时,附带了20Ether,那么就会给account账户转移10ether,给合约账户转移10ether
1234 | function transfer3() public payable{ address account = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c; account.transfer(10*10**18);} |
123456789101112131415161718192021222324252627282930313233343536373839404142434445 | 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协议 许可协议。转载请注明出处!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。