My contract for ERC1155 marketplace to mint buy and sell the NFT.
The nft is getting minted , However the NFT is not showing in market place and not able to purchase. I am facing this error.I have also applied setApprovedforAll method while minting still no help.
Should create and execute market sales:
Error: VM Exception while processing transaction: reverted with reason string 'ERC1155: caller is not owner nor approved'
at NFT1155.balanceOf (#openzeppelin/contracts/token/ERC1155/ERC1155.sol:71)
at NFT1155.isApprovedForAll (#openzeppelin/contracts/token/ERC1155/ERC1155.sol:110)
at NFT1155.createMarketSale (contracts/NFT1155.sol:165)
at async HardhatNode._mineBlockWithPendingTxs (node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:1772:23)
at async HardhatNode.mineBlock (node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:466:16)
at async EthModule._sendTransactionAndReturnHash (node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:1496:18)
at async HardhatNetworkProvider.request (node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:118:18)
at async EthersProviderWrapper.send (node_modules/#nomiclabs/hardhat-ethers/src/internal/ethers-provider-wrapper.ts:13:20)
My contract for ERC1155 marketplace to mint buy and sell the NFT.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "#openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
import "hardhat/console.sol";
contract NFT1155 is ERC1155, Ownable, ERC1155Supply {
//contract address goes here and id will be dynamic and will be passed in the _mint function calls
//example https://ipfs.io/ipfs/QmT51bbxTbSiYGcF2X39sG6DGYyAX2413A1sZfiACMgJGP?filename={id}.json
//if the if id 1 then https://ipfs.io/ipfs/QmT51bbxTbSiYGcF2X39sG6DGYyAX2413A1sZfiACMgJGP?filename=1.json will return the data that needs to be minted
constructor() ERC1155("") {}
mapping(uint256 => string) internal _tokenURIs;
mapping(uint256 => MarketItem) private idToMarketItem;
Counters.Counter private _itemsSold;
struct MarketItem {
uint256 tokenId;
address payable seller;
address payable owner;
uint256 price;
bool sold;
}
event MarketItemCreated(
uint256 indexed tokenId,
address seller,
address owner,
uint256 price,
bool sold
);
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
//To chnage the URL String after the contract is deployed
function setURI(string memory newuri) public onlyOwner {
_setURI(newuri);
}
function mintToken(
string memory tokenURI,
uint256 amount,
uint256 price
) public returns (uint256) {
uint256 newItemId = _tokenIds.current();
_mint(address(this), newItemId, amount, "");
_setTokenUri(newItemId, tokenURI);
//createMarketItem(newItemId, price, amount);
_tokenIds.increment();
return newItemId;
}
function createMarketItem(
uint256 tokenId,
uint256 price,
uint256 amount
) private {
require(price > 0, "Price must be at least 1 wei");
idToMarketItem[tokenId] = MarketItem(
tokenId,
payable(msg.sender),
payable(address(this)),
price,
false
);
setApprovalForAll(address(this), true);
safeTransferFrom(msg.sender, address(this), tokenId, amount, "");
emit MarketItemCreated(
tokenId,
msg.sender,
address(this),
price,
false
);
}
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _value,
bytes calldata _data
) external returns (bytes4) {
return
bytes4(
keccak256(
"onERC1155Received(address,address,uint256,uint256,bytes)"
)
);
}
function _setTokenUri(uint256 tokenId, string memory tokenURI) private {
_tokenURIs[tokenId] = tokenURI;
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public onlyOwner {
_mintBatch(to, ids, amounts, data);
}
// 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);
}
/* allows someone to resell a token they have purchased */
function resellToken(
uint256 tokenId,
uint256 price,
uint256 amount
) public payable {
require(
idToMarketItem[tokenId].owner == msg.sender,
"Only item owner can perform this operation"
);
idToMarketItem[tokenId].sold = false;
idToMarketItem[tokenId].price = price;
idToMarketItem[tokenId].seller = payable(msg.sender);
idToMarketItem[tokenId].owner = payable(address(this));
_itemsSold.decrement();
safeTransferFrom(msg.sender, address(this), tokenId, amount, "");
}
/* Creates the sale of a marketplace item */
/* Transfers ownership of the item, as well as funds between parties */
function createMarketSale(uint256 tokenId, uint256 amount) public payable {
uint256 price = idToMarketItem[tokenId].price;
address seller = idToMarketItem[tokenId].seller;
console.log(
" ~ file: NFT1155.sol ~ line 147 ~ createMarketSale ~ price",
msg.value,
price
);
// require(
// msg.value == price,
// "Please submit the asking price in order to complete the purchase"
// );
idToMarketItem[tokenId].owner = payable(msg.sender);
idToMarketItem[tokenId].sold = true;
idToMarketItem[tokenId].seller = payable(address(0));
_itemsSold.increment();
safeTransferFrom(address(this), msg.sender, tokenId, amount, "");
setApprovalForAll(address(this), true);
// payable(owner).transfer(listingPrice);
payable(seller).transfer(msg.value);
}
/* Returns all unsold market items */
function fetchMarketItems() public view returns (MarketItem[] memory) {
uint256 itemCount = _tokenIds.current();
uint256 unsoldItemCount = _tokenIds.current() - _itemsSold.current();
uint256 currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
for (uint256 i = 0; i < itemCount; i++) {
if (idToMarketItem[i + 1].owner == address(this)) {
uint256 currentId = i + 1;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/* Returns only items that a user has purchased */
function fetchMyNFTs() public view returns (MarketItem[] memory) {
uint256 totalItemCount = _tokenIds.current();
uint256 itemCount = 0;
uint256 currentIndex = 0;
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == msg.sender) {
itemCount += 1;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == msg.sender) {
uint256 currentId = i + 1;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/* Returns only items a user has listed */
function fetchItemsListed() public view returns (MarketItem[] memory) {
uint256 totalItemCount = _tokenIds.current();
uint256 itemCount = 0;
uint256 currentIndex = 0;
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].seller == msg.sender) {
itemCount += 1;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].seller == msg.sender) {
uint256 currentId = i + 1;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
}
The problem is that because of the way you are minting, you don't own the token, the contract does.
Since you don't own the token, it doesn't appear in marketplaces and you can't call approve or transfer because you are not the owner of the token.
Here is the culprit:
_mint(address(this), newItemId, amount, "");
You are minting to address(this) which is the address of the contract itself.
You'll need a way to send the token from the contract to whomever you want using a custom function, or the probably better solution, you can just mint to the address calling your mintToken function by doing:
_mint(msg.sender, newItemId, amount, "");
Best of luck!!
When You call safeTransferFrom, require statement is not passing
function safeTransferFrom(address from,address to,uint256 id,uint256 amount,bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
Most likely you are transferring a token from the account that does not own the token,
You are using safeTransferFrom which is a public function. Try using _safeTransferFrom.You should add a custom function users can call, and internally use _safeTransferFrom
Related
I'm new to dydx flashloans and im builidng a flashloan that should borrow 1INCH tokens but when i tested it on remix it gave an error saying that the token wasnt supported. Is my code wrong or i just cant borrow 1INCH tokens from dydx.
import "#uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "#openzeppelin/contracts/token/ERC20/IERC20.sol";
interface Structs {
struct Val {
uint256 value;
}
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AssetDenomination {
Wei // the amount is denominated in wei
}
enum AssetReference {
Delta // the amount is given as a delta from the current value
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
abstract contract DyDxPool is Structs {
function getAccountWei(Info memory account, uint256 marketId)
public
view
virtual
returns (Wei memory);
function operate(Info[] memory, ActionArgs[] memory) public virtual;
}
contract DyDxFlashLoan is Structs {
DyDxPool pool = DyDxPool(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
address public WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
mapping(address => uint256) public currencies;
constructor() {
currencies[WETH] = 1;
}
modifier onlyPool() {
require(
msg.sender == address(pool),
"FlashLoan: could be called by DyDx pool only"
);
_;
}
function tokenToMarketId(address token) public view returns (uint256) {
uint256 marketId = currencies[token];
require(marketId != 0, "FlashLoan: Unsupported token");
return marketId - 1;
}
// the DyDx will call `callFunction(address sender, Info memory accountInfo, bytes memory data) public` after during `operate` call
function flashloan(
address token,
uint256 amount,
bytes memory data
) internal {
IERC20(token).approve(address(pool), amount + 1);
Info[] memory infos = new Info[](1);
ActionArgs[] memory args = new ActionArgs[](3);
infos[0] = Info(address(this), 0);
AssetAmount memory wamt = AssetAmount(
false,
AssetDenomination.Wei,
AssetReference.Delta,
amount
);
ActionArgs memory withdraw;
withdraw.actionType = ActionType.Withdraw;
withdraw.accountId = 0;
withdraw.amount = wamt;
withdraw.primaryMarketId = tokenToMarketId(token);
withdraw.otherAddress = address(this);
args[0] = withdraw;
ActionArgs memory call;
call.actionType = ActionType.Call;
call.accountId = 0;
call.otherAddress = address(this);
call.data = data;
args[1] = call;
ActionArgs memory deposit;
AssetAmount memory damt = AssetAmount(
true,
AssetDenomination.Wei,
AssetReference.Delta,
amount + 1
);
deposit.actionType = ActionType.Deposit;
deposit.accountId = 0;
deposit.amount = damt;
deposit.primaryMarketId = tokenToMarketId(token);
deposit.otherAddress = address(this);
args[2] = deposit;
pool.operate(infos, args);
}
}
contract Arbitrage is DyDxFlashLoan {
IUniswapV2Router02 immutable uRouter;
IUniswapV2Router02 immutable sRouter;
address public owner;
constructor(address _uRouter, address _sRouter) {
uRouter = IUniswapV2Router02(_uRouter);
sRouter = IUniswapV2Router02(_sRouter);
owner = msg.sender;
}
function executeTrade(
address _tokenA,
uint _tokensFromFlashLoan,
address _tokenB,
bool _startOnUniswap
) external {
uint balanceBefore = IERC20(_tokenA).balanceOf(address(this));
bytes memory data = abi.encode(
_startOnUniswap,
_tokenA,
_tokenB,
_tokensFromFlashLoan,
balanceBefore
);
flashloan(_tokenA, _tokensFromFlashLoan, data);
}
function callFunction(
address,
Info calldata,
bytes calldata data
) external onlyPool {
(
bool _startOnUniswap,
address _tokenA,
address _tokenB,
uint256 _tokensFromFlashLoan,
uint256 balanceBefore
) = abi.decode(data, (bool, address, address, uint256, uint256));
uint balanceAfter = IERC20(_tokenA).balanceOf(address(this));
require(
balanceAfter - balanceBefore == _tokensFromFlashLoan,
"didnt receive flash loan"
);
address[] memory tokens;
if (_startOnUniswap == true) {
tokens[0] = _tokenA;
tokens[1] = _tokenB;
swapOnUniswap(_tokensFromFlashLoan, 0, tokens);
tokens[0] = _tokenB;
tokens[1] = _tokenA;
swapOnSushiswap(
IERC20(tokens[0]).balanceOf(address(this)),
0,
tokens
);
} else {
tokens[0] = _tokenA;
tokens[1] = _tokenB;
swapOnSushiswap(_tokensFromFlashLoan, 0, tokens);
tokens[0] = _tokenB;
tokens[1] = _tokenA;
swapOnUniswap(
IERC20(tokens[0]).balanceOf(address(this)),
0,
tokens
);
}
}
function swapOnUniswap(
uint _amountIn,
uint _amountOut,
address[] memory _path
) internal {
require(
IERC20(_path[0]).approve(address(uRouter), _amountIn),
"Uniswap failed the approval"
);
uRouter.swapExactTokensForTokens(
_amountIn,
_amountOut,
_path,
address(this),
(block.timestamp + 1200)
);
}
function swapOnSushiswap(
uint _amountIn,
uint _amountOut,
address[] memory _path
) internal {
require(
IERC20(_path[0]).approve(address(sRouter), _amountIn),
"Sushiswap failed the approval"
);
uRouter.swapExactTokensForTokens(
_amountIn,
_amountOut,
_path,
address(this),
(block.timestamp + 1200)
);
}
}```
I tried to look at dydx docs but i didnt find nothing that could help me
My goal is to sell nfts that can be bought with my own cryptocurrency on my market. For this, I access my own token using the IERC20 interface within my market contract. But I'm not that good at solidity. If I come to the plain. How do I get permission to shop with the BVC token (my token) in the user's wallet when the buy button is clicked on my website and I make this payment.
THIS MARKET.sol CODE
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.9;
import "#openzeppelin/contracts/utils/Counters.sol";
import "#openzeppelin/contracts/security/ReentrancyGuard.sol";
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/token/ERC20/IERC20.sol";
contract Market is ReentrancyGuard, Ownable {
struct TokenInfo{
IERC20 paytoken;
uint256 listingFee;
uint256 mintingFee;
uint256 price;
}
using Counters for Counters.Counter;
Counters.Counter private _itemIds;
Counters.Counter private _itemsSold;
IERC20 public paytoken;
TokenInfo[] public AllowedCrypto;
address payable holder;
//uint256 listingFee = 0.0025 ether;
//uint256 mintingFee = 0.0075 ether;
constructor() {
holder = payable(msg.sender);
}
struct VaultItem {
uint itemId;
address nftContract;
uint256 tokenId;
address payable seller;
address payable holder;
uint256 price;
bool sold;
}
mapping(uint256 => VaultItem) private idToVaultItem;
event VaultItemCreated (
uint indexed itemId,
address indexed nftContract,
uint256 indexed tokenId,
address seller,
address holder,
uint256 price,
bool sold
);
function AddCurrency (IERC20 _paytoken,uint256 _listingFee,uint256 _mintingFee,uint256 _price) public onlyOwner {
AllowedCrypto.push(TokenInfo({
paytoken:_paytoken,
listingFee:_listingFee,
mintingFee: _mintingFee,
price:_price
}));
}
function approveCRI (uint256 _pid) public payable nonReentrant{
TokenInfo storage tokens = AllowedCrypto[_pid];
paytoken = tokens.paytoken;
uint256 amount = 200000000000000000000000000;
paytoken.approve(msg.sender, amount);
}
function allowenceCRI (uint256 _pid) public payable nonReentrant{
TokenInfo storage tokens = AllowedCrypto[_pid];
paytoken = tokens.paytoken;
paytoken.allowance(address(this), msg.sender);
}
function getListingFee(uint256 _pid) public view returns (uint256) {
TokenInfo storage tokens = AllowedCrypto[_pid];
uint256 listingFee;
listingFee = tokens.listingFee;
return listingFee;
}
function createVaultItem(address nftContract,uint256 tokenId,uint256 _pid) public payable nonReentrant {
TokenInfo storage tokens = AllowedCrypto[_pid];
paytoken = tokens.paytoken;
uint256 listingFee;
listingFee = tokens.listingFee;
uint256 price;
price = tokens.price;
require(price > 0, "Price cannot be zero");
require(msg.value == listingFee, "Price cannot be listing fee");
_itemIds.increment();
uint256 itemId = _itemIds.current();
idToVaultItem[itemId] = VaultItem(itemId,nftContract,tokenId,payable(msg.sender),payable(address(0)),price,false);
IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId);
emit VaultItemCreated(itemId,nftContract,tokenId,msg.sender,address(0),price,false);
}
function n2DMarketSale(address nftContract,uint256 itemId,uint256 _pid) public payable nonReentrant {
TokenInfo storage tokens = AllowedCrypto[_pid];
paytoken = tokens.paytoken;
uint256 listingFee;
listingFee = tokens.listingFee;
uint price = tokens.price; //idToVaultItem[itemId].price;
uint tokenId = idToVaultItem[itemId].tokenId;
paytoken.approve(msg.sender, price);
require(msg.value == paytoken.balanceOf(address(this)), "Not enough balance to complete transaction");
idToVaultItem[itemId].seller.transfer(msg.value);
IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);
idToVaultItem[itemId].holder = payable(msg.sender);
idToVaultItem[itemId].sold = true;
_itemsSold.increment();
payable(holder).transfer(listingFee);
}
function getAvailableNft() public view returns (VaultItem[] memory) {
uint itemCount = _itemIds.current();
uint unsoldItemCount = _itemIds.current() - _itemsSold.current();
uint currentIndex = 0;
VaultItem[] memory items = new VaultItem[](unsoldItemCount);
for (uint i = 0; i < itemCount; i++) {
if (idToVaultItem[i + 1].holder == address(0)) {
uint currentId = i + 1;
VaultItem storage currentItem = idToVaultItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
function getMyNft() public view returns (VaultItem[] memory) {
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToVaultItem[i + 1].holder == msg.sender) {
itemCount += 1;
}
}
VaultItem[] memory items = new VaultItem[](itemCount);
for (uint i = 0; i < totalItemCount; i++) {
if (idToVaultItem[i + 1].holder == msg.sender) {
uint currentId = i + 1;
VaultItem storage currentItem = idToVaultItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
function getMyMarketNfts() public view returns (VaultItem[] memory) {
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToVaultItem[i + 1].seller == msg.sender) {
itemCount += 1;
}
}
VaultItem[] memory items = new VaultItem[](itemCount);
for (uint i = 0; i < totalItemCount; i++) {
if (idToVaultItem[i + 1].seller == msg.sender) {
uint currentId = i + 1;
VaultItem storage currentItem = idToVaultItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
function withdraw(uint256 _pid) public payable onlyOwner() {
TokenInfo storage tokens = AllowedCrypto[_pid];
paytoken = tokens.paytoken;
require(msg.sender.balance == paytoken.balanceOf(address(this)));
paytoken.transfer(msg.sender, paytoken.balanceOf(address(this)));
}
}
the approval must be called directly from the token contract, as the approval is performed through the msg.sender (the user).
the approval is used to give permission for an address to use a maximum of X tokens from another address, so the approval should have as input the marketplace contract address and the maximum amount of tokens that will be spent.
through the UIX, first make the user approve by calling the approve function (address marketplace, amount) directly from the token contract, then you will enable the button that calls the function that needs the tokens
I am working on dapp using hardhat and goerli testnet and when I run it using npx hardhat run scripts/deploy.js --network goerli, I receive this error, I do have goerli faucet eth on my wallet but still it will display that my account balance is 0:
Error: insufficient funds for intrinsic transaction cost [ See: https://links.ethers.org/v5-errors-INSUFFICIENT_FUNDS ] (error={"name":"ProviderError","_stack":"ProviderError: HttpProviderError\n at HttpProvider.request (C:\\Users\\SAIFUL\\RTW3-Week7-NFT-Marketplace\\node_modules\\hardhat\\src\\internal\\core\\providers\\http.ts:78:19)\n at LocalAccountsProvider.request (C:\\Users\\SAIFUL\\RTW3-Week7-NFT-Marketplace\\node_modules\\hardhat\\src\\internal\\core\\providers\\accounts.ts:181:36)\n at processTicksAndRejections (internal/process/task_queues.js:95:5)\n at EthersProviderWrapper.send (C:\\Users\\SAIFUL\\RTW3-Week7-NFT-Marketplace\\node_modules\\#nomiclabs\\hardhat-ethers\\src\\internal\\ethers-provider-wrapper.ts:13:20)","code":-32000,"_isProviderError":true}, method="sendTransaction", transaction=undefined, code=INSUFFICIENT_FUNDS, version=providers/5.7.2)
at Logger.makeError (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#ethersproject\logger\src.ts\index.ts:269:28)
at Logger.throwError (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#ethersproject\logger\src.ts\index.ts:281:20)
at checkError (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#ethersproject\providers\src.ts\json-rpc-provider.ts:98:16)
at C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#ethersproject\providers\src.ts\json-rpc-provider.ts:265:24
at processTicksAndRejections (internal/process/task_queues.js:95:5) {
reason: 'insufficient funds for intrinsic transaction cost',
code: 'INSUFFICIENT_FUNDS',
error: ProviderError: HttpProviderError
at HttpProvider.request (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\hardhat\src\internal\core\providers\http.ts:78:19)
at LocalAccountsProvider.request (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\hardhat\src\internal\core\providers\accounts.ts:181:36)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at EthersProviderWrapper.send (C:\Users\SAIFUL\RTW3-Week7-NFT-Marketplace\node_modules\#nomiclabs\hardhat-ethers\src\internal\ethers-provider-wrapper.ts:13:20),
method: 'sendTransaction',
transaction: undefined
}
here is my deploy.js file everything is supposed to fine and working but error won't disappear
require("#nomiclabs/hardhat-waffle");
require("#nomiclabs/hardhat-ethers");
const fs = require('fs');
// const infuraId = fs.readFileSync(".infuraid").toString().trim() || "";
task("accounts", "Prints the list of accounts", async(taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
module.exports = {
defaultNetwork: "hardhat",
networks: {
hardhat: {
chainId: 1337
},
goerli: {
url: "https://eth-mainnet.g.alchemy.com/v2/2Hmp7mz6XEpw6Z47cCZx2vEIAYXFGYOL",
accounts: ["private key here"]
}
},
solidity: {
version: "0.8.4",
settings: {
optimizer: {
enabled: true,
runs: 200
}
}
}
};
here is my solidity contract:
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
contract NFTMarketplace is ERC721URIStorage {
address payable owner;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
Counters.Counter private _itemsSold;
uint256 listPrice = 0.01 ether;
constructor() ERC721("NFTMarketplace", "NFTM") {
owner = payable(msg.sender);
}
struct ListedToken {
uint256 tokenId;
address payable owner;
address payable seller;
uint256 price;
bool currentlyListed;
}
mapping(uint256 => ListedToken) private idToListedToken;
function updateListPrice(uint256 _listprice) public payable {
require(owner == msg.sender, "only owner can update listing price ");
listPrice = _listprice;
}
function getListPrice() public view returns (uint256) {
return listPrice;
}
function getLatestIdToListedtoken()
public
view
returns (ListedToken memory)
{
uint256 currentTokenId = _tokenIds.current();
return idToListedToken[currentTokenId];
}
function getListedForToken(uint256 tokenId) public view returns (ListedToken memory) {
return idToListedToken[tokenId];
}
function getCurrentToken() public view returns (uint256) {
return _tokenIds.current();
}
function createToken(string memory tokenURI, uint256 price) public payable returns (uint) {
require(msg.value == listPrice, "Send enough ether to list");
require(price > 0, "Make sure the price isn't negative");
_tokenIds.increment();
uint256 currentTokenId = _tokenIds.current();
_safeMint(msg.sender, currentTokenId);
_setTokenURI(currentTokenId, tokenURI);
createListedToken(currentTokenId, price);
return currentTokenId;
}
function createListedToken(uint256 tokenId, uint256 price) private {
idToListedToken[tokenId] = ListedToken(
tokenId,
payable(address(this)),
payable(msg.sender),
price,
true
);
_transfer(msg.sender, address(this), tokenId);
}
function getAllNFTs() public view returns(ListedToken[] memory) {
uint nftCount = _tokenIds.current();
ListedToken[] memory tokens = new ListedToken[](nftCount);
uint currentIndex = 0;
for(uint i=0; i<nftCount; i++) {
uint currentId = i+1;
ListedToken storage currentItem = idToListedToken[currentId];
tokens[currentIndex] = currentItem;
currentIndex += 1;
}
return tokens;
}
function getMyNFTs() public view returns (ListedToken[] memory) {
uint totalItemCount = _tokenIds.current();
uint itemCount = 0;
uint currentIndex = 0;
uint currentId;
for(uint i=0; i < totalItemCount; i++)
{
if(idToListedToken[i+1].owner == msg.sender || idToListedToken[i+1].seller == msg.sender){
itemCount += 1;
}
}
ListedToken[] memory items = new ListedToken[](itemCount);
for(uint i=0; i < totalItemCount; i++) {
if(idToListedToken[i+1].owner == msg.sender || idToListedToken[i+1].seller == msg.sender) {
currentId = i+1;
ListedToken storage currentItem = idToListedToken[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
function executeSale(uint256 tokenId) public payable {
uint price = idToListedToken[tokenId].price;
require(msg.value == price, "please submit the relevant NFT price in order to purchase");
address seller = idToListedToken[tokenId].seller;
idToListedToken[tokenId].currentlyListed = true;
idToListedToken[tokenId].seller = payable(msg.sender);
_itemsSold.increment();
_transfer(address(this), msg.sender, tokenId);
approve(address(this), tokenId);
payable(owner).transfer(listPrice);
payable(seller).transfer(msg.value);
}
}
I tried different networks, but I have no choice except goerli because I will use alchemy Api.
You still need to get more Goerli ETH from faucets or from your other peers.
Try that and see if it will work
Finally I switched from INFURA to ALCHEMY and following the instructions here:
https://hardhat.org/tutorial/deploying-to-a-live-network
it worked!
Attached is the source code for the smart contract, could you advise if there's a function in it I can use to recover the 1.5 bnb? I still have access to the creation wallet and the contract isn't renounced.
it would be nice to try and work this out if possible as I am still learning to code.
/**
*Submitted for verification at BscScan.com on 2021-08-27
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
abstract contract Context {
function _msgSender() internal virtual view returns (address payable) {
return msg.sender;
}
function _msgData() internal virtual view returns (bytes memory) {
this;
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash
= 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Pair {
function sync() external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
}
// change "name1" into ur name
contract BlueMoon is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
//change "name1" and "symbol"
string private _name = "BlueMoon";
string private _symbol = "BMOON";
uint8 private _decimals = 8;
mapping(address => uint256) internal _reflectionBalance;
mapping(address => uint256) internal _tokenBalance;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 private constant MAX = ~uint256(0);
// change this for total supply (100e8 = 100) (100000000e8 = 100000000) (dont forget the e8 it has to be there)
uint256 internal _tokenTotal = 1_000_000_000e8;
// change this for total supply ^^^^^^^^^^^^^^^^^^^^^
uint256 internal _reflectionTotal = (MAX - (MAX % _tokenTotal));
mapping(address => bool) isTaxless;
mapping(address => bool) internal _isExcluded;
address[] internal _excluded;
uint256 public _feeDecimal = 2;
// thats the distribution to holders (400 = 4%)
uint256 public _taxFee = 100;
// thats the amount for liquidity pool
uint256 public _liquidityFee = 1000;
// this amount gets burned by every transaction
uint256 public _burnFee = 100;
// this goes to a specific wallet (line 403)
uint256 public _marketingFee = 300;
uint256 public _taxFeeTotal;
uint256 public _burnFeeTotal;
uint256 public _liquidityFeeTotal;
uint256 public _marketingFeeTotal;
address public marketingWallet;
bool public isTaxActive = true;
bool private inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public maxTxAmount = _tokenTotal;
uint256 public minTokensBeforeSwap = 10_000e8;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(uint256 tokensSwapped,uint256 ethReceived, uint256 tokensIntoLiqudity);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() public {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // for BSC
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // for Ethereum
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506); // for Sushi testnet
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
//paste the wallet adress, that earns the marketingFee here
marketingWallet = 0xD64E87ad309f21De5725e91EAFB82c50e486D374;
//paste the wallet ^^^^^^^^^^^^^^^^^^^^^ adress, that earns the marketingFee here
isTaxless[_msgSender()] = true;
isTaxless[address(this)] = true;
_reflectionBalance[_msgSender()] = _reflectionTotal;
emit Transfer(address(0), _msgSender(), _tokenTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public override view returns (uint256) {
return _tokenTotal;
}
function balanceOf(address account) public override view returns (uint256) {
if (_isExcluded[account]) return _tokenBalance[account];
return tokenFromReflection(_reflectionBalance[account]);
}
function transfer(address recipient, uint256 amount)
public
override
virtual
returns (bool)
{
_transfer(_msgSender(),recipient,amount);
return true;
}
function allowance(address owner, address spender)
public
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override virtual returns (bool) {
_transfer(sender,recipient,amount);
_approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub( amount,"ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tokenAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tokenAmount <= _tokenTotal, "Amount must be less than supply");
if (!deductTransferFee) {
return tokenAmount.mul(_getReflectionRate());
} else {
return
tokenAmount.sub(tokenAmount.mul(_taxFee).div(10** _feeDecimal + 2)).mul(
_getReflectionRate()
);
}
}
function tokenFromReflection(uint256 reflectionAmount)
public
view
returns (uint256)
{
require(
reflectionAmount <= _reflectionTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getReflectionRate();
return reflectionAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(
account != address(uniswapV2Router),
"ERC20: We can not exclude Uniswap router."
);
require(!_isExcluded[account], "ERC20: Account is already excluded");
if (_reflectionBalance[account] > 0) {
_tokenBalance[account] = tokenFromReflection(
_reflectionBalance[account]
);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "ERC20: Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tokenBalance[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= maxTxAmount, "Transfer Limit exceeded!");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap;
if (!inSwapAndLiquify && overMinTokenBalance && sender != uniswapV2Pair && swapAndLiquifyEnabled) {
swapAndLiquify(contractTokenBalance);
}
uint256 transferAmount = amount;
uint256 rate = _getReflectionRate();
if(isTaxActive && !isTaxless[_msgSender()] && !isTaxless[recipient] && !inSwapAndLiquify){
transferAmount = collectFee(sender,amount,rate);
}
_reflectionBalance[sender] = _reflectionBalance[sender].sub(amount.mul(rate));
_reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate));
if (_isExcluded[sender]) {
_tokenBalance[sender] = _tokenBalance[sender].sub(amount);
}
if (_isExcluded[recipient]) {
_tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount);
}
emit Transfer(sender, recipient, transferAmount);
}
function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) {
uint256 transferAmount = amount;
//#dev tax fee
if(_taxFee != 0){
uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(taxFee);
_reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate));
_taxFeeTotal = _taxFeeTotal.add(taxFee);
}
//#dev liquidity fee
if(_liquidityFee != 0){
uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(liquidityFee);
_reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate));
if(_isExcluded[address(this)]){
_tokenBalance[address(this)] = _tokenBalance[address(this)].add(liquidityFee);
}
_liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee);
emit Transfer(account,address(this),liquidityFee);
}
//#dev burn fee
if(_burnFee != 0){
uint256 burnFee = amount.mul(_burnFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(burnFee);
_tokenTotal = _tokenTotal.sub(burnFee);
_reflectionTotal = _reflectionTotal.sub(burnFee.mul(rate));
_burnFeeTotal = _burnFeeTotal.add(burnFee);
emit Transfer(account,address(0),burnFee);
}
//#dev Marketing fee
if(_marketingFee != 0){
uint256 marketingFee = amount.mul(_marketingFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(marketingFee);
_reflectionBalance[marketingWallet] = _reflectionBalance[marketingWallet].add(marketingFee.mul(rate));
if (_isExcluded[marketingWallet]) {
_tokenBalance[marketingWallet] = _tokenBalance[marketingWallet].add(marketingFee);
}
_marketingFeeTotal = _marketingFeeTotal.add(marketingFee);
emit Transfer(account,marketingWallet,marketingFee);
}
return transferAmount;
}
function _getReflectionRate() private view returns (uint256) {
uint256 reflectionSupply = _reflectionTotal;
uint256 tokenSupply = _tokenTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (
_reflectionBalance[_excluded[i]] > reflectionSupply ||
_tokenBalance[_excluded[i]] > tokenSupply
) return _reflectionTotal.div(_tokenTotal);
reflectionSupply = reflectionSupply.sub(
_reflectionBalance[_excluded[i]]
);
tokenSupply = tokenSupply.sub(_tokenBalance[_excluded[i]]);
}
if (reflectionSupply < _reflectionTotal.div(_tokenTotal))
return _reflectionTotal.div(_tokenTotal);
return reflectionSupply.div(tokenSupply);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
if(contractTokenBalance > maxTxAmount)
contractTokenBalance = maxTxAmount;
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
uint256 initialBalance = address(this).balance;
swapTokensForEth(half);
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
address(this),
block.timestamp
);
}
function setPair(address pair) external onlyOwner {
uniswapV2Pair = pair;
}
function setMarketingWallet(address account) external onlyOwner {
marketingWallet = account;
}
function setTaxless(address account, bool value) external onlyOwner {
isTaxless[account] = value;
}
function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner {
swapAndLiquifyEnabled = enabled;
SwapAndLiquifyEnabledUpdated(enabled);
}
function setTaxActive(bool value) external onlyOwner {
isTaxActive = value;
}
function setTaxFee(uint256 fee) external onlyOwner {
_taxFee = fee;
}
function setBurnFee(uint256 fee) external onlyOwner {
_burnFee = fee;
}
function setLiquidityFee(uint256 fee) external onlyOwner {
_liquidityFee = fee;
}
function setMarketingFee(uint256 fee) external onlyOwner {
_marketingFee = fee;
}
function setMaxTxAmount(uint256 amount) external onlyOwner {
maxTxAmount = amount;
}
function setMinTokensBeforeSwap(uint256 amount) external onlyOwner {
minTokensBeforeSwap = amount;
}
receive() external payable {}
}
as far as im aware im sure most contracts have some sort of clear stuck balance function in them which you can use. but I dont see one here. is it an oversight? or can it still be called using other functions.
Thanks for any advise. am willing to try what is recommended.
after reading many post i can't found the issues about this Smart contract who compile but it think i miss something about the inheritance and the Abstract contract.
This is the SC :
// solium-disable linebreak-style
pragma solidity >=0.4.21 <0.6.0;
import "../node_modules/#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../node_modules/#openzeppelin/contracts/math/SafeMath.sol";
/**
* #title Ownable
* #dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address payable public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* #dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor (Ownable) public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* #dev Allows the current owner to transfer control of the contract to a newOwner.
* #param newOwner The address to transfer ownership to.
*/
function transferOwnership(address payable newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Sample is Ownable {
event NewResource (uint resourceId, string name , uint quality);
uint qualityUnits = 16;
uint qualityModulo = qualityUnits;
uint cooldownTime = 1 days;
struct Resource {
string name;
uint quality;
uint32 rarity;
uint256 cooldownTime;
uint16 stockGain;
uint16 stockLoss;
uint32 readyTime;
uint256 extractionTime;
uint256 extractionId;
uint256 magnetiteId;
uint256 hematiteId;
uint256 class;
uint256 sediments;
uint qualityUnits;
}
//mapping address and apply stocks
mapping (uint => address) public resourceToOwner;
mapping (address => uint) ownerResourceGain;
Resource[] public resources;
/// #dev function to crack the resource stacks
function _createResource (string memory _name , uint _quality) internal {
uint id = resources.push(Resource(_name,_quality ,1 , uint256( now + cooldownTime), 0 , 0, 0,
0, 0, 0, 0, 0, 0, 16) )+1;
resourceToOwner[id] = msg.sender;
ownerResourceGain[msg.sender]++;
emit NewResource(id, _name , _quality);
}
//function to generate rand stats for resources
function _generateRandomQuality(string memory _str ) private view returns (uint) {
uint rand = uint(keccak256(abi.encode(_str)));
return rand % qualityModulo;
}
//function to generate the resource stacks
function createResourceStack(string memory _name) public {
require(ownerResourceGain[msg.sender] ==0);
uint randomQuality = _generateRandomQuality(_name);
randomQuality = randomQuality - randomQuality % 100;
_createResource(_name, randomQuality);
}
}
contract CoreRefined is Sample {
//address public newContractAddress;
function getResourcesStats(uint256 _id)
external
view
returns (
bool isRefiningInProcess,
bool isReady,
uint256 cooldownTime,
//uint256 nextActionAt,
uint256 extractionTime,
uint256 extractionId,
uint256 magnetiteId,
uint256 hematiteId,
uint256 class,
uint256 sediments
)
{
Resource storage stats = resources[_id];
isRefiningInProcess = (stats.quality != 0);
isReady = (stats.cooldownTime <= block.number);
cooldownTime = uint256(stats.cooldownTime);
extractionTime = uint256(stats.extractionTime);
extractionId = uint256(stats.extractionId);
magnetiteId = uint256(stats.magnetiteId);
hematiteId = uint256(stats.hematiteId);
class = uint256(stats.class);
sediments = stats.sediments;
}
}
/// #title RefiningInterface for resource modification called refining
/// #dev Refining function inside for improving stats of resources.
contract RefiningInterface is Sample {
function refining(uint256 _id) external view returns (
bool isRefiningInProcess,
bool isReady,
uint256 cooldownTime,
uint256 nextActionsAt,
uint256 extractionTime,
uint256 extractionId,
uint256 magnetiteId,
uint256 hematiteId,
uint256 class,
uint256 sediments
);
}
contract ResourceRefined is Sample , CoreRefined {
ResourceRefined CoreRefinedContract;
modifier onlyOwnerOf(uint _resourceId) {
require(msg.sender == resourceToOwner[_resourceId]);
_;
}
function SetAnotherContractAddress (address _address) external onlyOwner {
CoreRefinedContract
= ResourceRefined(_address);
}
function triggerCooldown (Resource storage _resource ) internal {
_resource.readyTime = uint32(now+cooldownTime);
}
function _isReady ( Resource storage _resource ) internal view returns (bool) {
return (_resource.readyTime <= now);
}
function refinedAndMultiply( uint _resourceId, uint _targetQuality, string memory _types) internal onlyOwnerOf(_resourceId) {
Resource storage myResource = resources[_resourceId];
require(_isReady(myResource));
_targetQuality % qualityModulo;
uint newQuality = (myResource.quality + _targetQuality) / 2;
if(keccak256(abi.encode((_types))) == keccak256(abi.encode("Resources"))) {
newQuality = newQuality - newQuality % 100 + 99;
}
_createResource("NoName", newQuality);
triggerCooldown(myResource);
}
function refineOnInterface(uint256 _resourceId, uint256 _idResources ) public {
uint256 materialUsed;
(,,,,,,,,materialUsed) = CoreRefinedContract.getResourcesStats(_idResources);
refinedAndMultiply(_resourceId,materialUsed,"Resources");
}
}
contract ResourceHelper is ResourceRefined {
//cost ether for rarityUp fee
uint rarityForFee = 0.001 ether;
//modify rarity !=not LEVEL
modifier aboveCostLevel (uint _rarity ,uint _resourceId){
require(resources[_resourceId].rarity >= _rarity);
_;
}
//function to withdraw FIX ISSUE
/*function withdraw() external onlyOwner {
owner.transfer(this).balance;
}*/
//rarityfee for resources improvements
function setRarityFee(uint _fee) external onlyOwner {
rarityForFee = _fee;
}
//Rarity improvement function
/// #dev this function is set by using RefinedResource.sol contract in order to gain better resources
function rarityUp(uint _resourceId) external payable {
require(msg.value == rarityForFee);
resources[_resourceId].rarity++;
}
//change the name of resources
function changeName(uint _resourceId, string calldata _Newname) external aboveCostLevel(2, _resourceId) onlyOwnerOf (_resourceId){
resources[_resourceId].name = _Newname;
}
//change the qualityUnits
function changeQualityUnits(uint _resourceId, uint _newQualityUnits) external aboveCostLevel(2, _resourceId) onlyOwnerOf (_resourceId) {
resources[_resourceId].qualityUnits = _newQualityUnits;
}
//grabe the resources ! array of it.
function getTheResourceToOwner( address _owner) external view returns (uint[] memory) {
uint[] memory result = new uint[](ownerResourceGain[_owner]);
uint counter = 0;
//loop
for (uint i = 0; i < resources.length; i++) {
if (resourceToOwner[i] == _owner){
result[counter] = i;
counter++;
}
}
return result;
}
}
contract ResourceUp is ResourceHelper {
uint randNonce = 0;
uint resourceUpProba = 70;
/*function randMod(uint _modulus) internal returns(uint) {
randNonce++;
return uint(keccak256( (abi.encodePacked(now, msg.sender,randNonce))) % uint(_modulus));
}*/
function setUp(uint _resourceId, uint _targetId) external onlyOwnerOf(_resourceId) {
Resource storage myResource = resources[_resourceId];
Resource storage anotherResource = resources[_targetId];
uint rand = 100;
if (rand <= resourceUpProba) {
myResource.stockGain++;
myResource.rarity++;
anotherResource.stockLoss++;
refinedAndMultiply(_resourceId, anotherResource.quality, "resource");
} else {
myResource.stockLoss++;
anotherResource.stockGain++;
triggerCooldown(myResource);
}
}
}
contract Harvest is ResourceUp, ERC721 {
using SafeMath for uint256;
mapping (uint => address) resourceApproval;
function balanceOf(address _owner) public view returns (uint256 _balance) {
return ownerResourceGain[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
return resourceToOwner[_tokenId];
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownerResourceGain[_to] = ownerResourceGain[_to].add(1);
ownerResourceGain[msg.sender] = ownerResourceGain[msg.sender].sub(1);
resourceToOwner[_tokenId] = _to;
_transfer(_from, _to, _tokenId);
}
function transferTo(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
transferTo(_to, _tokenId);
}
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
resourceApproval[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
function harvest(uint256 _tokenId) public {
require(resourceApproval[_tokenId] == msg.sender);
address owner = ownerOf(_tokenId);
_transfer(owner, msg.sender, _tokenId);
}
}
My depoy js file :
const Harvest = artifacts.require("Harvest");
module.exports = function(deployer) {
deployer.deploy(Harvest)
};
The output of the truffle migrate
* Import abstractions into the '.sol' file that uses them instead of deploying them separately.
* Contracts that inherit an abstraction must implement all its method signatures exactly.
* A contract that only implements part of an inherited abstraction is also considered abstract.
verions :
Truffle v5.1.9 (core: 5.1.9)
Solidity v0.5.16 (solc-js)
Node v10.16.3
Web3.js v1.2.1
Thank you for your support.
The problem is with Ownable constructor
constructor (Ownable) public {
owner = msg.sender;
}
It is defined in a way that it will receive one parameter of type Ownable.
To fix the error define it without any input parameter:
constructor() public {
owner = msg.sender;
}