Multiplication and Division with contract value - solidity

I am trying to insert a if-clause in the following contract to check if the withdrawal (it is a sample bank contract) is less than the 10% of the whole contracts value, i.e. of the complete bank.
When I insert the code as below it gives me an error such as
"UnimplementedFeatureError: Not yet implemented - FixedPointType."
What am I doing wrong?
Can you help me?
Many thanks in advance!!
pragma solidity ^0.4.24;
contract bank{
mapping (address => uint) private balance;
address public Owner;
function WithDrawMoreMoney(uint a) public{
require (balance[msg.sender]>=0);
require (address(this).balance>=0);
require ((a) =< (address (this).balance)*(uint(1.1))); // The problematic line
balance[msg.sender]-=a;
(msg.sender).transfer(a);

check if the withdrawal ... is less than [10%] of the whole [contract's] value
I think you just want this:
require(a <= address(this).balance / 10);
Your code multiplied by 1.1 when I think you meant 0.1, but either way Solidity only has integers. Dividing by 10 works. You also had a typo: =< instead of <=.
If you want to check some other percentage, like 23%:
require(a <= address(this).balance * 23 / 100);
Make sure to do the multiplication first, and always remember to guard against integer overflows.

Related

I need to understand below smart contract code

Can you help me explain below smart contract code I found on tomb finance, tomb.sol contract?
// Initial distribution for the first 24h genesis pools
uint256 public constant INITIAL_GENESIS_POOL_DISTRIBUTION = 11000 ether;
// Initial distribution for the day 2-5 TOMB-WFTM LP -> TOMB pool
uint256 public constant INITIAL_TOMB_POOL_DISTRIBUTION = 140000 ether;
// Distribution for airdrops wallet
uint256 public constant INITIAL_AIRDROP_WALLET_DISTRIBUTION = 9000 ether;
Why do they distribute ether for the pools?
Why ether?
Can they do that?
What exactly is the value of 1 ether?
If they had deployed this on BNB Chain, will this code will change?
This snippet alone doesn't distribute any ether, it only declares 3 constants. It's likely that there's some other functions in the code, that wasn't shared, that make use of these constants.
ether in this case is a Solidity global unit. No matter on which network you deploy the contract, it multiplies the specified number by 10^18 (or 1000000000000000000). Current version of Solidity (0.8) is not able to store decimal numbers, so all native and ERC-20 balances are stored in the smallest units of the token. In case of native tokens (ETH on Ethereum, MATIC on Polygon, ...), that's wei. And 10^18 wei == 1 ETH (or 1 MATIC, etc - depending on the network).
If this code was deployed on other EVM network (such as Binance Smart Chain), the ether unit is the same. It doesn't work with ETH tokens, it "just" multiplies the number.

Why does this solidity function run into gas errors?

I'm trying to figure out some strange behavior. The function below takes in an array like [1,2,3,4,5], loops through it, and looks at another contract to verify ownership. I wrote it like this (taking in a controlled / limited array) to limit the amount of looping required (to avoid gas issues). The weird part (well, to me) is that I can run this a few times and it works great, mapping the unmapped values. It will always process as expected until I run about 50 items through it. After that, the next time it will gas out even if the array includes only one value. So, I'm wondering what's going on here...
function claimFreeNFTs (uint[] memory _IDlist) external payable noReentrant {
IERC721 OGcontract = IERC721(ERC721_contract);
uint numClaims = 0;
for (uint i = 0; i < _IDlist.length; i++) {
uint thisID = _IDlist[i];
require(OGcontract.ownerOf(thisID)==msg.sender, 'Must own token.' );
if ( !claimedIDList(thisID) ) { // checks mapping here...
claimIDset(thisID); // maps unmapped values here;
numClaims++;
}
}
if ( numClaims > 0 ) {
_safeMint(msg.sender, numClaims);
emit Mint(msg.sender, totalSupply());
}
}
Any thoughts / directions appreciated. :-)
Well, there was a bit more to the function, actually. I'd edited out some of what I thought was extraneous, but it turned out my error was in the extra stuff. The above does actually work. (Sorry.) After doing the mint, I was also reducing the supply of a reserve wallet on the contract -- one that held (suprise!) 50 NFTs. So, after this function processed 50, it was making that wallet hold negative NFTs, which screwed things up. Long story, but on Remix, I'd forgotten to set values in the constructor in the proper order, which is how I screwed it up in the first place. Anyway, solved.

Solidity -- using uninitialized storage pointers safely

I'm trying to gas-optimize the following solidity function by allowing users to sort the array they pass in such a way that I can perform less storage reads. However, to do this I need to use an uninitialized storage pointer -- which the compiler doesnt let me do (^0.8.0). How can I safely use an uninitialized storage pointer and have it be accepted by the compiler?
function safeBatchReleaseCollaterals(
uint256[] memory bondIds,
uint256[] memory collateralIds,
address to
) public {
// 'memoization' variables
uint256 lastAuthorizedBond = 2**256 - 1;
uint256 lastCurrencyRef = 2**256 - 1;
Currency storage currency;
for (uint256 i = 0; i < bondIds.length; i++) {
uint256 bondId = bondIds[i];
// check if we authorized this bond previously?
if (lastAuthorizedBond != bondId) {
require( // expensive check. Reads 2 slots!!
_isAuthorizedToReleaseCollateral(bondId, msg.sender),
"CollateralManager: unauthorized to release collateral"
);
lastAuthorizedBond = bondId;
}
uint256 collateralId = collateralIds[i];
Collateral storage c = collateral[bondId][collateralId];
// check if we read this Currency previously?
if (lastCurrencyRef != c.currencyRef) {
currency = currencies[c.currencyRef]; // expensive 1 slot read
lastCurrencyRef = c.currencyRef;
}
_transferGenericCurrency(currency, address(this), to, c.amountOrId, "");
emit CollateralReleased(bondId, collateralId, to);
}
}
As a quick explanation of the structure: this is similar to a batch erc1155 transfer, except I'm storing a lot of data related to the transaction in some slots under the Currency and Collateral and Bond objects. Since the reads can get intensive, I want to optimize gas by caching reads. Since having an actual cache map is also expensive, I instead optimize by caching only the previous list item, and rely on the user to sort the array in such a way that results in the smallest gas costs.
The lastAuthorizedBond variable caches which bondId was last authorized -- if it repeats, we can cut out an expensive 2-slot read! (which results in maybe 16% gas savings during tests. You can see, significant). I tried doing something similar with the currency read, storing the lastCurrencyRef and hoping to store the actual result of the read into the currency variable. The compiler complains about this however, and maybe justly so.
Is there a way to pass this by the compiler? Do I just have to ditch this optimization? Though nobody is allowed to register the 2**256-1 currency or bond, is this code even safe?
Note that the collateral entry gets deleted after this runs -- cannot double release.

Solidity how to get random number with ratio

I want to create my own NFT according to ERC1155 standard.
My hero has 6 parts, each part has 4 types as shown in the picture.
Now I want to create a function that takes a random number with the ratio shown in the image.
Here is simple function return random number. With _mod = 10^n it will return number of length n-1.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract RandomNumbers{
function random(uint _mod) public view returns(uint){
return uint(keccak256(abi.encodePacked(block.timestamp,block.difficulty,
msg.sender))) % _mod;
}
}
I've been struggling with this for a whole day.
Thanks for help.
Just so you know. You shouldn't use keccak256(abi.encodePacked(block.timestamp,block.difficulty,msg.sender)) to generate a random number because that actually creates a pseudo-random guessable number. Take a look at Chainlink VRF.
For the ratio you could try to check out this Data structure (GitHub): you manually set values for the leaves and then when you have your random number you can call the draw function to set the different stats.

Low Level Events in Solidity and log3 - uint to byte32

I have a question regarding low level events in solidity I can't really wrap my head around.
So in theory an event that looks like this:
event MyEvent(address indexed oneAddress, bool isTrueOrNot, uint256 myUnsingedNumber);
inside a function I would use it like that for example:
MyEvent(msg.sender, true, 5);
But now going to low-level events with log2 (log_i = i+1 parameters = 3). How would that be used there? I've tried around a bit but couldn't come up with the right solution...
log2(??, sha3("MyEvent(address,bool,uint256)"), msg.sender, ??)
In the samples in the Docs its quite straight forward, but I have real trouble putting that into this example here.
Here's the link to the docs: http://solidity.readthedocs.io/en/develop/contracts.html#events
Especially together with indexed, and uint256 to byte32 conversion, as all the parameters must be in byte32. Hope I haven't overlooked something...
Thanks!
I think the usage is log1( value, 'log_topic'); and then log2(value, 'log-topic1', 'log-topic2')
So if msg.sender is the value analyzed put it first in both cases.