I want to issue a token on Tron blockchain and I got it's template from the address below :
https://github.com/TRON-Developer-Hub/TRC20-Contract-Template
The problem is that I want to set my token to automatically mint a specified number of tokens daily. (For example mint 2000 tokens per day)
What should I add to the template?
you can add a functionm, below like that.
But you have to excute mintDaily() manually
uint256 constant private dailyMinted = 2000e18;
uint256 lastMintTime;
address public _owner;
constructor(
string memory name,
string memory symbol,
uint8 decimals,
address owner
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_owner = owner;
lastMintTime = block.timestamp;
}
function mintDaily() public {
require(_owner == msg.sender, "not permitted");
// 24h = 86400
require(lastMintTime + 86400 >= block.timestamp, "mint already" );
_mint(msg.sender, dailyMinted);
lastMintTime = block.timestamp;
}
Related
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;
}
}
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'));
}
I have an error in 5 line
The instance member
'generateId' can't be accessed in an initializer. Try replacing the
reference to the instance member with a different expression
what i shoud do to write a function result to instance variable?
import 'dart:math';
class User{
int id = generateId(10); // error i here
String firstName;
String lastName;
String eMail;
String password;
final DateTime regDate = DateTime.now();
User(this.firstName, this.lastName, this.eMail, this.password,){
id = generateId(10);
}
#override
String toString() =>'User: \n$firstName \n$lastName';
int generateId(int count){
int result;
List <int> nums = [];
for (int i = 0; i < count; i++){
nums.add((Random().nextInt(9) + 1).toInt());
}
result = int.parse(nums.join());
return result;
}
}
void main() {
User newUser = User("D", "P", "example#ex.com", "password");
print(newUser);
}
You should make the generateId method static.
The method does not need access to the object, it uses no instance methods or fields, so it can, and should, be declared static.
(It can also be significantly simplified.)
static int generateId(int count){
var result = 0;
var random = Random();
for (var i = 0; i < count; i++) {
result = result * 10 + random.nextInt(9) + 1;
}
return result;
}
Also consider whether you really need all digits to be non-zero, or you just need the first digit to be non-zero. If so, you can do:
final int id = 1000000000 + Random().nextInt(9000000000);
to get a random ten-digit identifier.
Well, since you have only a single constructor and that sets the id anyway, you can basically remove it:
This:
int id = generateId(10); // error i here
becomes:
late int id;
Done.
In case your really, really need that line, you could make the generateId method either a function instead of a class method, or you could make it static. That should work, too.
i set an initial price for my token in solidity, how does It Works the price on the market? if i set a fixed variable TokenPrice in my smart contract, can my token price change thanks to request_offer of market?
The price that i fixed in the smart contract and the price of the market are differents?
OK, I show you a small example of solidity and JS code of ICO and how you can do it
solidity:
contract OwnerContract{
address owner;
constructor(){
owner = msg.sender;
}
modifier isOwner(){
require(msg.sender == owner, "Access denied!");
_;
}
}
//Interface of standard token if you want to accept for example USDT token (as in this example)
interface IERC20{
function allowance(address owner, address spender) external view returns (uint256);
function decimals() external view returns (uint8);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
contract ICO_Contract is ownerContract{
//Declare the price and ICO token sell amount
uint256 eachTokenPrice;
uint256 maximumAmount;
uint256 sellAmount;
constructor(uint256 maximumAmount_){
maximumAmount = maximumAmount_;
}
modifier maximumReached(uint256 _amount){
require((sellAmount + _amount) <= maximumAmount, "Maximum amount of ICO reached!");
_;
}
//declare the USDT token
address USDTtokenAddress = USDT_TOKEN_ADDRESS_ON_DEPLOYED_NETWORK;
function changeUSDTtokenAddress(address _address) public isOwner{
USDTtokenAddress = _address;
}
address ICOtokenAddress = TOKEN_ADDRESS_ICO;
function changeICOtokenAddress(address _address) public isOwner{
ICOtokenAddress = _address;
}
IERC20 USDTtoken = IERC20(USDTtokenAddress);
IERC20 ICOtoken = IERC20(ICOtokenAddress);
function buyToken(uint256 _amount) public maximumReached(_amount){
require(_amount > 0, "You need to spend USDT");
uint256 approvedAmount = USDTtoken.allowance(msg.sender, address(this));
require(approvedAmount == _amount, "Check the token allowance, not enough approved!");
uint256 totalPrice = price * _amount * (USDtoken.decimals()/ICOtoken.decimals());
USDTtoken.transferFrom(msg.sender, address(this), totalPrice);
//ICOtoken is in the contract
ICOtoken.transfer(msg.sender, _amount);
sellAmount += _amount;
}
function showPrice() external view returns(uint256){
return price;
}
function showsoldAmount() external view returns(uint256){
return sellAmount;
}
function showMaxAmount() external view returns(uint256){
return maximumAmount;
}
}
I guess this is it. (I did not test and it definitely will throw errors which you have to handle it)
JS code (ethers.js & ethereum libraries) (Because I don't know back-end language I only deploy front-end and just use front-end):
const {ethers} = require('ethers');
let price;
let soldAmount;
let maxAmount;
let provider;
let signer;
let signerAddress;
let contract;
const contractAddress = ICO_CONTRACT_ADDRESS;
const contractABI = {'function showsoldAmount() external view returns(uint256)',
'function showPrice() external view returns(uint256)',
'function buyToken(uint256 _amount) external maximumReached(_amount)',
'function showMaxAmount() external view returns(uint256)'}
//Actually I am not sure if it needs modifier in the interface or not
async () => {
await ethereum.request({ method: 'eth_requestAccounts' });
provider = new ethers.providers.Web3Provider(window.ethereum);
signer = provider.getSigner();
signerAddress = await signer.getAddress();
contract = await new ethers.Contract(contractAddress, contractABI, signer);
price = await contract.showPrice();
soldAmount= await contract.showSoldAmount();
maxAmount = contract.showMaxAmount();
//Show price and sold amount and maximum amount of selling in your page somewhere you want
}
//set a button and input in the page to call the buyToken function and connect it to function below.
function buyToken(){
let amount = document.getElementById("INPUT_TO_KNOW_AMOUNT_ID").value;
contract.buyToken(ethers.utils.parseEther(amount));
}
I hope I did not forget anything but if you have any question simply ask
Best regards :)
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;
}
}
}