New answers tagged

1

In your case you need to get specific provider in window.ethereum: const metamaskProvider = window.ethereum.providers.find((provider) => provider.isMetaMask);


0

no. Solidity doesnt have decimals, for that reason we decided to add a decimal part to the ERC20 standard, usually (and unless specified otherwise in the code) tokens are considered to have 18 decimals ( so 1 token in the code is is actually 1 * 10**18). Meaning you total supply has to behave the same ( 40000000 * 10**18) and all the relevant numbers in your ...


0

If you want to run a local node I would suggest 2 options. Ganache Hardhat Ganache: you just install it and when you open it you'll get 20 addresses with 100 ETH as balance and the url to connect to it. Hardhat: You could run a local node with the commend npx hardhat node --fork providerURl, that url can be from a free account on Alchemy Disclaimer: I have ...


0

Please tell me, do we need to download a full node or a pruned one? Both light or full node will work if you want to get balance. However, note that if using a light node, the light node will require to connect to another full node to obtain this information, so queries will be slower and will fail if your node fails to connect to a full node. How long ...


0

Not sure if they have a provider available still, but Alchemy is a good alternative. You just sign up for an account, create an app, and then view key:


0

"provider" is a reference to Ethereum node providers A node is essentially a program running on a single computer that allows you to connect with the rest of the blockchain network. It peers with other nodes to send information back and forth, checks that transactions sent between people are valid, and stores important information about the state ...


0

Answer To The Question I have figured out a way to deal with this. The problem was the data was being saved correctly but when fetching the records solidity was assigning msg.sender to the creator of the contract not the one who sent the transaction. So, in order to deal with this I am sending the user address from frontend in the call function and receiving ...


0

You can use bit masks to extract the number on position, but still it would not fit into decimal system. You would have to update your solution to use bites instead of decimals. I don't think that there is a solution (at least trivial which would not cost huge amount of gas) how to extract a decimal on some position in a number.


0

you can use the contract function and that will work. For example if you want to initiate an ETH transaction and you have the function buy() in your contract used for purchasing goods, you can call it with your contract instance: Declare the contract instance: const instance = new web3.eth.Contract(contract.abi, contractAddress) Use the contract instance ...


1

As KonyTech sais "web3.eth.getGasPrice() returns a Promise so you must treat it as such. In your example a is the Promise, not the gas price" (so you need to understand what are promises in JS before learning web3js :) ) When you connect to Ethereum you need to use BigNumber most of the time because js cannot handle those big numbers used in ...


0

If you deployed the contract and lost the address you can simply retrieve it by truffle commands. You just need the name of the deployed contract. For example, I deployed NewContract but lost his address. truffle console --network private truffle(private)> truffle(private)> let contract = await NewContract.deployed() truffle(private)> contract....


0

It's not possible. The connect/disconnect functionality is entirely in the user's hands due to security and privacy concerns. You can only pretend a disconnect by resetting a provider, chainId and selectedAccount to null and clearing the cache of the provided you previously used. P.S.: I know this is a harsh reality. Upvote this as it's the only correct ...


0

If the contract is being deployed you can obviously read it from the log. What if the contract has deployed but you did not take a record of it? There are a few ways to do it: 1. Using etherscan (or Rinkeby scan, Ropsten scan etc..) and search your wallet address used for deployment of the contract. But what if I don't recall the wallet address used? You can ...


0

Something like this should work const events = await erc20Contract.getPastEvents('Transfer', { filter: { to: 0xdead }, fromBlock: 0, toBlock: 'latest' }) This gets you all transfer events for a certain ERC20 token.


1

That seems right for the best case. For the worst case something like this makes sense: quote.buyAmount * (1-slippagePercentage) - (quote.gas * quote.gasPrice) - quote.value - originalWethAmount, where slippagePercentage is the request param you pass in (defaults to 0.01, 1%) But this only works when W/ETH is the buyToken. For a more general solution you ...


0

I was running into the same problem when deploying locally to a Hardhat development node. Everything seemed to work fine when I didn't wait for the deployment to complete (or if I deployed to a live network). To fix the issue, I set autoMine: true in my deployment request and things started working just fine.


1

As far as I can see, I don' see anywhere in your code the syntax where you're actually calling the method. You have the instance of the contract which is myCollectionbut you're not calling the function properly. instead of this: function updateCollection() { myCollection.getNumberObjects (function(errGNO, resGNO) { you can try this: let collection = ...


0

I faced the same issue here, using web3 ^1.3.6. It looks like a problem with the lib itself according to this issue on web3.js repo My solution was storing the transaction hash of each event and comparing this before executing any logic.


0

I think Wallet has to be a var not a const - you can’t update or re-declare a const. So: dotenv.config(); var Web3 = require("web3"); var web3 = new Web3("https://rinkeby.infura.io/v3/" + process.env.INFURA_KEY); web3.eth.getBlock("latest").then(console.log); let gasUsedLast = web3.eth.getBlock("latest").then((...


0

In my case, using truffle, I've solved this way: ...catch((err) => { let message = JSON.parse(err.message.substring(56).trim().replace("'", "")).value.data.data; console.log(message[Object.keys(message)[0]].reason); On this way I can show the message I set on my solidity contract.


0

Please inspect your tokenId. Currently, you are using the output of web3.utils.keccak256 which is a String. But the input of ...ownerOf is expecting an integer (i.e. a BN). To convert from the former to the latter, please try web3.utils.toBN.


0

You can do something like this. Const gasUsed = async()=>{ const result = await web3.eth.getblock("latest") return result } ;(async()=>{ const gasFees = await gasUsed() console.log(gasFees) } The function would look something like this. I'm also learning solidity & ether but this is how i would do it.


1

Can you try decodeParameters? Like: const erc20TransferABI = [{ type: "address", name: "receiver" },{ type: "uint256", name: "amount" }]; const decoded = web3.eth.abi.decodeParameters( erc20TransferABI, tx.input.slice(10)); // Or (11), not sure Even perhaps, take ...


0

If you want the user to pay with tokens. Your contract should look like this pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/tokens/ERC20/IERC20.sol" // npm install @openzeppelin-contracts required contract PaymentInvoiceSplit { uint productPrice; constructor (uint defaultProductPrice) { owner = msg.sender; ...


0

use This Library https://github.com/MikeMcl/bignumber.js/ as like import BigNumber from "bignumber.js"; // or import { BigNumber } from "bignumber.js"; let x = new BigNumber(123.4567); let y = BigNumber('123456.7e-3'); let z = new BigNumber(x); x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z);


0

You shouldn't be using web3.currentProvider anymore. This is the old way. Do this instead: if (window.ethereum) { web3 = new Web3(window.ethereum); } else { // Code for HttpProvider remains unchanged } await window.ethereum.send('eth_requestAccounts'); See How to Connect Web3.js to MetaMask in 2021


1

Wierd, it seems to read your input as 1*10^-15, you sure you really typed -1*10^15? anyways if it still doesnt work after double checking i suggest inputting the full number with all the 0s written


0

If you write a new contract, you can simulate different code paths in Solidity using unit tests.


0

Found out that the value should be string hex.


0

Only Ethereum nodes are able to execute transactions or request information from the blockchain. The provider is a service that directly communicates with Ethereum nodes to fetch or send information to the blockchain. Whenever Web3 needs to access the Ethereum blockchain (e.g. sending a transaction) a request is made to a provider that directly forwards the ...


0

The actual issue here is that you are using the await at the top level of the JS, you would avoid the issue by doing something like this (but it's worth noting that you are probably going to run into other issues after this - since there's nothing really being done with that web3 variable): import React from 'react'; import { ChainId, DAppProvider } from &...


0

ONe thing that maybe causing this issue The front sends 1 ether contractInstance.methods.betxc(x).send({value: web3.utils.toWei("1", "ether")}) and the contract when winning send twice that amount msg.sender.transfer(msg.value*2); For the transfer to succeed the contract needs to have a balance greater than 2 ether. Note: block....


1

I had same errors and I solved it now by raising the gas limit when sending transaction! I recommend you raise your gas limit and try it again.


1

Well I ended up figuring this out myself I think. In case anyone else runs into this issue, here is the relevant code at site-packages/eth_abi/encoding.py: def encode(cls, value): cls.validate_value(value) if not value: padded_value = b'\x00' * 32 else: padded_value = zpad_right(value, ceil32(len(value))) ...


0

web3.toDecimal(web3.fromWei(web3.eth.getBalance('wallet-address'))) OR web3.toDecimal(web3.fromWei(web3.eth.getBalance('wallet-address'),'ether'))


0

You are likely using too old node version. Please check out when top level await reached out Node.js support.


0

You will not be able achieve this. Metamask is providing your browser with a web3 module that you can use to connect your app to the blockchain. The users will be able to connect to your app to sign transaction. In order to connect your app to the blockchain, you will need web3 or ethersjs. https://web3js.readthedocs.io/en/v1.5.2/getting-started.html https://...


0

If you have the contract's ABI you can use encodeABI. If you don't have the contract's ABI then you can use web3.eth.abi.encodeFunctionCall, or combine some of the other functions from web3.eth.abi.*. You can also use ethereumjs-abi that implements this functionality.


1

Connecting your wallet doesn't really do much: it doesn't send any transactions. About all it does it gives your wallet's public address to the website and the possibility for the website to request actions from the wallet - actions which you, as a user, need to accept manually. In theory, everything would be smoother and more user friendly if your wallet ...


0

If this function is just a view function then no gas should be required. Maybe your ABI was altered and when you make the instance of the contract locally, the web3 library thinks that this requires some gas cause it is changing the state


0

Yes there is an official list. And here is an example implementation in Javascript JSON format: const METAMASK_POSSIBLE_ERRORS = { '-32700': { standard: 'JSON RPC 2.0', message: 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.', }, '-32600': { standard: 'JSON ...


1

web3 contract instance had gasPrice set very low. You can use https://ethgasstation.info/ to get actual price. I didn't knew that it does meters when you .call() not .send()


0

First, web3.eth.getGasPrice() returns a Promise so you must treat it as such. In your example a is the Promise, not the gas price. The cleanest way to achieve this is to await on the Promise. Since it is asynchronous, by awaiting it you automatically get the value returned by the Promise: // Get the gas price a = await web3.eth.getGasPrice(); However, we're ...


0

Looking at the documentation, it says Returns: String|BN: If a string is given it returns a number string, otherwise a BN.js instance. Which means, if you instantiated your wei amount using a string, like this: const amount= web3.utils.toWei("1000","ether") It will return a string value. Now if you try to add two strings together, as ...


0

As Jaime pointed above, I had to pad the hex representation with 0's until it had 32 bytes. I've made the following function to pad the hex string: function padUntil32Bytes(string) { string = string.padEnd(32,'0'); return string; } And created the hash as follows: secret = web3.utils.toHex('A'); secret = padUntil32Bytes(secret) const result = await ...


0

It seems that there are changes when using the web3 library everytime. At the time of writing. It seems that the block variable is a promise! What is meant by promise? Promises in JavaScript represent processes that are already happening, which can be chained with callback functions as described here. So it seems that the only viable way to get how many ...


0

There is no way to determine in which block your transaction is mined. The transaction order depends on the miner configuration, transaction nonce, etc. Nothing that you can determine in advance.


0

if it is for basic dApp requirement, you can use web3.eth.getBlockNumber(). Please let me share an example code snippet available on GitHub from a recently updated repository. getPastLockboxSoldEvents: async function (pastBlockCount) { if (this.contract) { let events = await this.contract.getPastEvents('LockboxSold', { ...


1

The issue is the representation of the data. When you move to bytes32 the resulting data after abi.encodedPacked has 32 bytes, but the data used for the hash in your code SHA256(A) is not 32 bytes. So you need to pad the hex representation of A with the necessary number of zeros to make it 32 bytes long, because this is what your smart contract is also doing....


0

All errors thrown or returned by the MetaMask provider follow this interface: interface ProviderRpcError extends Error { message: string; code: number; data?: unknown; } The ethereum.request(args) method throws errors eagerly. You can often use the error code property to determine why the request failed. Common codes and their meaning include: 4001 : ...


Top 50 recent answers are included