Is there a good way to index a lot of data in a smart contract to be able to read it efficiently? - ethereum

I am writing a solidity smart contract in which users would be able add a string (eg. one line joke), and other users should be able to vote on these jokes. If there are for example a million jokes in the contract (all with a different vote count), Would it be possible to rank these jokes by vote count? Eg. display the highest voted 10 of the million jokes? I know it is possible on a small scale, but on a larger scale I'm not so sure.

A variant of the contract that implements the main functionality you need is attached below:
registration of "jokes" records
registration of voting without repeats
definition of the top 10 (I hope I was not mistaken in the sorting algorithm).
The hash from its text is used as the identifier of the "joke".
However, in order to provide users with quality functionality, you need an external application that will monitor the events JokeCreated and JokeVoted of this contract and maintain an external database of "jokes" records.
This is because Ethereum contracts are ineffective for iterative operations with large arrays and you need an external service to:
providing users with a common list of "jokes"
providing users with a general rating list of "jokes"
When using an external application, you can also exclude the function of determining the top 10 from the contract (in function VotesForJoke), which will significantly reduce the cost of the voting transaction.
In addition, you need to keep in mind the problem of identifying users to avoid re-voting, since in general it cannot be solved at the level of Ethereum itself.
pragma solidity ^0.5.8;
contract Jokes
{
struct Joke
{
string text ;
address sender ;
bytes32 author ;
uint256 votes ;
mapping (bytes32=>bool) voters ;
}
mapping (bytes32 => Joke) JokesList ;
bytes32[10] Top10 ;
event JokeCreated(bytes32 hash, string text, address sender, bytes32 author) ;
event JokeVoted (bytes32 hash, bytes32 voter) ;
constructor() public
{
}
function NewJoke(string memory text_, bytes32 author_) public
{
bytes32 hash ;
hash=keccak256(abi.encodePacked(text_)) ;
if(JokesList[hash].author!=0x00) require(false) ;
JokesList[hash] =Joke({ text: text_,
sender: tx.origin,
author: author_,
votes: 0 }) ;
emit JokeCreated(hash, text_, tx.origin, author_) ;
}
function VotesForJoke(bytes32 hash_, bytes32 voter_) public
{
uint256 votes ;
uint256 i ;
// Check for existance
if(JokesList[hash_].author==0x00) require(false) ;
// Check for re-voting
if(JokesList[hash_].voters[voter_]==true) require(false) ;
JokesList[hash_].voters[voter_]=true ;
JokesList[hash_].votes++ ;
// Ordering top 10
votes=JokesList[hash_].votes ;
for(i=9 ; i>=0 ; i--)
if(votes>=JokesList[Top10[i]].votes)
{
if(i!=9 && Top10[i]!=hash_) Top10[i+1]=Top10[i] ;
}
else
{
break ;
}
if(i!=9) Top10[i+1]=hash_ ;
// Emit event of voting
emit JokeVoted(hash_, voter_) ;
}
function GetJoke(bytes32 hash_) public view returns (string memory, address, bytes32,uint256 retVal)
{
return(JokesList[hash_].text, JokesList[hash_].sender, JokesList[hash_].author, JokesList[hash_].votes) ;
}
function GetTop10() public view returns (bytes32[10] memory retVal)
{
return(Top10) ;
}
}

Related

Uniswap v2 swap() function. What are balance0 & balance1?

I'm learning how the Uniswapv2 contracts work but I can't seem to wrap my mind around the swap() function.
Reference: https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L173
Lines 173-174 contain:
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
My question is, when & whose balances are these?
A. These are the same as _reserve0 & _reserve1 after the most recent swap and will be used to synchronize reserves.
B. These are the quantities of each token the user making the swap currently possesses.
C. None of the above. It's something else. Please explain the flow of this function. I cannot find a clear and concise definition anywhere.
answer is "C" :)
balanceOf is a mapping in ERC20 implementation to return the amount that given address holds:
// address => holds uint amount
mapping(address => uint) public balanceOf;
Since current contract is inheriting from UniswapV2ERC20:
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20{}
it can access to UniswapV2ERC20.sol
Since the mapping balanceOf is public, solidity assigns getters to the public variables
In the functions:
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
address(this) refers to the current contract which is UniswapV2Pair. So balance0 is how much the current contract owns _token0 and balance1 is how much the current contract address owns _token1. token0 and token1 are contract addresses and each ERC20 token contract, keeps track of addresses and their balances. so you are visiting each token contract and getting how much balance the current contract has.
Think ERC20 contract like a bank. you have token0 bank and token1 bank. Each bank keeps track of the balances of their users. balancesOf is where ERC20 tokens store those balances. Your current contract also owns some of those tokens so you just want to get how much tokens the current contract holds
swap function will be called by the user. Before executing the swap, contract checks if it has enough funds
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');

The transaction has been reverted to the initial state. The called function should be payable if you send value

the Error being specified is
revert
The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.
Debug the transaction to get more information.
//SPDX-License-Identifier:MIT
pragma solidity 0.8.8;
contract Giftcard{
event UniqueCardId(uint indexed Id,address indexed owner);
//Enter The Giftcard amount
//Pay the gift card by making multiple transations
//require(giftcard owner should approve the withdrawl )
address[] Giftcardowners;
mapping(address => uint) amountUploaded;
function Addamount() external payable{
require(msg.value >= 1 ether,"Gift card amount to small");
amountUploaded[msg.sender] = msg.value;
Giftcardowners.push(msg.sender);
emit UniqueCardId(Giftcardowners.length-1,msg.sender);
}
function GetGiftcard(uint _cardId) payable external {
require(Giftcardowners.length > _cardId,"Id doesnot exits");
address owner = Giftcardowners[_cardId-1];
uint amount = amountUploaded[owner];
require(amount >= 1 ether,"transfered is less than 1 ether");
// (bool successs,) = payable(msg.sender).call{value:amount}("");
//require(successs,"transaction reverted");
payable(msg.sender).transfer(1 ether);
}
function getBalance() external view returns(uint balance){
return address(this).balance;
}
}
Firstly I called the Addamount function by paying more than 1 ether to the smart contract
now after that when the GetGiftcard function is called the transaction is reverted. I am unable to find a solution
unable to understand the concept
Error is here
address owner = Giftcardowners[_cardId-1];
should be
address owner = Giftcardowners[_cardId];
When you call addAmount, this line executes
Giftcardowners.push(msg.sender);
in the Giftcardowners array you have only 1 item
Giftcardowners=[0x7EF2e0048f5bAeDe046f6BF797943daF4ED8CB47]
when you call the GetGiftcard, you need to pass _cardId=0, you are actually assigning the index of the array as the id. when you pass 0, index will be -1 here
address owner = Giftcardowners[_cardId-1];
You cannot pass 1 to get 1-1=0, because you have this condition
require(Giftcardowners.length > _cardId,"Id doesnot exits");

In what slots are variables stored that are defined after an array in Solidity?

So I know how arrays are stored in storage. If I understand it correctly it first stores the number of items in an array in the first slot, and then in the next slots, it stores the hashed values.
My question is what if I define uint after the array and the array during deployment has only 2 values. So it should take up 3 slots. Then in the fourth slot is the uint I defined.
What if there is a function that will push something to the array? How is it stored?
Will it be stored in the next free slot? Or will it push the uint to the next slot and replace it with the new value?
I hope the question is clear if not I will try to rephrase it.
Also if there is some good resource where I can learn all about storage in solidity please share the link.
Thanks a lot!
Fixed-size array stores its values in sequential order, starting with the 0th index. There's no prepended slot that would show the total length. Any unset values use the default value of 0.
pragma solidity ^0.8;
contract MyContract {
address[3] addresses; // storage slots 0, 1, 2
uint256 number; // storage slot 3
constructor(address[2] memory _addresses, uint256 _number) {
addresses = _addresses;
number = _number;
}
}
Passing 2 addresses to the constructor, storage slot values in this case:
0: _addresses[0]
1: _addresses[1]
2: default value of zero (third address was not defined)
3: _number
Dynamic-size array stores its values in keys that are hash of the property storage slot (in example below that's 0, as that's the first storage property), and immediately following slots. In the property storage slot, it stores the array length.
pragma solidity ^0.8;
contract MyContract {
/*
* storage slots:
* p (in this case value 0, as this is the first storage property) = length of the array
* keccak256(p) = value of index 0
* keccak256(p) + 1 = value of index 1
* etc.
*/
address[] addresses;
// storage slot 1
uint256 number;
constructor(address[] memory _addresses, uint256 _number) {
addresses = _addresses;
number = _number;
}
}
Passing 2 addresses to the constructor, storage slot values in this case:
0: value 2 (length of the array)
1: _number
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563 (hash of uint 0): _addresses[0]
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e564 (hash of uint 0, plus 1): _addresses[1]
Docs: https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_storage.html#mappings-and-dynamic-arrays
So to answer your questions:
What if there is a function that will push something to the array? How is it stored?
Will it be stored in the next free slot? Or will it push the uint to the next slot and replace it with the new value?
Fixed-size arrays cannot be resized. You can only rewrite its values, while the default value of each item is 0.
In case of dynamic-size arrays, it pushes the new value right after the last one. Since they are stored in slots which indexes are based on a hash, the probability of rewriting another value is practically 0 (i.e. that would mean a hash collision).
In both cases, it doesn't affect how other storage properties are stored.

How does makeLog instruction function works in Ethereum virtual machine

The following code snippet is a constituent piece of the instructions.go file in geth.
// make log instruction function
func makeLog(size int) executionFunc {
return func(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) {
if interpreter.readOnly {
return nil, ErrWriteProtection
}
topics := make([]common.Hash, size)
stack := scope.Stack
mStart, mSize := stack.pop(), stack.pop()
for i := 0; i < size; i++ {
addr := stack.pop()
topics[i] = addr.Bytes32()
}
d := scope.Memory.GetCopy(int64(mStart.Uint64()), int64(mSize.Uint64()))
interpreter.evm.StateDB.AddLog(&types.Log{
Address: scope.Contract.Address(),
Topics: topics,
Data: d,
// This is a non-consensus field, but assigned here because
// core/state doesn't know the current block number.
BlockNumber: interpreter.evm.Context.BlockNumber.Uint64(),
})
return nil, nil
}
}
The question is, how does log0 ,log1,Log2 etc opcode works and what is their use in Ethereum virtual machine?
The LOG<n> opcodes are used for emitting event logs.
The <n> value depends on the number of indexed and non-indexed topics of the event. Since the <n> value is limited (currently at 4), there's also a limit of max indexed topics per each event definition (currently 3, so it's possible to process unindexed topics of the same event as well).
Example in Solidity:
event MyEmptyEvent();
event MyEvent(bool indexed, bool indexed, bool, bool);
function foo() external {
// Produces the `LOG0` opcode as there are no topics
emit MyEmptyEvent();
// Produces the `LOG3` opcode
// as the 2 indexed topics are stored separately
// but the unindexed topics are stored as 1 topic with concatenated value
emit MyEvent(true, true, true, true);
}
After a transaction is included in a mined block, the produced event logs are broadcasted along with other state changes (e.g. storage values and address balances).
There's a great article describing the details in more depth.

Solidity setting a mapping to empty

I am trying to create a smart contract using Solidity 0.4.4.
I was wondering if there is a way to set a mapping with some values already entered to an empty one?
For example:
This initailises a new mappping
mapping (uint => uint) map;
Here I add some values
map[0] = 1;
map[1] = 2;
How can I set the map back to empty without iterating through all the keys?
I have tried delete but my contract does not compile
Unfortunately, you can't. See the Solidity documentation for details on the reasons why. Your only option is to iterate through the keys.
If you don't know your set of keys ahead of time, you'll have to keep the keys in a separate array inside your contract.
I believe there is another way to handle this problem.
If you define your mapping with a second key, you can increment that key to essentially reset your mapping.
For example, if you wanted to your mapping to reset every year, you could define it like this:
uint256 private _year = 2021;
mapping(uint256 => mapping(address => uint256)) private _yearlyBalances;
Adding and retrieving values works just like normal, with an extra key:
_yearlyBalances[_year][0x9101910191019101919] = 1;
_yearlyBalances[_year][0x8101810181018101818] = 2;
When it's time to reset everything, you just call
_year += 1