Git Product home page Git Product logo

unorderedkeyset's Introduction

See https://github.com/rob-Hitchens/SetTypes for newer experimental version.

Hitchens Unordered Key Set

https://github.com/rob-Hitchens/UnorderedKeySet

Solidity Library that implements the Solidity CRUD pattern.

Use this library to implement Create, Retrieve, Update and Delete operations in data sets in Solidity contracts.

Supports logical delete

While it is true that blockchain data is immutable, there are frequently cases when a logical delete from a set is required. For example, a set of subscribers where the subscribers are transient.

While several patterns exist (e.g. set a bool active = false) such structures frequently lead to the need to iterate over data and this leads to gas cost increases with scale which is unacceptable in many cases. See Getting Loopy with Solidity. The Solidity CRUD pattern is a general-purpose CRUD solution:

  • Create
  • Retrieve
  • Update
  • Delete

plus

  • Count
  • Iterate
  • Verify existence

Scale Invariant

The operations in this pattern produce consistent gas cost at any scale.

Example Implementation

A data set with an arbitrary layout can be implemented in clean, unrepetitive code. Example, to play around in Remix:

pragma solidity 0.5.1;

import "./HitchensUnorderedKeySet.sol";

contract Widget {
    
    using HitchensUnorderedKeySetLib for HitchensUnorderedKeySetLib.Set;
    HitchensUnorderedKeySetLib.Set widgetSet;
    
    struct WidgetStruct {
        string name;
        bool delux;
        uint price;
    }
    
    mapping(bytes32 => WidgetStruct) widgets;
    
    event LogNewWidget(address sender, bytes32 key, string name, bool delux, uint price);
    event LogUpdateWidget(address sender, bytes32 key, string name, bool delux, uint price);    
    event LogRemWidget(address sender, bytes32 key);
    
    function newWidget(bytes32 key, string memory name, bool delux, uint price) public {
        widgetSet.insert(key); // Note that this will fail automatically if the key already exists.
        WidgetStruct storage w = widgets[key];
        w.name = name;
        w.delux = delux;
        w.price = price;
        emit LogNewWidget(msg.sender, key, name, delux, price);
    }
    
    function updateWidget(bytes32 key, string memory name, bool delux, uint price) public {
        require(widgetSet.exists(key), "Can't update a widget that doesn't exist.");
        WidgetStruct storage w = widgets[key];
        w.name = name;
        w.delux = delux;
        w.price = price;
        emit LogUpdateWidget(msg.sender, key, name, delux, price);
    }
    
    function remWidget(bytes32 key) public {
        widgetSet.remove(key); // Note that this will fail automatically if the key doesn't exist
        delete widgets[key];
        emit LogRemWidget(msg.sender, key);
    }
    
    function getWidget(bytes32 key) public view returns(string memory name, bool delux, uint price) {
        require(widgetSet.exists(key), "Can't get a widget that doesn't exist.");
        WidgetStruct storage w = widgets[key];
        return(w.name, w.delux, w.price);
    }
    
    function getWidgetCount() public view returns(uint count) {
        return widgetSet.count();
    }
    
    function getWidgetAtIndex(uint index) public view returns(bytes32 key) {
        return widgetSet.keyAtIndex(index);
    }
}

A production dapp would probably have access control for the state-changing functions. This is deliberately set aside for brevity and to show that the library is unopinionated about how that should work. For example, add onlyOwner modifiers to newWidget(), updateWidget() and remWidget() functions if appropriate.

Motivation

The Solidity CRUD pattern is a reliable way of managing arbitrary data sets with transient members. However, contracts that implement multiple or nested sets tend to become cognitively heavy for developers and reviewers.

Nesting sets can be important in cases such as Enforcing Referential Integrity.

This library separates key rules enforcement concerns from the layout of the data the application is concerned with. The result is smaller, simpler contracts that are easy to reason about.

Example (for illustration, does not run):

using HitchensUnorderedKeySetLib for HitchensUnorderedKeySetLib.Set;
HitchensUnorderedKeySetLib.Set masterKeySet;

struct MasterThing {
  uint something;
  uint somethingElse;
  HitchensUnorderedKeySet.Set whereUsedSet;
}

mapping(bytes32 => MasterThing) masterThings;

function deleteMasterRecord(bytes32 key) public ... {
  require(masterThings[key].whereUsed.count() == 0);
  masterKeySet.remove(key);
  delete masterThings[key];
}

In the spirit of bumpers and guard rails, the remove() method requires that the key to be removed actually exists. Similarly, duplicate key inserts are prevented.

Deployment

Load the example and the dependencies in Remix and enjoy.

Two variants:

  • ...KeySet.sol uses bytes32 keys.
  • ...AddressSet.sol uses addresses.

Tests

NO TESTING OF ANY KIND HAS BEEN PERFORMED AND YOU USE THIS LIBRARY AT YOUR OWN EXCLUSIVE RISK.

Contributors

Optimization and clean-up is ongoing.

The author welcomes pull requests, feature requests, testing assistance and feedback. Contact the author if you would like assistance with customization or calibrating the code for a specific application or gathering of different statistics. License

License

Copyright (c), 2019 Rob Hitchens. The MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Hope it helps.

unorderedkeyset's People

Contributors

paulrberg avatar rob-hitchens avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

unorderedkeyset's Issues

Change nukeSet() from public to internal

I'm using Truffle V5.1.13 and in my contracts pragma solidity ^0.5.1;
Having nukeSet be public causes truffle tests to fail with the following error message

    "before all" hook: prepare suite: TypeError: Cannot read property 'typeClass' of undefined

Changing nukeSet() to be internal allows tests to go through

Add Integer Keys?

=First off, great library!

I wanted to ask, do you think it's possible to add integers as keys an option? I like the addresses and bytes32 but I have a use case where Integers seem like a better key option.

Expound on what "logical deletes" mean

This library doesn't remove the elements of a mapping from storage, it only clears the key of that mapping from its associated index array.

I understand why absolute deletes are not feasible in Solidity, yet it might be worth it to tell the user about this limitation and why this library performs deletion the way it does.

Iteration example

This is not an issue, but more of a request. The README states that you can use the library for Iteration, but it's not clear from the examples how I would write a function to iterate over a set to perform an operation on each member of the set. Could this be added to the Widget example?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.