🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 回退函数(fallback function) 每一个合约有且仅有一个没有名字的函数。这个函数无参数,也无返回值。如果调用合约时,没有匹配上任何一个函数(或者没有传哪怕一点数据),就会调用默认的回退函数。 此外,当合约收到`ether`时(没有任何其它数据),这个函数也会被执行。在此时,一般仅有少量的gas剩余,用于执行这个函数(准确的说,还剩2300gas)。所以应该尽量保证回退函数使用少的gas。 下述提供给回退函数可执行的操作会比常规的花费得多一点。 - 写入到存储(storage) - 创建一个合约 - 执行一个外部(external)函数调用,会花费非常多的gas - 发送`ether` 请在部署合约到网络前,保证透彻的测试你的回退函数,来保证函数执行的花费控制在2300gas以内。 一个没有定义一个回退函数的合约。如果接收ether,会触发异常,并返还ether(solidity v0.4.0开始)。所以合约要接收ether,必须实现回退函数。下面来看个例子: ``` pragma solidity ^0.4.0; contract Test { // This function is called for all messages sent to // this contract (there is no other function). // Sending Ether to this contract will cause an exception, // because the fallback function does not have the "payable" // modifier. function() { x = 1; } uint x; } // This contract keeps all Ether sent to it with no way // to get it back. contract Sink { function() payable { } } contract Caller { function callTest(Test test) { test.call(0xabcdef01); // hash does not exist // results in test.x becoming == 1. // The following call will fail, reject the // Ether and return false: test.send(2 ether); } } ``` 在浏览器中跑的话,记得要先存ether。