Applying condition of whitelisted users to sell bep20 token on pancake swap - token

I want to add one condition in my bep20 token, only whitelisted addresses should be able to sell my token on the exchange. I tried this but it is not working since all addresses are able to sell. Need help in figuring this out, thanks.
pragma solidity ^0.8.7;
contract CHANCE is ERC20, Ownable {
using SafeMath for uint256;
IPancakeV2Router02 public pancakeV2Router;
address public immutable pancakeV2Pair;
mapping (address => bool) public Whitelist;
constructor() ERC20("CHANCE", "CHCE") {
IPancakeV2Router02 _pancakeV2Router = IPancakeV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1);
// Create a pancake pair for this new token
address _pancakeV2Pair = IPancakeV2Factory(_pancakeV2Router.factory())
.createPair(address(this), _pancakeV2Router.WETH());
pancakeV2Router = _pancakeV2Router;
pancakeV2Pair = _pancakeV2Pair;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 200000000000 * 10 ** 18);
emit Transfer(address(0), msg.sender, totalSupply());
}
function burn (uint256 amount) public onlyOwner {
_burn(msg.sender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(to == pancakeV2Pair){
require(Whitelist[msg.sender] == true,"Whitelist can mint only!");
super._transfer(from, to, amount);
}
super._transfer(from, to, amount);
}
function whitelist(address _address) public onlyOwner returns (bool){
Whitelist[_address] = true;
return true;
}
}

Related

Create a Dividend paying Token

How can I create an erc20 token that pays it's holders a dividends monthly
Ive created a normal erc20 token but i can't seem to get this type of token
Contract can not initiate transactions by itself. But you can do something like this. In consctructor i defined 2,3 and 4 account that i have in remix, for testing, you can comment or delete it and mannually add your addresses in addParticipant();
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
contract DividentToken is ERC20 ("DividentToken", "DVD"), Ownable{
uint dividentAmount;
address[] participants;
constructor() {
_mint(msg.sender, 1000000000000 *10 ** 18);
addParticipant(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);
addParticipant(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);
addParticipant(0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB);
}
function mint(address to, uint amount) external onlyOwner {
_mint(to, amount);
}
//return list of addresses of participants
function viewParticipants() public view returns(address[] memory) {
return participants;
}
function setDividentAmount(uint _dividentAmount) public onlyOwner {
dividentAmount = _dividentAmount;
}
function addParticipant(address _participant) public onlyOwner {
participants.push(_participant);
}
function payDividents() public onlyOwner {
for(uint i = 0; i < participants.length; i++) {
transferFrom(owner(), participants[i], dividentAmount); //in
this case first you got to increase allowance for owner()
// _mint(participants[i], dividentAmount); also you can use mint
instead of transfer
}
}
}

tranfer 2 diferent tokens

What I need is to transfer some amount of an especific token (100) when a "father" token is used.It is some kind of tax on a "child" token when the "father" token is used.So I manage to transfer an amount of that "child" token executing manually "transferERC20" function.How could I execute that function automatically when the "father" token is sent ?when I execute a transfer the "father" token (the created one : TTDT01) is transfered correctly but I do not manage to execute the transfer of the "child token" at the same time...
import "#openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract FinalToken {
string public name; // Holds the name of the token
string public symbol; // Holds the symbol of the token
uint8 public decimals; // Holds the decimal places of the token
uint256 public totalSupply; // Holds the total suppy of the token
//address payable public owner; // Holds the owner of the token
address payable public owner;
uint256 public balance;
address public receiverad = 0xE6057bA67838dE723AA46c861F6F867f26FE09c4;
address public tokenContractAddress = 0x762a0Ce3D24Ea4Fe5bB3932e15Dd2BD87F894F98;
IERC20 tokennew = IERC20(address(tokenContractAddress));
/* This creates a mapping with all balances */
mapping (address => uint256) public balanceOf;
/* This creates a mapping of accounts with allowances */
mapping (address => mapping (address => uint256)) public allowance;
/* This event is always fired on a successfull call of the
transfer, transferFrom, mint, and burn methods */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This event is always fired on a successfull call of the approve method */
event Approve(address indexed owner, address indexed spender, uint256 value);
event TransferReceived(address _from, uint256 _amount);
event TransferSent(address _from, address _destAddr, uint256 _amount);
constructor() {
name = "TestTokenDT01"; // Sets the name of the token, i.e Ether
symbol = "TTDT01"; // Sets the symbol of the token, i.e ETH
decimals = 18; // Sets the number of decimal places
uint256 _initialSupply = 1000000000 * 10 ** 18; // Holds an initial supply of coins
/* Sets the owner of the token to whoever deployed it */
owner = payable(msg.sender);
balanceOf[owner] = _initialSupply; // Transfers all tokens to owner
totalSupply = _initialSupply; // Sets the total supply of tokens
/* Whenever tokens are created, burnt, or transfered,
the Transfer event is fired */
emit Transfer(address(0), msg.sender, _initialSupply);
}
function getOwner() public view returns (address) {
return owner;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
/* uint256 senderBalance = balanceOf[msg.sender];
uint256 receiverBalance = balanceOf[_to];
require(_to != address(0), "Receiver address invalid");
require(_value >= 0, "Value must be greater or equal to 0");
require(senderBalance > _value, "Not enough balance");
balanceOf[msg.sender] = senderBalance - _value;
balanceOf[_to] = receiverBalance + _value; */
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
/*uint256 senderBalance = balanceOf[msg.sender];
uint256 fromAllowance = allowance[_from][msg.sender];
uint256 receiverBalance = balanceOf[_to];
require(_to != address(0), "Receiver address invalid");
require(_value >= 0, "Value must be greater or equal to 0");
require(senderBalance > _value, "Not enough balance");
require(fromAllowance >= _value, "Not enough allowance");
balanceOf[_from] = senderBalance - _value;
balanceOf[_to] = receiverBalance + _value;
allowance[_from][msg.sender] = fromAllowance - _value;
*/
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require(_value > 0, "Value must be greater than 0");
allowance[msg.sender][_spender] = _value;
emit Approve(msg.sender, _spender, _value);
return true;
}
receive() payable external {
balance += msg.value;
emit TransferReceived(msg.sender, msg.value);
}
function withdraw(uint amount, address payable destAddr) public {
require(msg.sender == owner, "Only owner can withdraw funds");
require(amount <= balance, "Insufficient funds");
destAddr.transfer(amount);
balance -= amount;
emit TransferSent(msg.sender, destAddr, amount);
}
function transferERC20(IERC20 token, address to, uint256 amount) public {
require(msg.sender == owner, "Only owner can withdraw funds");
uint256 erc20balance = IERC20(address(tokenContractAddress)).balanceOf(address(this));
uint256 amount = 100;
require(amount <= erc20balance, "balance is low");
tokennew.transfer(receiverad, amount);
emit TransferSent(msg.sender, receiverad, amount);
}
}
As far my best knowledge, we you need to make two different function in your Solidity smart control, and in the frontend you have to call it in this way using web3 package after compiling and setting up the network using truffle and getting the abi and bytecode of the smart contract.
contractToken1.methods.function1().send({from: account}).on('transactionHash', (hash)=>{
contractToken2.methods.function2().send({from: account}).on('transactionHash',(hash)=> console.log('this was successful'));
}

UnimplementedFeatureError: Copying of type struct {ContractName.StructName} memory[] memory to storage not yet supported

・I want to create the lottery contract that user can buy some lottery numbers.
And, if the lottery was finished, I want to initialize it to create a new lottery.
That's why we implemented it this way.
lotChances = new LotChance[](0);
But, I faced this is error ...👇
UnimplementedFeatureError: Copying of type struct Lottery.LotChance memory[] memory to storage not yet supported.
Minimal example:
contract Lottery {
// Lot Structs
struct LotChance {
address payable userAddress;
uint256 ids;
}
LotChance[] public lotChances;
function getResult() public onlyOwner {
luckyPerson.transfer(address(this).balance);
lotteryId++;
lotChances = new LotChance[](0);
}
}
Please advise me😌
For reset an array and set his values to default you can use delete keyword in Solidity. In your case, you must to change your getResult() function in this way:
function getResult() public onlyOwner {
luckyPerson.transfer(address(this).balance);
lotteryId++;
delete lotChances;
}
You can see an example of smart contract code, here following:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
contract Lottery {
address owner;
constructor() {
owner = msg.sender;
}
// Lot Structs
struct LotChance {
address payable userAddress;
uint256 ids;
}
modifier onlyOwner() {
require(msg.sender == owner, "You aren't smart contract owner!");
_;
}
LotChance[] public lotChances;
function getResult(address _luckyPerson) public onlyOwner {
uint lotteryId = 0;
payable(_luckyPerson).transfer(address(this).balance);
lotteryId++;
// I reset array length about to '0'
delete lotChances;
}
function partecipateToLottery(uint _id) public {
lotChances.push(LotChance(payable(msg.sender), _id));
}
function getLengthArray() external view returns(uint) {
return lotChances.length;
}
}

Why is the balance of the ethereum account still zero after I create a token based on the private chain I built?

I used the contract codes available on the ethereum official website,[create your own cryto-currency][1] to create an advanced token on the private chain run in geth console. The version of geth is 1.5.5,and the version of solc is 0.4.8.
My steps are:
1.initialize my geth:geth init genesis.json then geth --networkid 42 --nodiscover --maxpeers 0 console
2.check the compiler:***eth.getCompilers()***returns:solidity
3.I used the online compiling website [Remix][2]to give me the relative abi and code to directly deploy my contract.
I input:
(1)abi=[{"constant":false,"inputs":[{"name":"newSellPrice","type":"uint256"},…… too long to copy the result;
(2)then create the contract:multiplyContract = web3.eth.contract(abi)
(3)multiply= multiplyContract.new(10000,"AKING",2,"AK",0xf32200730fdaca83f18171015c0be2a6342d46c4,{from: primaryAddress, data: 0x+code})
the first parameter means the initial supply,the second one represents the name of the token, the third one means the decimalUnit,the forth one is the address which can have the initial supply of tokens.
4.check whether my contract has deployed:
I input :txpool.status
then I got:pending:1
5.I began to mine the contract:
input: miner.start() and miner.stop()
then I input:eth.getBlock(5319)
I found that transaction.
6.Interact with my contract:
Input:MyContract = eth.contract(abi)
Then:myContract = MyContract.at(multiply.address)
Start mining for a while.
The whole process went well, however when I input
myContract.balanceOf(0xf32200730fdaca83f18171015c0be2a6342d46c4) (the address is the eth.account[0]and also the address which possesses the tokens I created. I also tried some other addresses , they all returned to zero. And I also tried some other expressions like myContract.balanceOf(eth.accounts[0], {from: eth.accounts[0]}) or myContract.balanceOf.sendTransaction(eth.accounts[0], {from: eth.accounts[0]})
If I used :eth.getBalance(eth.accounts[0]) it only returns the ethers in my account which is not what I want to see.
So,is there anything wrong with my process? or is there anything important that is missed ? What‘s the point?
The whole codes are as follows:
pragma solidity ^0.4.2;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
contract token {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function token(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
tokenRecipient spender = tokenRecipient(_spender);
return true;
}
/* Approve and then comunicate the approved contract in a single tx */
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
}
contract MyAdvancedToken is owned, token {
uint256 public sellPrice;
uint256 public buyPrice;
uint256 public totalSupply;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MyAdvancedToken(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
address centralMinter
) token (initialSupply, tokenName, decimalUnits, tokenSymbol) {
if(centralMinter != 0 ) owner = centralMinter; // Sets the owner as specified (if centralMinter is not specified the owner is msg.sender)
balanceOf[owner] = initialSupply; // Give the owner all initial tokens
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (frozenAccount[msg.sender]) throw; // Check if frozen
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (frozenAccount[_from]) throw; // Check if frozen
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function mintToken(address target, uint256 mintedAmount) onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable {
uint amount = msg.value / buyPrice; // calculates the amount
if (balanceOf[this] < amount) throw; // checks if it has enough to sell
balanceOf[msg.sender] += amount; // adds the amount to buyer's balance
balanceOf[this] -= amount; // subtracts amount from seller's balance
Transfer(this, msg.sender, amount); // execute an event reflecting the change
}
function sell(uint256 amount) {
if (balanceOf[msg.sender] < amount ) throw; // checks if the sender has enough to sell
balanceOf[this] += amount; // adds the amount to owner's balance
balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance
if (!msg.sender.send(amount * sellPrice)) { // sends ether to the seller. It's important
throw; // to do this last to avoid recursion attacks
} else {
Transfer(msg.sender, this, amount); // executes an event reflecting on the change
}
}
}
Enclose the address in quotes.
change this myContract.balanceOf(0xf32200730fdaca83f18171015c0be2a6342d46c4) to this myContract.balanceOf("0xf32200730fdaca83f18171015c0be2a6342d46c4")

creating Ethereum tokens as mining rewards

I have managed to create a registered Ethereum "Token" using Primarily the "how to" from the Frontier website. I intend to proceed with a crowdsource ing contract to raise funds for what will be a fundraising event capable of doing some good in the world, but more on that later. The token creation text includes this suggestion for improving the functionality of my new token:
You could for example reward ethereum miners, by creating a transaction that will reward who found the current block:
mapping (uint => address) miningReward;
function claimMiningReward() {
if (miningReward[block.number] == 0) {
coinBalanceOf[block.coinbase] += 1;
miningReward[block.number] = block.coinbase;
}
}
simply pasting this code into my contract naturally produces error messages.
Q: What do I need to tweak, enter, change, to make it possible to reward minors with one of my tokens? for each and every mined new block.
Thank you.
You can copy and paste your code snippet into the token contract. It will look like that:
contract token {
mapping (address => uint) public coinBalanceOf;
event CoinTransfer(address sender, address receiver, uint amount);
/* Initializes contract with initial supply tokens to the creator of the contract */
function token(uint supply) {
if (supply == 0) supply = 10000;
coinBalanceOf[msg.sender] = supply;
}
/* Very simple trade function */
function sendCoin(address receiver, uint amount) returns(bool sufficient) {
if (coinBalanceOf[msg.sender] < amount) return false;
coinBalanceOf[msg.sender] -= amount;
coinBalanceOf[receiver] += amount;
CoinTransfer(msg.sender, receiver, amount);
return true;
}
mapping (uint => address) miningReward;
/* Reward Ethereum block miner with a token */
function claimMiningReward() {
if (miningReward[block.number] == 0) {
coinBalanceOf[block.coinbase] += 1;
miningReward[block.number] = block.coinbase;
}
}
}
I dont know if you figured this out yet. Anyone else having the same issue try the following snippet:
contract MyToken {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MyToken(uint256 _supply, string _name, string _symbol, uint8 _decimals) {
/* if supply not given then generate 1 million of the smallest unit of the token */
if (_supply == 0) _supply = 1000000;
/* Unless you add other functions these variables will never change */
balanceOf[msg.sender] = _supply;
name = _name;
symbol = _symbol;
/* If you want a divisible token then add the amount of decimals the base unit has */
decimals = _decimals;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
/* if the sender doenst have enough balance then stop */
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
/* Add and subtract new balances */
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
/* Notifiy anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value);
}
}
Then adding your code to reward the miners but changing "coinBalanceOf" with "balanceOf" like so:
mapping (uint => address) miningReward;
function claimMiningReward() {
if (miningReward[block.number] == 0) {
balanceOf[block.coinbase] += 1;
miningReward[block.number] = block.coinbase;
}
}
So Your final contract would look like this:
contract MyToken {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MyToken(uint256 _supply, string _name, string _symbol, uint8 _decimals) {
/* if supply not given then generate 1 million of the smallest unit of the token */
if (_supply == 0) _supply = 1000000;
/* Unless you add other functions these variables will never change */
balanceOf[msg.sender] = _supply;
name = _name;
symbol = _symbol;
/* If you want a divisible token then add the amount of decimals the base unit has */
decimals = _decimals;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
/* if the sender doenst have enough balance then stop */
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
/* Add and subtract new balances */
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
/* Notifiy anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value);
}
mapping (uint => address) miningReward;
function claimMiningReward() {
if (miningReward[block.number] == 0) {
balanceOf[block.coinbase] += 1;
miningReward[block.number] = block.coinbase;
}
}
}

Resources