0

I try to integrate an html field where users can interact with my contract using Metamask wallet. So the visitor can connect with page , but after placing for example a buy order , on browser console showing this error :

Sending transaction: {to: '0xCxxxxxxxxxxxxxxxxxxxxxxxxxx'(this is my contract address), from: >'0x78xxxxxxxxxxxxxxxxxxxxxxxx'(this is my wallet address), gas: 253058n, gasPrice: 7210362858n, >data: '0x55b057fa0000000000000000000000000000000000000000…>00000000000000000000000000000000000000000000003e8'} contentscript.js:1 MetaMask: Content script lost connection to "MetaMask Background Multiplex". >Error: PortDuplexStream - disconnected contentscript.js:1 MetaMask: Content script lost connection to "MetaMask Background Legacy >Multiplex". Error: PortDuplexStream - disconnected lockdown-install.js:1 Error: Premature close (anonymous) @ lockdown-install.js:1 error (anonymous) @ lockdown-install.js:1 (anonymous) @ lockdown-install.js:1 globalThis.lockdown @ lockdown-install.js:1 (anonymous) @ lockdown-run.js:4 contentscript.js:1 MetaMask: Muxed traffic for channel "metamask-provider" failed. Error: >Premature close contentscript.js:1 MetaMask: Muxed traffic between channels "provider" and "metamask-provider" >failed. Error: Premature close contentscript.js:1 MetaMask: Muxed traffic for channel "publicConfig" failed. Error: Premature >close .

And here is the html code of my web page :

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MetaMask Connection</title>
    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <style>
        #connectButton {
            background-color: blue;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
        }
        #connectButton img {
            width: 20px;
            height: 20px;
            margin-right: 10px;
        }
        #connectButton:hover {
            background-color: darkblue;
        }
        #walletInfo {
            min-height: 100px;
            border: 1px solid #000;
            padding: 10px;
        }
        #formContainer {
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            width: 300px;
        }
        input, button {
            display: block;
            width: 100%;
            margin: 10px 0;
            padding: 10px;
            font-size: 16px;
        }
    </style>
    </head>
    <body>
    <button id="connectButton">
        <img src="https://support.metamask.io/img/supportlogo.svg" alt="MetaMask Logo" style="width: 50px;">
        Connect
    </button>
    <div id="walletInfo"></div>
    <div id="formContainer">
        <input type="text" id="priceInput" placeholder="Enter price in WEI">
        <input type="text" id="amountInput" placeholder="Enter amount in smallest unit">
        <button id="placeOrderButton">Place Buy Order</button>
        <div id="orderStatus"></div>
    </div>
    <script>
        const web3 = new Web3(window.ethereum);
        const contractAddress = '0xCxxxxxxxxxxxxxxxxxxxxxxxx'; (this is my contract address)
        const contractABI = [
            {
                "inputs": [
                    { "internalType": "uint256", "name": "_price", "type": "uint256" },
                    { "internalType": "uint256", "name": "_amount", "type": "uint256" }
                ],
                "name": "placeBuyOrderEther",
                "outputs": [],
                "stateMutability": "payable",
                "type": "function"
            }
        ];
        let contract;
        let userAccount;
        const connectButton = document.getElementById('connectButton');
        const walletInfo = document.getElementById('walletInfo');
        const priceInput = document.getElementById('priceInput');
        const amountInput = document.getElementById('amountInput');
        const placeOrderButton = document.getElementById('placeOrderButton');
        const orderStatus = document.getElementById('orderStatus');
        async function connectMetaMask() {
            try {
                const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
                userAccount = accounts[0];
                updateUIOnConnect();
                loadContract();
            } catch (error) {
                console.error('Error connecting to MetaMask:', error);
            }
        }
        async function checkMetaMaskConnection() {
            try {
                const accounts = await ethereum.request({ method: 'eth_accounts' });
                if (accounts.length > 0) {
                    userAccount = accounts[0];
                    updateUIOnConnect();
                    loadContract();
                } else {
                    connectButton.innerText = 'Connect';
                    connectButton.addEventListener('click', connectMetaMask);
                }
            } catch (error) {
                console.error('Error checking MetaMask connection:', error);
            }
        }
        async function displayWalletDetails() {
            const balance = await ethereum.request({
                method: 'eth_getBalance',
                params: [userAccount, 'latest']
            });
            const balanceInEth = web3.utils.fromWei(balance, 'ether');
            walletInfo.innerHTML = `Wallet Address: ${userAccount} <br> Balance: ${balanceInEth} ETH`;
        }
        function updateUIOnConnect() {
            connectButton.innerText = 'Connected';
            connectButton.removeEventListener('click', connectMetaMask);
            displayWalletDetails();
        }
        function loadContract() {
            contract = new web3.eth.Contract(contractABI, contractAddress);
        }
        async function attemptTransaction(transactionParameters) {
    try {
        console.log('Sending transaction:', transactionParameters);
        const txHash = await ethereum.request({
            method: 'eth_sendTransaction',
            params: [transactionParameters],
        });
        console.log('Transaction successful:', txHash);
        orderStatus.innerText = 'Order placed: ' + txHash;
    } catch (error) {
        console.error('Transaction error:', error);
        orderStatus.innerText = 'Transaction failed: ' + error.message;
    }
}
       placeOrderButton.addEventListener('click', async () => {
    if (!userAccount) {
        orderStatus.innerText = 'Please connect to MetaMask first.';
        return;
    }
    try {
        const priceInWei = priceInput.value.trim();
        const amountInSmallestUnit = amountInput.value.trim();

        if (!priceInWei || !amountInSmallestUnit) {
            throw new Error('Please fill in all required fields (price and amount).');
        }
        // Calculate the expected payable amount in WEI
        const expectedPayable = priceInWei * amountInSmallestUnit;
        // Fetch current gas price and estimate gas required
        const gasPrice = await web3.eth.getGasPrice();
        const gasEstimate = await contract.methods
            .placeBuyOrderEther(priceInWei, amountInSmallestUnit)
            .estimateGas({ from: userAccount, value: expectedPayable.toString() });
        // Show instructions for the user about entering the value manually in MetaMask
        const expectedPayableEth = web3.utils.fromWei(expectedPayable.toString(), 'ether');
        orderStatus.innerText = `Expected payable amount: ${expectedPayableEth} ETH. Please enter this amount manually in MetaMask.`;
        // Build transaction parameters
        const transactionParameters = {
            to: contractAddress,
            from: userAccount,
            gas: gasEstimate,
            gasPrice: gasPrice,
            data: contract.methods.placeBuyOrderEther(priceInWei, amountInSmallestUnit).encodeABI(),
        };
        // Initiate the transaction and handle confirmation/retries
        await attemptTransaction(transactionParameters);
    } catch (error) {
        console.error('Transaction setup error:', error);
        orderStatus.innerText = 'Transaction setup failed: ' + error.message;
    }
});
        ethereum.on('disconnect', () => {
            console.error('MetaMask disconnected.');
            connectButton.innerText = 'Connect';
            walletInfo.innerHTML = '';
        });
        ethereum.on('accountsChanged', accounts => {
            if (accounts.length > 0) {
                userAccount = accounts[0];
                updateUIOnConnect();
            } else {
                connectButton.innerText = 'Connect';
                walletInfo.innerHTML = '';
            }
        });
        ethereum.on('chainChanged', () => window.location.reload());
        // Check connection status when the page loads
        window.addEventListener('load', checkMetaMaskConnection);
    </script>
</body>

In this code, i prompt users to insert value with transaction, manually in wallet in order to make the code more simple. But even i integrate the value in to code and user put it in page, the error message is same .So the reason seems not to be the value with transaction. I tried with extension of metamask on Brave and Opera and also on android metamask browser.The error happens everywhere.
Please if possible give some help of why this could happen. Many thanks !

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.