Skip to content

Instantly share code, notes, and snippets.

@cwhinfrey
Created March 22, 2019 03:55
Show Gist options
  • Save cwhinfrey/438d40160c447d92981e1dd65f395d16 to your computer and use it in GitHub Desktop.
Save cwhinfrey/438d40160c447d92981e1dd65f395d16 to your computer and use it in GitHub Desktop.
LibraryEncapsulation.sol
pragma solidity ^0.5.5;
// Libs
library FooLib {
struct Foo {
uint a;
uint b;
uint c;
}
function addToFoos(Foo storage foo, uint amount) public {
foo.a += amount;
foo.b += amount;
foo.c += amount;
}
function sumFoos(Foo storage foo) public view returns (uint) {
return foo.a + foo.b + foo.c;
}
}
library BarLib {
struct Bar {
uint d;
uint e;
}
function doSomeStateChange(Bar storage bar, uint amount) public {
bar.d = bar.e + amount;
}
}
// Wrappers
contract FooWrapper {
using FooLib for FooLib.Foo;
FooLib.Foo private foo;
/**
* Public interface of Foo wrapper
* Outside of this contract, only these functions can change foo's state
*/
function addToFoos(uint amount) public {
foo.addToFoos(amount);
}
/**
* Foo getters
*/
function getA() public view returns (uint) {
return foo.a;
}
function getB() public view returns (uint) {
return foo.b;
}
function getC() public view returns (uint) {
return foo.c;
}
}
contract BarWrapper {
BarLib.Bar private bar;
function getD() public view returns (uint) {
return bar.d;
}
function getE() public view returns (uint) {
return bar.e;
}
}
// Main Contract
// The main contract has state that is one Foo struct and on Bar struct.
// All state changes to Foo state must happen through the FooWrapper interface
// All state changes to Bar state must happen through the BarWrapper interface
contract MainContract is FooWrapper, BarWrapper {
function addDToAllFoos() public {
// gets D from BarWrapper
uint d = getD();
// sets values in Foo through the Foo wrapper interface
addToFoos(d);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment