web3j Error processing transaction request: insufficient funds for gas * price + value - smartcontracts

Following this tutorial
https://github.com/web3j/web3j
Started the geth client as a private network.
Here is the contract code
pragma solidity ^0.4.10;
contract Counter {
uint256 counter =0;
function increase() public {
counter++;
}
function decrease() public{
counter--;
}
function getCounter() public constant returns (uint256) {
return counter;
}
}
Compiled the contract and genetaed the wrapper code for the contract.
Java code for Counter.sol was generated, then I tried to deploy the contract
Web3j web3 = Web3j.build(new org.web3j.protocol.http.HttpService("http://localhost:8080"));
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();
Counter contract = Counter.deploy(web3, credentials,Counter.GAS_PRICE;,Counter.GAS_LIMIT).send(); // constructor params
System.out.println("before increase counter "+contract.getCounter());
contract.increase();
System.out.println("after increase counter "+contract.getCounter());
contract.decrease();
System.out.println("after decrease counter "+contract.getCounter());
Getting exception
ontract gas limit 4300000
[info] counter gas price 22000000000
[error] java.lang.RuntimeException: java.lang.RuntimeException: Error processing transaction request: insufficient funds for gas * price + value
[error] at org.web3j.tx.Contract.deploy(Contract.java:350)
[error] at org.web3j.tx.Contract.lambda$deployRemoteCall$5(Contract.java:384)
[error] at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:30)
[error] at models.smartcontract.FirstContractJava.main(FirstContractJava.java:33)
[error] Caused by: java.lang.RuntimeException: Error processing transaction request: insufficient funds for gas * price + value
[error] at org.web3j.tx.TransactionManager.processResponse(TransactionManager.java:67)
[error] at org.web3j.tx.TransactionManager.executeTransaction(TransactionManager.java:51)
[error] at org.web3j.tx.ManagedTransaction.send(ManagedTransaction.java:87)
[error] at org.web3j.tx.Contract.executeTransaction(Contract.java:275)
[error] at org.web3j.tx.Contract.create(Contract.java:317)
[error] at org.web3j.tx.Contract.deploy(Contract.java:346)
[error] ... 3 more
Then I deployed the contract using ethereum wallet because it estimates the gas limit and gas price for us.
It estimated
gas price 86440
gas limit 186440
So I changed the code like this
BigInteger gp = BigInteger.valueOf(86440);
BigInteger gl = BigInteger.valueOf(186440);
Counter contract = Counter.deploy(web3, credentials,gp,gl).send(); // constructor params
But the exception remained same.
Please guide me how to resolve this exception also how to estimate gas price and gas limit for a contract.

Web3j doesn't give very good default gas price/limit values. I believe they are hardcoded regardless of the contract you develop or the action you try to take. That being said, their default values SHOULD be ok (most of the time) if you have enough ether in your account.
Gas Price
Gas prices fluctuate depending on how much activity is on the network. The more you pay, the more likely (and faster) your transaction will be picked up. Gas prices are measured in Gwei (1 Gwei = 1000000000 Wei). You can see recent gas prices being in MainNet at https://ethgasstation.info/. Usually, you'll see most transactions paying 1-10 Gwei. For higher priority transactions (usually coin/ether transfers as those transactions don't consume a lot of gas), you may see gas prices at 100 or even 1000 Gwei. If you're running a private network, you can use whatever gas price you want (even 0), but you have to set up your miners to accept work at that low of a price. For example, with geth, you can set the minimal gas price with the --gasprice option.
MINER OPTIONS:
--mine Enable mining
--minerthreads value Number of CPU threads to use for mining (default: 8)
--etherbase value Public address for block mining rewards (default = first account created) (default: "0")
--targetgaslimit value Target gas limit sets the artificial target gas floor for the blocks to mine (default: 4712388)
--gasprice "18000000000" --> Minimal gas price to accept for mining a transactions <--
--extradata value Block extra data set by the miner (default = client version)
In your case, the default 22 Gwei is ok, but you can probably lower that to 1-5. However, the 86440 Wei when you deployed through Ethereum Wallet almost certainly won't work.
Gas Limit
Web3j just uses an old default block gas limit as its default value. It has changed over time and is currently around 8 million. Ropsten is fixed and is about 4.7 million. Web3j's default of 4.3 million is just to make sure you don't hit block size limits in test environments. However, if you start a transaction specifying 4.3 million gas at 22 Gwei, you have to have ~0.1 ether in your account. You should be able to lower you gas limit to 200,000 (based off your debug output from deployment, but you would need to post the contract code to confirm).
Balance
Finally, make sure you have ether in your account! Run a simple web3.eth.getBalance() in your geth console to confirm your balance. You can initialize an account balance in your private network in the genesis.json
{
...
"alloc": {
"<ACCT_ID>": {
"balance": "30000000000000000000000000000"
}
}
}

Related

solana spl-token transfer fee "Error: Program(IncorrectProgramId)"

I want to create my own Solana token that takes %2 fee to all transactions and total supply should be 100k token. That's why i used spl-token cli for this spl-token create-token --transfer-fee 50 1000, however after executing this command i get an error like
Error: Program(IncorrectProgramId)
How can i fix this error or how can i create my own token with transaction fee.
When creating a new token with transfer fees, you must specify the program id as the token-2022 program id of TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb, so instead, do:
spl-token --program-id TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb create-token --transfer-fee 50 1000

EVM(Solidity) "read" in "write" behavior

Let's see a Solidity pseudocode example:
function myFunction() external payable onlyOwner {
ExternalContract contract = ExternalContract(address);
uint result = contract.readFunction();
required(result > 0, 'might failed here') //if FALSE transaction not executing at all (works as **view**)
myCustomWriteLogic();
}
The gas fee will NOT be charged if required() will fail.
Is that mean I'm performing "READ" to the blockchain and then putting the transaction to txpool?
How to force push the transaction to txpool? In my case, I belive that result willl be >0 at the execution moment.
I'm executing a transaction via truffle and I want to push it EVEN it might failed:
const obj = await MyContract.deployed();
obj.myFunction({value: 1000});
The gas fee will NOT be charged if required() will fail.
This is correct only if the snippet is invoked using a (read-only) call. If it's invoked using a transaction, gas fees will be deducted for executing of the code until the point where the require() condition fails and produces a revert.
Calls do not go through the mempool, they are executed directly on the node that you're connected to.
How to force push transaction if your wallet recommends you to not send it (as it might fail)? That depends on the specific wallet or code that you're using to broadcast the transaction. For example the MetaMask UI shows a button to force sending the transaction - see the screenshot:

Error: Transaction reverted: function call failed to execute

I am currently working on an nft marketplace and wanna integrate a 2.5% fee on every sale. I have read and reasearched online on how to calcuate percentage in solidity and was successful on that part but the problem is that result its a huge number i.e 2.5 * 150/100 is supposed to return 3.75
but i get this figure instead: 3750000000000000000000000000000000000
My test
const auctionPrice = ethers.utils.parseUnits("1", "ether");
const [_, userAddress] = await ethers.getSigners();
let fee = (2.5 * auctionPrice) / 100;
const commission = ethers.utils.parseUnits(fee.toString(), "ether");
let commissionValue = commission.toString();
console.log(commission.toString());
console.log(fee);
await market
.connect(userAddress)
.createMarketSale(nftContractAddress, 1, commissionValue, {
value: auctionPrice,
});
The Result
250000000000000000000000000000000
1 failing
1) NFTMarket
Should create and execute market sales:
Error: Transaction reverted: function call failed to execute
at NFTMarket.createMarketSale (contracts/NFTMarket.sol:165)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at runNextTicks (node:internal/process/task_queues:65:3)
at listOnTimeout (node:internal/timers:526:9)
at processTimers (node:internal/timers:500:7)
at HardhatNode._mineBlockWithPendingTxs (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:1602:23)
at HardhatNode.mineBlock (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:435:16)
at EthModule._sendTransactionAndReturnHash (node_modules\hardhat\src\internal\hardhat-network\provider\modules\eth.ts:1494:18)
So my question is there any way to turn this number (3750000000000000000000000000000000000) into a decimal or whole number? I have searched but couldnt find any thing online talking about this
In fact there is no problem with your calculation. The problem is the use of the function ethers.utils.parseUnits().
Let's do a quick recap first:
Under the hood, all transactions in Ethereum are paid in wei, that is the smallest denomination of ether. So, if you send 1 ETH to some contract, you are actually sending 1,000,000,000,000,000,000 wei, because 1 ETH = 10^18 wei.
Your code
In the tests, when you use the function ethers.utils.parseUnits("1", "ether"), you are atually saing "I want to send 1 ETH, so please convert this 1 ETH to wei to make my life easier". Then this function simply adds 18 zeros to your "1" string.
Finally, when you perform your calculation (2.5 * auctionPrice) / 100, the result are already in the right format. So you don't have to call perseUnits again, because you are adding more 18 zeros! =D

In my js file for testing .I call a send transaction to the smart contract, so what is the difference between value and gas :

it("allows a manager to make a payment request f(createRequest) ", async ()=> {
await campaign.methods.createRequest('buy beer', accounts[2], '100').send({
from: accounts[0],
gas: '1000000'
});
it('Contribute money from another account & checks whether it is approved or not', async () =>{
await campaign.methods.contribute().send({
from: accounts[1],
value: '200'
});
I want to know deciding factors, when to use gas and when to use value?
value is the amount of the native token that you send with the transaction.
Network
Native token
Ethereum
ETH
Binance Smart Chain
BNB
Tron
TRX
It's expressed in the smallest non-divisible unit. In case of ETH, that's wei. 1 ETH is 10^18 wei.
So as per your example, when you set the value to 200, you're going to send along 0.0000000000000002 ETH to the contract with the execution of the contribute() function.
An example use of the value is when a contract wants to sell you a token for 0.1 ETH. In this case, you set the value to 0.1 ETH while executing the contract's buy() function.
The value does NOT replace the gas fee:
gas is the amount of the fee that you send along with the transaction. For better explanation, what gas is, there's a great post on the Ethereum StackExchange.
But in short - gas is a way of payment for the execution of the smart contract function.
The minimal amount of gas required to execute the function can be usually calculated using the web3 estimateGas() method (there are some exceptions when the estimate is incorrect or impossible to calculate).
Depending on the gasPrice (that's either calculated automatically from recent data or you can overwrite it manually), the total transaction fee is calculated in the native token (e.g. ETH).

binance.exceptions.BinanceAPIException: APIError(code=-1013): Filter failure: LOT_SIZE || binance api || Python

I have a problem with Binance API when placing a market order using the order_market_buy method.
def order_market_buy(symbol, quantity):
client.order_market_buy(symbol=symbol, quantity=quantity, recvWindow=50000)
order_market_buy('BNBBTC', 0.0001)
When you run this code, the following error occurs.
BTC on the wallet account is enough to carry out a transaction.
What could be the cause of the error?
Using the BNBBTC pair means you want to buy BNB using BTC. That error suggests that you don't have enough BTC in your Binance account. Also, the minimum transaction size is $10 so with the current price of BNB you might have to buy closer to .017 of it.