S23Web3 / Alchemy

In here I put code I struggled with
0 stars 1 forks source link

Withdraw in solidity #1

Open S23Web3 opened 11 months ago

S23Web3 commented 11 months ago

I wanted to withdraw an amount from a smartcontract. I thought I need to use the withdraw function.

eventually I found this

/ SPDX-License-Identifier: MIT pragma solidity ^0.8.20;

contract Contract { address public owner; address public charity;

constructor (address _charity){ owner = msg.sender; charity = _charity; }

receive() external payable {}

function tip() public payable{ (bool s, ) = owner.call{value:msg.value}(""); require(s); }

function donate() public payable{ (bool s, ) = charity.call{value:address(this).balance}(""); require(s); } }

Later

I found out that donate does not need to be payable and still I do not know why it is not better to make a withdraw function and the boolean here.

S23Web3 commented 11 months ago

Based on the search results, there are indeed other ways to transfer Ether in Solidity. Here are three methods:

Using the send function: The send function forwards 2300 gas to the receiving contract. It returns a boolean value indicating whether the transfer was successful or not. If the transfer was not successful, it doesn't throw an exception. Here's how you can use the send function: function withdraw() public { require(msg.sender == owner, "NotOwner"); bool success = owner.send(address(this).balance); require(success, "Transfer failed."); } Using the call function: The call function is a low-level function that allows you to specify the exact amount of gas to forward to the receiving contract. It returns a boolean value indicating whether the call was successful or not. Here's how you can use the call function: function withdraw() public { require(msg.sender == owner, "NotOwner"); (bool success, ) = owner.call{value: address(this).balance}(""); require(success, "Transfer failed."); } Using the transfer function: The transfer function is similar to the send function, but it throws an exception if the transfer was not successful. Here's how you can use the transfer function: function withdraw() public { require(msg.sender == owner, "NotOwner"); owner.transfer(address(this).balance); } Please note that the transfer function is not recommended because it forwards only 2300 gas to the receiving contract, which may not be enough if the receiving contract needs to execute more logic.