# Questions tagged [math]

The tag has no usage guidance.

85 questions
Filter by
Sorted by
Tagged with
25 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 ...
1 vote
40 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 ...
1 vote
27 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 ...
14 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 ...
153 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 ...
1 vote
42 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 * ...
61 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 ...
1 vote
105 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 ...
16 views

### How do I implement RSA in solidity for large numbers?

I want to implement RSA in solidity, but for large values, it gives back an overflow error and it does not work correctly. How do I fix it?
1 vote
495 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 ...
1 vote
42 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 ...
185 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
58 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 ...
91 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 ...
13 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?
49 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
294 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 ...
1 vote
266 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 ...
1 vote
843 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 ...
1 vote
164 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 (...
47 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 ...
127 views

### How to calculate linear bonding curve Y = X

I am studying simple linear bonding curve. Y = X token supply = price 1 token = \$1 Alice buys 10 tokens(10th tokens) with \$55 ( \$1+\$2...+\$9+\$10) Bob buys 10 tokens(20th tokens) with \$155 (\$10+\$11+...\$...
95 views

### Gnosis sqrt function vs Uniswap sqrt function

The Uniswap sqrt function makes sense to me. I can input 100 and it returns 10. Gnosis on the other hand has a gnarly 368 lines of code expressing the same function (I think) but the return value is ...
190 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 ...
2k views

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

I need help with math of UniSwap V3 virtual and real reserves. Need to find the true reserves of a pair (value of token0 = value of token1). Example: Let's say we have this DAI/WETH pair: ...
1 vote
77 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 vote
205 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; ...
1 vote
22 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 ...
1k 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 ...
107 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 ...
1 vote
1k 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 = ...
1 vote
17 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); }
78 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 ...
90 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 = ...
269 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); ...
115 views

### Require check after math operation ^0.8

I'm going over some protocol contracts, and I've seen they check pretty obvious math operations with a require() statement. This contract uses solidity 0.8.11 uint256 id = vaultCount; vaultCount = ...
90 views

### What is the use or importance of square roots in solidity and in blockchain in general?

I have been seeing many posts about different implementations of finding the square root of a number with regard to blockchain and there is an edit in this question: https://math.stackexchange.com/...
1 vote
174 views

### Why are protocols like Sushiswap using multiplier 1e10 instead of 1e18?

I've been reviewing a protocol that utilizes MULTIPLIER for their calculations which increases the precision because there are no decimal numbers in solidity. That is fine, but I've seen a lot of ...
1 vote
65 views

### How to solve linear equations using solidity?

I am setting up a contract which gets initialized with the following parameters: startDate, endDate, startPrice The price at any given points is the line connecting the two points a and b where a*...
68 views

### Complicated ERC20 Arithmetic

I'm trying to compose a formula in Solidity that has a combination of unsigned integers, signed and exponents, however having a hard time figuring out how to do so. The formula would look something ...
26 views

### broken for loop

can someone let me know what i got wrong in this for loop, if you need the full code let me know. function calculateSplitPercent() public { for(uint256 i = 0; i >= uniqueIdCounter; i++) { ...
59 views

### Percentages in solidity

How would i work out "x is what percent of y" or for example 5 is what percent 10 = 50%. For some reason i just cant wrap my head around it. A clip of my code is below, i want to work out ...
487 views

### Division of big numbers in a smart contract

I am building a function that will payout dividends based on the percentage of tokens owned. function simulateRent() public payable{ uint256 rent_received = msg.value; for (...
267 views

### Division error getting token value with too many decimals

I am using the method below to get the value of a token, it works very well when the token value is not something very low like \$0.000004101, the problem is in the division of the wBNB / TOKEN reserve,...
720 views

### How to floor or ceil a fixed point number?

Say I have a signed 64.64 fixed point number 18444899399302180000 or 0.9999 in floating point notation. How can I define a floor and ceil function that floors or ceils an int128 signed 64.64 fixed ...
1 vote
2k views

### How to handle division by zero in solidity?

In popular programming languages dividing by zero results in an exception being thrown such as ZeroDivisionError in python. Does solidity allow for such exception handling? and if so how would I ...
604 views

### How to convert uint8 to uint256 bitmap in solidity?

Say I have a uint8 with binary value 0000_1001 i.e. 8+1=9 in decimal. How do I convert this uint8 in a gas efficient way to a uint256 which represents a bitmap?, such that in this example the 9th bit(...