Making a solidity transfer automatically without metamask

Viewed 4092

I am very new to solidity. Im a bit more experienced with javascript html and css. But i now am making a free token giver on my front end website. Where the user inputs his or her address and gets a free token. The contract is linked to my web3js and everything is working well. But i cant't automatically transfer tokens without having to approve the transaction on metamask. I really want to automate this process so i could implement alot of new functions to my website.

When i interact with my contract in remix it works well but in java it has to do metamask things.

Here is my function code in javascript :

function Coingiver()
    {
        const web3 = new Web3(window.ethereum);
        var slotContract = new web3.eth.Contract(abi, address);

        const addressreceive = document.getElementById("address").value;    
        const addressend = "0x582077e61D52bB1Ae6FB9EcEDa1eb39153E9A269";

        window.ethereum.enable();

        slotContract.methods.transferFrom(addressend, addressreceive, 1).send({from : addressend},function(err, res)
        {
            if(err)
            {
                console.log("error", err)
                return
            }
            console.log("Hash of the transaction: ", res)
        });

        checkBalance();
    }

So how do i automate this process so i dont have to approve the transaction everytime? Thanks for helping me ( a beginner ) out guys!

2 Answers

In order for the user to send a transaction to get your coins, they will have to pay for the gas for the transactions. One reason metamask always asks the user first before sending the transacting through is to prevent sites from draining all a users ETH by repeatedly spending their ETH as gas.

If you really want to do this at no cost for the user, you could use node.js or python on the server, and have it sign and send the coins when a user fills out a form.

Note that there is a huge amount of fraud around collecting airdrops, and if you just send to any address, scammers will generate endless addresses to get coins to, and you will also pay the gas costs.

To automate any transaction from your JavaScript code, you need to sign transactions with a local private key that has ETH balance for gas fees. Then, your application manages the private key, not MetaMask.

Usually such private key is distributed through environment, secrets file, etc. and never in the source code directly - to avoid leaking important keys.

A good solution to manage this is Truffle's hdwallet-provider package.

Related