How to deposit eth to contract writen in solidity on front-end app using useDapp - solidity

Given i have this smart contract in remix
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract DepositWithdraw {
mapping(address => uint256) private balances;
event Deposit(address indexed depositor, uint256 amount);
event Withdrawal(address indexed withdrawer, uint256 amount);
function deposit() public payable {
balances[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 amount) public {
require(balances[msg.sender] >= amount, "Insufficient balance");
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
emit Withdrawal(msg.sender, amount);
}
function balanceOf(address account) public view returns (uint256) {
return balances[account];
}
}
Deposit by remix ide works, but when I'm trying to deposit using useDapp lib in javascript by using useContractFunction I can't pass the amount to deposit. When I'm redirected to meta mask to accept transaction there is no amount shown.
my front-end code:
import { Contract } from 'ethers';
import { Interface } from 'ethers/lib/utils';
import { useContractFunction } from '#usedapp/core';
const contractAddress = // my contract address;
const ABI = new Interface(
//...copied contract ABI from remix
);
const contract = new Contract(contractAddress, ABI);
const { send } = useContractFunction(contract, 'deposit');
// send(value) will error that deposit function argument length is no correct (it want 0 arguments)
tried adding third argument with options to useContractFunction but no success.
When i call send without arguments it will process to metamask but no amount shown, only gas fees
any ideas?

Related

Getting Block Hash of another contract

I've seen some problems with calling functions from other contracts but I believe my problem is fairly genuine to demand a separate question if only to be negated in its possibility.
So I am trying to call a contract within another contract. Is it possible to get the blockhash of a particular block number of the callee contract within my caller? If so how?
Every syntax I've attempted fails for some reason.
Contract A
enter code here
contract DiceGame {
uint256 public nonce = 0;
uint256 public prize = 0;
event Roll(address indexed player, uint256 roll);
event Winner(address winner, uint256 amount);
constructor() payable {
resetPrize();
}
function resetPrize() private {
prize = ((address(this).balance * 10) / 100);
}
function rollTheDice() public payable {
require(msg.value >= 0.002 ether, "Failed to send enough value");
bytes32 prevHash = blockhash(block.number - 1);
bytes32 hash = keccak256(abi.encodePacked(prevHash, address(this), nonce));
uint256 roll = uint256(hash) % 16;
console.log('\t'," Dice Game Roll:",roll);
nonce++;
prize += ((msg.value * 40) / 100);
emit Roll(msg.sender, roll);
if (roll > 2 ) {
return;
}
uint256 amount = prize;
(bool sent, ) = msg.sender.call{value: amount}("");
require(sent, "Failed to send Ether");
resetPrize();
emit Winner(msg.sender, amount);
}
receive() external payable { }
}
Contract B
enter code here
contract RiggedRoll is Ownable {
DiceGame public diceGame;
constructor(address payable diceGameAddress) {
diceGame = DiceGame(diceGameAddress);
}
//Add withdraw function to transfer ether from the rigged contract to an address
//Add riggedRoll() function to predict the randomness in the DiceGame contract and only roll when it's going to be a winner
function riggedRoll(bytes32 riggedHash) public payable {
riggedHash = address(diceGame).blockhash(block.number-1); //I am aware this syntax is broken but I am not able to find a legitimate one to access the data from contract A.
}
//Add receive() function so contract can receive Eth
receive() external payable { }
}
A contract doesn't know when it was last called, unless you explicitly store this information.
Then you can get the block hash using the native blockhash() function (accepts the block number as a parameter).
contract Target {
uint256 public lastCalledAtBlockNumber;
// The value is stored only if you invoke the function using a (read-write) transaction.
// If you invoke the function using a (read-only) call, then it's not stored.
function foo() external {
lastCalledAtBlockNumber = block.number;
}
}
bytes32 blockHash = blockhash(block.number);

OpenZeppelin ERC721URIStorage _setTokenURI

i'm trying to create a smart contract for minting NFT's. When i try to import and use _setTokenUri from OpenZeppelin, there is an error accours in Remix ide says that "Undeclared identifier". I wonder why, so here is my code ;
pragma solidity ^0.8.9;
import '#openzeppelin/contracts/token/ERC721/ERC721.sol';
import '#openzeppelin/contracts/access/Ownable.sol';
import '#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol';
contract MintNft is ERC721, Ownable {
uint256 public mintPrice = 0.005 ether;
uint public totalSupply;
uint public maxSupply;
bool public isMintEnabled;
// Mapping for amount of minted nfts by an address
mapping(address => uint256) public mintedWallets;
constructor() payable ERC721('Pokemon Card', 'POKE') {
maxSupply = 20;
}
function toggleIsMintEnabled() external onlyOwner {
isMintEnabled = !isMintEnabled;
}
function setMaxSupply(uint256 _maxSupply) external onlyOwner {
maxSupply = _maxSupply;
}
function mint(string memory tokenURI) external payable {
require(isMintEnabled,"Minting is not enable");
require(mintedWallets[msg.sender] < 2, 'You have reached maximum mint number');
require(msg.value == mintPrice, "Wrong value");
require(maxSupply > totalSupply, "Sold Out ! ");
mintedWallets[msg.sender]++;
totalSupply++;
uint256 tokenId = totalSupply;
_safeMint(msg.sender, tokenId);
_setTokenURI(tokenId,tokenURI);
}
}
Thanks already.
Okay i figured out that i forget to implement ERC721URIStorage when naming my contract.
i changed it to contract MintNft is ERC721URIStorage, Ownable
Now it works fine.

How do I accept an ERC20 token for Nft mint payment instead of ETH

How do I accept an ERC 20 token for minting NFTS on my smart contract. I’m currently paying for the minting using ETH, and I will like to accept another ERC 20 token.
You can change your mint function in order to accept the preferred token type as payment. And in order to prevent paying gas in eth, you can use biconomy forward.Check out their docs.
https://docs.biconomy.io/products/enable-paying-gas-in-erc20
You need a reference from the NFT contract to your token contract.
Let's say we have these two contracts: NFTContract, TokenContract.
contract NFTContract {
TokenContract tokenContract;
...
mint() {
tokensContract.transfer(msg.sender(), addressReceiver, tokensToSend);
...
}
}
contract TokenContract {
transfer(sender, receiver, balance) {}
}
You can check an example of how I did this in my repo I'm developing for my thesis.
https://github.com/NickVanzo/Contracts_For_Thesis
Maybe it will work for you but be careful you can take errors for solidity versions.
pragma solidity ^0.8.9;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract LSTNFT is ERC721, ERC721Burnable, Ownable {
uint256 public cost;
uint256 maxSupply = 20;
uint256 maxMintAmountPerTx = 2;
// address of the ERC-20 contract
address public erc20Contract = "ERC-20 address is here";
// instance of the ERC-20 contract
ERC20 public erc20;
constructor() ERC721("Lestonz NFT", "LSTN") {
erc20 = ERC20(erc20Contract);
}
function _baseURI() internal pure override returns (string memory) {
return "ipfs://your ipfs url";
}
modifier mintPriceCompliance(uint256 _mintAmount) {
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount, 'Insufficient funds!');
}
_;
}
function mint(uint256 _mintAmount) public payable mintPriceCompliance(_mintAmount) {
require(erc20.balanceOf(msg.sender) >= msg.value, "Not enough ERC-20 tokens");
_safeMint(_msgSender(), _mintAmount);
}
function setCost(uint256 _cost) public onlyOwner {
cost = _cost;
}
}

DeclarationError: Identifier not found or not unique

I'm trying to compile my sol file, but it's giving me this error. Why am I getting this error?
DeclarationError: Identifier not found or not unique. -->
project:/contracts/MemoTokenSale.sol:11:5: | 11 | MemoToken
public token; | ^^^^^^^^^
Compilation failed. See above. Truffle v5.4.23 (core: 5.4.23) Node
v16.13.0
The following is my code
// SPX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './MemoToken.sol';
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract MemoTokenSale {
address payable public admin;
address payable private ethFunds = payable(0x15b22B37679eF92672dA117F4357e048319008AD); // Web3 Account
MemoToken public token;
uint256 public tokensSold;
int public tokenPriceUSD;
AggregatorV3Interface internal priceFeed;
uint256 public transactionCount;
event Sell(address _buyer, uint256 _amount);
struct Transaction {
address buyer;
uint256 amount;
}
mapping(uint256 => Transaction) public transaction;
constructor(MemoToken _token) {
priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); // ChainLink Contracts
tokenPriceUSD = 50;
token = _token;
admin = payable(msg.sender);
}
function getETHPrice() public view returns(int) {
(, int price, , , ) = priceFeed.latestRoundData();
return (price / 10^8);
}
function memoTokenPriceInETH() public view returns(int) {
int ethPrice = getETHPrice();
return tokenPriceUSD / ethPrice;
}
function buyToken(uint256 _amount) public payable {
int memoTokenPriceETH = memoTokenPriceInETH();
// Check that the buyer sends the enough ETH
require(int(msg.value) >= memoTokenPriceETH * int(_amount));
// Check that the sale contract provides the enough ETH to make this transaction.
require(token.balanceOf(address(this)) >= _amount);
// Make the transaction inside of the require
// transfer returns a boolean value.
require(token.transfer(msg.sender, _amount));
// Transfer the ETH of the buyer to us
ethFunds.transfer(msg.value);
// Increase the amount of tokens sold
tokensSold += _amount;
// Increase the amount of transactions
transaction[transactionCount] = Transaction(msg.sender, _amount);
transactionCount++;
// Emit the Sell event
emit Sell(msg.sender, _amount);
}
function endSale() public {
require(msg.sender == admin);
// Return the tokens that were left inside of the sale contract
uint256 amount = token.balanceOf(address(this));
require(token.transfer(admin, amount));
selfdestruct(payable(admin));
}
}

contract to contract transfer of fund error solidity

want to transfer funds from one contract to another
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.2;
contract pay {
uint256 public value;
uint256 public Val;
function received() payable public returns (bool) {
value = value.Add(msg.value).mul(95).div(100);
Val = val.add(msg.value).mul(5).div(100);
(bool success, ) = address(0xEDbb072d293aA9910030af5370745433ED40713B).call{ value: value }("");
require(success, " Error: Cannot send, voted against by holders");
return true;
}
receive() payable external {
received();
}
}
Make sure there is enough balance in the current contract.(contract pay)
check contract balance:
function getBalance() public view returns(uint){
return address(this).balance;
}