# Questions tagged [math]

The tag has no usage guidance.

97 questions
Filter by
Sorted by
Tagged with
15 views

### How does Curve Finance `_checkpoint` works? Especially the for loop

The code is converted to solidity but why it was implemented this way. function _checkpoint( uint _tokenId, LockedBalance memory old_locked, LockedBalance memory new_locked ...
• 129
1 vote
33 views

### How to precisely remove a specific amount of token0 or token1 liquidity from a Uniswap V2 Pair in Solidity

I need to remove an exact amount of token0 or token1 from a Uniswap V2 pair. To achieve this, I must calculate the amount of LP tokens to burn. The calculation formula is straightforward: Where: ...
32 views

### Multiplication of two uint256

How do I compute the multiplication of two uint256 so the result doesn't overflow? In the end, this multiplication is an intermediate step within a larger operation, in case this extra piece of info ...
• 938
32 views

### How multiplication and division works in solidity?

How is this calculated? According to solidity precedence, multiplication has precedence against division Amount= (15- 10) * 10 / 15 * (10_000 - 5_000) / 10_000; So Shouldn't it be 5 * 10 / 15 * ...
• 129
16 views

### How to prevent division before multiplication precision loss?

In the else statement, where the Boolean is false, the amount has more than 18 decimals. In this example I used a 24 decimal amount, 123456789123456789123456. Now, it will return 123456789123456789. ...
• 129
26 views

### How to calculate the graph edge weights when doing arbitrage on Uniswap using Bellman-Ford?

I am trying to create an arbitrage bot on Uniswap by using graph data structure. On this graph tokens represent nodes and the exchange rate between tokens represent edge weights. By applying -log ...
• 253
23 views

### Uniswap V3 protocol tick price conversions

Right now, I'm delving into the mathematics and corresponding code of the Uniswap v3 protocol, and I've stumbled upon this function. Despite scouring numerous documents and forums, I haven't found any ...
• 41
1 vote
9 views

### Misalignment between Uniswap V2 calculateSwapInput and calculateSwapOutput functions

I've written my own functions calculateSwapInput and calculateSwapOutput for liquidity pools, based off of the Uniswap v2 spec. My functions are below: // Calculates how much of one token we need to ...
• 111
21 views

### Casting different from bit manipulation

Casting between uints and bytes16 yields different results as that of manipulating the bits directly. Why? I thought that with casting we were just changing the representation from bits to bytes, and ...
• 938
1 vote
41 views

### Rebase algorithm

I'm building a rebase token and need some help with the algorithm. These are the variables, constants, and constraints (the values themselves are just examples): Set of variables 1: a1 = ...
• 938
82 views

### How to do pow_mod256?

Vyper has the built in function a ** b % (2 ** 256). Is there any way to make the same calculation in Solidity?
898 views

### Uniswap V2 optimal arbitrage amount

Tried out whole week to find an answer somewhere for this question, but, nothing to see, unfortunately, Let suppose there are 2 USDT/WETH pairs, one on Uniswap and another one on any Uniswap v2 fork ( ...
25 views

### Increase the odds to extract a specific number in a series. Save GAS!

This is a cool problem! Can I increase the chances to pick a certain (random) number in a given range? Let's say I have 10 numbers from 1 to 10 and I wish number "3" to have 1,6x the chances ...
• 1
41 views

### Math error 1e18 - 0.1e18, is there a problem?

When I run this code, the output is 1e16 or 10000000000000000, shouldn't it be 0.9e18 or 9e17? // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract A { function addthis() public pure ...
• 129
21 views

### How do you calculate percentage change for token supply?? Is there a need for scaling factor?

Is this how you calculate percentage change of new token price? I am not using any oracle. // START_REBASING_SHARE_PRICE is 1e30. uint256 percentChange = (sharesAfter * ...
• 129
67 views

### Rebasing tokenomics

I have the following variables where all values are multiplied by 1e18 to represent fixed-point numbers on the EVM: uint totalShares = 100; uint sharesAlice = 20; uint sharesBob = 30; uint ...
• 938
138 views

### Is there a shortcut for "greater than or equals to" in Solidity assembly?

I have some code where I was experimenting with the Math library, namely the logarithm functions, and I figured these would be the perfect functions to optimize with assembly, after slightly improving ...
• 125
1 vote
60 views

### How is the derivation of the Constant Product AMM formula of Uniswap?

I was researching about Uniswap v1 and I found that the code is using the following formula to get the amount out of a swap: Formula: Reference to code Everyone says that this formula is derived of ...
• 11
23 views

### What happens if you divide a uint256 by a uint88 using divU64?

I am looking at the following function. It takes a uint256 (ercDebtSocialized) and uses safemath divU64 to divide it by a uint88. I assume this would just throw an error? I unfortunately cannot test ...
530 views

### Why are the Aave V2 supply and borrow index rate calculations done differently?

I have a question about the math in Aave V2 that performs the update liquidity and borrow index. This question was also asked and unanswered in the Aave Governance Forum. I see calculateLinearInterest ...
• 111
1 vote
62 views

### How to calculate make precision calculations with very small ETH amounts?

In the given scenario that I have the following code, in which a user sets a token amount and an ETH amount, I want to determine a price of token using the following code: pricePerToken = (ethAmount * ...
138 views

### Percentage Calculation in Solidity

I am wondering if my idea is correct. Total shares: 11,000 User A's shares : 10,000 User A's share percentage = User A's share / Total share. = 10,000 / 11,000 ...
• 377
325 views

### What are Wei, Gwei and other Ether multipliers [duplicate]

So, when someone sends you 1 Wei, are they sending you the constant "Wei", or 1e-18 Ether? Like what I'm asking is that, Ether, Wei or Gwei, they are constant values, but they are not ...
• 45
1 vote
922 views

### How would I safely calcuate a percentage of a BigNumber?

I need to multiple and divide a big number in a safe way - without overlow. It won't have to result in an accurate amount to suit me; namely, if it gets round by some function to remain integer rather ...
• 91
1 vote
86 views

### How I do I calculate the price of a Token as the amount of the token bought increases

Let say I created a Min price = 0.00056 ether for 150 coins which is the Min amount and the Max price = 0.1 for 20,000 coins which is the Max amount. What will be the price of the coin when I buy 1000 ...
379 views

### Is profitable direct arbitrage impossible with getAmountsOut?

I’ve run the math on a uniswap v2 arbitrage trade that looks more or less like this: 1) Buy X amount of token1 with Y amount of token0 on Uniswap 2) Sell equivalent amount of token1 in exchange for ...
1 vote
76 views

### Uniswap and other exchange. How the bots calculate the amount to buy

Met with such a problem that I can not calculate the amount to buy in front of the user, so that his transaction would be successful. All of the formulas I used to do this produced to the point that ...
• 11
138 views

### How to implement negation in Solidity?

I know that the EVM uses the two's complement system to represent signed values, and that EVM words have 256 bits. How can I negate a number in Solidity, i.e. obtain its negation under the two's ...
• 18.4k
17 views

### Why does negation flip all high bits of a number expect for the least significant bit?

In his blog post on 512 bit division, Remco Bloemen makes the following assertion: ... negation flips all high bits of a number up to but not including the least significant one Why is that?
• 18.4k
64 views

### web3 and some math

There is a transaction that is in pending. In which the user gives 0.02 WBNB (2000000000000000000) to get at least 35460 TM (35460000000000000000000). If he gets less than that the transaction will be ...
1 vote
383 views

### How to find percentage change of two BigNumbers of ether.js?

So I have this for calculating percentage change between two BigNumbers: const percentageChange = (a: BigNumber, b: BigNumber) => b.sub(a).div(a).mul(BigNumber.from('100')) Now the issue is when I ...
• 111
1 vote
394 views

### Manipulating Uniswap V2's pair totalSupply via flash loan

Let's assume that I'm writing a UniswapV2 LP token price oracle. Would it be a bad idea to rely on the LP token totalSupply for my calculation? Would it be possible to manipulate its value through a ...
• 4,594
1 vote
2k views

### Why does Uniswap V3 use ticks [-887272,887272] to represent the price range [0,∞]?

When providing liquidity to an already-created Uniswap V3 pool, you are offered the option to provide liquidity across the price range [0,∞] (effectively performing as a Uniswap V2 LP position). My ...
• 4,594
1 vote
265 views

### Are Uniswap V3 liquidity units fungible across different price ranges?

If I provide liquidity to a Uniswap V3 pool with a set fee, and I provide x amount of token0 and y amount of token1 within a certain price range, let's call it [pa, pb], and I receive a value of L (...
• 4,594
54 views

### Computing the exact exponentiation of a fractional base

not the same solution as this In a function, I need to calculate the exponential of a fraction. The exponent is a whole number, and the base is not. I tried using the ABDKMath64x64 library and using ...
• 1
278 views

### how is the EXP opcode priced? and when to use it?

In the EVM, the MUL opcode costs 5 gas and is used to perform multiplication. For example, the arithmetic behind computing 20 * 30 = 600 should cost 5 gas. The EXP opcode is used to perform ...
• 51
2k views

### How to get the virtual and real reserves from a Uniswap V3 pair?

I need help with math of Uniswap V3 virtual and real reserves. Need to find the true reserves of a pair. Example: let's say we have this DAI/WETH pair: 0x60594a405d53811d3BC4766596EFD80fd545A270 ...
• 11
1 vote
93 views

### "bitwise and" operation between value and its two's component

this operation uint256 pow2 = d & -d is from FullMath.sol function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d ...
• 1,705
1 vote
246 views

### Is there a math error in solidity?

I'm getting a rounding error in solidity that I'm not getting in python uint contributor_balance = 51.50350 ether; uint principal = 21.756 ether; uint WAD = 1000000000000000000; ...
• 638
1 vote
32 views

### What is the most efficience way to compute the nth root, log(x) and e^x of a given number in solidity

This is just something that came out of curiousity.I have been looking for methods for this all over the internet and can't seem to find any. Is there an actually efficient method or any method for ...
2k views

### Using block.prevrandao as randomness for Miller-Rabin Primality test

I am interested in using the new PREVRANDAO value as a source of pseudo-randomness in calculating the Miller-Rabin probabilistic primality test on-chain. Chainlink VRF is an option but ideally I would ...
• 89
146 views

### Math integral in Solidity

I have a particular bonding curve to integrate into Solidity. I have the function and would like to know if there is a Solidity contract that does math integral. Something equivalent to this python ...
• 185
1 vote
2k views

### Cast uint64 to uint32 and uint16

I wrote a contract to understand the difference of casting variable to uint16 and uint32. Code as below: // SPDX-License-Identifier: MIT pragma solidity 0.8.0; contract Learning{ bytes8 theKey = ...
• 95
1 vote
21 views

### How would you write this function in Solidity ? I keep getting error because of the floats

function calcPercentage(int elapsedTime){ return round(8000 + (elapsedTime * (100/36))/10000); }
87 views

### How to write a linear formula for percentage in Solidity?

So id like to write this function in solidity but im having issues because of the integers not being accepted. s being the startin time. Lets say 1 second in unix time. x being the ending time. Lets ...
• 13
97 views

### **Math/Stableswap Formula** Explaining the subsitution of "Chi" to get Stableswap invariant formular

Hello, I'm having a trouble of understanding this operation: In Curve.fi Stable Swap's paper, page 5, they substitue into this formular With some simplification step, we get the Stableswap invariant:...
26 views

### How do I remove decimals from a uint256 [duplicate]

I am calculating a buyPrice that has a factor of 1.2 times the normal price. To do this I get the token price and multiply it by 1200000000000000000 (18). It looks something like: uint256 buyPrice = ...
312 views

### Rewrite equation to pass "performs a multiplication on the result of a division" on slither

I am using slither and I get the following medium severity error: performs a multiplication on the result of a division Now this is the equation in question. uint256 mult = (_type == 1 ? 5 : 2); ...