Transferring ETH to and from Smart Contracts Using MetaMask

·

Introduction

This guide explains how to send and receive ETH (Ether) via MetaMask when interacting with smart contracts. Whether you're a developer or a blockchain enthusiast, understanding this process is essential for decentralized application (DApp) development.

Part 1: Setting Up MetaMask

1. Installing MetaMask

2. Creating a MetaMask Account

3. Acquiring Test ETH

👉 Need help with MetaMask?


Part 2: Smart Contract Deployment

1. Writing and Deploying a Contract

pragma solidity ^0.4.24;

contract GameContract {
    address public fromAddress;
    uint256 public value;
    uint256 public code;
    uint256 public team;

    function buyKey(uint256 _code, uint256 _team) public payable {
        fromAddress = msg.sender;
        value = msg.value;
        code = _code;
        team = _team;
    }

    function getInfo() public view returns (address, uint256, uint256, uint256) {
        return (fromAddress, value, code, team);
    }

    function withdraw() public {
        address send_to_address = 0xfdd7a3f5375C6Fcc7852C0372bCE202b3080F451;
        uint256 _eth = 333000000000000000; // 0.333 ETH in wei
        send_to_address.transfer(_eth);
    }
}

2. Verifying the Contract


Part 3: Interacting with the Contract via Web3

1. ETH Deposit (buyKey)

contract.buyKey('1', '1', { 
    from: address, 
    value: web3.toWei(0.2, 'ether') 
}, function(error, result) {
    if (!error) console.log("Deposit successful:", result);
});

2. ETH Withdrawal (withdraw)

contract.withdraw({ 
    from: address 
}, function(error, result) {
    if (!error) console.log("Withdrawal successful:", result);
});

Key Notes:

👉 Explore advanced Web3 techniques


FAQs

Q1: Why is my MetaMask transaction failing?

A: Ensure you have sufficient ETH for gas fees and correct network selection (e.g., Rinkeby).

Q2: How do I convert ETH to wei?

A: Use web3.toWei(amount, 'ether') (1 ETH = 10^18 wei).

Q3: Can I change the withdrawal address in the contract?

A: Yes, modify the send_to_address variable in the withdraw() function before redeploying.


Conclusion

Mastering ETH transfers with MetaMask and smart contracts opens doors to DApp development. Always: