so i was reading through this https://www.ethereum.org/token#minimum-viable-token article which is providing an example for an ethereum token with such functionalities as transferring and burning coins. Lets take a piece of code:
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
everything is pretty clear to me here, we take coins from sender, then take it from the total supply, but what's with line:
Burn(msg.sender, _value);
Where does this function come from? what it does which wasnt done already?
It's publishing an event, declared earlier in the code:
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
Here's a blog post I wrote about events, including how they're monitored client-side: https://programtheblockchain.com/posts/2018/01/24/logging-and-watching-solidity-events/.
Related
I want the following function to activate after 6 mins(360 secs) of contract deployment because my task requires a withdrawal lock. should I put if (block.timestamp > 360) before the function or inside the function just before the remaining code?
function withdraw(uint256 amount) external updateReward(msg.sender) nonReentrant {
if (block.timestamp > 360) {
s_totalSupply -= amount;
s_balances[msg.sender] -= amount;
emit WithdrewStake(msg.sender, amount);
// transfer: send tokens from contract back to msg.sender.
bool success = s_stakingToken.transfer(msg.sender, amount);
if (!success) {
revert TransferFailed(); // revert resets everything done in a failed transaction.
}}
}
But I'm not even sure if if (block.timestamp > 360) is the right code for this case.
Figured it out for you my brother:
pragma solidity ^0.8.7;
import "hardhat/console.sol";
contract TimeTest{
uint256 public initialTime;
constructor () public{
initialTime = block.timestamp;
}
function withdraw() public {
uint256 nowTime = block.timestamp-initialTime; // time between deployment of contract and now.
console.log(nowTime);
if (nowTime > 60) {
console.log("Time is up");
}
}
}
The reason why you have to do that is because block.timestamp doesnt represent the time since the contract was deployed, but the time since the unix epoch. The name of the variable is a little misleading.
You can find more info here: https://docs.soliditylang.org/en/v0.8.13/units-and-global-variables.html
Or here:https://programtheblockchain.com/posts/2018/01/12/writing-a-contract-that-handles-time/ (just know that "now" doesnt exist anymore since version 0.0.7. "now" was equivalent to "block.timestamp". But the tutorial is still valid if you replace "now" with "block.timestamp".
I'm using HashLips' new LowGasFees smart contract. I'm deploying on Polygon network, and I´m minting all NFTs into my opensea to sell later on in batches. So no DAPP involved.
For me to be safe in terms of avoiding free-minters, I put the cost to 100 ether, that would be 100 matic. But whenever I test through Remix or even through contract itself on polygon scan, it never shows the cost added, only gas fees. Which are way above normal price on mainnet don't know why (~0,47 MATIC when normal is like ~0,005-0,007 MATIC).
What could be the reason of this? Is this normal? I don't want anyone to snipe my nfts for pennies whenever I unpause the contract.
This is how I set up my public props
string public uriPrefix = "";
string public uriSuffis = ".json";
string public hiddenMetadataUri;
uint256 public cost = 100 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmountPerTx = 50;
bool public paused = true;
bool public revealed = true;
This is how the mint works:
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "Contract is paused");
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
}
_mintLoop(msg.sender, _mintAmount);
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for(uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
I also wish to be able to modify the maxSupply on runtime, so I made this setter function, not really sure if it's okay or if there's something else to check on that I could have missed.
function setMaxSupply(uint256 _maxSupply) public onlyOwner {
require(_maxSupply >= supply.current(), "You can't set a value lower than current supply minted!");
maxSupply = _maxSupply;
}
Thanks in advance.
thats because your contract is paused, making it unusable. You need to transact on your deployed contract to make pause = false. It will let you mint normally and the gas will drop to realistic prices.
I'm trying to add liquidity to my smart contract on Uniswap, however whenever I try to add liquidity, I can approve the transaction, but hitting apply does nothing. The Javascript console shows an error saying: not able to predict gas gee. There's also a problem with TransferFrom.
function transfer(address to, uint value) public returns(bool) {
require(balanceOf(msg.sender) >= value, 'balance too low');
//burn&tax
burn(msg.sender,burnTaxFee(value));
sendDev(msg.sender,devTaxFee(value));
balances[to] += value; //send the value - burnt tokens to reciever
balances[msg.sender] -= value ; //subtract value sent from sender.
emit Transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) public returns(bool) {
require(balanceOf(from) >= value, 'balance too low');
require(allowance[from][msg.sender] >= value, 'allowance too low');
//burn&tax
burn(msg.sender,burnTaxFee(value));
sendDev(msg.sender,devTaxFee(value));
balances[to] += value; //send the value - burnt tokens to reciever
balances[from] -= value; //subtract value sent from sender.
emit Transfer(from, to, value);
return true;
}
I'm thinking it might have to do with my smart contract? for each transfer, I also do 2 separate transfers that go into two separate wallets. Do multiple transfers triggered by the normal transfer function cause problems with uniswap?
Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={"code":-32603,"message":"execution reverted: TransferHelper: TRANSFER_FROM_FAILED","data":{"originalError":{"code":3,"data":"0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000245472616e7366657248656c7065723a205452414e534645525f46524f4d5f4641494c454400000000000000000000000000000000000000000000000000000000","message":"execution reverted: TransferHelper: TRANSFER_FROM_FAILED"}}}, method="estimateGas", transaction={"from":"0xA6486944b1119CDAB743694873e28ad8eF3f89e2","to":"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D","value":{"type":"BigNumber","hex":"0x1717b72f0a4000"},"data":"0xf305d71900000000000000000000000054620e1c1c39d689fc73214bb1de16f743214dce0000000000000000000000000000000000000000000113d788ba2b887b6c80000000000000000000000000000000000000000000000113d788ba2b887b6c8000000000000000000000000000000000000000000000000000001717b72f0a4000000000000000000000000000a6486944b1119cdab743694873e28ad8ef3f89e20000000000000000000000000000000000000000000000000000000060c1817e","accessList":null}, code=UNPREDICTABLE_GAS_LIMIT, version=providers/5.2.0)
Another idea I had was that I'm not using the SafeMath library, would non-safemath equations cause issues with Uniswap?
I'm writing a LibraryPortal Smart Contract in which multiple users can rent their books to each other. So, in this contract the msg.value contain the total amount which is a combination of the Security Deposit & the Renting Rate.
What I have to do is transfer the Renting amount to the owner of the book instantly & store the remaining amount in the contract i.e., the Security Deposit.
If the Renter will not return the book with in the time specified then the security amount will be transfered to the Owner of the book, otherwise get returned to the Renter.
Here is my snippet:
function borrowBook(string _bName) payable returns (string){
if(msg.sender != books[_bName].owner){
if(books[_bName].available == true){
if(getBalance()>=(books[_bName].amtSecurity + books[_bName].rate) ){
books[_bName].borrower = msg.sender;
books[_bName].available = false;
books[_bName].owner.transfer(msg.value - books[_bName].amtSecurity);
// Code missing
// For storing
// ETH into the Contact
return "Borrowed Succesful";
}else{
return "Insufficient Fund";
}
}else{
return "Currently this Book is Not Available!";
}
}else{
return "You cannot Borrow your own Book";
}
}
You can achieve the result from something called as Escrow contract.
Following is the implementation of Escrow contract by open-zeppelin:
contract Escrow is Secondary {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* #dev Stores the sent amount as credit to be withdrawn.
* #param payee The destination address of the funds.
*/
function deposit(address payee) public onlyPrimary payable {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].add(amount);
emit Deposited(payee, amount);
}
/**
* #dev Withdraw accumulated balance for a payee.
* #param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payee) public onlyPrimary {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.transfer(payment);
emit Withdrawn(payee, payment);
}
}
You can just instantiate the contract in your contract and forward the funds to the contract.
For full implementation of similar functionality have a look at the refundable crowdsale contract
Thank you guys for answers but, later I came to know that the VALUE sent along with the transaction to the contract is stored in the Contract itself, & you can access that by using the address(this).balance which will always gives you the Balance available in that instance of the contract. Due to this you don't require any variable or other stuff to store ETHER in your contract.
New to solidity and geth for my traineeship, I started deploying contrcts using the solidity online IDE and the geth dev mode. My problem is I tried a few different ways to do it but nothing seems to really work.
Code:
contract Transaction {
address public owner;
mapping (address => uint) public balances;
function Transaction () {
owner = msg.sender;
}
function validateTransaction (address receiver, uint amount) constant returns (bool) {
if (balances[owner] < amount || owner == receiver || amount == 0)
return (false);
balances[owner] -= msg.value;
return (true);
}
function transact (address receiver, uint amount) {
if (!validateTransaction(receiver, amount))
return ;
balances[receiver] += msg.value;
}
function remove () {
if (msg.sender == owner)
selfdestruct(owner);
}
}
I also tried this contract of a solidity tutorial but it also don't work as I expected:
contract Coin {
// The keyword "public" makes those variables
// readable from outside.
address public minter;
mapping (address => uint) public balances;
// Events allow light clients to react on
// changes efficiently.
event Sent(address from, address to, uint amount);
// This is the constructor whose code is
// run only when the contract is created.
function Coin() {
minter = msg.sender;
}
function mint(address receiver, uint amount) {
if (msg.sender != minter) return;
balances[receiver] += amount;
}
function send(address receiver, uint amount) {
if (balances[msg.sender] < amount) return;
balances[msg.sender] -= amount;
balances[receiver] += amount;
Sent(msg.sender, receiver, amount);
}
}
I am just trying to make a smart contract that can make transactions between the sender and a receiver but the accounts balances don't move. Are that functions only abstract to learn how solidity works or can this really make the balances change ? Thanks for your answers :)
After have searched and work deeper on solidity I found that, indeed, this contract makes abstract transactions into HIS data. So the ether aren't truely sent and the balance variable is local to this contract.