This is not a unique approach but something I personally used when I had to shave off a few kilobytes off the contract size and also reduce the gas usage. In my use-case, I needed multiple sorting to decide certain winners, rankings, price distributions and such.
Now, I don't have access to a backend code to try this on when writing this, maybe I could update this later with some scaffold-eth, but this is how I would possible implement this.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Array {
uint[] public arr;
uint[] public arrSorted;
address payable public _admin;
constructor()
{
_admin = payable(msg.sender);
}
event sort(uint[]);
function sortOffChain() public returns (uint[] memory)
{
emit sort(arr);
return arrSorted;
}
function getSortedData(uint[] memory arrData) public
{
require(msg.sender == _admin);
arrSorted = arrData;
}
}
On the backend, the algorithm would look something like this -
- event listener listening for
sort()
- calls
bubbleSort()
[Or whatever suits you] upon getting triggered - calls
getSortedData()
function with returned value ofbubbleSort()
This of course shouldn't be used everywhere, but it is a quick and easy way of sorting data.
Top comments (1)
what would the backend code look like for this? I'm still new to dapps and programming, so I'm having trouble grasping how on-chain and off-chain would come together without an explicit example.