Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

330-uniswap-trading How works on real chain? #162

Open
ChristianErdtmann opened this issue Apr 11, 2022 · 0 comments
Open

330-uniswap-trading How works on real chain? #162

ChristianErdtmann opened this issue Apr 11, 2022 · 0 comments

Comments

@ChristianErdtmann
Copy link

ChristianErdtmann commented Apr 11, 2022

Hey i have written a nearly similar code to yours but i try to automate this for a swap on Qickswap router here is my code:
dont be confused, the Contrac-sddresses not matching the Variablesnames.

I have the following problem i alltimes get the message: transaction underpriced but i dont know why. I have allready set the gas fee to manual to 1000000000000000000 how you can see. So thats enough but i still fighting with this message. I would be verry happy if you can tell me how i get this code to run.

I have also tried it with the seccound code snipped, the seccound one dos just a transaction from me to me wich cost me gas and do nothing, but i expect a swap transaction, i dont know whats wrong with these both code snippets it would very nice if you can help with 1 of these.

const ethers = require('ethers');
Web3 = require('web3')
//This contains an Endpoint URL, and a wallet private key!!!

privatKey = 'MY_PRIVATE_KEY'

//All Values are for the Polygon Mainnet, the Variables not matching with the contract addresse!!!!!!!!

const WBNB = "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270";
const BUSD = "0xBbba073C31bF03b8ACf7c28EF0738DeCF3695683";
const router = "0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff";

const web3 = new Web3("https://polygon-mainnet.g.alchemy.com/v2/OfATG5uHb8ZdFbaCLfD79M236-hICOPz")
const provider = new ethers.providers.JsonRpcProvider('https://polygon-mainnet.g.alchemy.com/v2/OfATG5uHb8ZdFbaCLfD79M236-hICOPz');
const wallet = new ethers.Wallet(privatKey);
const signer = wallet.connect(provider);

const routerContract = new ethers.Contract(
    router,
    [
        'function getAmountsOut(uint amountIn, address[] memory path) public view returns(uint[] memory amounts)',
        'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
    ],
    signer
);

const busdContract = new ethers.Contract(
    BUSD,
    [
        'function approve(address spender, uint256 amount) external returns (bool)'
    ],
    signer
)

async function main() {

    const BUSDamountIn = ethers.utils.parseUnits('0.05', 18);
    let amounts = await routerContract.getAmountsOut(BUSDamountIn, [BUSD, WBNB]);
    const WBNBamountOutMin = amounts[1].sub(amounts[1].div(10));

    console.log(ethers.utils.formatEther(BUSDamountIn));
    console.log(ethers.utils.formatEther(WBNBamountOutMin));

    block = await web3.eth.getBlock("latest");
    gasLimitRoundedAmount = Math.round(block.gasLimit / block.transactions.length);

    const approveTx = await busdContract.approve(
        router,
        BUSDamountIn
    );
    let reciept = await approveTx.wait();
    console.log(reciept);

    const swapTx = await routerContract.swapExactTokensForTokens(
        BUSDamountIn,
        WBNBamountOutMin,
        [BUSD, WBNB],
        wallet.address,
        Date.now() + 1000 * 60 * 10
        { gasLimit: 1000000000000000000 }
    )

        receipt = await swapTx.wait();
        console.log(receipt);
}

main().then().finally(() => { });
    Web3 = require('web3')
    const { Console } = require('console');
    const fs = require('fs');
    const qs = require('quickswap-sdk')
    const ethers = require('ethers')
    
    const privateKey = process.env.PRIVATE_KEY
    const publicKey = '0x560CC2be59c5deF53431783C3583B8f9F63b7793'
    const provider = new ethers.providers.JsonRpcProvider("https://polygon-mainnet.g.alchemy.com/v2/OfATG5uHb8ZdFbaCLfD79M236-hICOPz")
    const wMaticAddress = '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270'
    const mSandAddress = '0xBbba073C31bF03b8ACf7c28EF0738DeCF3695683'

   getUnixCurrentTimestamp = Math.floor(Date.now())
    getDeadlineAfter1Day = getUnixCurrentTimestamp + 1000 * 60 * 10 //Add 10 Minutes
    console.log(getUnixCurrentTimestamp)


    matic = await qs.Fetcher.fetchTokenData(137, wMaticAddress, provider)
    sand = await qs.Fetcher.fetchTokenData(137, mSandAddress, provider)
    pair = await qs.Fetcher.fetchPairData(matic, sand, provider)
    route = new qs.Route([pair], sand) //how much is sand in matic
    price = route.midPrice.toSignificant(6) //Parameter are Decimal Points

    amountSand = 0.05
    amountMatic = amountSand * price
    amountSandWEI = Math.round(amountSand * (10 ** 18)).toString()
    amountMaticWEI = Math.round(amountMatic * (10 ** 18)).toString()
    console.log(amountSand)
    console.log(amountMatic)

    encoded = quickSwapRouterContract.methods.swapExactTokensForTokens(amountSandWEI, amountMaticWEI, [mSandAddress, wMaticAddress], publicKey, getDeadlineAfter1Day).encodeABI()
    block = await web3.eth.getBlock("latest");
    gasLimit = Math.round(block.gasLimit / block.transactions.length);

    var tx = {
        gas: gasLimit,
        to: publicKey,
        data: encoded
    }

    web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
        web3.eth.sendSignedTransaction(signed.rawTransaction).on('receipt', console.log)
    })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant