# Questions tagged [safemath]

The tag has no usage guidance.

46 questions
Filter by
Sorted by
Tagged with
16 views

### Fotomatriza ist Encoding

Фотоматрицу кодируют на заводе, и драйверы к фотоматрице устанавливают на заводе. Они (фотоматрицы) изготовлены из квантовых полупроводников очень маленького размера и работают с информацией через ...
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. ...
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
35 views

### What was the purpose of adding the safeTransferFrom method? What are the cases when the plain transferFrom fails silently?

I was wondering what is the case when the plain transferFrom ERC20 method fails silently, i.e., just returning false. Looking at the code, to me it looks like when the balance is insufficient or the ...
• 1,179
1 vote
103 views

### What are the benefits of using SafeMath in version >=0.8?

When looking online, I see some answers that there is no use for SafeMath, but I still see some contracts that use it. Is it necessary, or are there any other benefits?
• 11
178 views

### SafeMath Dangers calculating percent in smart contract

I'm making a fund manager using solidity and I'd like to calculate the percentage, however I'm wonder whether the use of safeMath is actually incorrect. using SafeMath for uint256; uint256 percent = 5 ...
• 271
221 views

### How to express a negative power in Solidity?

Trying to express y=2^x where x is a negative number. As Solidity does not support negative powers, is there another way to express this? Thanks for any tips! We are trying to create a decay formula
• 3
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); }
1 vote
54 views

### Unable to withdraw to multiple wallets IF money is in the contract?

This withdraw function works perfectly fine if there is 0 ethereum in the contract; however, the minute there is ethereum (I have been testing sending 0.04 ethereum), the withdraw function breaks. I ...
• 77
1 vote
28 views

### Solidity multiplication always resulting in 0

I'm trying to pay royalties from a contract to multiple wallets, however the multiplication is always sending me to 0. function withdraw_to_taxman() public view returns (uint256){ uint256 balance ...
• 77
82 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
108 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/...
583 views

### Where is the single-parameter version of function sub() defined in SafeMath?

I'm going through the Ethernaut challenges to learn Solidity, and in challenge 3 ("Coin Flip"), they show the following code which subtracts 1 from the current block number: I assumed that ...
• 139
1 vote
194 views

• 21
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++) { ...
33 views

### Can someone please tell me what i have wrong here

function calculateSplitPercent() public { for(uint256 i = 0; i >= uniqueIdCounter; i++) { uint256 spliPercent = balanceOf[uniqueIdToAddress[i]].div(totalFunded).mul(100); ...
65 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 ...
1 vote
735 views

### 'Error: Member "mod" not found or not visible after argument-dependent lookup in uint256' when trying to use Chainlink

I got this error while trying to compile function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness.mod(20).add(1); } I saw it in ...
2k views

### calculate percentage in solidity using SafeMath

I hope this question is not asked, but i googled too much and tried to find out the problem my self. I'm trying to get a dynamic percentage using SafeMath uint256 lowNumber = 316442921; uint256 ...
25k views

### What is the purpose of "unchecked" in Solidity?

According to Solidity documentation: Prior to Solidity 0.8.0, arithmetic operations would always wrap in case of under- or overflow leading to widespread use of libraries that introduce additional ...
• 1,868
1 vote
331 views

### Multiply number with Pi in solidity

I'm finding a library to implement this formula in solidity. Is there is a library to implement this formula.
• 683
97 views

### Does using SafeMath for uint is herited from child contract

I have this code: contract A { using SafeMath for uint; ... } contract B is A { ... } Does my contract B herits from "using SafeMath for uint;"?
422 views

### Calculate Percentage

I want to calculate user reward per day. uint256 totalBalance = 111; uint256 rewardPerDay = 1000; function calculateReward(uint256 userBalance) public view returns (uint256) { uint256 ...
1 vote
1k views

### Where to find SafeMath pragma solidity ^0.6.6?

While trying to use SafeMath to compute the modulo of a uint256 like shown in this video:https://www.youtube.com/watch?v=JqZWariqh5s (without SafeMath) I'm having some trouble finding a pragma ...
• 65
35 views

### SafeMath Utility Error in Ethereum Document 'Unique Digital Asset' Code

I refer to the example code 'Unique Digital Asset' code in Ethereum Doc (https://ethereum.org/en/developers/docs/smart-contracts/anatomy/#unique-digital-asset) line 60. uint256 id = SafeMath.sub(...
141 views

### OpenZeppelin import problem

I am trying to import a couple of OpenZeppelin contracts to my project, but each time I am given an error related to unsuccessful imports from sources. I'm gonna attach a screenshot of my code. I have ...
• 402
1 vote
62 views

### Loaded Die Algorithm in Solidity?

I am trying to implement a smart contract, that takes in a discreet distribution and returns a loaded random number. The higher the number higher the chance from 1-10000. **anyone has any experience ...
• 43
2k views

I'm playing Ethernaut (https://ethernaut.openzeppelin.com/). I'm currently on level 3 (Coin Flip). This is the Coin Flip contract: // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import '@...
656 views

### Round integer down to nearest 10

Is there a good way of floor rounding a number to the nearest 10 in solidity? I have a function that calculates a percentage of a number but I want only to return multiples of 10. e.g. if it is 12% ...
• 361
1 vote
929 views

### Using SafeMath with older Solidity compiler

I've been told SafeMath doesn't matter. Does SafeMath slow things down, cost more ETH, or does it add an extra level of stability? Will SafeMath be unsupported one day? contract SafeMath { function ...
206 views

### How to add three numbers using safemath?

I know this might sound obvious but in solidity you can never be too sure. Let us say I have three numbers 5, 7 and 8. Can I add them like so: using SafeMath for uint256; 5.add(7.add(8)); // or even ...
• 1,843
167 views

### How to make a multiplication and division without overflow and any loss of precision in Vyper

How can I calculate X * Y / Z in vyper uint256 without overflow and any loss of precision? I want to build Vyper FullMath library functions similar to the Uniswap V3 FullMath library written in ...
• 126
1 vote
4k views

i have created a token ....but it gives me error " erc20.sol:94:25: TypeError: Member "add" not found or not visible after argument-dependent lookup in uint256. balances[account] = ...
• 31
1 vote
48 views

### Why is the math code causing transactions to fail

Ok so This is my first time working on solidity contracts and I'm at a loss how to debug this code. This code fails: function claimReturns(address claimant) private { uint otherTotals = ...
• 115
174 views

### I want to store decimal value in a storage variable and later use that variable at same precision in the formula later internally

I want to store uint public MINTING_VELOCITY = 0.000002; And later use it in the formula: A x t x MINTING_VELOCITY ,where A = 2000 ,t(staking_duration_time) = 120 Issue is currently MINTING_VELOCITY ...
14k views

### Is the SafeMath library obsolete in solidity 0.8.0?

SafeMath was commonly used to revert the transaction on overflow and underflow, instead of allowing the number to wrap around. The solidity 0.8.0 release notes state: Code Generator: All arithmetic ...
• 10.5k
1 vote
650 views

### How can I use decimal in solidity

how can i calculate: 1083.83 / 8.25 = 131.37. As I see its not possible in simple way. I have tried a lot of math function but not works. Is there any solution for this?
• 51
830 views

### what happens if I do using SafeMath for uint256 but then divide by uint8?

example using SafeMath for uint256; uint8 number8 = 10; uint256 number256 = 1000; function something() { return number256.div(number8); } is it still using safemath even if my number8 is uint8?
• 227
806 views

### Chainlink import causing Truffle console to crash

Related issue on GitHub: https://github.com/trufflesuite/truffle/issues/3329 If I compile my contracts with truffle compile and then open the truffle console with truffle develop then this happens: ...
266 views

### Efficient, safe pow using EXP opcode

I recently stumbled across ds-math's rpow() being a O(lg n) safe implementation of exponentiation. Such a function is ultimately created because the EVM EXP opcode is unsafe wrt. overflows. The ...
• 123
108 views

### Is there a tool to add SafeMath to production code?

There are a lot of tools to prepare JavaScript/CSS code for production, e.g. to minimize, to convert ES8 code to ES5. Is there a tool to automatically apply SafeMath library to a .sol file? The ...
• 163
280 views

### Using Fractions in Leasing contract

I want to create a smart contract that allows people to lend dai stable coin to other or a smart contract at an interest. suppose at 4 % interest I need to calculate (1+0.04/12)^n (n is the period in ...
528 views

### Safemath Library version for Solidity v0.5?

Is there a version of the SafeMath library that is compliant to SOlidity v0.5? Thanks for your inputs in advance
84 views

### Why is my calculation broken?

I have a smart contract that holds a token balance, let's call it Token A, users may send this smart contract Token B to receive Token A, they do so by specifying the amount of Token A they would like ...
• 3
2k views

### Compilation error using SafeMath

I am trying to do subtraction operation using the SafeMath library. The following is my code: pragma solidity ^0.5.1; library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (...
• 1,406