0

So I am writing my own smart contract on remix.ethereum.org, and it is for a token, and in the code, I have written a simple ICO:

function() public payable {
        if (totalSupply >= 1000) {
        BTA+=1;
        } else {
        uint toMint = msg.value/price;
        totalSupply+=toMint;
        balances[msg.sender]+=toMint;
        emit Transfer(0, msg.sender, toMint);
  }

Is there a way for the smart contract to transfer the ether that people send to it to my metamask wallet?

  • I forgot to add my pragma version, it is soljson-v0.4.21+commit.dfe3193c – ETHguy Sep 8 '19 at 22:03
2

Yes there is, however keep in mind that your function does not do that. Instead, when a user calls the function, it is automatically paid into the smart contract. As my collegue has already stated, using address.transfer() is your solution. I don't know the pragma version you're using as it has not been specified so I will try my best to give you a full answer that works for the latest compiler: version:0.5.11+commit.c082d0b4.Emscripten.clang

Your smart contract can become something like this:

address payable contractManager = youraddress;   
function() external payable {
            if (totalSupply >= 1000) {
            BTA+=1;
            } else {
            uint toMint = msg.value/price;
            totalSupply+=toMint;
            balances[msg.sender]+=toMint;
            contractManager.transfer(msg.value);
            emit Transfer(0, msg.sender, toMint);
      }

I have changed a few things: rather than calling your callback function as public, I declared it as external (best practices when using callback function).

Furthermore, some sources will tell you to declare the address as public. You need to call it payable in order to call the .transfer function.

When writing your address in the contractManager, make sure you pass the address with the correct checksum. In other words this doesn't work

address payable contractManager = 0xf805f3618039389a2cddf2720ee98ae065b44608;

This works:

address payable contractManager = 0xF805F3618039389a2cDDf2720Ee98ae065B44608;

To make it easy to get the right address with the right checksum, just search your address on etherscan. Giving you an example https://etherscan.io/address/0xf805f3618039389a2cddf2720ee98ae065b44608

enter image description here

Out of topic

I assume you're a person who knows what you're doing, but why are you worried about gas costs since you can pay them just once when you withdraw the full amount?

| improve this answer | |
0

yes with address.transfer() function with the address variable is a payable address. You can see the example here: https://solidity.readthedocs.io/en/develop/solidity-by-example.html#safe-remote-purchase

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.