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');
Related
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");
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)
So I know how arrays are stored in storage. If I understand it correctly it first stores the number of items in an array in the first slot, and then in the next slots, it stores the hashed values.
My question is what if I define uint after the array and the array during deployment has only 2 values. So it should take up 3 slots. Then in the fourth slot is the uint I defined.
What if there is a function that will push something to the array? How is it stored?
Will it be stored in the next free slot? Or will it push the uint to the next slot and replace it with the new value?
I hope the question is clear if not I will try to rephrase it.
Also if there is some good resource where I can learn all about storage in solidity please share the link.
Thanks a lot!
Fixed-size array stores its values in sequential order, starting with the 0th index. There's no prepended slot that would show the total length. Any unset values use the default value of 0.
pragma solidity ^0.8;
contract MyContract {
address[3] addresses; // storage slots 0, 1, 2
uint256 number; // storage slot 3
constructor(address[2] memory _addresses, uint256 _number) {
addresses = _addresses;
number = _number;
}
}
Passing 2 addresses to the constructor, storage slot values in this case:
0: _addresses[0]
1: _addresses[1]
2: default value of zero (third address was not defined)
3: _number
Dynamic-size array stores its values in keys that are hash of the property storage slot (in example below that's 0, as that's the first storage property), and immediately following slots. In the property storage slot, it stores the array length.
pragma solidity ^0.8;
contract MyContract {
/*
* storage slots:
* p (in this case value 0, as this is the first storage property) = length of the array
* keccak256(p) = value of index 0
* keccak256(p) + 1 = value of index 1
* etc.
*/
address[] addresses;
// storage slot 1
uint256 number;
constructor(address[] memory _addresses, uint256 _number) {
addresses = _addresses;
number = _number;
}
}
Passing 2 addresses to the constructor, storage slot values in this case:
0: value 2 (length of the array)
1: _number
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563 (hash of uint 0): _addresses[0]
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e564 (hash of uint 0, plus 1): _addresses[1]
Docs: https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_storage.html#mappings-and-dynamic-arrays
So to answer your questions:
What if there is a function that will push something to the array? How is it stored?
Will it be stored in the next free slot? Or will it push the uint to the next slot and replace it with the new value?
Fixed-size arrays cannot be resized. You can only rewrite its values, while the default value of each item is 0.
In case of dynamic-size arrays, it pushes the new value right after the last one. Since they are stored in slots which indexes are based on a hash, the probability of rewriting another value is practically 0 (i.e. that would mean a hash collision).
In both cases, it doesn't affect how other storage properties are stored.
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
Aloha.
Web3 version is 0.20, and, according to documentation:
web3.eth.sendTransaction
web3.eth.sendTransaction(transactionObject [, callback])
Sends a transaction to the network.
Parameters
Object - The transaction object to send:
from: String - The address for the sending account. Uses the web3.eth.defaultAccount property, if not specified.
to: String - (optional) The destination address of the message, left undefined for a contract-creation transaction.
value: Number|String|BigNumber - (optional) The value transferred for the transaction in Wei, also the endowment if it's a contract-creation transaction.
gas: Number|String|BigNumber - (optional, default: To-Be-Determined) The amount of gas to use for the transaction (unused gas is refunded).
gasPrice: Number|String|BigNumber - (optional, default: To-Be-Determined) The price of gas for this transaction in wei, defaults to the mean network gas price.
data: String - (optional) Either a byte string containing the associated data of the message, or in the case of a contract-creation transaction, the initialisation code.
nonce: Number - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.
Number|String - (optional) If you pass this parameter it will not use the default block set with web3.eth.defaultBlock.
Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.
I have function placeBet() which accepts multiple parameters:
function placeBet(uint8 _outcome, uint desiredMatchIndex, uint _amount) public payable{
// find a way to store a bid in order to be easily searchable, in order to easily send money to winners;
// require(!roundEnd, "Interactions with contract are locked, be careful next time!");
// require(state == State.Active, "Betting is over, game have already started!");
require(msg.value > 0, "It isn't possible to place a bet without a money ");
if(!isDuplicate(msg.sender)) addressIndices.push(msg.sender);
testina(msg.sender, _outcome, desiredMatchIndex);
existingBets[msg.sender].push(Bet({
bettor: msg.sender,
// name: name,
amount: _amount,
bet: desiredMatchIndex,
outcome: _outcome
}));
//emit event, finally;
}
, so my question is how should I include needed additional parameters (outcome, desiredMatchIndex, amount ) [maybe last one is reduntant ] alongside
transactionObject using web3.js?
Thanks : )
Oh, i am sorry, there was an example in documentation, just not adequately referenced.
/ Explicitly sending a transaction to this method
myContractInstance.myMethod.sendTransaction(param1 [, param2, ...] [, transactionObject] [, callback])