How to update a NFT mint price by ethereum price in USD? - ethereum

I am trying to build a smart contract that would give a fixed price in USD for each NFT to be minted by others, which they will need to pay in ETH. But I found a problem that the price of ETH is always changing, and each update of the NFT price in ETH would need some gas fee, which could cost a lot in long term for maintenance. Is there a way to periodically update ETH price inside the smart contract, or is manual updating the only way to do it?
Or I might have to remove the NFT price limit and completely rely on the frontend to handle the pricing part. But I think that's too risky.

You can use a Chainlink datafeed that returns the price of ETH in USD.
There are no datafeeds in emulators (e.g. Ganache or the Remix IDE built-in network), so you can test this snippet on your local fork of the Ethereum mainnet.
pragma solidity 0.8;
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract MyContract {
AggregatorV3Interface priceFeed;
// 18 decimals
uint256 requiredPriceInUsd = 1000 * 1e18;
constructor() {
// https://etherscan.io/address/0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419#code
// Chainlink ETH/USD Price Feed for Ethereum Mainnet
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
// returns amount of wei
function getRequiredPriceInWei() public view returns (uint256) {
(,int answer,,,) = priceFeed.latestRoundData();
// returned price is 8 decimals, convert to 18 decimals
uint256 ethUsdPrice = uint256(answer) * 1e10;
// 36 decimals / 18 decimals = 18 decimals
return (requiredPriceInUsd * 1e18) / ethUsdPrice;
}
}
Output from my test:
answer is 122884000000 (1228 USD and 8 decimals)
returned value from getRequiredPriceInWei() is 813775593242407473 (of wei, that's ~0.8 ETH for 1,000 USD)

Related

Uniswap v2 swap() function. What are balance0 & balance1?

I'm learning how the Uniswapv2 contracts work but I can't seem to wrap my mind around the swap() function.
Reference: https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L173
Lines 173-174 contain:
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
My question is, when & whose balances are these?
A. These are the same as _reserve0 & _reserve1 after the most recent swap and will be used to synchronize reserves.
B. These are the quantities of each token the user making the swap currently possesses.
C. None of the above. It's something else. Please explain the flow of this function. I cannot find a clear and concise definition anywhere.
answer is "C" :)
balanceOf is a mapping in ERC20 implementation to return the amount that given address holds:
// address => holds uint amount
mapping(address => uint) public balanceOf;
Since current contract is inheriting from UniswapV2ERC20:
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20{}
it can access to UniswapV2ERC20.sol
Since the mapping balanceOf is public, solidity assigns getters to the public variables
In the functions:
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
address(this) refers to the current contract which is UniswapV2Pair. So balance0 is how much the current contract owns _token0 and balance1 is how much the current contract address owns _token1. token0 and token1 are contract addresses and each ERC20 token contract, keeps track of addresses and their balances. so you are visiting each token contract and getting how much balance the current contract has.
Think ERC20 contract like a bank. you have token0 bank and token1 bank. Each bank keeps track of the balances of their users. balancesOf is where ERC20 tokens store those balances. Your current contract also owns some of those tokens so you just want to get how much tokens the current contract holds
swap function will be called by the user. Before executing the swap, contract checks if it has enough funds
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');

The transaction has been reverted to the initial state. The called function should be payable if you send value

the Error being specified is
revert
The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.
Debug the transaction to get more information.
//SPDX-License-Identifier:MIT
pragma solidity 0.8.8;
contract Giftcard{
event UniqueCardId(uint indexed Id,address indexed owner);
//Enter The Giftcard amount
//Pay the gift card by making multiple transations
//require(giftcard owner should approve the withdrawl )
address[] Giftcardowners;
mapping(address => uint) amountUploaded;
function Addamount() external payable{
require(msg.value >= 1 ether,"Gift card amount to small");
amountUploaded[msg.sender] = msg.value;
Giftcardowners.push(msg.sender);
emit UniqueCardId(Giftcardowners.length-1,msg.sender);
}
function GetGiftcard(uint _cardId) payable external {
require(Giftcardowners.length > _cardId,"Id doesnot exits");
address owner = Giftcardowners[_cardId-1];
uint amount = amountUploaded[owner];
require(amount >= 1 ether,"transfered is less than 1 ether");
// (bool successs,) = payable(msg.sender).call{value:amount}("");
//require(successs,"transaction reverted");
payable(msg.sender).transfer(1 ether);
}
function getBalance() external view returns(uint balance){
return address(this).balance;
}
}
Firstly I called the Addamount function by paying more than 1 ether to the smart contract
now after that when the GetGiftcard function is called the transaction is reverted. I am unable to find a solution
unable to understand the concept
Error is here
address owner = Giftcardowners[_cardId-1];
should be
address owner = Giftcardowners[_cardId];
When you call addAmount, this line executes
Giftcardowners.push(msg.sender);
in the Giftcardowners array you have only 1 item
Giftcardowners=[0x7EF2e0048f5bAeDe046f6BF797943daF4ED8CB47]
when you call the GetGiftcard, you need to pass _cardId=0, you are actually assigning the index of the array as the id. when you pass 0, index will be -1 here
address owner = Giftcardowners[_cardId-1];
You cannot pass 1 to get 1-1=0, because you have this condition
require(Giftcardowners.length > _cardId,"Id doesnot exits");

Is there a good way to index a lot of data in a smart contract to be able to read it efficiently?

I am writing a solidity smart contract in which users would be able add a string (eg. one line joke), and other users should be able to vote on these jokes. If there are for example a million jokes in the contract (all with a different vote count), Would it be possible to rank these jokes by vote count? Eg. display the highest voted 10 of the million jokes? I know it is possible on a small scale, but on a larger scale I'm not so sure.
A variant of the contract that implements the main functionality you need is attached below:
registration of "jokes" records
registration of voting without repeats
definition of the top 10 (I hope I was not mistaken in the sorting algorithm).
The hash from its text is used as the identifier of the "joke".
However, in order to provide users with quality functionality, you need an external application that will monitor the events JokeCreated and JokeVoted of this contract and maintain an external database of "jokes" records.
This is because Ethereum contracts are ineffective for iterative operations with large arrays and you need an external service to:
providing users with a common list of "jokes"
providing users with a general rating list of "jokes"
When using an external application, you can also exclude the function of determining the top 10 from the contract (in function VotesForJoke), which will significantly reduce the cost of the voting transaction.
In addition, you need to keep in mind the problem of identifying users to avoid re-voting, since in general it cannot be solved at the level of Ethereum itself.
pragma solidity ^0.5.8;
contract Jokes
{
struct Joke
{
string text ;
address sender ;
bytes32 author ;
uint256 votes ;
mapping (bytes32=>bool) voters ;
}
mapping (bytes32 => Joke) JokesList ;
bytes32[10] Top10 ;
event JokeCreated(bytes32 hash, string text, address sender, bytes32 author) ;
event JokeVoted (bytes32 hash, bytes32 voter) ;
constructor() public
{
}
function NewJoke(string memory text_, bytes32 author_) public
{
bytes32 hash ;
hash=keccak256(abi.encodePacked(text_)) ;
if(JokesList[hash].author!=0x00) require(false) ;
JokesList[hash] =Joke({ text: text_,
sender: tx.origin,
author: author_,
votes: 0 }) ;
emit JokeCreated(hash, text_, tx.origin, author_) ;
}
function VotesForJoke(bytes32 hash_, bytes32 voter_) public
{
uint256 votes ;
uint256 i ;
// Check for existance
if(JokesList[hash_].author==0x00) require(false) ;
// Check for re-voting
if(JokesList[hash_].voters[voter_]==true) require(false) ;
JokesList[hash_].voters[voter_]=true ;
JokesList[hash_].votes++ ;
// Ordering top 10
votes=JokesList[hash_].votes ;
for(i=9 ; i>=0 ; i--)
if(votes>=JokesList[Top10[i]].votes)
{
if(i!=9 && Top10[i]!=hash_) Top10[i+1]=Top10[i] ;
}
else
{
break ;
}
if(i!=9) Top10[i+1]=hash_ ;
// Emit event of voting
emit JokeVoted(hash_, voter_) ;
}
function GetJoke(bytes32 hash_) public view returns (string memory, address, bytes32,uint256 retVal)
{
return(JokesList[hash_].text, JokesList[hash_].sender, JokesList[hash_].author, JokesList[hash_].votes) ;
}
function GetTop10() public view returns (bytes32[10] memory retVal)
{
return(Top10) ;
}
}

What is address(1) in solidity?

Recently, i read smart contracts of compound finance.
In PriceOracleProxy.sol(https://etherscan.io/address/0xe7664229833AE4Abf4E269b8F23a86B657E2338D#code)
line 3863 shows:
address constant usdcOracleKey = address(1);
i'm confusing of this address(1), what's meaning of it.
/**
* #notice address of the cUSDC contract, which we hand pick a key for
*/
address public cUsdcAddress;
/**
* #notice address of the USDC contract, which we hand pick a key for
*/
address constant usdcOracleKey = address(1);
last used:
return v1PriceOracle.assetPrices(usdcOracleKey);
Its just another way to write 0x0000000000000000000000000000000000000001,
by the same logic address(0) is 0x0000000000000000000000000000000000000000

How to calculate optimal gas limit and gas price?

Im training to write on Solidity and when I try download ERC20 example in blockchain I need choose gas limit and gas price. How to calculate optimal?
https://www.ethgasstation.info says that with 5 gwei gas price confirmation time will be 0.46 mins, is it true? I read forums and I think this is too few
How much gas limit I need for ERC20 transfer?
you can calculate like this
const gasPrice = await web3.eth.getGasPrice();
const gasPriceLimit = await web3.eth.estimateGas({
"from" : walletbase,
"nonce" : value,
"to" : contractAddr,
"data" : data
})