DEV Community

abhinav the builder
abhinav the builder

Posted on

3 2

Off-chain Sorting over on-chain Sorting in Solidity

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

On the backend, the algorithm would look something like this -

  1. event listener listening for sort()
  2. calls bubbleSort() [Or whatever suits you] upon getting triggered
  3. calls getSortedData() function with returned value of bubbleSort()

This of course shouldn't be used everywhere, but it is a quick and easy way of sorting data.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (1)

Collapse
 
tacticaltuna123 profile image
TacticalTuna123 • Edited

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.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay