-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfallback-functions-practice
More file actions
95 lines (61 loc) · 2.63 KB
/
fallback-functions-practice
File metadata and controls
95 lines (61 loc) · 2.63 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
pragma solidity ^0.8.2;
/* Describe Fallback functions
- cannot have a name (anonymous)
- does not take any inputs
- does not return any outputs
- must be declared as external
*/
contract FallBack {
event Log(uint gas);
fallback () external payable {
// not recommended to write much code in here - because the function will fail if it uses too much gas
// invoke the send and transfer methods: we get 2300 gas which is enough to emit a log
// invoke the call method: we get all the gas
// special solidity function gasleft returns how much gas is left
emit Log(gasleft());
}
function getBalance() public view returns(uint) {
// return the stored balance of the contract
return address(this).balance;
}
}
// new contract will send ether to Fallback contract which will triggger fallback functions
contract SendToFallBack {
function transferToFallBack(address payable _to) public payable {
// send ether with the transfer method
// automatically transfer will transfer 2300 gas amount
_to.transfer(msg.value);
}
function callFallBack(address payable _to) public payable {
// send ether with the call method
(bool sent,) = _to.call{value:msg.value}('');
require(sent, 'Failed to send!');
}
}
// Exercise is to understand these contracts and write it out and explain the logic event Log(uint gas);
fallback () external payable {
// not recommended to write much code in here - because the function will fail if it uses too much gas
// invoke the send and transfer methods: we get 2300 gas which is enough to emit a log
// invoke the call method: we get all the gas
// special solidity function gasleft returns how much gas is left
emit Log(gasleft());
}
function getBalance() public view returns(uint) {
// return the stored balance of the contract
return address(this).balance;
}
}
// new contract will send ether to Fallback contract which will triggger fallback functions
contract SendToFallBack {
function transferToFallBack(address payable _to) public payable {
// send ether with the transfer method
// automatically transfer will transfer 2300 gas amount
_to.transfer(msg.value);
}
function callFallBack(address payable _to) public payable {
// send ether with the call method
(bool sent,) = _to.call{value:msg.value}('');
require(sent, 'Failed to send!');
}
}
}