Skip to content

Instantly share code, notes, and snippets.

@vietlq
Forked from tomw1808/send_transfer_call.sol
Created March 9, 2018 10:56
Show Gist options
  • Save vietlq/6d235b71307bc4da6e4e0e2c7434bf32 to your computer and use it in GitHub Desktop.
Save vietlq/6d235b71307bc4da6e4e0e2c7434bf32 to your computer and use it in GitHub Desktop.
This is an example of the difference between "address.send()", "address.call.value()()" and "address.transfer()" in Solidity. If you like this example, then checkout my courses I do on Udemy (https://vomtom.at/tag/course/)
pragma solidity ^0.4.13;
contract someContract {
mapping(address => uint) balances;
function deposit() payable {
balances[msg.sender] += msg.value;
}
function withdrawVeryBad1(uint amount) {
if(balances[msg.sender] >= amount) {
msg.sender.send(amount);
balances[msg.sender] -= amount;
}
}
function withdrawVeryVeryBad2(uint amount) {
if(balances[msg.sender] >= amount) {
msg.sender.call.gas(2500000).value(amount)();
balances[msg.sender] -= amount;
}
}
function withdrawVeryVeryBad3(uint amount) {
if(balances[msg.sender] >= amount) {
if(msg.sender.call.gas(2500000).value(amount)()) {
balances[msg.sender] -= amount;
}
}
}
function withdrawBad1(uint amount) {
if(balances[msg.sender] >= amount) {
if(msg.sender.send(amount)) {
balances[msg.sender] -= amount;
}
}
}
function withdrawOkayish(uint amount) {
if(balances[msg.sender] >= amount) {
balances[msg.sender] -= amount;
if(!msg.sender.send(amount)) {
throw;
}
}
}
function withdrawBad2(uint amount) {
if(balances[msg.sender] >= amount) {
balances[msg.sender] -= amount;
if(!msg.sender.call.gas(2500000).value(amount)()) {
throw;
}
}
}
//OKAY FUNCTIONS
function withdrawOK(uint amount) {
if(balances[msg.sender] >= amount) {
balances[msg.sender] -= amount;
msg.sender.transfer(amount);
}
}
//New Exception handling
function withdrawGood(uint amount) {
require(balances[msg.sender] >= amount);
balances[msg.sender] -= amount;
msg.sender.transfer(amount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment