I'm fairly new to blockchain and I'm struggling with sending a transaction to a smart contract - I'm getting intrinsic gas too low error. I've tried searching online for a solution but just couldn't solve it.
From https://stackoverflow.com/a/71261434/20453413 I understand that I need to 'allocate more gas by setting a higher gasLimit', okey, but by how much? Am I calculating gasPrice correctly?
I've deployed my contract to a goerli testnet and I'm using Infura as a provider to the blockchain.
let baseNonce = await provider.getTransactionCount(wallet.getAddress());
const gasPrice = await provider.getGasPrice()
const tx = await someContract.populateTransaction.setFoo('hello');
tx.nonce = baseNonce + 1
tx.value = ethers.utils.parseUnits('0.001', 'ether')
tx.gasPrice = gasPrice
await wallet.signTransaction(tx).then(signedTransaction => {
provider.sendTransaction(signedTransaction).then(transactionResponse => {
console.log("Our transaction response: " + transactionResponse)
})
})
provider.getGasPrice() returns a BigNumber object. Something like this { BigNumber: "21971214174" }
But you need to convert this BigNumber to a string. BigNumber object has a toString() to method. you can check the docs
tx.gasPrice = gasPrice.toString()
I made a smart contract for token on the Polygon network. The server part is NodeJS.
Now I'm trying to implement the functionality of sending tokens to the recipient's wallet from the token creator's wallet.
The transfer method in the contract is simply taken from OpenZeppelin's ERC20 contract.
/**
* #dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
Calling the contract method from the server looks like this:
const web3Instance = new web3('providerUrl');
const tokenSmartContract = new this.web3Instance.eth.Contract(TokenABI, 'tokenAddress');
async sendTokenToWallet(amount, wallet) {
await this.tokenSmartContract.methods.transfer(wallet, amount).send();
}
But no transfer happens.
I know I need to use the sender's private key somewhere, but I can't figure out where.
Solved my own problem. Maybe my code example will help someone:
async sendTokenToWallet(amount, wallet) {
const tokenAmount = web3.utils.toWei(amount.toString(), 'ether');
const account = this.web3Instance.eth.accounts.privateKeyToAccount('0x' + 'privateKey');
this.web3Instance.eth.accounts.wallet.add(account);
this.web3Instance.eth.defaultAccount = account.address;
const nonce = await this.web3Instance.eth.getTransactionCount(account.address, 'latest');
const gasPrice = Math.floor(await this.web3Instance.eth.getGasPrice() * 1.10);
const gas = await this.tokenSmartContract.methods
.transfer(wallet, tokenAmount)
.estimateGas({ from: account.address });
await this.tokenSmartContract.methods
.transfer(wallet, tokenAmount)
.send({ from: account.address, gasPrice, nonce, gas });
}
I'm building a website where people log in to their phantom wallet then by clicking on a button they will send a certain amount of our custom token to one wallet.
The code shown below is working with SOL and I would like to make it work with our custom SPL token, I have the mint address of the token but I couldn't find any way to make it work. Could anyone help me?
async function transferSOL(toSend) {
// Detecing and storing the phantom wallet of the user (creator in this case)
var provider = await getProvider();
console.log("Public key of the emitter: ",provider.publicKey.toString());
// Establishing connection
var connection = new web3.Connection(
"https://api.mainnet-beta.solana.com/"
);
// I have hardcoded my secondary wallet address here. You can take this address either from user input or your DB or wherever
var recieverWallet = new web3.PublicKey("address of the wallet recieving the custom SPL Token");
var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: provider.publicKey,
toPubkey: recieverWallet,
lamports: (web3.LAMPORTS_PER_SOL)*toSend //Investing 1 SOL. Remember 1 Lamport = 10^-9 SOL.
}),
);
// Setting the variables for the transaction
transaction.feePayer = await provider.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
// Request creator to sign the transaction (allow the transaction)
let signed = await provider.signTransaction(transaction);
// The signature is generated
let signature = await connection.sendRawTransaction(signed.serialize());
// Confirm whether the transaction went through or not
console.log(await connection.confirmTransaction(signature));
//Signature chhap diya idhar
console.log("Signature: ", signature);
}
I'd like to specify that people will use phantom and I cant have access to their private keys (cause it was needed in all the answers I found on internet)
You're very close! You just need to replace the web3.SystemProgram.transfer instruction with an instruction to transfer SPL tokens, referencing the proper accounts. There's an example at the Solana Cookbook covering this exactly situation: https://solanacookbook.com/references/token.html#transfer-token
You can do this with help of anchor and spl-token, which is used for dealing with custom tokens on solana.
This is a custom transfer function. You'll need the mint address of the token, wallet from which the tokens will be taken( which you get in front end when user connects wallet. Can make use of solana-web3), to address and amount.
import * as splToken from "#solana/spl-token";
import { web3, Wallet } from "#project-serum/anchor";
async function transfer(tokenMintAddress: string, wallet: Wallet, to: string, connection: web3.Connection, amount: number) {
const mintPublicKey = new web3.PublicKey(tokenMintAddress);
const {TOKEN_PROGRAM_ID} = splToken
const fromTokenAccount = await splToken.getOrCreateAssociatedTokenAccount(
connection,
wallet.payer,
mintPublicKey,
wallet.publicKey
);
const destPublicKey = new web3.PublicKey(to);
// Get the derived address of the destination wallet which will hold the custom token
const associatedDestinationTokenAddr = await splToken.getOrCreateAssociatedTokenAccount(
connection,
wallet.payer,
mintPublicKey,
destPublicKey
);
const receiverAccount = await connection.getAccountInfo(associatedDestinationTokenAddr.address);
const instructions: web3.TransactionInstruction[] = [];
instructions.push(
splToken.createTransferInstruction(
fromTokenAccount.address,
associatedDestinationTokenAddr.address,
wallet.publicKey,
amount,
[],
TOKEN_PROGRAM_ID
)
);
const transaction = new web3.Transaction().add(...instructions);
transaction.feePayer = wallet.publicKey;
transaction.recentBlockhash = (await connection.getRecentBlockhash()).blockhash;
const transactionSignature = await connection.sendRawTransaction(
transaction.serialize(),
{ skipPreflight: true }
);
await connection.confirmTransaction(transactionSignature);
}
I am new at ethereum development and I am working on a simple script to execute swaps using Pancakeswap. Everything seems to be working well up to the point where I am building my transaction and calculate the tx-cost. I am using the UniswapRouterV02 abi create my Pancakeswap contract. The code:
const init = async () => {
const [WBNB, BUSD] = await Promise.all(
[addresses.WBNB, addresses.BUSD].map(tokenAddress => (
new Token(
ChainId.MAINNET,
tokenAddress,
18
)
)));
const pair = await Fetcher.fetchPairData(WBNB, BUSD, provider)
const route = await new Route([pair], WBNB)
const trade = await new Trade(route, new TokenAmount(WBNB, tradeAmount), TradeType.EXACT_INPUT)
const executionPrice = trade.executionPrice.toSignificant(12)
// Correct prices; everything seems correct up until here
const slippageTolerance = new Percent('50', '10000')
const amountOutMin = trade.minimumAmountOut(slippageTolerance).raw
const path = [WBNB.address, BUSD.address]
const to = MY_ADDRESS
const deadline = Math.floor(Date.now() / 1000) + 60 * 20
const value = trade.inputAmount.raw
// Correct prices everything seems correct up until here
const pancakeSwap = new web3.eth.Contract(
abis.uniswapRouter.abi,
addresses.PANCAKE_ROUTER //'0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F'
);
let tx = pancakeSwap.methods.swapExactTokensForTokens(
tradeAmount,
web3.utils.toBN(amountOutMin.toString()),
path,
to,
deadline
)
const [gasPrice, gasCost] = await Promise.all([
web3.eth.getGasPrice(),
tx.estimateGas({from: admin}),
]);
console.log(`gasPrice: ${gasPrice}`)
console.log(`gasCost: ${gasCost}`)
}
init()
The price calculation for the swap returns correct prices. However when I try to calculate the transaction costs the following error is thrown:
Error: Returned error: gas required exceeds allowance (44038122) or always failing transaction
Any help would be greatly appreciated, please let me know if more of my code should be clarified!
In turns out that with web3 it is not possible to interact with the Pancakeswap contract. I found a solution using ethers.js. Following code worked for me to execute a swap on Pancake on mainnet.
Before executing the first transaction Pancakeswap needs to be allowed, this code is commented out.
I had to play around with the gasprice and gasLimit a bit to make it work.
require("dotenv").config()
const ethers = require('ethers')
const {ChainId, Token, TokenAmount, Fetcher, Pair, Route, Trade, TradeType, Percent} =
require('#pancakeswap-libs/sdk');
const Web3 = require('web3');
const web3 = new Web3('wss://apis.ankr.com/wss/c40792ffe3514537be9fb4109b32d257/946dd909d324e5a6caa2b72ba75c5799/binance/full/main');
const {JsonRpcProvider} = require("#ethersproject/providers");
const provider = new JsonRpcProvider('https://bsc-dataseed1.binance.org/');
const { address: admin } = web3.eth.accounts.wallet.add(process.env.PRIVATE_KEY)
const addresses = {
WBNB: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',
BUSD: '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56',
PANCAKE_ROUTER: '0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F'
}
const ONE_ETH_IN_WEI = web3.utils.toBN(web3.utils.toWei('1'))
const tradeAmount = ONE_ETH_IN_WEI.div(web3.utils.toBN('1000'))
const init = async () => {
const [WBNB, BUSD] = await Promise.all(
[addresses.WBNB, addresses.BUSD].map(tokenAddress => (
new Token(
ChainId.MAINNET,
tokenAddress,
18
)
)));
const pair = await Fetcher.fetchPairData(WBNB, BUSD, provider)
const route = await new Route([pair], WBNB)
const trade = await new Trade(route, new TokenAmount(WBNB, tradeAmount), TradeType.EXACT_INPUT)
const slippageTolerance = new Percent('50', '10000')
// create transaction parameters
const amountOutMin = trade.minimumAmountOut(slippageTolerance).raw
const path = [WBNB.address, BUSD.address]
const to = admin
const deadline = Math.floor(Date.now() / 1000) + 60 * 20
// Create signer
const wallet = new ethers.Wallet(
Buffer.from(
process.env.PRIVATE_KEY, // paste your private key from metamask here
"hex"
)
)
const signer = wallet.connect(provider)
// Create Pancakeswap ethers Contract
const pancakeswap = new ethers.Contract(
addresses.PANCAKE_ROUTER,
['function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'],
signer
)
// Allow Pancakeswap
// let abi = ["function approve(address _spender, uint256 _value) public returns (bool success)"]
// let contract = new ethers.Contract(WBNB.address, abi, signer)
// await contract.approve(addresses.PANCAKE_ROUTER, ethers.utils.parseUnits('1000.0', 18), {gasLimit: 100000, gasPrice: 5e9})
// Execute transaction
const tx = await pancakeswap.swapExactTokensForTokens(
ethers.utils.parseUnits('0.001', 18),
ethers.utils.parseUnits(web3.utils.fromWei(amountOutMin.toString()), 18),
path,
to,
deadline,
{ gasLimit: ethers.utils.hexlify(200000), gasPrice: ethers.utils.parseUnits("10", "gwei") }
)
console.log(`Tx-hash: ${tx.hash}`)
const receipt = await tx.wait();
console.log(`Tx was mined in block: ${receipt.blockNumber}`)
}
init()
You can check this working example that buys a token from pancakeswap.finance:
https://github.com/religion-counter/onlyone/blob/main/helper-scripts/buy-onlyone-pancakeswap.js
// Helper script that buys ONLYONE token from a specified address specified on text file SPECIFY_ACCOUNTS_YOU_WANT_TO_BUY_FOR_HERE.json
// The amount is specified with 'originalAmountToBuyWith' variable in the source
// The JSON file should have an array with objects with 'address' field and 'privateKey' field.
// Buys ONLYONE for ${bnbAmount} BNB from pancakeswap for address ${targetAccounts[targetIndex].address}
// targetIndex is passed as an argument: process.argv.splice(2)[0]
var fs = require('fs')
var Tx = require('ethereumjs-tx').Transaction;
var Web3 = require('web3')
var Common = require('ethereumjs-common').default;
var web3 = new Web3(new Web3.providers.HttpProvider('https://bsc-dataseed.binance.org/'))
var BSC_FORK = Common.forCustomChain(
'mainnet',
{
name: 'Binance Smart Chain Mainnet',
networkId: 56,
chainId: 56,
url: 'https://bsc-dataseed.binance.org/'
},
'istanbul',
);
// SPECIFY_THE_AMOUNT_OF_BNB_YOU_WANT_TO_BUY_FOR_HERE
var originalAmountToBuyWith = '0.007' + Math.random().toString().slice(2,7);
var bnbAmount = web3.utils.toWei(originalAmountToBuyWith, 'ether');
var targetAccounts = JSON.parse(fs.readFileSync('SPECIFY_ACCOUNTS_YOU_WANT_TO_BUY_FOR_HERE.json', 'utf-8'));
var targetIndex = Number(process.argv.splice(2)[0]);
var targetAccount = targetAccounts[targetIndex];
console.log(`Buying ONLYONE for ${originalAmountToBuyWith} BNB from pancakeswap for address ${targetAccount.address}`);
var res = buyOnlyone(targetAccounts[targetIndex], bnbAmount);
console.log(res);
async function buyOnlyone(targetAccount, amount) {
var amountToBuyWith = web3.utils.toHex(amount);
var privateKey = Buffer.from(targetAccount.privateKey.slice(2), 'hex') ;
var abiArray = JSON.parse(JSON.parse(fs.readFileSync('onlyone-abi.json','utf-8')));
var tokenAddress = '0xb899db682e6d6164d885ff67c1e676141deaaa40'; // ONLYONE contract address
var WBNBAddress = '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c'; // WBNB token address
// var onlyOneWbnbCakePairAddress = '0xd22fa770dad9520924217b51bf7433c4a26067c2';
// var pairAbi = JSON.parse(fs.readFileSync('cake-pair-onlyone-bnb-abi.json', 'utf-8'));
// var pairContract = new web3.eth.Contract(pairAbi, onlyOneWbnbCakePairAddress/*, {from: targetAccount.address}*/);
var amountOutMin = '100' + Math.random().toString().slice(2,6);
var pancakeSwapRouterAddress = '0x10ed43c718714eb63d5aa57b78b54704e256024e';
var routerAbi = JSON.parse(fs.readFileSync('pancake-router-abi.json', 'utf-8'));
var contract = new web3.eth.Contract(routerAbi, pancakeSwapRouterAddress, {from: targetAccount.address});
var data = contract.methods.swapExactETHForTokens(
web3.utils.toHex(amountOutMin),
[WBNBAddress,
tokenAddress],
targetAccount.address,
web3.utils.toHex(Math.round(Date.now()/1000)+60*20),
);
var count = await web3.eth.getTransactionCount(targetAccount.address);
var rawTransaction = {
"from":targetAccount.address,
"gasPrice":web3.utils.toHex(5000000000),
"gasLimit":web3.utils.toHex(290000),
"to":pancakeSwapRouterAddress,
"value":web3.utils.toHex(amountToBuyWith),
"data":data.encodeABI(),
"nonce":web3.utils.toHex(count)
};
var transaction = new Tx(rawTransaction, { 'common': BSC_FORK });
transaction.sign(privateKey);
var result = await web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'));
console.log(result)
return result;
}
You can also contribute to the repository if you are interested.
I am a total beginner but have the same goal as you. I'm trying to get your code to work.
I used the following Code to create the signer. I used my 'mnemonic' instead of the private key:
const wallet = ethers.Wallet.fromMnemonic(mnemonic);
I noticed that pancake uses the swapExactETHForTokens() function instead of swapExactTokensForTokens() for the transactions. Does that make any difference?
I am not quite sure whether the Output and Input Amount is calculated correctly... I don't quite understand it yet, but will try to go through it as soon as possible.
jklepatch has written a code which contains trading via pancakeswap V2. However, the trade does not work if i execute the code because the AmountOut generats an error (codeline 78)...
In the meantime, have you been able to modify your code or make it work? If it is helpful I can also post my version of your code here.
I have created a smart contract that facilitates a token sale. I want a user to be able to press a button that automatically generates an ERC20 wallet that tokens can be sent to.
I am using the truffle HDWallet Provider and Infura. I don't want the user to have to use MetaMask or anything else. I will sign the transactions on the backend using the private key of the user's generated wallet.
How would I go about implementing this so a new wallet is created for every new user that wants to perform a transaction?
This is the code that allowed me to create a wallet on a button press. I now need to find a way to store the credentials of these wallets so I can sign transactions and transfer tokens to them.
var bip39 = require('bip39');
const EthereumUtil = require('ethereumjs-util');
const hdkey = require('hdkey');
const mnemonic = bip39.generateMnemonic(); //generates string
const seed = bip39.mnemonicToSeed(mnemonic); //creates seed buffer
const root = hdkey.fromMasterSeed(seed);
const masterPrivateKey = root.privateKey.toString('hex');
const addrNode = root.derive("m/44'/60'/0'/0/0");
const pubKey = EthereumUtil.privateToPublic(addrNode._privateKey);
const addr = EthereumUtil.publicToAddress(pubKey).toString('hex');
const address = EthereumUtil.toChecksumAddress(addr);
Its pretty simple, just create a HDWalletProvider and the provider.addresses has all the accounts you can use:
Here is the code:
const createWallet = function(_providerUrl) {
const mnemonicPhrase = bip39.generateMnemonic()
let provider = new HDWalletProvider({
mnemonic: {
phrase: mnemonicPhrase
},
providerOrUrl: "http://localhost:8545"
});
return provider.addresses
}
Addresses has the accounts
The solution has already been commented above, but I have a better suggestion for you. I think it's better to generate only one mnemonic in your backend and you create infinite accounts from that mnemonic. From each account you extract the private key and store it, store the address of the account and the index of the account.
Management code:
const HDWalletProvider = require("#truffle/hdwallet-provider");
const Web3 = require("web3");
const mnemonicPhrase = "mnemonicPhrase here";
const urlRPC = "https://bsc-dataseed.binance.org";
//Creating another instance to query balances
const Web3Instance = require('web3');
const web3instance = new Web3Instance(new Web3Instance.providers.HttpProvider(urlRPC));
//HD Wallet Provider loads by default only 10 accounts
//We change the limit to as many accounts as we want
//You cannot run the loop below for i greater than 10, because for
const limit = 50;
async function getAccount() {
provider = new HDWalletProvider({
mnemonic: mnemonicPhrase,
numberOfAddresses: limit,
providerOrUrl: urlRPC,
addressIndex: 0,
});
//HDWalletProvider is compatible with Web3
//Use it at Web3 constructor, just like any other Web3 Provider
const web3 = new Web3(provider);
//I realized that iterating a loop to limit always gives an error when it reaches limit
//This happens in this HD Wallet Provider package
//limit - 1 seems to work best
for (let i = 0; i < limit - 1; i ++) {
var get = await web3.eth.getAccounts()
var address = get[i];
var balanceETH = await web3instance.eth.getBalance(address)
//Checking the adress
console.log(address);
console.log(balanceETH);
}
}
getAccount();
Here is more information:
https://ethereum.stackexchange.com/questions/52370/web3-create-account-from-mnemonic-passphrase/144340#144340