DEV Community

abhinav the builder
abhinav the builder

Posted on


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;

        _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.

Top comments (1)

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.

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<