MetaMask - RPC Error: Internal JSON-RPC error - error-handling

I am developing a NFT Minting Website on CELO. My mint function looks like this:
function safeMint(address to) public payable {
require(msg.value >= mintPrice, "Not enough ETH sent; check price!");
uint256 tokenId = _tokenIdCounter.current();
_safeMint(to, tokenId);
_tokenIdCounter.increment();
// string memory token_uri=tokenURI(tokenId);
}
My react front end looks like this:
async function mintNFT() {
if (typeof window.ethereum !== 'undefined') {
await requestAccount()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(t_tokenAddress, Token.abi, signer);
try{
await window.ethereum.enable();
const transation = await contract.safeMint(userAccount);
await transation.wait();
fetchNFTIndex();
}
catch(e){
console.log(e.data.message);
}
}
}
I get the following error when I run the transaction with mintPrice =1 wei or ether:
Error
When I run the transaction with mintPrice=0 ether or wei it works fine. I dont know what is the problem here. I have 5 celos in my account so I have enough funds, I assume that ethers are converted and paid in CELO.
Can anyone understand the problem here!

The linked error contains the custom message "Not enough ETH sent", which means the error originates from the require() condition.
require(msg.value >= mintPrice, "Not enough ETH sent; check price!");
Your JS snippet executes the function, but doesn't send any ETH value with the transaction.
In order to send ETH value, you need to define it in the overrides parameter.
const transation = await contract.safeMint(userAccount, {
// send along 1 wei
value: 1
});

Related

AAVE v3 - POLYGON - TEST <UnrecognizedContract>.<unknown> When running a script to deposit tokens to AAVE using a fork of the polygon mainnet

I'm testing v3 AAVE contracts on a fork of the polygon mainnet using harhat locally, but when I call de supply() function I get this error:
Error: Transaction reverted without a reason string
at <UnrecognizedContract>.<unknown> (0x794a61358d6845594f94dc1db02a252b5b4814ad)
at <UnrecognizedContract>.<unknown> (0x794a61358d6845594f94dc1db02a252b5b4814ad)
at <UnrecognizedContract>.<unknown> (0x794a61358d6845594f94dc1db02a252b5b4814ad)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at HardhatNode._mineBlockWithPendingTxs (/home/daniel/daniel/dev/chainlink/flowmi/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:1802:23)
at HardhatNode.mineBlock (/home/daniel/daniel/dev/chainlink/flowmi/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:491:16)
at EthModule._sendTransactionAndReturnHash (/home/daniel/daniel/dev/chainlink/flowmi/node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:1522:18)
at HardhatNetworkProvider.request (/home/daniel/daniel/dev/chainlink/flowmi/node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:118:18)
at EthersProviderWrapper.send (/home/daniel/daniel/dev/chainlink/flowmi/node_modules/#nomiclabs/hardhat-ethers/src/internal/ethers-provider-wrapper.ts:13:20)
The script I'm trying to run:
const { getNamedAccounts, ethers } = require("hardhat");
async function main() {
const { deployer } = await getNamedAccounts();
// Mainnet pool adready given by the deployment
// Deposit
// Aprove to get Matic
const AMOUNT = ethers.utils.parseEther("0.11");
//const maticTokenAddress = "0x0000000000000000000000000000000000001010"; //mainnet
const Pool = await getPool(deployer);
const maticTokenAddress = "0xD65d229951E94a7138F47Bd9e0Faff42A7aCe0c6"; // testnet matic address
await approveErc20(maticTokenAddress, Pool.address, AMOUNT, deployer);
console.log("Depositing...");
console.log("Address provided: ", Pool.address);
await Pool.supply(maticTokenAddress, AMOUNT, deployer, 0);
console.log("Deposited!");
}
async function getPool(account) {
const PoolAddressesProvider = await ethers.getContractAt(
"IPoolAddressesProvider",
"0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb", // mainnet pool addresses provider
//"0x5343b5bA672Ae99d627A1C87866b8E53F47Db2E6", // testnet pool addresses provider
account
);
const PoolAddress = await PoolAddressesProvider.getPool();
const Pool = await ethers.getContractAt("IPool", PoolAddress, account);
return Pool;
}
async function approveErc20(
erc20Address,
spenderAddress,
amountToSpend,
account
) {
const erc20Token = await ethers.getContractAt(
"IERC20",
erc20Address,
account
);
const tx = await erc20Token.approve(spenderAddress, amountToSpend);
await tx.wait(1);
console.log("Approved!");
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
When I ask for which address was provided the answer is:
Address provided: 0x794a61358D6845594F94dc1DB02A252b5b4814aD
Which happens to be a polygon mainnet pool address according to documentation. Notice is the same address the error gives.
I'll be most thankful if someone points out my mistake
I've tried different combinations of "mainnet" and "testnet" addresses, for the maticToken, and the pool addresses provider
The problem was the matic address, It seems I misundertood documentation, thought the fact that matic is an ERC20 compliant implied it should not need to be wrapped to deposit.
But the script only works with the address of wrapped matic on mainnet.
Maybe is a problem of the mainnet fork, don't know but I moved on.

Error in Remix "Error from IDE : Invalid account selected"

I'm new to Remix and Solidity and don't understand why I recieve error message "Error from IDE : Invalid account selected".
Below line is executed successfully:
await contract.methods.SetMaxSupply("600").send({from: accounts[0]});
Below line results in above mentioned error message:
let supply = await contract.methods.current_supply().call()
Solidity code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
contract Test is Ownable {
uint public max_supply;
function SetMaxSupply(uint amount) public onlyOwner {
max_supply = amount;
}
function current_supply() public view returns(uint) {
return max_supply * 3;
}
}
Remix JS Script:
// Right click on the script name and hit "Run" to execute
(async () => {
try {
console.log('Running deployWithWeb3 script...')
// replace with contract address
const contractAddress = '0xd9145CCE52D386f254917e481eB44e9943F39138'
const contractName = 'Test' // Change this for other contract
// Note that the script needs the ABI which is generated from the compilation artifact.
// Make sure contract is compiled and artifacts are generated
const artifactsPath = `browser/contracts/StackOverflow/artifacts/${contractName}.json` // Change this for different path
const metadata = JSON.parse(await remix.call('fileManager', 'getFile', artifactsPath))
const abi = metadata.abi
// instantiate a new web3 Contract object
let contract = new web3.eth.Contract(abi, contractAddress)
const accounts = await web3.eth.getAccounts()
await contract.methods.SetMaxSupply("600").send({from: accounts[0]});
let supply = await contract.methods.current_supply().call()
console.log(supply)
} catch (e) {
console.log(e.message)
}
})()
Try changing the Account parameter in the Deploy & Run Transaction

How can do a contract to Approve user manipuler her tokens?

Like I have own token
And I develope an Dapp to transfer between us my own personal token.
To do that I have to Approve and then use transferFrom, aren't¿
I check some nft games and always, then force my to approve before play.
I have tryed to do that but if I have
Contrat MyToken
Contract MyDapp
When I save user address to Approve, I send Approve from MyDapp to MyToken, then approve no works.
How can I do that? or what is the good way to do that?
Thanks
Let's say you want to approve compound USDT with this contract address on Rinkeby
your JavaScript code with ethers.js library (it could be python or java too, library is important) (Note that I only use front-end and I personally know nothing about back-end)
const ethers = require('ethers');
const USDTInterface = ['function approve(address spender, uint256 amount) external returns (bool)'];
const USDTAddress = '0xD9BA894E0097f8cC2BBc9D24D308b98e36dc6D02';
const yourContractAddress = YOUR_DAPP_CONTRACT_ADDRESS;
let provider;
let signer;
let signerAddress;
let USDTContract;
const startFunction = async () => {
await ethereum.request({ method: 'eth_requestAccounts'});
await ethereum.request({ method: 'wallet_switchEthereumChain', params:[{chainId: '0x4'}]});
provider = new ethers.providers.Web3Provider(window.ethereum);
signer = provider.getSigner();
signerAddress = await signer.getAddress();
USDTContract = await new ethers.Contract(USDTAddress, USDTInterface, signer);
}
startFunction();
async function approveUSDT(){
USDTContract.approve(yourContractAddress, BigInt("9007199254740990")**3n);
}
//Whenever this function is called, a transaction request is sent to user's metamask and whenever
//user confirms it, it is approved!

TronWeb to send trc20 usdt

I want to use TronWeb to send trc20 token. Whether I need to use contract().at() to do this? It means I need to treat trc20 token just as smart contract?
first things first, to clarify every token on any network (not just tron) has its own smart contract that has been published to the network
here is the code to get your account balance and another to transfer USDT
don't forget to init the code with your private key and network endpoints
note that you need tron energy and bandwidth to perform a transaction
you can read about them using this link
const CONTRACT = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
async function getBalance(account) {
const {
abi
} = await tronWeb.trx.getContract(CONTRACT);
const contract = tronWeb.contract(abi.entrys, CONTRACT);
const balance = await contract.methods.balanceOf(account).call();
console.log("balance:", balance.toString());
}
async function transferUSDT(destination, amount) {
const {
abi
} = await tronWeb.trx.getContract(CONTRACT);
const contract = tronWeb.contract(abi.entrys, CONTRACT);
const resp = await contract.methods.transfer(destination, amount).send();
console.log("transfer:", resp);
}
When you init the tronweb compnent with private key ,you could use the contract().at()
tronWeb = new TronWeb(
'https://api.nileex.io/',
'https://api.nileex.io/',
'https://event.nileex.io/',
'your privateKey'
);

My is metamask returning RPC Error: Error: [ethjs-rpc] rpc error with payload, metamask shows failed [object, object]

My metamask shows ALERT: Transaction Error. Exception thrown in contract code. When I am about to transfer using truffle, open zeppelin and ganache on localhost:7545
after confirming the transaction it shows
inpage.js:1 MetaMask - RPC Error: Error: [ethjs-rpc] rpc error with payload {"id":6736485951990,"jsonrpc":"2.0","params":["0xf86f048504a817c800836170d494ef9b511c0ddaea1f38ed82becb523a414dc6d7cc8806f05b59d3b2000080822d46a0fa7b64f06fe5520527e3ea35a445d3c461ca97ac25d73062caa9d64025fde7aaa02a5127f46ea982b6b71fd88ebe2a22679b45de0ebaef32137a65171f562caa03"],"method":"eth_sendRawTransaction"} [object Object] {code: -32603, message: "Error: [ethjs-rpc] rpc error with payload {"id":67…method":"eth_sendRawTransaction"} [object Object]", stack: "Error: Error: [ethjs-rpc] rpc error with payload {…method":"eth_sendRawTransaction"} [object Object]"}
My Crowdsale code
pragma solidity ^0.5.8;
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol";
contract MyCrowdsale is Crowdsale, TimedCrowdsale, CappedCrowdsale, AllowanceCrowdsale {
constructor (
uint256 _rate,
address payable _wallet,
ERC20 _token,
uint256 _openingTime,
uint256 _closingTime,
uint256 _cap,
address _tokenAdd
)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
CappedCrowdsale(_cap)
AllowanceCrowdsale(_wallet)
public
{
}
}
deploy_contract.js
module.exports = async function (deployer, network, accounts) {
await deployer.deploy(A1Token, "A1Token", "A1T", 2,5000000);
//deployer.deploy(AddNumbers);
const deployedToken = await A1Token.deployed();
console.log(deployedToken.address)
const rate = 1000;
const wallet = accounts[0];
const timeNow = Math.floor(Date.now() / 1000);
const openingTime = timeNow + duration.seconds(30);
const closingTime = timeNow + duration.years(1);
const cap = web3.utils.toWei("100");
console.log(cap)
await deployer.deploy(MyCrowdsale,
rate, wallet, deployedToken.address, openingTime, closingTime, cap, wallet
);
const deployedCrowdsale = await MyCrowdsale.deployed();
//await deployedToken.transfer(deployedCrowdsale.address, await deployedToken.totalSupply());
deployedToken.approve(deployedCrowdsale.address, 20000);
console.log(deployedCrowdsale.address);
}
And this is linked to a ERC20 token with an initial supply.
I have tried reinstalling metamask and clearing cache, i have enabled ethereum.enable();, tried using truffle develop account, ganache CLI and GUI, changing gas limit and gas. How do i fix this?