deposits the corresponding USDT transactions using MetaMask and PHP.

 To implement MetaMask as the provider for your MLM project, I'll guide you through the complete code that handles:



1. Connecting the user's MetaMask wallet.

2. Sending USDT from the user's MetaMask wallet to your project's wallet.

3. Confirming the transaction and updating the user's balance on your platform.


Here’s the step-by-step breakdown and the complete code:


### Prerequisites:

- **MetaMask** installed in the user’s browser.

- **Web3.js** to interact with the blockchain.

- **USDT contract address and ABI** (you already have this).


---


### 1. **Install Web3.js**

First, you need to include the Web3.js library in your project. You can either download it or include it directly via CDN:


```html

<script src="https://cdn.jsdelivr.net/npm/web3@1.7.3/dist/web3.min.js"></script>

```


### 2. **HTML and JavaScript: MetaMask Connection and USDT Transfer**


Here is the HTML and JavaScript code to:

- Connect the user's MetaMask wallet.

- Transfer USDT from MetaMask to your project's wallet.

- Notify the backend to update the user’s balance.


```html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>USDT Deposit</title>

    <script src="https://cdn.jsdelivr.net/npm/web3@1.7.3/dist/web3.min.js"></script>

</head>

<body>

    <h1>Deposit USDT</h1>


    <!-- Button to connect MetaMask -->

    <button onclick="connectMetaMask()">Connect MetaMask</button>

    <p id="walletAddress"></p>


    <!-- Input to enter the amount of USDT to deposit -->

    <label for="usdtAmount">Enter USDT Amount:</label>

    <input type="number" id="usdtAmount" placeholder="Amount in USDT" step="0.01">

    <br><br>


    <!-- Button to initiate USDT transfer -->

    <button onclick="depositUSDT()">Deposit USDT</button>


    <p id="statusMessage"></p>


    <script>

        // Web3 instance

        let web3;

        let userAccount;


        // USDT Contract Address (Ethereum Mainnet)

        const USDT_CONTRACT_ADDRESS = "0xdAC17F958D2ee523a2206206994597C13D831ec7";


        // USDT Contract ABI (shortened version)

        const USDT_ABI = [

            {

                "constant": true,

                "inputs": [],

                "name": "balanceOf",

                "outputs": [

                    {

                        "name": "balance",

                        "type": "uint256"

                    }

                ],

                "payable": false,

                "stateMutability": "view",

                "type": "function"

            },

            {

                "constant": false,

                "inputs": [

                    {

                        "name": "_to",

                        "type": "address"

                    },

                    {

                        "name": "_value",

                        "type": "uint256"

                    }

                ],

                "name": "transfer",

                "outputs": [

                    {

                        "name": "",

                        "type": "bool"

                    }

                ],

                "payable": false,

                "stateMutability": "nonpayable",

                "type": "function"

            }

        ];


        // Project Wallet Address (replace with your actual wallet address)

        const PROJECT_WALLET_ADDRESS = "YOUR_PROJECT_WALLET_ADDRESS";


        // Connect MetaMask and get the user's account

        async function connectMetaMask() {

            if (window.ethereum) {

                try {

                    // Request account access

                    const accounts = await ethereum.request({ method: 'eth_requestAccounts' });

                    userAccount = accounts[0];

                    document.getElementById('walletAddress').innerText = "Connected MetaMask Address: " + userAccount;

                    web3 = new Web3(window.ethereum);

                } catch (error) {

                    console.error("MetaMask connection failed:", error);

                }

            } else {

                alert("MetaMask is not installed. Please install MetaMask to continue.");

            }

        }


        // Deposit USDT from MetaMask to the project's wallet

        async function depositUSDT() {

            const amountInUSDT = document.getElementById('usdtAmount').value;


            if (!userAccount || !amountInUSDT || isNaN(amountInUSDT)) {

                alert("Please connect MetaMask and enter a valid amount.");

                return;

            }


            // Convert USDT amount to the correct decimal format (USDT has 6 decimals)

            const amountInWei = web3.utils.toWei(amountInUSDT, 'mwei');


            // Create USDT contract instance

            const usdtContract = new web3.eth.Contract(USDT_ABI, USDT_CONTRACT_ADDRESS);


            try {

                // Send USDT to the project's wallet

                const result = await usdtContract.methods.transfer(PROJECT_WALLET_ADDRESS, amountInWei).send({ from: userAccount });

                console.log("Transaction successful:", result);


                // Notify the backend to update the user's balance

                updateUserBalance(userAccount, amountInUSDT);


                document.getElementById('statusMessage').innerText = "Deposit successful! Transaction hash: " + result.transactionHash;

            } catch (error) {

                console.error("USDT transfer failed:", error);

                document.getElementById('statusMessage').innerText = "USDT transfer failed. Please try again.";

            }

        }


        // Notify backend to update the user's balance in the database

        function updateUserBalance(walletAddress, amountInUSDT) {

            $.ajax({

                url: 'update_balance.php',

                type: 'POST',

                data: {

                    walletAddress: walletAddress,

                    amount: amountInUSDT

                },

                success: function(response) {

                    console.log("Balance updated:", response);

                },

                error: function(error) {

                    console.error("Error updating balance:", error);

                }

            });

        }

    </script>

</body>

</html>

```


### 3. **Backend PHP Script (`update_balance.php`)**


This PHP script will handle the backend part of recording the deposit and updating the user’s balance in your database.


```php

<?php

// update_balance.php


$walletAddress = $_POST['walletAddress']; // MetaMask wallet address of the user

$amount = $_POST['amount']; // Amount in USDT


// Database connection

$servername = "localhost";

$username = "your_db_username";

$password = "your_db_password";

$dbname = "your_db_name";


$conn = new mysqli($servername, $username, $password, $dbname);


// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}


// Find user by MetaMask wallet address and update balance

$sql = "UPDATE users SET usdt_balance = usdt_balance + ? WHERE wallet_address = ?";

$stmt = $conn->prepare($sql);

$stmt->bind_param("ds", $amount, $walletAddress);


if ($stmt->execute()) {

    echo "Balance updated successfully!";

} else {

    echo "Error updating balance: " . $conn->error;

}


$stmt->close();

$conn->close();

?>

```


### Breakdown of the Code:

1. **MetaMask Connection**: The user clicks the button to connect their MetaMask wallet. Once connected, their wallet address is displayed, and Web3 is initialized using the MetaMask provider.

   

2. **USDT Transfer**: The user enters the amount of USDT they want to deposit, and the `depositUSDT` function is called. It transfers the specified amount of USDT from the user’s MetaMask wallet to the project's wallet address.


3. **Update User Balance**: After a successful transaction, an AJAX request is sent to the backend to update the user's balance in the database based on their MetaMask wallet address.


### Summary:

- **No need for Infura**: This code directly uses MetaMask as the provider, so no third-party service is required.

- **USDT Transfer**: The code handles USDT transfers from the user's MetaMask wallet to your project’s wallet.

- **Backend Integration**: The PHP script updates the user's balance on the server after a successful deposit.


This solution uses MetaMask for authentication and transaction handling, making it simple and free to use without needing to sign up for external blockchain services like Infura.

Newest
Previous
Next Post »