How to calculate LP token worth - ethereum

I am trying to implement my own USDC liquidity pool that allows various users to deposit USDC into it to earn a fixed interest rate based on how long they park the USDC in my pool (meanwhile I will use the USDC for other things) But I am trying to work out how I can give them a ‘live’ balance on their deposit and interest earned so far. Anyone have any ideas on how I could do this ?
I am guessing that once they deposit 100 USDC then I should give them 100 LP tokens in return right ? but how to auto increment the value of those LP tokens etc has me confused

Related

UniswapV2Pair, mint function, how is liquidity is created proportion to pair liquidity added

function mint(address to) external lock returns (uint liquidity) {
}
The function above is implemented such that liquidity is added to the to address, however the liquidity is just minted depending on the difference of reserves and balance of token how will it create the liquidity in proportion to liquidity added by sender,
Am i missing something, what if a user always calls the mint function will he not get free LP token added to the address as we can see that the mint function is external not internal
Am i missing something, what if a user always calls the mint function will he not get free LP token added to the address as we can see that the mint function is external not internal
You are missing the function body and all the logic and checks inside it.
what if a user always calls the mint function will he not get free LP token added to the address
The mint() function itself only mints LP tokens to make up for a difference between actual LP balance and expected LP balance. If there's no difference between the actual and expected balances, no LP tokens are minted.
A common practice is to use the router function addLiquidity() which sends tokens to the Pair contract, and then invokes the mint() function - both as part of one transaction, so there's no way to frontrun this action.
If there were underlying tokens sent to the Pair contract without invoking the mint() function, then anyone could invoke this function freely claiming LP tokens representing this difference. However only once, as the LP mint zeros up the difference.
what if a user always calls the mint function will he not get free LP
token added to the address as we can see that the mint function is
external not internal
mint() is called when a user added liquidity.
however the liquidity is just minted depending on the difference of
reserves and balance of token how will it create the liquidity in
proportion to liquidity added by sender,
Because the main equation is based on increasing liquidity is proportional to an increase in LP token shares. This makes sense because adding liquidity has no effect on price, so if you add more liquidity, you should receive LP tokens proportional to what you have received before
Let's say you have T shares and you want to increase liquidity from L0 to L1. How many more shares will be minted for you?
L1 / L0 = (T + mintAmount)/T
We need to find mintAmount.
(L1/L0) * T = T + mintAmount // leave mintAmount alone
((L1/L0)*T) - T = mintAmount // multiply T with L0/L0
((L1/L0)*T) - (T*L0)/L0 = mintAmount
Finally
mintAmount = ((L1-L0)/L0) * T

web3js Uniswap handle event log data

I am building a scraper to get all Swap data from Uniswap using web3js.
So far I subscribe to the log and filter topics by Swap() event.
then I decode the data and get amount0In, amount1In, amount0Out, amount1Out.
My problem is in the swapExactETHForTokensSupportingFeeOnTransferTokens() function.
Normally a swap has token0 in and token1 out, but this function gives me values for 3 of the 4 and I can not seem to understand how to handle that. eventually what I want is to know what they spend, what they got and what I need to update the new reserves of that pair.
If someone has the understanding of the Uniswap RouterV2 contract swap functions, I would like to get some pointers on how to handle the data to get my calculations right.
I found the solution here ethereum.stackexchange Anyone with the same question gets a very detailed answer there.
some contracts actually transfers to recipient specified amount of tokens minus 10% (5% tax fee and 5% liquidity fee) 208940457743532637 - 10% = 188046411969179375 and emits Transfer event. Then, PancakePair _swap function emits Swap event with base value of Amount0Out 208940457743532637
Amount0In is greater than zero because the token contract returns part of tokens as a liquidity pair on Pancake Swap.

Best way to register for a vote in solidity

Hi I'm creating a voting smart contract for a DAO and I have a security question. The voting system works like this:
You send your tokens to the smart contract then the smart contract registers how much tokens you have and assignes you "Power" which you use when you vote. Then the smart contract sends the funds back immidiately.
My question is if there is more secure way to do this. Without funds leaving usere's wallet.
Here is the code I have so far.
function getPower() payable public {
require(msg.value > 0, "The amount can't be 0");
require(election_state == ELECTION_STATE.OPEN);
require(votingPeriod > block.timestamp);
uint amountSent = msg.value;
// This function will take their money and assign power to the voter
// The power is equal to their deposit in eth * 10 so for each eth they get 10 power
voters[msg.sender].power = msg.value * 10;
payable(msg.sender).transfer(amountSent);
}
Thanks in advance.
Based on the provided code and question, I'm assuming you want to calculate the voting power based on the users' ETH balance - not based on their balance of the DAO token.
You can get the current ETH balance of an address, using the .balance member of an address type. So you could simplify your function as this:
function getPower() public {
require(election_state == ELECTION_STATE.OPEN);
require(votingPeriod > block.timestamp);
voters[msg.sender].power = msg.sender.balance * 10;
}
After performing the validations, it assigns the value based on the msg.sender ETH balance at the moment of the getPower() function being invoked. Without them needing to send ETH to the contract.
Note that this approach is not common and can be misused for example by users loaning a large amount of ETH just before executing the getPower() function. I'd recommend you to use a more common pattern of calculating the voting power based on their current holdings of the token representing their stake in the DAO.

Solidity gas estimation - always out of gas when setting to 0

I'm trying to figure out a solution to this problem, to do with transaction confirmation order and setting values to 0
pragma solidity ^0.5.17;
contract Test {
uint256 amount;
constructor() public {}
function join() public {
amount += 100;
}
function leave() public {
amount -= 100;
}
}
Given these transactions (tested on ropsten):
tx 1) Call Join Confirmed
amount == 100
tx 2) Call Join (gas price 1) Pending
amount == 100 should tx3 get mined first
tx 3) Call Leave (gas price 100) Pending
amount == 0
However tx 2 will always fail with an out of gas error for as long as the amount is set back to 0. This doesn't happen if the value is any higher than 0. My understanding is that it costs more gas to set a value to its 0 state instead of a positive integer, and the gas estimation isn't taking this into account. I've tried delete hoping this would give a gas refund to compensate for the too-low gas limit, but it still failed.
Is there an elegant way to handle this scenario? The only ways I can think of are over-estimating the gas for all join transactions, which has its obvious drawbacks, or never setting amount back to 0.
You are making correct observations.
by setting it to 0 you delete storage, and get gas refund. This is why it takes less amount of gas. But gas refunds have top limit, so you can't use it to store ETH.
It costs 20,000 gas to store one value in a slot (source:https://github.com/ethereum/go-ethereum/blob/d13c59fef0926af0ef0cff0a2e793f95d46442f0/params/protocol_params.go#L41 )
it costs 2,200 gas to load one value from a storage slot (source: https://github.com/ethereum/go-ethereum/blob/d13c59fef0926af0ef0cff0a2e793f95d46442f0/params/protocol_params.go#L89)
That's why you are seeing different gas consumption values.
Just set your gasLimit to some empirically found roughly-estimated value.
Do a trace of your transaction and you will see all gas consumption values.
Now, the way gas refunds work is that during the state transition function, you're asked for the full gas for the run of your contract. During this run, all gas refunds are accumulated in StateDB (temporary state object). At the end of the state transition function, you will get refunds for all storage releases your contract is going to make. This is why you have to set higher gas limit that Etherscan shows, because lets say your contract needs 15,000 gas to run, after storage is released (say for 5,000 gas) , Etherscan will show like the transaction needed 10,000 gas. This is not true because you have got gas refunds at the end, but at the beginning you needed the whole amount of gas (15,000). Gas refunds are sponsored by the miner, his account is going to get less ETH because he is paying you these refunds.

Is it safe to read the ethereum smart contract balance directly to calculate the transfer of assets to users?

I have contract, through which users can trade on DEX.
Like this:
// transfer asset A from msg.sender
ERC20(AToken).transferFrom(msg.sender, address(this), amount);
// do trade A to B
... trade logic here
// get balance of asset B after trade
// asset B after trade gets to this contract address
uint256 returnAmount = ERC20(BToken).balanceOf(address(this));
// transfer asset B to msg.sender
ERC20(BToken).transfer(msg.sender, returnAmount);
I wonder about returnAmount, is this logic safe?
Transactions in ethereum are performed either completely or not performed at all, and also in order of priority.
But I’m still wondering if there could be such a case when returnAmount shows incorrectly, for example, contract get the balance after the transaction of another user?
Transactions in ETH are executed one by one, other transactions can not interfere to execution of a transaction when it's running by EVM.