I'm so new to solidity and I'm trying to implement payable Nft using ethers.js. I think I'm checking the balance of the address and comparing it with mintRate * amount wrong. I tried something like this require(msg.value >= mintRate * amount,"not enough ether") but it kept on throwing me the "not enough ether" error although I have enough. The mintRate is 0.0001 eth. but I have like 1.1177 eth. I don't know why I'm getting this error. kindly help me figure this out. thanks in advance
Solidity code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
contract MintNFT_ERC1155 is ERC1155, Ownable, ERC1155Supply {
uint256 public mintRate = 0.0001 ether;
constructor() ERC1155("") {}
function mint(
address account,
uint256 id,
uint256 amount,
string memory uri
) public payable {
require(address(this).balance >= mintRate * amount, "not enough ether sent");
_mint(account, id, amount, "");
_setURI(uri);
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts
) public payable {
_mintBatch(to, ids, amounts, "");
}
// The following functions are overrides required by Solidity.
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal override(ERC1155, ERC1155Supply) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
js :
require("dotenv").config()
const API_URL = process.env.API_URL
const PUBLIC_KEY = process.env.PUBLIC_KEY
const PRIVATE_KEY = process.env.PRIVATE_KEY
const { createAlchemyWeb3 } = require("@alch/alchemy-web3")
const web3 = createAlchemyWeb3(API_URL)
const contract = require("../artifacts/contracts/MintNFT_ERC1155.sol/MintNFT_ERC1155.json")
console.log(JSON.stringify(contract.abi))
const contractAddress = "xxxxxxxxxxx";
const nftContract = new web3.eth.Contract(contract.abi, contractAddress)
mintNFT("ipfs://xxxxxxxxxx",1, 3,)
async function mintNFT(tokenUri, id, amount) {
const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce
//the transaction
const tx = {
'from': PUBLIC_KEY,
'to': contractAddress,
'nonce': nonce,
'gas': 300000,
'data': nftContract.methods.mint(PUBLIC_KEY,id, amount,tokenUri).encodeABI()
};
console.log(tx);
const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY)
signPromise
.then((signedTx) => {
web3.eth.sendSignedTransaction(
signedTx.rawTransaction,
function (err, hash) {
if (!err) {
console.log(
"The hash of your transaction is: ",
hash,
"\nCheck Alchemy's Mempool to view the status of your transaction!"
)
} else {
console.log(
"Something went wrong when submitting your transaction:",
err
)
}
}
)
})
.catch((err) => {
console.log(" Promise failed:", err)
})
}