diff --git a/.gitignore b/.gitignore
index 36e6113..7e2a55a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,7 @@
.DS_Store
-
-node_modules
\ No newline at end of file
+cache/
+node_modules
+dist/
+out/
+coverage/
+*.log
diff --git a/.prettierrc.js b/.prettierrc.js
new file mode 100644
index 0000000..03a335e
--- /dev/null
+++ b/.prettierrc.js
@@ -0,0 +1,28 @@
+/**
+ * @file Prettier configuration for Conformance
+ * @version 1.1.0
+ * @summary base config adapted from AirBNB to maximize performance
+ * @schema http://json.schemastore.org/prettierrc
+ */
+
+'use strict';
+
+module.exports = {
+ arrowParens: 'always',
+ bracketSameLine: true,
+ bracketSpacing: false,
+ embeddedLanguageFormatting: 'auto',
+ htmlWhitespaceSensitivity: 'strict',
+ insertPragma: false,
+ jsxSingleQuote: false,
+ printWidth: 110,
+ proseWrap: 'always',
+ quoteProps: 'consistent',
+ requirePragma: false,
+ semi: true,
+ singleQuote: true,
+ tabWidth: 2,
+ trailingComma: 'all',
+ useTabs: false,
+ vueIndentScriptAndStyle: false
+};
\ No newline at end of file
diff --git a/contracts/correct_large_integers.sol b/contracts/correct_large_integers.sol
new file mode 100644
index 0000000..deead35
--- /dev/null
+++ b/contracts/correct_large_integers.sol
@@ -0,0 +1,6 @@
+function _getSwapAmount(uint256 userIn, uint256 reserveIn) internal pure returns (uint256) {
+ return
+ (Babylonian.sqrt(reserveIn * (userIn * 3_988_000 + reserveIn * 3_988_009)) -
+ reserveIn *
+ 1_997) / 1_994;
+ }
\ No newline at end of file
diff --git a/contracts/fail-constructor.sol b/contracts/fail-constructor.sol
new file mode 100644
index 0000000..f82cf0d
--- /dev/null
+++ b/contracts/fail-constructor.sol
@@ -0,0 +1,10 @@
+contract A is B, C, D {
+ uint x;
+
+ constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
+ B(param1)
+ C(param2, param3)
+ D(param4) {
+ x = param5;
+ }
+}
\ No newline at end of file
diff --git a/contracts/fail-function-order.sol b/contracts/fail-function-order.sol
new file mode 100644
index 0000000..3004748
--- /dev/null
+++ b/contracts/fail-function-order.sol
@@ -0,0 +1,7 @@
+function balance(uint256 from) public override view returns (uint256) {
+ return balanceOf[from];
+}
+
+function shutdown() onlyOwner public {
+ selfdestruct(owner);
+}
\ No newline at end of file
diff --git a/contracts/fail-whitespace.sol b/contracts/fail-whitespace.sol
new file mode 100644
index 0000000..cb3971f
--- /dev/null
+++ b/contracts/fail-whitespace.sol
@@ -0,0 +1,7 @@
+receive () external payable {
+//
+}
+
+fallback () external {
+//
+}
\ No newline at end of file
diff --git a/contracts/fmt_large_int.sol b/contracts/fmt_large_int.sol
new file mode 100644
index 0000000..585af59
--- /dev/null
+++ b/contracts/fmt_large_int.sol
@@ -0,0 +1,13 @@
+function _getSwapAmount(uint256 userIn, uint256 reserveIn)
+ internal
+ pure
+ returns (uint256)
+{
+ return
+ (
+ Babylonian.sqrt(reserveIn * (userIn * 3988000 + reserveIn * 3988009))
+ - reserveIn
+ * 1997
+ )
+ / 1994;
+}
diff --git a/contracts/no_control_statement.yul b/contracts/no_control_statement.yul
new file mode 100644
index 0000000..de50535
--- /dev/null
+++ b/contracts/no_control_statement.yul
@@ -0,0 +1,55 @@
+object "test"
+{
+ code
+ {
+
+ // This assumes each limb is 256-bit and the half of the second limb is not dirty.
+ function add_with_carry_384_orig(x1, x2, y1, y2) - > out1, out2, carry
+ {
+ // limb 1
+ out1: = add(x1, y1)
+ carry: = lt(out1, x1)
+
+ // limb 2
+ x2: = add(x2, carry)
+ carry: = lt(x2, carry)
+ out2: = add(x2, y2)
+ carry: = or(carry, lt(out2, x2))
+ }
+
+ // This assumes each limb is 256-bit and the half of the second limb is not dirty.
+ function add_with_carry_384(x1, x2, y1, y2) - > out1, out2, carry
+ {
+ // limb 1
+ out1: = add(x1, y1)
+ let carry1: = lt(out1, x1)
+
+ // limb 2
+ let t: = add(x2, y2)
+ let carry2: = lt(t, x2)
+
+ out2: = add(t, carry1)
+ carry: = lt(out2, t)
+
+ carry: = or(carry2, carry)
+ }
+
+ let x1: = calldataload(0)
+ let x2: = calldataload(32)
+ let y1: = calldataload(64)
+ let y2: = calldataload(96)
+
+ let a: = 0
+ let b: = 0
+ let c: = 0
+ a, b, c: = add_with_carry_384_orig(x1, x2, y1, y2)
+
+ mstore(0, a)
+ mstore(32, b)
+ mstore(64, c)
+
+ // orig: 600035604035810181811080602035019250606035830182600052806020528381108285101760405250505050
+ // new: 6000356020356040358201606035820183821081018260005280602052818110848310176040525050505050
+
+ }
+}
diff --git a/contracts/pass-constructor.sol b/contracts/pass-constructor.sol
new file mode 100644
index 0000000..aede647
--- /dev/null
+++ b/contracts/pass-constructor.sol
@@ -0,0 +1,12 @@
+contract A is B, C, D {
+ uint x;
+
+ constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
+ B(param1)
+ C(param2, param3)
+ D(param4)
+ {
+ // do something with param5
+ x = param5;
+ }
+}
\ No newline at end of file
diff --git a/contracts/pass-function-order.sol b/contracts/pass-function-order.sol
new file mode 100644
index 0000000..e82e5be
--- /dev/null
+++ b/contracts/pass-function-order.sol
@@ -0,0 +1,7 @@
+function balance(uint256 from) public view override returns (uint256) {
+ return balanceOf[from];
+}
+
+function shutdown() public onlyOwner {
+ selfdestruct(owner);
+}
\ No newline at end of file
diff --git a/contracts/pass-whitespace.sol b/contracts/pass-whitespace.sol
new file mode 100644
index 0000000..0ac73d6
--- /dev/null
+++ b/contracts/pass-whitespace.sol
@@ -0,0 +1,7 @@
+receive() external payable {
+//
+}
+
+fallback() external {
+//
+}
\ No newline at end of file
diff --git a/contracts/wrong_large_integers.sol b/contracts/wrong_large_integers.sol
new file mode 100644
index 0000000..0f10de5
--- /dev/null
+++ b/contracts/wrong_large_integers.sol
@@ -0,0 +1,6 @@
+ function _getSwapAmount(uint256 userIn, uint256 reserveIn) internal pure returns (uint256) {
+ return
+ (Babylonian.sqrt(reserveIn * (userIn * 3988000 + reserveIn * 3988009)) -
+ reserveIn *
+ 1997) / 1994;
+}
\ No newline at end of file
diff --git a/contracts/yes_control_statement_braces.yul b/contracts/yes_control_statement_braces.yul
new file mode 100644
index 0000000..2797232
--- /dev/null
+++ b/contracts/yes_control_statement_braces.yul
@@ -0,0 +1,51 @@
+object "test" {
+ code {
+
+ // This assumes each limb is 256-bit and the half of the second limb is not dirty.
+ function add_with_carry_384_orig(x1, x2, y1, y2) - > out1, out2, carry {
+ // limb 1
+ out1: = add(x1, y1)
+ carry: = lt(out1, x1)
+
+ // limb 2
+ x2: = add(x2, carry)
+ carry: = lt(x2, carry)
+ out2: = add(x2, y2)
+ carry: = or(carry, lt(out2, x2))
+ }
+
+ // This assumes each limb is 256-bit and the half of the second limb is not dirty.
+ function add_with_carry_384(x1, x2, y1, y2) - > out1, out2, carry {
+ // limb 1
+ out1: = add(x1, y1)
+ let carry1: = lt(out1, x1)
+
+ // limb 2
+ let t: = add(x2, y2)
+ let carry2: = lt(t, x2)
+
+ out2: = add(t, carry1)
+ carry: = lt(out2, t)
+
+ carry: = or(carry2, carry)
+ }
+
+ let x1: = calldataload(0)
+ let x2: = calldataload(32)
+ let y1: = calldataload(64)
+ let y2: = calldataload(96)
+
+ let a: = 0
+ let b: = 0
+ let c: = 0
+ a, b, c: = add_with_carry_384_orig(x1, x2, y1, y2)
+
+ mstore(0, a)
+ mstore(32, b)
+ mstore(64, c)
+
+ // orig: 600035604035810181811080602035019250606035830182600052806020528381108285101760405250505050
+ // new: 6000356020356040358201606035820183821081018260005280602052818110848310176040525050505050
+
+ }
+}
diff --git a/contracts/yes_obj_fmt.yul b/contracts/yes_obj_fmt.yul
new file mode 100644
index 0000000..de50535
--- /dev/null
+++ b/contracts/yes_obj_fmt.yul
@@ -0,0 +1,55 @@
+object "test"
+{
+ code
+ {
+
+ // This assumes each limb is 256-bit and the half of the second limb is not dirty.
+ function add_with_carry_384_orig(x1, x2, y1, y2) - > out1, out2, carry
+ {
+ // limb 1
+ out1: = add(x1, y1)
+ carry: = lt(out1, x1)
+
+ // limb 2
+ x2: = add(x2, carry)
+ carry: = lt(x2, carry)
+ out2: = add(x2, y2)
+ carry: = or(carry, lt(out2, x2))
+ }
+
+ // This assumes each limb is 256-bit and the half of the second limb is not dirty.
+ function add_with_carry_384(x1, x2, y1, y2) - > out1, out2, carry
+ {
+ // limb 1
+ out1: = add(x1, y1)
+ let carry1: = lt(out1, x1)
+
+ // limb 2
+ let t: = add(x2, y2)
+ let carry2: = lt(t, x2)
+
+ out2: = add(t, carry1)
+ carry: = lt(out2, t)
+
+ carry: = or(carry2, carry)
+ }
+
+ let x1: = calldataload(0)
+ let x2: = calldataload(32)
+ let y1: = calldataload(64)
+ let y2: = calldataload(96)
+
+ let a: = 0
+ let b: = 0
+ let c: = 0
+ a, b, c: = add_with_carry_384_orig(x1, x2, y1, y2)
+
+ mstore(0, a)
+ mstore(32, b)
+ mstore(64, c)
+
+ // orig: 600035604035810181811080602035019250606035830182600052806020528381108285101760405250505050
+ // new: 6000356020356040358201606035820183821081018260005280602052818110848310176040525050505050
+
+ }
+}
diff --git a/contracts/yes_own_line_braces.yul b/contracts/yes_own_line_braces.yul
new file mode 100644
index 0000000..2797232
--- /dev/null
+++ b/contracts/yes_own_line_braces.yul
@@ -0,0 +1,51 @@
+object "test" {
+ code {
+
+ // This assumes each limb is 256-bit and the half of the second limb is not dirty.
+ function add_with_carry_384_orig(x1, x2, y1, y2) - > out1, out2, carry {
+ // limb 1
+ out1: = add(x1, y1)
+ carry: = lt(out1, x1)
+
+ // limb 2
+ x2: = add(x2, carry)
+ carry: = lt(x2, carry)
+ out2: = add(x2, y2)
+ carry: = or(carry, lt(out2, x2))
+ }
+
+ // This assumes each limb is 256-bit and the half of the second limb is not dirty.
+ function add_with_carry_384(x1, x2, y1, y2) - > out1, out2, carry {
+ // limb 1
+ out1: = add(x1, y1)
+ let carry1: = lt(out1, x1)
+
+ // limb 2
+ let t: = add(x2, y2)
+ let carry2: = lt(t, x2)
+
+ out2: = add(t, carry1)
+ carry: = lt(out2, t)
+
+ carry: = or(carry2, carry)
+ }
+
+ let x1: = calldataload(0)
+ let x2: = calldataload(32)
+ let y1: = calldataload(64)
+ let y2: = calldataload(96)
+
+ let a: = 0
+ let b: = 0
+ let c: = 0
+ a, b, c: = add_with_carry_384_orig(x1, x2, y1, y2)
+
+ mstore(0, a)
+ mstore(32, b)
+ mstore(64, c)
+
+ // orig: 600035604035810181811080602035019250606035830182600052806020528381108285101760405250505050
+ // new: 6000356020356040358201606035820183821081018260005280602052818110848310176040525050505050
+
+ }
+}
diff --git a/contracts/yul_erc20_cannonical.yul b/contracts/yul_erc20_cannonical.yul
new file mode 100644
index 0000000..cbc04b5
--- /dev/null
+++ b/contracts/yul_erc20_cannonical.yul
@@ -0,0 +1,186 @@
+object "Token" {
+ code {
+ // Store the creator in slot zero.
+ sstore(0, caller())
+
+ // Deploy the contract
+ datacopy(0, dataoffset("runtime"), datasize("runtime"))
+ return(0, datasize("runtime"))
+ }
+ object "runtime" {
+ code {
+ // Protection against sending Ether
+ require(iszero(callvalue()))
+
+ // Dispatcher
+ switch selector()
+ case 0x70a08231 /* "balanceOf(address)" */ {
+ returnUint(balanceOf(decodeAsAddress(0)))
+ }
+ case 0x18160ddd /* "totalSupply()" */ {
+ returnUint(totalSupply())
+ }
+ case 0xa9059cbb /* "transfer(address,uint256)" */ {
+ transfer(decodeAsAddress(0), decodeAsUint(1))
+ returnTrue()
+ }
+ case 0x23b872dd /* "transferFrom(address,address,uint256)" */ {
+ transferFrom(decodeAsAddress(0), decodeAsAddress(1), decodeAsUint(2))
+ returnTrue()
+ }
+ case 0x095ea7b3 /* "approve(address,uint256)" */ {
+ approve(decodeAsAddress(0), decodeAsUint(1))
+ returnTrue()
+ }
+ case 0xdd62ed3e /* "allowance(address,address)" */ {
+ returnUint(allowance(decodeAsAddress(0), decodeAsAddress(1)))
+ }
+ case 0x40c10f19 /* "mint(address,uint256)" */ {
+ mint(decodeAsAddress(0), decodeAsUint(1))
+ returnTrue()
+ }
+ default {
+ revert(0, 0)
+ }
+
+ function mint(account, amount) {
+ require(calledByOwner())
+
+ mintTokens(amount)
+ addToBalance(account, amount)
+ emitTransfer(0, account, amount)
+ }
+ function transfer(to, amount) {
+ executeTransfer(caller(), to, amount)
+ }
+ function approve(spender, amount) {
+ revertIfZeroAddress(spender)
+ setAllowance(caller(), spender, amount)
+ emitApproval(caller(), spender, amount)
+ }
+ function transferFrom(from, to, amount) {
+ decreaseAllowanceBy(from, caller(), amount)
+ executeTransfer(from, to, amount)
+ }
+
+ function executeTransfer(from, to, amount) {
+ revertIfZeroAddress(to)
+ deductFromBalance(from, amount)
+ addToBalance(to, amount)
+ emitTransfer(from, to, amount)
+ }
+
+
+ /* ---------- calldata decoding functions ----------- */
+ function selector() -> s {
+ s := div(calldataload(0), 0x100000000000000000000000000000000000000000000000000000000)
+ }
+
+ function decodeAsAddress(offset) -> v {
+ v := decodeAsUint(offset)
+ if iszero(iszero(and(v, not(0xffffffffffffffffffffffffffffffffffffffff)))) {
+ revert(0, 0)
+ }
+ }
+ function decodeAsUint(offset) -> v {
+ let pos := add(4, mul(offset, 0x20))
+ if lt(calldatasize(), add(pos, 0x20)) {
+ revert(0, 0)
+ }
+ v := calldataload(pos)
+ }
+ /* ---------- calldata encoding functions ---------- */
+ function returnUint(v) {
+ mstore(0, v)
+ return(0, 0x20)
+ }
+ function returnTrue() {
+ returnUint(1)
+ }
+
+ /* -------- events ---------- */
+ function emitTransfer(from, to, amount) {
+ let signatureHash := 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
+ emitEvent(signatureHash, from, to, amount)
+ }
+ function emitApproval(from, spender, amount) {
+ let signatureHash := 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925
+ emitEvent(signatureHash, from, spender, amount)
+ }
+ function emitEvent(signatureHash, indexed1, indexed2, nonIndexed) {
+ mstore(0, nonIndexed)
+ log3(0, 0x20, signatureHash, indexed1, indexed2)
+ }
+
+ /* -------- storage layout ---------- */
+ function ownerPos() -> p { p := 0 }
+ function totalSupplyPos() -> p { p := 1 }
+ function accountToStorageOffset(account) -> offset {
+ offset := add(0x1000, account)
+ }
+ function allowanceStorageOffset(account, spender) -> offset {
+ offset := accountToStorageOffset(account)
+ mstore(0, offset)
+ mstore(0x20, spender)
+ offset := keccak256(0, 0x40)
+ }
+
+ /* -------- storage access ---------- */
+ function owner() -> o {
+ o := sload(ownerPos())
+ }
+ function totalSupply() -> supply {
+ supply := sload(totalSupplyPos())
+ }
+ function mintTokens(amount) {
+ sstore(totalSupplyPos(), safeAdd(totalSupply(), amount))
+ }
+ function balanceOf(account) -> bal {
+ bal := sload(accountToStorageOffset(account))
+ }
+ function addToBalance(account, amount) {
+ let offset := accountToStorageOffset(account)
+ sstore(offset, safeAdd(sload(offset), amount))
+ }
+ function deductFromBalance(account, amount) {
+ let offset := accountToStorageOffset(account)
+ let bal := sload(offset)
+ require(lte(amount, bal))
+ sstore(offset, sub(bal, amount))
+ }
+ function allowance(account, spender) -> amount {
+ amount := sload(allowanceStorageOffset(account, spender))
+ }
+ function setAllowance(account, spender, amount) {
+ sstore(allowanceStorageOffset(account, spender), amount)
+ }
+ function decreaseAllowanceBy(account, spender, amount) {
+ let offset := allowanceStorageOffset(account, spender)
+ let currentAllowance := sload(offset)
+ require(lte(amount, currentAllowance))
+ sstore(offset, sub(currentAllowance, amount))
+ }
+
+ /* ---------- utility functions ---------- */
+ function lte(a, b) -> r {
+ r := iszero(gt(a, b))
+ }
+ function gte(a, b) -> r {
+ r := iszero(lt(a, b))
+ }
+ function safeAdd(a, b) -> r {
+ r := add(a, b)
+ if or(lt(r, a), lt(r, b)) { revert(0, 0) }
+ }
+ function calledByOwner() -> cbo {
+ cbo := eq(owner(), caller())
+ }
+ function revertIfZeroAddress(addr) {
+ require(addr)
+ }
+ function require(condition) {
+ if iszero(condition) { revert(0, 0) }
+ }
+ }
+ }
+}
diff --git a/examples/param.diff b/examples/param.diff
new file mode 100644
index 0000000..9628503
--- /dev/null
+++ b/examples/param.diff
@@ -0,0 +1,10 @@
+5,7c5,9
+< B(param1)
+< C(param2, param3)
+< D(param4) {
+---
+> B(param1)
+> C(param2, param3)
+> D(param4)
+> {
+> // do something with param5
diff --git a/examples/param.patch b/examples/param.patch
new file mode 100644
index 0000000..9628503
--- /dev/null
+++ b/examples/param.patch
@@ -0,0 +1,10 @@
+5,7c5,9
+< B(param1)
+< C(param2, param3)
+< D(param4) {
+---
+> B(param1)
+> C(param2, param3)
+> D(param4)
+> {
+> // do something with param5
diff --git a/foundry.toml b/foundry.toml
new file mode 100644
index 0000000..d19c22b
--- /dev/null
+++ b/foundry.toml
@@ -0,0 +1,52 @@
+[default]
+allow_paths = []
+auto_detect_solc = true
+block_base_fee_per_gas = 0
+block_coinbase = '0x0000000000000000000000000000000000000000'
+block_difficulty = 0
+block_number = 1
+block_timestamp = 1
+broadcast = 'broadcast'
+build_info = false
+bytecode_hash = 'ipfs'
+cache = true
+cache_path = 'cache'
+evm_version = 'london'
+extra_output = []
+extra_output_files = []
+ffi = false
+force = false
+fuzz_max_global_rejects = 65536
+fuzz_max_local_rejects = 1024
+fuzz_runs = 256
+gas_limit = 9223372036854775807
+gas_reports = ['*']
+ignored_error_codes = [
+ 1878,
+ 5574,
+]
+initial_balance = '0xffffffffffffffffffffffff'
+libraries = []
+libs = ['node_modules']
+memory_limit = 33554432
+names = false
+no_storage_caching = false
+offline = false
+optimizer = true
+optimizer_runs = 200
+out = 'out'
+remappings = []
+script = 'script'
+sender = '0x00a329c0648769a73afac7f9381e08fb43dbea72'
+sizes = false
+sparse_mode = false
+src = 'src'
+test = 'test'
+tx_origin = '0x00a329c0648769a73afac7f9381e08fb43dbea72'
+verbosity = 0
+via_ir = false
+
+[default.rpc_storage_caching]
+chains = 'all'
+endpoints = 'all'
+
diff --git a/js/behavior.js b/js/behavior.js
new file mode 100644
index 0000000..7daf4dc
--- /dev/null
+++ b/js/behavior.js
@@ -0,0 +1,342 @@
+let $ = jQuery;
+
+/*
+ * ## Convert List of Files to File Tree
+ * @param {Array} list Files in flat list
+ * @return {Object} Files in tree (by folders)
+ *
+ * @example
+ * ```javascript
+ * Schema(list) == [{
+ * path: String,
+ * originalName: String,
+ * originalPath: String,
+ * name: String,
+ * lang: String,
+ * toc: [Headline]
+ * }]
+ * ```
+ */
+let listToTree = function(list) {
+ let tree = {};
+
+ for (let file of Array.from(list)) {
+ let path = file.path.split('/');
+ let fileDepth = path.length - 1;
+ let cur = tree;
+
+ for (let depth = 0; depth < path.length; depth++) {
+ let part = path[depth];
+ if (((cur[part] != null ? cur[part].type : undefined) !== 'file') && (depth === (fileDepth-1)) && file.originalName.match(/index\.(js|coffee)/)) {
+ if (!cur[part]) { cur[part] = {}; }
+ cur[part].path = file.path;
+ cur[part].originalName = file.originalName;
+ cur[part].originalPath = file.originalPath;
+ cur[part].name = file.name;
+ cur[part].title = part;
+ cur[part].type = 'file';
+ if (!cur[part].children) { cur[part].children = {}; }
+ break;
+ }
+ if (depth === fileDepth) {
+ cur[part] = file;
+ cur[part].type = 'file';
+ } else {
+ if (!cur[part]) { cur[part] = {name: part, type: 'folder'}; }
+ cur = cur[part].children || (cur[part].children = {});
+ }
+ }
+ }
+
+ return tree;
+};
+
+/*
+ * ## Convert TOC to Headline Tree
+ * @param {Array} toc List of Headlines
+ * @return {Array} Tree of Headlines
+ *
+ * @example
+ * ```javascript
+ * Schema(toc) == [{
+ * level: Number,
+ * title: String,
+ * slug: String,
+ * }]
+ * ```
+ */
+let tocToTree = function(toc) {
+ let headlines = [];
+ let last = {};
+
+ for (let headline of Array.from(toc)) {
+ let level = headline.level || (headline.level = 1);
+ if (last[level - 1]) {
+ var name;
+ if (!last[name = level - 1].children) { last[name].children = []; }
+ last[level - 1].children.push(headline);
+ } else {
+ headlines.push(headline);
+ }
+ last[level] = headline;
+ }
+
+ return headlines;
+};
+
+
+/*
+ * ## Build File Tree Recursively
+ * @param {Array} tree List of file or folder Objects
+ * @param {jQuery} ul DOM node of list to append this tree to
+ * @param {Object} metaInfo Project information
+ * @return {jQuery} The ul element
+ */
+var buildFileTree = function(tree, ul, metaInfo) {
+ let $ul = $(ul);
+ if (tree == null) {
+ console.warn('No File Tree!');
+ return $ul;
+ }
+
+ $.each(tree, function(fileName, node) {
+ let position;
+ let $node = $(`
`);
+ if (node.type === 'file') {
+ let currentFile = node === metaInfo.currentFile;
+ $node.append(`${node.title || node.originalName || node.name}`);
+ } else { // folder
+ $node.append(`${node.name}`);
+ }
+
+ if (node.children != null) {
+ let $children = $('');
+ $node.append(buildFileTree(node.children, $children, metaInfo));
+ }
+
+ if ((node.originalName != null ? node.originalName.match(/^readme\.(md|txt|rst)/i) : undefined)) {
+ position = 'prepend';
+ } else {
+ position = 'append';
+ }
+ $ul[position]($node);
+ });
+
+ return $ul;
+};
+
+
+/*
+ * ## Build Headlines Tree Recursively
+ * @param {Object} tree Tree of headlines
+ * @param {jQuery} ul DOM node of list to append this tree to
+ * @param {Object} metaInfo Project information
+ * @return {jQuery} The ul element
+ */
+var buildHeadlinesTree = function(tree, ul, metaInfo) {
+ ul = $(ul);
+ if (!(tree != null ? tree.length : undefined)) {
+ return ul;
+ }
+
+ $.each(tree, function(index, node) {
+ let $node = $("
");
+ $node.append(`${node.title}`);
+
+ if ((node.children != null ? node.children.length : undefined) > 0) {
+ let $children = $('');
+ $node.append(buildHeadlinesTree(node.children, $children, metaInfo));
+ }
+
+ ul.append($node);
+ });
+
+ return ul;
+};
+
+/*
+ * ## Create Navigation Element
+ * @param {Object} metaInfo Project information
+ * @return {jQuery} Navigation element
+ */
+let createNav = function(metaInfo) {
+ let $nav = $(`\
+\
+`
+ );
+
+ return $nav;
+};
+
+/*
+ * ## Add Button to Toggle Side Menu Visibility
+ * @param {jQuery} $container The element the button should be prepended to
+ * @param {jQuery} $nav The navigation element; class 'open' will be toggled
+ * @return {jQuery} $container element
+ */
+let createMenuToggle = function($container, $nav) {
+ let $button = $(``
+ );
+
+ $button.on('click', function(event) {
+ event.preventDefault();
+ return $nav.toggleClass('open');
+ });
+
+ // $('#file-area').on 'click', (event) ->
+ // return if $(event.target).hasClass('toggle-menu')
+ // if $nav.hasClass('open')
+ // event.preventDefault()
+ // $nav.removeClass('open')
+ // return
+
+ $container.prepend($button);
+
+ return $container;
+};
+
+/*
+ * ## Search Tree
+ * @param {jQuery} $tree The tree element to be searched
+ * @param {jQuery} $search The search input field
+ */
+let searchTree = function($tree, $search) {
+ /*
+ @method throttle
+ @param {Function} fn Callback
+ @param {Number} timeout
+ */
+ let throttle = (function() {
+ ({timer: null});
+ return function(fn, timeout=100) {
+ let timer;
+ if (timer) { window.clearTimeout(timer); }
+ return timer = window.setTimeout((function() {
+ timer = null;
+ return (typeof fn === 'function' ? fn() : undefined);
+ }), timeout);
+ };
+ })();
+
+ /*
+ * @method search
+ * @param {jQuery} tree
+ * @param {String} value Search query
+ */
+ let search = function($tree, value) {
+ value = value.trim().toLowerCase();
+ $tree.find('.matched').removeClass('matched');
+
+ if (value === "") {
+ console.log('stop searching');
+ $tree.removeClass('searching');
+ return;
+ }
+
+ $tree.addClass('searching');
+ return $tree.find('a').each(function(index, item) {
+ let $item = $(item);
+ if (($item.text().toLowerCase().indexOf(value) > -1) || ($item.attr('href').toLowerCase().indexOf(value) > -1)) {
+ $item.addClass('matched');
+ // show folders above matched item
+ $item.parents('li').children('.label').addClass('matched');
+ }
+ });
+ };
+
+ let value = null;
+ $search.on('keyup search', function(event) {
+ let newVal = event.target.value;
+ if (newVal === value) { return; }
+ if ((newVal < 2) && (newVal !== "")) { return; }
+ value = newVal;
+ throttle(() => search($tree, value));
+ });
+
+ // ESC
+ return $search.on('keydown', function(event) {
+ if (event.keyCode === 27) { // Esc
+ if ($search.val().trim() === '') {
+ return $search.blur();
+ } else {
+ return $search.val('');
+ }
+ }
+ });
+};
+
+/*
+ * ## Build Navigation
+ * @param {Array} files List of Files
+ * @param {Object} metaInfo Project information
+ * @return {jQuery} The nav element
+ */
+let buildNav = function(files, metaInfo) {
+ if (!files) { return $(''); }
+ let $nav = createNav(metaInfo);
+
+ // Find current file
+ for (let file of Array.from(files)) {
+ if (file.originalPath === metaInfo.documentPath) {
+ metaInfo.currentFile = file;
+ break;
+ }
+ }
+
+ // Build file tree
+ let fileTree = listToTree(files);
+ buildFileTree(fileTree, $nav.find('#file-tree'), metaInfo);
+ searchTree($nav.find('#file-tree'), $nav.find('#search-files'));
+
+ // Build headlines tree
+ if (metaInfo.currentFile) {
+ let headlineTree = tocToTree(metaInfo.currentFile.toc || []);
+
+ buildHeadlinesTree(headlineTree, $nav.find('#headline-tree'), metaInfo);
+ searchTree($nav.find('#headline-tree'), $nav.find('#search-headlines'));
+ }
+
+ return $nav;
+};
+
+$(function() {
+ let metaInfo = {
+ relativeRoot: $('meta[name="groc-relative-root"]').attr('content'),
+ githubURL: $('meta[name="groc-github-url"]').attr('content'),
+ documentPath: $('meta[name="groc-document-path"]').attr('content'),
+ projectPath: $('meta[name="groc-project-path"]').attr('content')
+ };
+
+ let $nav = buildNav(window.files, metaInfo);
+ $nav.prependTo($('body'));
+
+ createMenuToggle($('#meta'), $nav);
+
+ window.listToTree = listToTree;
+ return window.tocToTree = tocToTree;
+});
diff --git a/output2 b/output2
new file mode 100644
index 0000000..6fb7336
--- /dev/null
+++ b/output2
@@ -0,0 +1,547 @@
+::: index
+style, coding style
+:::
+
+# Style Guide
+
+## Introduction
+
+This guide is intended to provide coding conventions for writing
+Solidity code. This guide should be thought of as an evolving document
+that will change over time as useful conventions are found and old
+conventions are rendered obsolete.
+
+Many projects will implement their own style guides. In the event of
+conflicts, project specific style guides take precedence.
+
+The structure and many of the recommendations within this style guide
+were taken from python\'s [pep8 style
+guide](https://www.python.org/dev/peps/pep-0008/).
+
+The goal of this guide is *not* to be the right way or the best way to
+write Solidity code. The goal of this guide is *consistency*. A quote
+from python\'s
+[pep8](https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds)
+captures this concept well.
+
+::: note
+::: title
+Note
+:::
+
+A style guide is about consistency. Consistency with this style guide is
+important. Consistency within a project is more important. Consistency
+within one module or function is most important.
+
+But most importantly: **know when to be inconsistent** \-- sometimes the
+style guide just doesn\'t apply. When in doubt, use your best judgment.
+Look at other examples and decide what looks best. And don\'t hesitate
+to ask!
+:::
+
+## Code Layout
+
+### Indentation
+
+Use 4 spaces per indentation level.
+
+### Tabs or Spaces
+
+Spaces are the preferred indentation method.
+
+Mixing tabs and spaces should be avoided.
+
+### Blank Lines
+
+Surround top level declarations in Solidity source with two blank lines.
+
+Yes:
+
+
+No:
+
+
+Within a contract surround function declarations with a single blank
+line.
+
+Blank lines may be omitted between groups of related one-liners (such as
+stub functions for an abstract contract)
+
+Yes:
+
+
+No:
+
+
+### Maximum Line Length {#maximum_line_length}
+
+Maximum suggested line length is 120 characters.
+
+Wrapped lines should conform to the following guidelines.
+
+1. The first argument should not be attached to the opening
+ parenthesis.
+2. One, and only one, indent should be used.
+3. Each argument should fall on its own line.
+4. The terminating element, , should be placed on the final line by
+ itself.
+
+Function Calls
+
+Yes:
+
+
+No:
+
+
+Assignment Statements
+
+Yes:
+
+
+No:
+
+
+Event Definitions and Event Emitters
+
+Yes:
+
+
+No:
+
+
+### Source File Encoding
+
+UTF-8 or ASCII encoding is preferred.
+
+### Imports
+
+Import statements should always be placed at the top of the file.
+
+Yes:
+
+
+No:
+
+
+### Order of Functions
+
+Ordering helps readers identify which functions they can call and to
+find the constructor and fallback definitions easier.
+
+Functions should be grouped according to their visibility and ordered:
+
+- constructor
+- receive function (if exists)
+- fallback function (if exists)
+- external
+- public
+- internal
+- private
+
+Within a grouping, place the and functions last.
+
+Yes:
+
+
+No:
+
+
+### Whitespace in Expressions
+
+Avoid extraneous whitespace in the following situations:
+
+Immediately inside parenthesis, brackets or braces, with the exception
+of single line function declarations.
+
+Yes:
+
+
+No:
+
+
+Exception:
+
+
+Immediately before a comma, semicolon:
+
+Yes:
+
+
+No:
+
+
+More than one space around an assignment or other operator to align with
+another:
+
+Yes:
+
+
+No:
+
+
+Don\'t include a whitespace in the receive and fallback functions:
+
+Yes:
+
+
+No:
+
+
+### Control Structures
+
+The braces denoting the body of a contract, library, functions and
+structs should:
+
+- open on the same line as the declaration
+- close on their own line at the same indentation level as the
+ beginning of the declaration.
+- The opening brace should be preceded by a single space.
+
+Yes:
+
+
+No:
+
+
+The same recommendations apply to the control structures , ,
+, and .
+
+Additionally there should be a single space between the control
+structures , , and and the parenthetic block
+representing the conditional, as well as a single space between the
+conditional parenthetic block and the opening brace.
+
+Yes:
+
+
+No:
+
+
+For control structures whose body contains a single statement, omitting
+the braces is ok *if* the statement is contained on a single line.
+
+Yes:
+
+
+No:
+
+
+For blocks which have an or clause, the
+should be placed on the same line as the \'s closing brace. This is
+an exception compared to the rules of other block-like structures.
+
+Yes:
+
+
+No:
+
+
+### Function Declaration
+
+For short function declarations, it is recommended for the opening brace
+of the function body to be kept on the same line as the function
+declaration.
+
+The closing brace should be at the same indentation level as the
+function declaration.
+
+The opening brace should be preceded by a single space.
+
+Yes:
+
+
+No:
+
+
+The modifier order for a function should be:
+
+1. Visibility
+2. Mutability
+3. Virtual
+4. Override
+5. Custom modifiers
+
+Yes:
+
+
+No:
+
+
+For long function declarations, it is recommended to drop each argument
+onto its own line at the same indentation level as the function body.
+The closing parenthesis and opening bracket should be placed on their
+own line as well at the same indentation level as the function
+declaration.
+
+Yes:
+
+
+No:
+
+
+If a long function declaration has modifiers, then each modifier should
+be dropped to its own line.
+
+Yes:
+
+
+No:
+
+
+Multiline output parameters and return statements should follow the same
+style recommended for wrapping long lines found in the
+{.interpreted-text
+role="ref"} section.
+
+Yes:
+
+
+No:
+
+
+For constructor functions on inherited contracts whose bases require
+arguments, it is recommended to drop the base constructors onto new
+lines in the same manner as modifiers if the function declaration is
+long or hard to read.
+
+Yes:
+
+
+No:
+
+
+When declaring short functions with a single statement, it is
+permissible to do it on a single line.
+
+Permissible:
+
+
+These guidelines for function declarations are intended to improve
+readability. Authors should use their best judgment as this guide does
+not try to cover all possible permutations for function declarations.
+
+### Mappings
+
+In variable declarations, do not separate the keyword from its
+type by a space. Do not separate any nested keyword from its
+type by whitespace.
+
+Yes:
+
+
+No:
+
+
+### Variable Declarations
+
+Declarations of array variables should not have a space between the type
+and the brackets.
+
+Yes:
+
+
+No:
+
+
+### Other Recommendations
+
+- Strings should be quoted with double-quotes instead of
+ single-quotes.
+
+Yes:
+
+
+No:
+
+
+- Surround operators with a single space on either side.
+
+Yes:
+
+
+No:
+
+
+- Operators with a higher priority than others can exclude surrounding
+ whitespace in order to denote precedence. This is meant to allow for
+ improved readability for complex statements. You should always use
+ the same amount of whitespace on either side of an operator:
+
+Yes:
+
+
+No:
+
+
+## Order of Layout
+
+Layout contract elements in the following order:
+
+1. Pragma statements
+2. Import statements
+3. Interfaces
+4. Libraries
+5. Contracts
+
+Inside each contract, library or interface, use the following order:
+
+1. Type declarations
+2. State variables
+3. Events
+4. Modifiers
+5. Functions
+
+::: note
+::: title
+Note
+:::
+
+It might be clearer to declare types close to their use in events or
+state variables.
+:::
+
+## Naming Conventions
+
+Naming conventions are powerful when adopted and used broadly. The use
+of different conventions can convey significant *meta* information that
+would otherwise not be immediately available.
+
+The naming recommendations given here are intended to improve the
+readability, and thus they are not rules, but rather guidelines to try
+and help convey the most information through the names of things.
+
+Lastly, consistency within a codebase should always supersede any
+conventions outlined in this document.
+
+### Naming Styles
+
+To avoid confusion, the following names will be used to refer to
+different naming styles.
+
+- (single lowercase letter)
+- (single uppercase letter)
+-
+-
+-
+- (or CapWords)
+- (differs from CapitalizedWords by initial lowercase
+ character!)
+
+::: note
+::: title
+Note
+:::
+
+When using initialisms in CapWords, capitalize all the letters of the
+initialisms. Thus HTTPServerError is better than HttpServerError. When
+using initialisms in mixedCase, capitalize all the letters of the
+initialisms, except keep the first one lower case if it is the beginning
+of the name. Thus xmlHTTPRequest is better than XMLHTTPRequest.
+:::
+
+### Names to Avoid
+
+- - Lowercase letter el
+- - Uppercase letter oh
+- - Uppercase letter eye
+
+Never use any of these for single letter variable names. They are often
+indistinguishable from the numerals one and zero.
+
+### Contract and Library Names
+
+- Contracts and libraries should be named using the CapWords style.
+ Examples: , , ,
+ , , .
+- Contract and library names should also match their filenames.
+- If a contract file includes multiple contracts and/or libraries,
+ then the filename should match the *core contract*. This is not
+ recommended however if it can be avoided.
+
+As shown in the example below, if the contract name is and
+the library name is , then their associated filenames should be
+ and .
+
+Yes:
+
+
+and in :
+
+
+No:
+
+
+and in :
+
+
+### Struct Names
+
+Structs should be named using the CapWords style. Examples: ,
+, .
+
+### Event Names
+
+Events should be named using the CapWords style. Examples: ,
+, , , .
+
+### Function Names
+
+Functions should use mixedCase. Examples: , ,
+, , .
+
+### Function Argument Names
+
+Function arguments should use mixedCase. Examples: ,
+, , , .
+
+When writing library functions that operate on a custom struct, the
+struct should be the first argument and should always be named .
+
+### Local and State Variable Names
+
+Use mixedCase. Examples: , , ,
+, , .
+
+### Constants
+
+Constants should be named with all capital letters with underscores
+separating words. Examples: , , ,
+.
+
+### Modifier Names
+
+Use mixedCase. Examples: , , .
+
+### Enums
+
+Enums, in the style of simple type declarations, should be named using
+the CapWords style. Examples: , , ,
+.
+
+### Avoiding Naming Collisions
+
+-
+
+This convention is suggested when the desired name collides with that of
+an existing state variable, function, built-in or otherwise reserved
+name.
+
+## NatSpec {#style_guide_natspec}
+
+Solidity contracts can also contain NatSpec comments. They are written
+with a triple slash () or a double asterisk block ()
+and they should be used directly above function declarations or
+statements.
+
+For example, the contract from
+{.interpreted-text
+role="ref"} with the comments added looks like the one below:
+
+
+It is recommended that Solidity contracts are fully annotated using
+{.interpreted-text role="ref"} for all public
+interfaces (everything in the ABI).
+
+Please see the section about {.interpreted-text
+role="ref"} for a detailed explanation.
diff --git a/src/Protobuf.sol b/src/Protobuf.sol
new file mode 100644
index 0000000..2a15ed9
--- /dev/null
+++ b/src/Protobuf.sol
@@ -0,0 +1,852 @@
+// SPDX-License-Identifier: Apache-2.0
+pragma solidity >=0.8.4 <0.9.0;
+
+contract ProtobufLib {
+ /// @notice Protobuf wire types.
+ enum WireType {
+ Varint,
+ Bits64,
+ LengthDelimited,
+ StartGroup,
+ EndGroup,
+ Bits32,
+ WIRE_TYPE_MAX
+ }
+
+ /// @dev Maximum number of bytes for a varint.
+ /// @dev 64 bits, in groups of base-128 (7 bits).
+ uint64 internal constant MAX_VARINT_BYTES = 10;
+
+ ////////////////////////////////////
+ // Decoding
+ ////////////////////////////////////
+
+ /// @notice Decode key.
+ /// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Field number
+ /// @return Wire type
+ function decode_key(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64,
+ WireType
+ )
+ {
+ // The key is a varint with encoding
+ // (field_number << 3) | wire_type
+ (bool success, uint64 pos, uint64 key) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0, WireType.WIRE_TYPE_MAX);
+ }
+
+ uint64 field_number = key >> 3;
+ uint64 wire_type_val = key & 0x07;
+ // Check that wire type is bounded
+ if (wire_type_val >= uint64(WireType.WIRE_TYPE_MAX)) {
+ return (false, pos, 0, WireType.WIRE_TYPE_MAX);
+ }
+ WireType wire_type = WireType(wire_type_val);
+
+ // Start and end group types are deprecated, so forbid them
+ if (wire_type == WireType.StartGroup || wire_type == WireType.EndGroup) {
+ return (false, pos, 0, WireType.WIRE_TYPE_MAX);
+ }
+
+ return (true, pos, field_number, wire_type);
+ }
+
+ /// @notice Decode varint.
+ /// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_varint(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ uint64 val;
+ uint64 i;
+
+ for (i = 0; i < MAX_VARINT_BYTES; i++) {
+ // Check that index is within bounds
+ if (i + p >= buf.length) {
+ return (false, p, 0);
+ }
+
+ // Get byte at offset
+ uint8 b = uint8(buf[p + i]);
+
+ // Highest bit is used to indicate if there are more bytes to come
+ // Mask to get 7-bit value: 0111 1111
+ uint8 v = b & 0x7F;
+
+ // Groups of 7 bits are ordered least significant first
+ val |= uint64(v) << uint64(i * 7);
+
+ // Mask to get keep going bit: 1000 0000
+ if (b & 0x80 == 0) {
+ // [STRICT]
+ // Check for trailing zeroes if more than one byte is used
+ // (the value 0 still uses one byte)
+ if (i > 0 && v == 0) {
+ return (false, p, 0);
+ }
+
+ break;
+ }
+ }
+
+ // Check that at most MAX_VARINT_BYTES are used
+ if (i >= MAX_VARINT_BYTES) {
+ return (false, p, 0);
+ }
+
+ // [STRICT]
+ // If all 10 bytes are used, the last byte (most significant 7 bits)
+ // must be at most 0000 0001, since 7*9 = 63
+ if (i == MAX_VARINT_BYTES - 1) {
+ if (uint8(buf[p + i]) > 1) {
+ return (false, p, 0);
+ }
+ }
+
+ return (true, p + i + 1, val);
+ }
+
+ /// @notice Decode varint int32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_int32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // [STRICT]
+ // Highest 4 bytes must be 0 if positive
+ if (val >> 63 == 0) {
+ if (val & 0xFFFFFFFF00000000 != 0) {
+ return (false, pos, 0);
+ }
+ }
+
+ return (true, pos, int32(uint32(val)));
+ }
+
+ /// @notice Decode varint int64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_int64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, int64(val));
+ }
+
+ /// @notice Decode varint uint32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_uint32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint32
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // [STRICT]
+ // Highest 4 bytes must be 0
+ if (val & 0xFFFFFFFF00000000 != 0) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, uint32(val));
+ }
+
+ /// @notice Decode varint uint64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_uint64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, val);
+ }
+
+ /// @notice Decode varint sint32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_sint32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // [STRICT]
+ // Highest 4 bytes must be 0
+ if (val & 0xFFFFFFFF00000000 != 0) {
+ return (false, pos, 0);
+ }
+
+ // https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086
+ uint64 zigzag_val;
+ unchecked {
+ zigzag_val = (val >> 1) - (~(val & 1) + 1);
+ }
+
+ return (true, pos, int32(uint32(zigzag_val)));
+ }
+
+ /// @notice Decode varint sint64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_sint64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086
+ uint64 zigzag_val;
+ unchecked {
+ zigzag_val = (val >> 1) - (~(val & 1) + 1);
+ }
+
+ return (true, pos, int64(zigzag_val));
+ }
+
+ /// @notice Decode Boolean.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded bool
+ function decode_bool(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ bool
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, false);
+ }
+
+ // [STRICT]
+ // Value must be 0 or 1
+ if (val > 1) {
+ return (false, pos, false);
+ }
+
+ if (val == 0) {
+ return (true, pos, false);
+ }
+
+ return (true, pos, true);
+ }
+
+ /// @notice Decode enumeration.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded enum as raw int
+ function decode_enum(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ return decode_int32(p, buf);
+ }
+
+ /// @notice Decode fixed 64-bit int.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_bits64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ uint64 val;
+
+ // Check that index is within bounds
+ if (8 + p > buf.length) {
+ return (false, p, 0);
+ }
+
+ for (uint64 i = 0; i < 8; i++) {
+ uint8 b = uint8(buf[p + i]);
+
+ // Little endian
+ val |= uint64(b) << uint64(i * 8);
+ }
+
+ return (true, p + 8, val);
+ }
+
+ /// @notice Decode fixed uint64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_fixed64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_bits64(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, val);
+ }
+
+ /// @notice Decode fixed int64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_sfixed64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_bits64(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, int64(val));
+ }
+
+ /// @notice Decode fixed 32-bit int.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_bits32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint32
+ )
+ {
+ uint32 val;
+
+ // Check that index is within bounds
+ if (4 + p > buf.length) {
+ return (false, p, 0);
+ }
+
+ for (uint64 i = 0; i < 4; i++) {
+ uint8 b = uint8(buf[p + i]);
+
+ // Little endian
+ val |= uint32(b) << uint32(i * 8);
+ }
+
+ return (true, p + 4, val);
+ }
+
+ /// @notice Decode fixed uint32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_fixed32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint32
+ )
+ {
+ (bool success, uint64 pos, uint32 val) = decode_bits32(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, val);
+ }
+
+ /// @notice Decode fixed int32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_sfixed32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ (bool success, uint64 pos, uint32 val) = decode_bits32(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, int32(val));
+ }
+
+ /// @notice Decode length-delimited field.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position (after size)
+ /// @return Size in bytes
+ function decode_length_delimited(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ // Length-delimited fields begin with a varint of the number of bytes that follow
+ (bool success, uint64 pos, uint64 size) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // Check for overflow
+ unchecked {
+ if (pos + size < pos) {
+ return (false, pos, 0);
+ }
+ }
+
+ // Check that index is within bounds
+ if (size + pos > buf.length) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, size);
+ }
+
+ /// @notice Decode string.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Size in bytes
+ function decode_string(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ string memory
+ )
+ {
+ (bool success, uint64 pos, uint64 size) = decode_length_delimited(p, buf);
+ if (!success) {
+ return (false, pos, "");
+ }
+
+ bytes memory field = new bytes(size);
+ for (uint64 i = 0; i < size; i++) {
+ field[i] = buf[pos + i];
+ }
+
+ return (true, pos + size, string(field));
+ }
+
+ /// @notice Decode bytes array.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position (after size)
+ /// @return Size in bytes
+ function decode_bytes(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return decode_length_delimited(p, buf);
+ }
+
+ /// @notice Decode embedded message.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position (after size)
+ /// @return Size in bytes
+ function decode_embedded_message(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return decode_length_delimited(p, buf);
+ }
+
+ /// @notice Decode packed repeated field.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position (after size)
+ /// @return Size in bytes
+ function decode_packed_repeated(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return decode_length_delimited(p, buf);
+ }
+
+ ////////////////////////////////////
+ // Encoding
+ ////////////////////////////////////
+
+ /// @notice Encode key.
+ /// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure
+ /// @param field_number Field number
+ /// @param wire_type Wire type
+ /// @return Marshaled bytes
+ function encode_key(uint64 field_number, uint64 wire_type) internal pure returns (bytes memory) {
+ uint64 key = (field_number << 3) | wire_type;
+
+ bytes memory buf = encode_varint(key);
+
+ return buf;
+ }
+
+ /// @notice Encode varint.
+ /// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_varint(uint64 n) internal pure returns (bytes memory) {
+ // Count the number of groups of 7 bits
+ // We need this pre-processing step since Solidity doesn't allow dynamic memory resizing
+ uint64 tmp = n;
+ uint64 num_bytes = 1;
+ while (tmp > 0x7F) {
+ tmp = tmp >> 7;
+ num_bytes += 1;
+ }
+
+ bytes memory buf = new bytes(num_bytes);
+
+ tmp = n;
+ for (uint64 i = 0; i < num_bytes; i++) {
+ // Set the first bit in the byte for each group of 7 bits
+ buf[i] = bytes1(0x80 | uint8(tmp & 0x7F));
+ tmp = tmp >> 7;
+ }
+ // Unset the first bit of the last byte
+ buf[num_bytes - 1] &= 0x7F;
+
+ return buf;
+ }
+
+ /// @notice Encode varint int32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_int32(int32 n) internal pure returns (bytes memory) {
+ return encode_varint(uint64(int64(n)));
+ }
+
+ /// @notice Decode varint int64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_int64(int64 n) internal pure returns (bytes memory) {
+ return encode_varint(uint64(n));
+ }
+
+ /// @notice Encode varint uint32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_uint32(uint32 n) internal pure returns (bytes memory) {
+ return encode_varint(n);
+ }
+
+ /// @notice Encode varint uint64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_uint64(uint64 n) internal pure returns (bytes memory) {
+ return encode_varint(n);
+ }
+
+ /// @notice Encode varint sint32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_sint32(int32 n) internal pure returns (bytes memory) {
+ // https://developers.google.com/protocol-buffers/docs/encoding#signed_integers
+ uint32 mask = 0;
+ if (n < 0) {
+ unchecked {
+ mask -= 1;
+ }
+ }
+ uint32 zigzag_val = (uint32(n) << 1) ^ mask;
+
+ return encode_varint(zigzag_val);
+ }
+
+ /// @notice Encode varint sint64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_sint64(int64 n) internal pure returns (bytes memory) {
+ // https://developers.google.com/protocol-buffers/docs/encoding#signed_integers
+ uint64 mask = 0;
+ if (n < 0) {
+ unchecked {
+ mask -= 1;
+ }
+ }
+ uint64 zigzag_val = (uint64(n) << 1) ^ mask;
+
+ return encode_varint(zigzag_val);
+ }
+
+ /// @notice Encode Boolean.
+ /// @param b Boolean
+ /// @return Marshaled bytes
+ function encode_bool(bool b) internal pure returns (bytes memory) {
+ uint64 n = b ? 1 : 0;
+
+ return encode_varint(n);
+ }
+
+ /// @notice Encode enumeration.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_enum(int32 n) internal pure returns (bytes memory) {
+ return encode_int32(n);
+ }
+
+ /// @notice Encode fixed 64-bit int.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_bits64(uint64 n) internal pure returns (bytes memory) {
+ bytes memory buf = new bytes(8);
+
+ uint64 tmp = n;
+ for (uint64 i = 0; i < 8; i++) {
+ // Little endian
+ buf[i] = bytes1(uint8(tmp & 0xFF));
+ tmp = tmp >> 8;
+ }
+
+ return buf;
+ }
+
+ /// @notice Encode fixed uint64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_fixed64(uint64 n) internal pure returns (bytes memory) {
+ return encode_bits64(n);
+ }
+
+ /// @notice Encode fixed int64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_sfixed64(int64 n) internal pure returns (bytes memory) {
+ return encode_bits64(uint64(n));
+ }
+
+ /// @notice Decode fixed 32-bit int.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_bits32(uint32 n) internal pure returns (bytes memory) {
+ bytes memory buf = new bytes(4);
+
+ uint64 tmp = n;
+ for (uint64 i = 0; i < 4; i++) {
+ // Little endian
+ buf[i] = bytes1(uint8(tmp & 0xFF));
+ tmp = tmp >> 8;
+ }
+
+ return buf;
+ }
+
+ /// @notice Encode fixed uint32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_fixed32(uint32 n) internal pure returns (bytes memory) {
+ return encode_bits32(n);
+ }
+
+ /// @notice Encode fixed int32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_sfixed32(int32 n) internal pure returns (bytes memory) {
+ return encode_bits32(uint32(n));
+ }
+
+ /// @notice Encode length-delimited field.
+ /// @param b Bytes
+ /// @return Marshaled bytes
+ function encode_length_delimited(bytes memory b) internal pure returns (bytes memory) {
+ // Length-delimited fields begin with a varint of the number of bytes that follow
+ bytes memory length_buf = encode_uint64(uint64(b.length));
+ bytes memory buf = new bytes(b.length + length_buf.length);
+
+ for (uint64 i = 0; i < length_buf.length; i++) {
+ buf[i] = length_buf[i];
+ }
+
+ for (uint64 i = 0; i < b.length; i++) {
+ buf[i + length_buf.length] = b[i];
+ }
+
+ return buf;
+ }
+
+ /// @notice Encode string.
+ /// @param s String
+ /// @return Marshaled bytes
+ function encode_string(string memory s) internal pure returns (bytes memory) {
+ return encode_length_delimited(bytes(s));
+ }
+
+ /// @notice Encode bytes array.
+ /// @param b Bytes
+ /// @return Marshaled bytes
+ function encode_bytes(bytes memory b) internal pure returns (bytes memory) {
+ return encode_length_delimited(b);
+ }
+
+ /// @notice Encode embedded message.
+ /// @param m Message
+ /// @return Marshaled bytes
+ function encode_embedded_message(bytes memory m) internal pure returns (bytes memory) {
+ return encode_length_delimited(m);
+ }
+
+ /// @notice Encode packed repeated field.
+ /// @param b Bytes
+ /// @return Marshaled bytes
+ function encode_packed_repeated(bytes memory b) internal pure returns (bytes memory) {
+ return encode_length_delimited(b);
+ }
+}
\ No newline at end of file
diff --git a/src/ProtobufLib.sol b/src/ProtobufLib.sol
new file mode 100644
index 0000000..3e25cd1
--- /dev/null
+++ b/src/ProtobufLib.sol
@@ -0,0 +1,852 @@
+// SPDX-License-Identifier: Apache-2.0
+pragma solidity >=0.8.4 <0.9.0;
+
+library ProtobufLib {
+ /// @notice Protobuf wire types.
+ enum WireType {
+ Varint,
+ Bits64,
+ LengthDelimited,
+ StartGroup,
+ EndGroup,
+ Bits32,
+ WIRE_TYPE_MAX
+ }
+
+ /// @dev Maximum number of bytes for a varint.
+ /// @dev 64 bits, in groups of base-128 (7 bits).
+ uint64 internal constant MAX_VARINT_BYTES = 10;
+
+ ////////////////////////////////////
+ // Decoding
+ ////////////////////////////////////
+
+ /// @notice Decode key.
+ /// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Field number
+ /// @return Wire type
+ function decode_key(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64,
+ WireType
+ )
+ {
+ // The key is a varint with encoding
+ // (field_number << 3) | wire_type
+ (bool success, uint64 pos, uint64 key) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0, WireType.WIRE_TYPE_MAX);
+ }
+
+ uint64 field_number = key >> 3;
+ uint64 wire_type_val = key & 0x07;
+ // Check that wire type is bounded
+ if (wire_type_val >= uint64(WireType.WIRE_TYPE_MAX)) {
+ return (false, pos, 0, WireType.WIRE_TYPE_MAX);
+ }
+ WireType wire_type = WireType(wire_type_val);
+
+ // Start and end group types are deprecated, so forbid them
+ if (wire_type == WireType.StartGroup || wire_type == WireType.EndGroup) {
+ return (false, pos, 0, WireType.WIRE_TYPE_MAX);
+ }
+
+ return (true, pos, field_number, wire_type);
+ }
+
+ /// @notice Decode varint.
+ /// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_varint(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ uint64 val;
+ uint64 i;
+
+ for (i = 0; i < MAX_VARINT_BYTES; i++) {
+ // Check that index is within bounds
+ if (i + p >= buf.length) {
+ return (false, p, 0);
+ }
+
+ // Get byte at offset
+ uint8 b = uint8(buf[p + i]);
+
+ // Highest bit is used to indicate if there are more bytes to come
+ // Mask to get 7-bit value: 0111 1111
+ uint8 v = b & 0x7F;
+
+ // Groups of 7 bits are ordered least significant first
+ val |= uint64(v) << uint64(i * 7);
+
+ // Mask to get keep going bit: 1000 0000
+ if (b & 0x80 == 0) {
+ // [STRICT]
+ // Check for trailing zeroes if more than one byte is used
+ // (the value 0 still uses one byte)
+ if (i > 0 && v == 0) {
+ return (false, p, 0);
+ }
+
+ break;
+ }
+ }
+
+ // Check that at most MAX_VARINT_BYTES are used
+ if (i >= MAX_VARINT_BYTES) {
+ return (false, p, 0);
+ }
+
+ // [STRICT]
+ // If all 10 bytes are used, the last byte (most significant 7 bits)
+ // must be at most 0000 0001, since 7*9 = 63
+ if (i == MAX_VARINT_BYTES - 1) {
+ if (uint8(buf[p + i]) > 1) {
+ return (false, p, 0);
+ }
+ }
+
+ return (true, p + i + 1, val);
+ }
+
+ /// @notice Decode varint int32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_int32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // [STRICT]
+ // Highest 4 bytes must be 0 if positive
+ if (val >> 63 == 0) {
+ if (val & 0xFFFFFFFF00000000 != 0) {
+ return (false, pos, 0);
+ }
+ }
+
+ return (true, pos, int32(uint32(val)));
+ }
+
+ /// @notice Decode varint int64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_int64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, int64(val));
+ }
+
+ /// @notice Decode varint uint32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_uint32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint32
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // [STRICT]
+ // Highest 4 bytes must be 0
+ if (val & 0xFFFFFFFF00000000 != 0) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, uint32(val));
+ }
+
+ /// @notice Decode varint uint64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_uint64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, val);
+ }
+
+ /// @notice Decode varint sint32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_sint32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // [STRICT]
+ // Highest 4 bytes must be 0
+ if (val & 0xFFFFFFFF00000000 != 0) {
+ return (false, pos, 0);
+ }
+
+ // https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086
+ uint64 zigzag_val;
+ unchecked {
+ zigzag_val = (val >> 1) - (~(val & 1) + 1);
+ }
+
+ return (true, pos, int32(uint32(zigzag_val)));
+ }
+
+ /// @notice Decode varint sint64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_sint64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086
+ uint64 zigzag_val;
+ unchecked {
+ zigzag_val = (val >> 1) - (~(val & 1) + 1);
+ }
+
+ return (true, pos, int64(zigzag_val));
+ }
+
+ /// @notice Decode Boolean.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded bool
+ function decode_bool(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ bool
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, false);
+ }
+
+ // [STRICT]
+ // Value must be 0 or 1
+ if (val > 1) {
+ return (false, pos, false);
+ }
+
+ if (val == 0) {
+ return (true, pos, false);
+ }
+
+ return (true, pos, true);
+ }
+
+ /// @notice Decode enumeration.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded enum as raw int
+ function decode_enum(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ return decode_int32(p, buf);
+ }
+
+ /// @notice Decode fixed 64-bit int.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_bits64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ uint64 val;
+
+ // Check that index is within bounds
+ if (8 + p > buf.length) {
+ return (false, p, 0);
+ }
+
+ for (uint64 i = 0; i < 8; i++) {
+ uint8 b = uint8(buf[p + i]);
+
+ // Little endian
+ val |= uint64(b) << uint64(i * 8);
+ }
+
+ return (true, p + 8, val);
+ }
+
+ /// @notice Decode fixed uint64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_fixed64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_bits64(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, val);
+ }
+
+ /// @notice Decode fixed int64.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_sfixed64(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int64
+ )
+ {
+ (bool success, uint64 pos, uint64 val) = decode_bits64(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, int64(val));
+ }
+
+ /// @notice Decode fixed 32-bit int.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_bits32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint32
+ )
+ {
+ uint32 val;
+
+ // Check that index is within bounds
+ if (4 + p > buf.length) {
+ return (false, p, 0);
+ }
+
+ for (uint64 i = 0; i < 4; i++) {
+ uint8 b = uint8(buf[p + i]);
+
+ // Little endian
+ val |= uint32(b) << uint32(i * 8);
+ }
+
+ return (true, p + 4, val);
+ }
+
+ /// @notice Decode fixed uint32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_fixed32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint32
+ )
+ {
+ (bool success, uint64 pos, uint32 val) = decode_bits32(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, val);
+ }
+
+ /// @notice Decode fixed int32.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Decoded int
+ function decode_sfixed32(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ (bool success, uint64 pos, uint32 val) = decode_bits32(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, int32(val));
+ }
+
+ /// @notice Decode length-delimited field.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position (after size)
+ /// @return Size in bytes
+ function decode_length_delimited(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ // Length-delimited fields begin with a varint of the number of bytes that follow
+ (bool success, uint64 pos, uint64 size) = decode_varint(p, buf);
+ if (!success) {
+ return (false, pos, 0);
+ }
+
+ // Check for overflow
+ unchecked {
+ if (pos + size < pos) {
+ return (false, pos, 0);
+ }
+ }
+
+ // Check that index is within bounds
+ if (size + pos > buf.length) {
+ return (false, pos, 0);
+ }
+
+ return (true, pos, size);
+ }
+
+ /// @notice Decode string.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position
+ /// @return Size in bytes
+ function decode_string(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ string memory
+ )
+ {
+ (bool success, uint64 pos, uint64 size) = decode_length_delimited(p, buf);
+ if (!success) {
+ return (false, pos, "");
+ }
+
+ bytes memory field = new bytes(size);
+ for (uint64 i = 0; i < size; i++) {
+ field[i] = buf[pos + i];
+ }
+
+ return (true, pos + size, string(field));
+ }
+
+ /// @notice Decode bytes array.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position (after size)
+ /// @return Size in bytes
+ function decode_bytes(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return decode_length_delimited(p, buf);
+ }
+
+ /// @notice Decode embedded message.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position (after size)
+ /// @return Size in bytes
+ function decode_embedded_message(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return decode_length_delimited(p, buf);
+ }
+
+ /// @notice Decode packed repeated field.
+ /// @param p Position
+ /// @param buf Buffer
+ /// @return Success
+ /// @return New position (after size)
+ /// @return Size in bytes
+ function decode_packed_repeated(uint64 p, bytes memory buf)
+ internal
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return decode_length_delimited(p, buf);
+ }
+
+ ////////////////////////////////////
+ // Encoding
+ ////////////////////////////////////
+
+ /// @notice Encode key.
+ /// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure
+ /// @param field_number Field number
+ /// @param wire_type Wire type
+ /// @return Marshaled bytes
+ function encode_key(uint64 field_number, uint64 wire_type) internal pure returns (bytes memory) {
+ uint64 key = (field_number << 3) | wire_type;
+
+ bytes memory buf = encode_varint(key);
+
+ return buf;
+ }
+
+ /// @notice Encode varint.
+ /// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_varint(uint64 n) internal pure returns (bytes memory) {
+ // Count the number of groups of 7 bits
+ // We need this pre-processing step since Solidity doesn't allow dynamic memory resizing
+ uint64 tmp = n;
+ uint64 num_bytes = 1;
+ while (tmp > 0x7F) {
+ tmp = tmp >> 7;
+ num_bytes += 1;
+ }
+
+ bytes memory buf = new bytes(num_bytes);
+
+ tmp = n;
+ for (uint64 i = 0; i < num_bytes; i++) {
+ // Set the first bit in the byte for each group of 7 bits
+ buf[i] = bytes1(0x80 | uint8(tmp & 0x7F));
+ tmp = tmp >> 7;
+ }
+ // Unset the first bit of the last byte
+ buf[num_bytes - 1] &= 0x7F;
+
+ return buf;
+ }
+
+ /// @notice Encode varint int32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_int32(int32 n) internal pure returns (bytes memory) {
+ return encode_varint(uint64(int64(n)));
+ }
+
+ /// @notice Decode varint int64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_int64(int64 n) internal pure returns (bytes memory) {
+ return encode_varint(uint64(n));
+ }
+
+ /// @notice Encode varint uint32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_uint32(uint32 n) internal pure returns (bytes memory) {
+ return encode_varint(n);
+ }
+
+ /// @notice Encode varint uint64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_uint64(uint64 n) internal pure returns (bytes memory) {
+ return encode_varint(n);
+ }
+
+ /// @notice Encode varint sint32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_sint32(int32 n) internal pure returns (bytes memory) {
+ // https://developers.google.com/protocol-buffers/docs/encoding#signed_integers
+ uint32 mask = 0;
+ if (n < 0) {
+ unchecked {
+ mask -= 1;
+ }
+ }
+ uint32 zigzag_val = (uint32(n) << 1) ^ mask;
+
+ return encode_varint(zigzag_val);
+ }
+
+ /// @notice Encode varint sint64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_sint64(int64 n) internal pure returns (bytes memory) {
+ // https://developers.google.com/protocol-buffers/docs/encoding#signed_integers
+ uint64 mask = 0;
+ if (n < 0) {
+ unchecked {
+ mask -= 1;
+ }
+ }
+ uint64 zigzag_val = (uint64(n) << 1) ^ mask;
+
+ return encode_varint(zigzag_val);
+ }
+
+ /// @notice Encode Boolean.
+ /// @param b Boolean
+ /// @return Marshaled bytes
+ function encode_bool(bool b) internal pure returns (bytes memory) {
+ uint64 n = b ? 1 : 0;
+
+ return encode_varint(n);
+ }
+
+ /// @notice Encode enumeration.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_enum(int32 n) internal pure returns (bytes memory) {
+ return encode_int32(n);
+ }
+
+ /// @notice Encode fixed 64-bit int.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_bits64(uint64 n) internal pure returns (bytes memory) {
+ bytes memory buf = new bytes(8);
+
+ uint64 tmp = n;
+ for (uint64 i = 0; i < 8; i++) {
+ // Little endian
+ buf[i] = bytes1(uint8(tmp & 0xFF));
+ tmp = tmp >> 8;
+ }
+
+ return buf;
+ }
+
+ /// @notice Encode fixed uint64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_fixed64(uint64 n) internal pure returns (bytes memory) {
+ return encode_bits64(n);
+ }
+
+ /// @notice Encode fixed int64.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_sfixed64(int64 n) internal pure returns (bytes memory) {
+ return encode_bits64(uint64(n));
+ }
+
+ /// @notice Decode fixed 32-bit int.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_bits32(uint32 n) internal pure returns (bytes memory) {
+ bytes memory buf = new bytes(4);
+
+ uint64 tmp = n;
+ for (uint64 i = 0; i < 4; i++) {
+ // Little endian
+ buf[i] = bytes1(uint8(tmp & 0xFF));
+ tmp = tmp >> 8;
+ }
+
+ return buf;
+ }
+
+ /// @notice Encode fixed uint32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_fixed32(uint32 n) internal pure returns (bytes memory) {
+ return encode_bits32(n);
+ }
+
+ /// @notice Encode fixed int32.
+ /// @param n Number
+ /// @return Marshaled bytes
+ function encode_sfixed32(int32 n) internal pure returns (bytes memory) {
+ return encode_bits32(uint32(n));
+ }
+
+ /// @notice Encode length-delimited field.
+ /// @param b Bytes
+ /// @return Marshaled bytes
+ function encode_length_delimited(bytes memory b) internal pure returns (bytes memory) {
+ // Length-delimited fields begin with a varint of the number of bytes that follow
+ bytes memory length_buf = encode_uint64(uint64(b.length));
+ bytes memory buf = new bytes(b.length + length_buf.length);
+
+ for (uint64 i = 0; i < length_buf.length; i++) {
+ buf[i] = length_buf[i];
+ }
+
+ for (uint64 i = 0; i < b.length; i++) {
+ buf[i + length_buf.length] = b[i];
+ }
+
+ return buf;
+ }
+
+ /// @notice Encode string.
+ /// @param s String
+ /// @return Marshaled bytes
+ function encode_string(string memory s) internal pure returns (bytes memory) {
+ return encode_length_delimited(bytes(s));
+ }
+
+ /// @notice Encode bytes array.
+ /// @param b Bytes
+ /// @return Marshaled bytes
+ function encode_bytes(bytes memory b) internal pure returns (bytes memory) {
+ return encode_length_delimited(b);
+ }
+
+ /// @notice Encode embedded message.
+ /// @param m Message
+ /// @return Marshaled bytes
+ function encode_embedded_message(bytes memory m) internal pure returns (bytes memory) {
+ return encode_length_delimited(m);
+ }
+
+ /// @notice Encode packed repeated field.
+ /// @param b Bytes
+ /// @return Marshaled bytes
+ function encode_packed_repeated(bytes memory b) internal pure returns (bytes memory) {
+ return encode_length_delimited(b);
+ }
+}
diff --git a/src/TestFixture.sol b/src/TestFixture.sol
new file mode 100644
index 0000000..9a9e667
--- /dev/null
+++ b/src/TestFixture.sol
@@ -0,0 +1,345 @@
+// SPDX-License-Identifier: Apache-2.0
+pragma solidity >=0.8.4 <0.9.0;
+
+import "./ProtobufLib.sol";
+
+contract TestFixture {
+ // Functions are not pure so that we can measure gas
+
+ function decode_key(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64,
+ ProtobufLib.WireType
+ )
+ {
+ return ProtobufLib.decode_key(p, buf);
+ }
+
+ function decode_varint(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return ProtobufLib.decode_varint(p, buf);
+ }
+
+ function decode_int32(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ return ProtobufLib.decode_int32(p, buf);
+ }
+
+ function decode_int64(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ int64
+ )
+ {
+ return ProtobufLib.decode_int64(p, buf);
+ }
+
+ function decode_uint32(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint32
+ )
+ {
+ return ProtobufLib.decode_uint32(p, buf);
+ }
+
+ function decode_uint64(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return ProtobufLib.decode_uint64(p, buf);
+ }
+
+ function decode_sint32(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ return ProtobufLib.decode_sint32(p, buf);
+ }
+
+ function decode_sint64(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ int64
+ )
+ {
+ return ProtobufLib.decode_sint64(p, buf);
+ }
+
+ function decode_bool(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ bool
+ )
+ {
+ return ProtobufLib.decode_bool(p, buf);
+ }
+
+ function decode_enum(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ return ProtobufLib.decode_enum(p, buf);
+ }
+
+ function decode_bits64(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return ProtobufLib.decode_bits64(p, buf);
+ }
+
+ function decode_fixed64(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return ProtobufLib.decode_fixed64(p, buf);
+ }
+
+ function decode_sfixed64(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ int64
+ )
+ {
+ return ProtobufLib.decode_sfixed64(p, buf);
+ }
+
+ function decode_bits32(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint32
+ )
+ {
+ return ProtobufLib.decode_bits32(p, buf);
+ }
+
+ function decode_fixed32(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint32
+ )
+ {
+ return ProtobufLib.decode_fixed32(p, buf);
+ }
+
+ function decode_sfixed32(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ int32
+ )
+ {
+ return ProtobufLib.decode_sfixed32(p, buf);
+ }
+
+ function decode_length_delimited(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return ProtobufLib.decode_length_delimited(p, buf);
+ }
+
+ function decode_string(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ string memory
+ )
+ {
+ return ProtobufLib.decode_string(p, buf);
+ }
+
+ function decode_bytes(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return ProtobufLib.decode_bytes(p, buf);
+ }
+
+ function decode_embedded_message(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return ProtobufLib.decode_embedded_message(p, buf);
+ }
+
+ function decode_packed_repeated(uint64 p, bytes memory buf)
+ public
+ pure
+ returns (
+ bool,
+ uint64,
+ uint64
+ )
+ {
+ return ProtobufLib.decode_packed_repeated(p, buf);
+ }
+
+ function encode_key(uint64 field_number, uint64 wire_type) public pure returns (bytes memory) {
+ return ProtobufLib.encode_key(field_number, wire_type);
+ }
+
+ function encode_varint(uint64 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_varint(n);
+ }
+
+ function encode_int32(int32 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_int32(n);
+ }
+
+ function encode_int64(int64 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_int64(n);
+ }
+
+ function encode_uint32(uint32 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_uint32(n);
+ }
+
+ function encode_uint64(uint64 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_uint64(n);
+ }
+
+ function encode_sint32(int32 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_sint32(n);
+ }
+
+ function encode_sint64(int64 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_sint64(n);
+ }
+
+ function encode_bool(bool b) public pure returns (bytes memory) {
+ return ProtobufLib.encode_bool(b);
+ }
+
+ function encode_enum(int32 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_enum(n);
+ }
+
+ function encode_bits64(uint64 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_bits64(n);
+ }
+
+ function encode_fixed64(uint64 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_fixed64(n);
+ }
+
+ function encode_sfixed64(int64 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_sfixed64(n);
+ }
+
+ function encode_bits32(uint32 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_bits32(n);
+ }
+
+ function encode_fixed32(uint32 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_fixed32(n);
+ }
+
+ function encode_sfixed32(int32 n) public pure returns (bytes memory) {
+ return ProtobufLib.encode_sfixed32(n);
+ }
+
+ function encode_length_delimited(bytes memory b) public pure returns (bytes memory) {
+ return ProtobufLib.encode_length_delimited(b);
+ }
+
+ function encode_string(string memory s) public pure returns (bytes memory) {
+ return ProtobufLib.encode_string(s);
+ }
+
+ function encode_bytes(bytes memory b) public pure returns (bytes memory) {
+ return ProtobufLib.encode_bytes(b);
+ }
+
+ function encode_embedded_message(bytes memory m) public pure returns (bytes memory) {
+ return ProtobufLib.encode_embedded_message(m);
+ }
+
+ function encode_packed_repeated(bytes memory b) public pure returns (bytes memory) {
+ return ProtobufLib.encode_packed_repeated(b);
+ }
+}
diff --git a/strip.md b/strip.md
new file mode 100644
index 0000000..68fffed
--- /dev/null
+++ b/strip.md
@@ -0,0 +1,547 @@
+::: index
+style, coding style
+:::
+
+# Style Guide
+
+## Introduction
+
+This guide is intended to provide coding conventions for writing
+Solidity code. This guide should be thought of as an evolving document
+that will change over time as useful conventions are found and old
+conventions are rendered obsolete.
+
+Many projects will implement their own style guides. In the event of
+conflicts, project specific style guides take precedence.
+
+The structure and many of the recommendations within this style guide
+were taken from python\'s [pep8 style
+guide](https://www.python.org/dev/peps/pep-0008/).
+
+The goal of this guide is *not* to be the right way or the best way to
+write Solidity code. The goal of this guide is *consistency*. A quote
+from python\'s
+[pep8](https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds)
+captures this concept well.
+
+::: note
+::: title
+Note
+:::
+
+A style guide is about consistency. Consistency with this style guide is
+important. Consistency within a project is more important. Consistency
+within one module or function is most important.
+
+But most importantly: **know when to be inconsistent** \-- sometimes the
+style guide just doesn\'t apply. When in doubt, use your best judgment.
+Look at other examples and decide what looks best. And don\'t hesitate
+to ask!
+:::
+
+## Code Layout
+
+### Indentation
+
+Use 4 spaces per indentation level.
+
+### Tabs or Spaces
+
+Spaces are the preferred indentation method.
+
+Mixing tabs and spaces should be avoided.
+
+### Blank Lines
+
+Surround top level declarations in Solidity source with two blank lines.
+
+Yes:
+
+
+No:
+
+
+Within a contract surround function declarations with a single blank
+line.
+
+Blank lines may be omitted between groups of related one-liners (such as
+stub functions for an abstract contract)
+
+Yes:
+
+
+No:
+
+
+### Maximum Line Length {#maximum_line_length}
+
+Maximum suggested line length is 120 characters.
+
+Wrapped lines should conform to the following guidelines.
+
+1. The first argument should not be attached to the opening
+ parenthesis.
+2. One, and only one, indent should be used.
+3. Each argument should fall on its own line.
+4. The terminating element, `);`, should be placed on the final line by
+ itself.
+
+Function Calls
+
+Yes:
+
+
+No:
+
+
+Assignment Statements
+
+Yes:
+
+
+No:
+
+
+Event Definitions and Event Emitters
+
+Yes:
+
+
+No:
+
+
+### Source File Encoding
+
+UTF-8 or ASCII encoding is preferred.
+
+### Imports
+
+Import statements should always be placed at the top of the file.
+
+Yes:
+
+
+No:
+
+
+### Order of Functions
+
+Ordering helps readers identify which functions they can call and to
+find the constructor and fallback definitions easier.
+
+Functions should be grouped according to their visibility and ordered:
+
+- constructor
+- receive function (if exists)
+- fallback function (if exists)
+- external
+- public
+- internal
+- private
+
+Within a grouping, place the `view` and `pure` functions last.
+
+Yes:
+
+
+No:
+
+
+### Whitespace in Expressions
+
+Avoid extraneous whitespace in the following situations:
+
+Immediately inside parenthesis, brackets or braces, with the exception
+of single line function declarations.
+
+Yes:
+
+
+No:
+
+
+Exception:
+
+
+Immediately before a comma, semicolon:
+
+Yes:
+
+
+No:
+
+
+More than one space around an assignment or other operator to align with
+another:
+
+Yes:
+
+
+No:
+
+
+Don\'t include a whitespace in the receive and fallback functions:
+
+Yes:
+
+
+No:
+
+
+### Control Structures
+
+The braces denoting the body of a contract, library, functions and
+structs should:
+
+- open on the same line as the declaration
+- close on their own line at the same indentation level as the
+ beginning of the declaration.
+- The opening brace should be preceded by a single space.
+
+Yes:
+
+
+No:
+
+
+The same recommendations apply to the control structures `if`, `else`,
+`while`, and `for`.
+
+Additionally there should be a single space between the control
+structures `if`, `while`, and `for` and the parenthetic block
+representing the conditional, as well as a single space between the
+conditional parenthetic block and the opening brace.
+
+Yes:
+
+
+No:
+
+
+For control structures whose body contains a single statement, omitting
+the braces is ok *if* the statement is contained on a single line.
+
+Yes:
+
+
+No:
+
+
+For `if` blocks which have an `else` or `else if` clause, the `else`
+should be placed on the same line as the `if`\'s closing brace. This is
+an exception compared to the rules of other block-like structures.
+
+Yes:
+
+
+No:
+
+
+### Function Declaration
+
+For short function declarations, it is recommended for the opening brace
+of the function body to be kept on the same line as the function
+declaration.
+
+The closing brace should be at the same indentation level as the
+function declaration.
+
+The opening brace should be preceded by a single space.
+
+Yes:
+
+
+No:
+
+
+The modifier order for a function should be:
+
+1. Visibility
+2. Mutability
+3. Virtual
+4. Override
+5. Custom modifiers
+
+Yes:
+
+
+No:
+
+
+For long function declarations, it is recommended to drop each argument
+onto its own line at the same indentation level as the function body.
+The closing parenthesis and opening bracket should be placed on their
+own line as well at the same indentation level as the function
+declaration.
+
+Yes:
+
+
+No:
+
+
+If a long function declaration has modifiers, then each modifier should
+be dropped to its own line.
+
+Yes:
+
+
+No:
+
+
+Multiline output parameters and return statements should follow the same
+style recommended for wrapping long lines found in the
+`Maximum Line Length `{.interpreted-text
+role="ref"} section.
+
+Yes:
+
+
+No:
+
+
+For constructor functions on inherited contracts whose bases require
+arguments, it is recommended to drop the base constructors onto new
+lines in the same manner as modifiers if the function declaration is
+long or hard to read.
+
+Yes:
+
+
+No:
+
+
+When declaring short functions with a single statement, it is
+permissible to do it on a single line.
+
+Permissible:
+
+
+These guidelines for function declarations are intended to improve
+readability. Authors should use their best judgment as this guide does
+not try to cover all possible permutations for function declarations.
+
+### Mappings
+
+In variable declarations, do not separate the keyword `mapping` from its
+type by a space. Do not separate any nested `mapping` keyword from its
+type by whitespace.
+
+Yes:
+
+
+No:
+
+
+### Variable Declarations
+
+Declarations of array variables should not have a space between the type
+and the brackets.
+
+Yes:
+
+
+No:
+
+
+### Other Recommendations
+
+- Strings should be quoted with double-quotes instead of
+ single-quotes.
+
+Yes:
+
+
+No:
+
+
+- Surround operators with a single space on either side.
+
+Yes:
+
+
+No:
+
+
+- Operators with a higher priority than others can exclude surrounding
+ whitespace in order to denote precedence. This is meant to allow for
+ improved readability for complex statements. You should always use
+ the same amount of whitespace on either side of an operator:
+
+Yes:
+
+
+No:
+
+
+## Order of Layout
+
+Layout contract elements in the following order:
+
+1. Pragma statements
+2. Import statements
+3. Interfaces
+4. Libraries
+5. Contracts
+
+Inside each contract, library or interface, use the following order:
+
+1. Type declarations
+2. State variables
+3. Events
+4. Modifiers
+5. Functions
+
+::: note
+::: title
+Note
+:::
+
+It might be clearer to declare types close to their use in events or
+state variables.
+:::
+
+## Naming Conventions
+
+Naming conventions are powerful when adopted and used broadly. The use
+of different conventions can convey significant *meta* information that
+would otherwise not be immediately available.
+
+The naming recommendations given here are intended to improve the
+readability, and thus they are not rules, but rather guidelines to try
+and help convey the most information through the names of things.
+
+Lastly, consistency within a codebase should always supersede any
+conventions outlined in this document.
+
+### Naming Styles
+
+To avoid confusion, the following names will be used to refer to
+different naming styles.
+
+- `b` (single lowercase letter)
+- `B` (single uppercase letter)
+- `lowercase`
+- `UPPERCASE`
+- `UPPER_CASE_WITH_UNDERSCORES`
+- `CapitalizedWords` (or CapWords)
+- `mixedCase` (differs from CapitalizedWords by initial lowercase
+ character!)
+
+::: note
+::: title
+Note
+:::
+
+When using initialisms in CapWords, capitalize all the letters of the
+initialisms. Thus HTTPServerError is better than HttpServerError. When
+using initialisms in mixedCase, capitalize all the letters of the
+initialisms, except keep the first one lower case if it is the beginning
+of the name. Thus xmlHTTPRequest is better than XMLHTTPRequest.
+:::
+
+### Names to Avoid
+
+- `l` - Lowercase letter el
+- `O` - Uppercase letter oh
+- `I` - Uppercase letter eye
+
+Never use any of these for single letter variable names. They are often
+indistinguishable from the numerals one and zero.
+
+### Contract and Library Names
+
+- Contracts and libraries should be named using the CapWords style.
+ Examples: `SimpleToken`, `SmartBank`, `CertificateHashRepository`,
+ `Player`, `Congress`, `Owned`.
+- Contract and library names should also match their filenames.
+- If a contract file includes multiple contracts and/or libraries,
+ then the filename should match the *core contract*. This is not
+ recommended however if it can be avoided.
+
+As shown in the example below, if the contract name is `Congress` and
+the library name is `Owned`, then their associated filenames should be
+`Congress.sol` and `Owned.sol`.
+
+Yes:
+
+
+and in `Congress.sol`:
+
+
+No:
+
+
+and in `Congress.sol`:
+
+
+### Struct Names
+
+Structs should be named using the CapWords style. Examples: `MyCoin`,
+`Position`, `PositionXY`.
+
+### Event Names
+
+Events should be named using the CapWords style. Examples: `Deposit`,
+`Transfer`, `Approval`, `BeforeTransfer`, `AfterTransfer`.
+
+### Function Names
+
+Functions should use mixedCase. Examples: `getBalance`, `transfer`,
+`verifyOwner`, `addMember`, `changeOwner`.
+
+### Function Argument Names
+
+Function arguments should use mixedCase. Examples: `initialSupply`,
+`account`, `recipientAddress`, `senderAddress`, `newOwner`.
+
+When writing library functions that operate on a custom struct, the
+struct should be the first argument and should always be named `self`.
+
+### Local and State Variable Names
+
+Use mixedCase. Examples: `totalSupply`, `remainingSupply`, `balancesOf`,
+`creatorAddress`, `isPreSale`, `tokenExchangeRate`.
+
+### Constants
+
+Constants should be named with all capital letters with underscores
+separating words. Examples: `MAX_BLOCKS`, `TOKEN_NAME`, `TOKEN_TICKER`,
+`CONTRACT_VERSION`.
+
+### Modifier Names
+
+Use mixedCase. Examples: `onlyBy`, `onlyAfter`, `onlyDuringThePreSale`.
+
+### Enums
+
+Enums, in the style of simple type declarations, should be named using
+the CapWords style. Examples: `TokenGroup`, `Frame`, `HashStyle`,
+`CharacterLocation`.
+
+### Avoiding Naming Collisions
+
+- `singleTrailingUnderscore_`
+
+This convention is suggested when the desired name collides with that of
+an existing state variable, function, built-in or otherwise reserved
+name.
+
+## NatSpec {#style_guide_natspec}
+
+Solidity contracts can also contain NatSpec comments. They are written
+with a triple slash (`///`) or a double asterisk block (`/** ... */`)
+and they should be used directly above function declarations or
+statements.
+
+For example, the contract from
+`a simple smart contract `{.interpreted-text
+role="ref"} with the comments added looks like the one below:
+
+
+It is recommended that Solidity contracts are fully annotated using
+`NatSpec `{.interpreted-text role="ref"} for all public
+interfaces (everything in the ABI).
+
+Please see the section about `NatSpec `{.interpreted-text
+role="ref"} for a detailed explanation.
diff --git a/style-guide.md b/style-guide.md
new file mode 100644
index 0000000..5fabd91
--- /dev/null
+++ b/style-guide.md
@@ -0,0 +1,1305 @@
+::: index
+style, coding style
+:::
+
+# Style Guide
+
+## Introduction
+
+This guide is intended to provide coding conventions for writing
+Solidity code. This guide should be thought of as an evolving document
+that will change over time as useful conventions are found and old
+conventions are rendered obsolete.
+
+Many projects will implement their own style guides. In the event of
+conflicts, project specific style guides take precedence.
+
+The structure and many of the recommendations within this style guide
+were taken from python\'s [pep8 style
+guide](https://www.python.org/dev/peps/pep-0008/).
+
+The goal of this guide is *not* to be the right way or the best way to
+write Solidity code. The goal of this guide is *consistency*. A quote
+from python\'s
+[pep8](https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds)
+captures this concept well.
+
+::: note
+::: title
+Note
+:::
+
+A style guide is about consistency. Consistency with this style guide is
+important. Consistency within a project is more important. Consistency
+within one module or function is most important.
+
+But most importantly: **know when to be inconsistent** \-- sometimes the
+style guide just doesn\'t apply. When in doubt, use your best judgment.
+Look at other examples and decide what looks best. And don\'t hesitate
+to ask!
+:::
+
+## Code Layout
+
+### Indentation
+
+Use 4 spaces per indentation level.
+
+### Tabs or Spaces
+
+Spaces are the preferred indentation method.
+
+Mixing tabs and spaces should be avoided.
+
+### Blank Lines
+
+Surround top level declarations in Solidity source with two blank lines.
+
+Yes:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.4.0 <0.9.0;
+
+contract A {
+ // ...
+}
+
+
+contract B {
+ // ...
+}
+
+
+contract C {
+ // ...
+}
+```
+
+No:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.4.0 <0.9.0;
+
+contract A {
+ // ...
+}
+contract B {
+ // ...
+}
+
+contract C {
+ // ...
+}
+```
+
+Within a contract surround function declarations with a single blank
+line.
+
+Blank lines may be omitted between groups of related one-liners (such as
+stub functions for an abstract contract)
+
+Yes:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.6.0 <0.9.0;
+
+abstract contract A {
+ function spam() public virtual pure;
+ function ham() public virtual pure;
+}
+
+
+contract B is A {
+ function spam() public pure override {
+ // ...
+ }
+
+ function ham() public pure override {
+ // ...
+ }
+}
+```
+
+No:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.6.0 <0.9.0;
+
+abstract contract A {
+ function spam() virtual pure public;
+ function ham() public virtual pure;
+}
+
+
+contract B is A {
+ function spam() public pure override {
+ // ...
+ }
+ function ham() public pure override {
+ // ...
+ }
+}
+```
+
+### Maximum Line Length {#maximum_line_length}
+
+Maximum suggested line length is 120 characters.
+
+Wrapped lines should conform to the following guidelines.
+
+1. The first argument should not be attached to the opening
+ parenthesis.
+2. One, and only one, indent should be used.
+3. Each argument should fall on its own line.
+4. The terminating element, `);`, should be placed on the final line by
+ itself.
+
+Function Calls
+
+Yes:
+
+```solidity
+thisFunctionCallIsReallyLong(
+ longArgument1,
+ longArgument2,
+ longArgument3
+);
+```
+
+No:
+
+```solidity
+thisFunctionCallIsReallyLong(longArgument1,
+ longArgument2,
+ longArgument3
+);
+
+thisFunctionCallIsReallyLong(longArgument1,
+ longArgument2,
+ longArgument3
+);
+
+thisFunctionCallIsReallyLong(
+ longArgument1, longArgument2,
+ longArgument3
+);
+
+thisFunctionCallIsReallyLong(
+longArgument1,
+longArgument2,
+longArgument3
+);
+
+thisFunctionCallIsReallyLong(
+ longArgument1,
+ longArgument2,
+ longArgument3);
+```
+
+Assignment Statements
+
+Yes:
+
+```solidity
+thisIsALongNestedMapping[being][set][toSomeValue] = someFunction(
+ argument1,
+ argument2,
+ argument3,
+ argument4
+);
+```
+
+No:
+
+```solidity
+thisIsALongNestedMapping[being][set][toSomeValue] = someFunction(argument1,
+ argument2,
+ argument3,
+ argument4);
+```
+
+Event Definitions and Event Emitters
+
+Yes:
+
+```solidity
+event LongAndLotsOfArgs(
+ address sender,
+ address recipient,
+ uint256 publicKey,
+ uint256 amount,
+ bytes32[] options
+);
+
+LongAndLotsOfArgs(
+ sender,
+ recipient,
+ publicKey,
+ amount,
+ options
+);
+```
+
+No:
+
+```solidity
+event LongAndLotsOfArgs(address sender,
+ address recipient,
+ uint256 publicKey,
+ uint256 amount,
+ bytes32[] options);
+
+LongAndLotsOfArgs(sender,
+ recipient,
+ publicKey,
+ amount,
+ options);
+```
+
+### Source File Encoding
+
+UTF-8 or ASCII encoding is preferred.
+
+### Imports
+
+Import statements should always be placed at the top of the file.
+
+Yes:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.4.0 <0.9.0;
+
+import "./Owned.sol";
+
+contract A {
+ // ...
+}
+
+
+contract B is Owned {
+ // ...
+}
+```
+
+No:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.4.0 <0.9.0;
+
+contract A {
+ // ...
+}
+
+
+import "./Owned.sol";
+
+
+contract B is Owned {
+ // ...
+}
+```
+
+### Order of Functions
+
+Ordering helps readers identify which functions they can call and to
+find the constructor and fallback definitions easier.
+
+Functions should be grouped according to their visibility and ordered:
+
+- constructor
+- receive function (if exists)
+- fallback function (if exists)
+- external
+- public
+- internal
+- private
+
+Within a grouping, place the `view` and `pure` functions last.
+
+Yes:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.7.0 <0.9.0;
+contract A {
+ constructor() {
+ // ...
+ }
+
+ receive() external payable {
+ // ...
+ }
+
+ fallback() external {
+ // ...
+ }
+
+ // External functions
+ // ...
+
+ // External functions that are view
+ // ...
+
+ // External functions that are pure
+ // ...
+
+ // Public functions
+ // ...
+
+ // Internal functions
+ // ...
+
+ // Private functions
+ // ...
+}
+```
+
+No:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.7.0 <0.9.0;
+contract A {
+
+ // External functions
+ // ...
+
+ fallback() external {
+ // ...
+ }
+ receive() external payable {
+ // ...
+ }
+
+ // Private functions
+ // ...
+
+ // Public functions
+ // ...
+
+ constructor() {
+ // ...
+ }
+
+ // Internal functions
+ // ...
+}
+```
+
+### Whitespace in Expressions
+
+Avoid extraneous whitespace in the following situations:
+
+Immediately inside parenthesis, brackets or braces, with the exception
+of single line function declarations.
+
+Yes:
+
+```solidity
+spam(ham[1], Coin({name: "ham"}));
+```
+
+No:
+
+```solidity
+spam( ham[ 1 ], Coin( { name: "ham" } ) );
+```
+
+Exception:
+
+```solidity
+function singleLine() public { spam(); }
+```
+
+Immediately before a comma, semicolon:
+
+Yes:
+
+```solidity
+function spam(uint i, Coin coin) public;
+```
+
+No:
+
+```solidity
+function spam(uint i , Coin coin) public ;
+```
+
+More than one space around an assignment or other operator to align with
+another:
+
+Yes:
+
+```solidity
+x = 1;
+y = 2;
+longVariable = 3;
+```
+
+No:
+
+```solidity
+x = 1;
+y = 2;
+longVariable = 3;
+```
+
+Don\'t include a whitespace in the receive and fallback functions:
+
+Yes:
+
+```solidity
+receive() external payable {
+ ...
+}
+
+fallback() external {
+ ...
+}
+```
+
+No:
+
+```solidity
+receive () external payable {
+ ...
+}
+
+fallback () external {
+ ...
+}
+```
+
+### Control Structures
+
+The braces denoting the body of a contract, library, functions and
+structs should:
+
+- open on the same line as the declaration
+- close on their own line at the same indentation level as the
+ beginning of the declaration.
+- The opening brace should be preceded by a single space.
+
+Yes:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.4.0 <0.9.0;
+
+contract Coin {
+ struct Bank {
+ address owner;
+ uint balance;
+ }
+}
+```
+
+No:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.4.0 <0.9.0;
+
+contract Coin
+{
+ struct Bank {
+ address owner;
+ uint balance;
+ }
+}
+```
+
+The same recommendations apply to the control structures `if`, `else`,
+`while`, and `for`.
+
+Additionally there should be a single space between the control
+structures `if`, `while`, and `for` and the parenthetic block
+representing the conditional, as well as a single space between the
+conditional parenthetic block and the opening brace.
+
+Yes:
+
+```solidity
+if (...) {
+ ...
+}
+
+for (...) {
+ ...
+}
+```
+
+No:
+
+```solidity
+if (...)
+{
+ ...
+}
+
+while(...){
+}
+
+for (...) {
+ ...;}
+```
+
+For control structures whose body contains a single statement, omitting
+the braces is ok *if* the statement is contained on a single line.
+
+Yes:
+
+```solidity
+if (x < 10)
+ x += 1;
+```
+
+No:
+
+```solidity
+if (x < 10)
+ someArray.push(Coin({
+ name: 'spam',
+ value: 42
+ }));
+```
+
+For `if` blocks which have an `else` or `else if` clause, the `else`
+should be placed on the same line as the `if`\'s closing brace. This is
+an exception compared to the rules of other block-like structures.
+
+Yes:
+
+```solidity
+if (x < 3) {
+ x += 1;
+} else if (x > 7) {
+ x -= 1;
+} else {
+ x = 5;
+}
+
+
+if (x < 3)
+ x += 1;
+else
+ x -= 1;
+```
+
+No:
+
+```solidity
+if (x < 3) {
+ x += 1;
+}
+else {
+ x -= 1;
+}
+```
+
+### Function Declaration
+
+For short function declarations, it is recommended for the opening brace
+of the function body to be kept on the same line as the function
+declaration.
+
+The closing brace should be at the same indentation level as the
+function declaration.
+
+The opening brace should be preceded by a single space.
+
+Yes:
+
+```solidity
+function increment(uint x) public pure returns (uint) {
+ return x + 1;
+}
+
+function increment(uint x) public pure onlyOwner returns (uint) {
+ return x + 1;
+}
+```
+
+No:
+
+```solidity
+function increment(uint x) public pure returns (uint)
+{
+ return x + 1;
+}
+
+function increment(uint x) public pure returns (uint){
+ return x + 1;
+}
+
+function increment(uint x) public pure returns (uint) {
+ return x + 1;
+ }
+
+function increment(uint x) public pure returns (uint) {
+ return x + 1;}
+```
+
+The modifier order for a function should be:
+
+1. Visibility
+2. Mutability
+3. Virtual
+4. Override
+5. Custom modifiers
+
+Yes:
+
+```solidity
+function balance(uint from) public view override returns (uint) {
+ return balanceOf[from];
+}
+
+function shutdown() public onlyOwner {
+ selfdestruct(owner);
+}
+```
+
+No:
+
+```solidity
+function balance(uint from) public override view returns (uint) {
+ return balanceOf[from];
+}
+
+function shutdown() onlyOwner public {
+ selfdestruct(owner);
+}
+```
+
+For long function declarations, it is recommended to drop each argument
+onto its own line at the same indentation level as the function body.
+The closing parenthesis and opening bracket should be placed on their
+own line as well at the same indentation level as the function
+declaration.
+
+Yes:
+
+```solidity
+function thisFunctionHasLotsOfArguments(
+ address a,
+ address b,
+ address c,
+ address d,
+ address e,
+ address f
+)
+ public
+{
+ doSomething();
+}
+```
+
+No:
+
+```solidity
+function thisFunctionHasLotsOfArguments(address a, address b, address c,
+ address d, address e, address f) public {
+ doSomething();
+}
+
+function thisFunctionHasLotsOfArguments(address a,
+ address b,
+ address c,
+ address d,
+ address e,
+ address f) public {
+ doSomething();
+}
+
+function thisFunctionHasLotsOfArguments(
+ address a,
+ address b,
+ address c,
+ address d,
+ address e,
+ address f) public {
+ doSomething();
+}
+```
+
+If a long function declaration has modifiers, then each modifier should
+be dropped to its own line.
+
+Yes:
+
+```solidity
+function thisFunctionNameIsReallyLong(address x, address y, address z)
+ public
+ onlyOwner
+ priced
+ returns (address)
+{
+ doSomething();
+}
+
+function thisFunctionNameIsReallyLong(
+ address x,
+ address y,
+ address z
+)
+ public
+ onlyOwner
+ priced
+ returns (address)
+{
+ doSomething();
+}
+```
+
+No:
+
+```solidity
+function thisFunctionNameIsReallyLong(address x, address y, address z)
+ public
+ onlyOwner
+ priced
+ returns (address) {
+ doSomething();
+}
+
+function thisFunctionNameIsReallyLong(address x, address y, address z)
+ public onlyOwner priced returns (address)
+{
+ doSomething();
+}
+
+function thisFunctionNameIsReallyLong(address x, address y, address z)
+ public
+ onlyOwner
+ priced
+ returns (address) {
+ doSomething();
+}
+```
+
+Multiline output parameters and return statements should follow the same
+style recommended for wrapping long lines found in the
+`Maximum Line Length `{.interpreted-text
+role="ref"} section.
+
+Yes:
+
+```solidity
+function thisFunctionNameIsReallyLong(
+ address a,
+ address b,
+ address c
+)
+ public
+ returns (
+ address someAddressName,
+ uint256 LongArgument,
+ uint256 Argument
+ )
+{
+ doSomething()
+
+ return (
+ veryLongReturnArg1,
+ veryLongReturnArg2,
+ veryLongReturnArg3
+ );
+}
+```
+
+No:
+
+```solidity
+function thisFunctionNameIsReallyLong(
+ address a,
+ address b,
+ address c
+)
+ public
+ returns (address someAddressName,
+ uint256 LongArgument,
+ uint256 Argument)
+{
+ doSomething()
+
+ return (veryLongReturnArg1,
+ veryLongReturnArg1,
+ veryLongReturnArg1);
+}
+```
+
+For constructor functions on inherited contracts whose bases require
+arguments, it is recommended to drop the base constructors onto new
+lines in the same manner as modifiers if the function declaration is
+long or hard to read.
+
+Yes:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.7.0 <0.9.0;
+// Base contracts just to make this compile
+contract B {
+ constructor(uint) {
+ }
+}
+
+
+contract C {
+ constructor(uint, uint) {
+ }
+}
+
+
+contract D {
+ constructor(uint) {
+ }
+}
+
+
+contract A is B, C, D {
+ uint x;
+
+ constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
+ B(param1)
+ C(param2, param3)
+ D(param4)
+ {
+ // do something with param5
+ x = param5;
+ }
+}
+```
+
+No:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.7.0 <0.9.0;
+
+// Base contracts just to make this compile
+contract B {
+ constructor(uint) {
+ }
+}
+
+
+contract C {
+ constructor(uint, uint) {
+ }
+}
+
+
+contract D {
+ constructor(uint) {
+ }
+}
+
+
+contract A is B, C, D {
+ uint x;
+
+ constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
+ B(param1)
+ C(param2, param3)
+ D(param4) {
+ x = param5;
+ }
+}
+
+
+contract X is B, C, D {
+ uint x;
+
+ constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
+ B(param1)
+ C(param2, param3)
+ D(param4) {
+ x = param5;
+ }
+}
+```
+
+When declaring short functions with a single statement, it is
+permissible to do it on a single line.
+
+Permissible:
+
+```solidity
+function shortFunction() public { doSomething(); }
+```
+
+These guidelines for function declarations are intended to improve
+readability. Authors should use their best judgment as this guide does
+not try to cover all possible permutations for function declarations.
+
+### Mappings
+
+In variable declarations, do not separate the keyword `mapping` from its
+type by a space. Do not separate any nested `mapping` keyword from its
+type by whitespace.
+
+Yes:
+
+```solidity
+mapping(uint => uint) map;
+mapping(address => bool) registeredAddresses;
+mapping(uint => mapping(bool => Data[])) public data;
+mapping(uint => mapping(uint => s)) data;
+```
+
+No:
+
+```solidity
+mapping (uint => uint) map;
+mapping( address => bool ) registeredAddresses;
+mapping (uint => mapping (bool => Data[])) public data;
+mapping(uint => mapping (uint => s)) data;
+```
+
+### Variable Declarations
+
+Declarations of array variables should not have a space between the type
+and the brackets.
+
+Yes:
+
+```solidity
+uint[] x;
+```
+
+No:
+
+```solidity
+uint [] x;
+```
+
+### Other Recommendations
+
+- Strings should be quoted with double-quotes instead of
+ single-quotes.
+
+Yes:
+
+```solidity
+str = "foo";
+str = "Hamlet says, 'To be or not to be...'";
+```
+
+No:
+
+```solidity
+str = 'bar';
+str = '"Be yourself; everyone else is already taken." -Oscar Wilde';
+```
+
+- Surround operators with a single space on either side.
+
+Yes:
+
+``` {.solidity force=""}
+x = 3;
+x = 100 / 10;
+x += 3 + 4;
+x |= y && z;
+```
+
+No:
+
+``` {.solidity force=""}
+x=3;
+x = 100/10;
+x += 3+4;
+x |= y&&z;
+```
+
+- Operators with a higher priority than others can exclude surrounding
+ whitespace in order to denote precedence. This is meant to allow for
+ improved readability for complex statements. You should always use
+ the same amount of whitespace on either side of an operator:
+
+Yes:
+
+```solidity
+x = 2**3 + 5;
+x = 2*y + 3*z;
+x = (a+b) * (a-b);
+```
+
+No:
+
+```solidity
+x = 2** 3 + 5;
+x = y+z;
+x +=1;
+```
+
+## Order of Layout
+
+Layout contract elements in the following order:
+
+1. Pragma statements
+2. Import statements
+3. Interfaces
+4. Libraries
+5. Contracts
+
+Inside each contract, library or interface, use the following order:
+
+1. Type declarations
+2. State variables
+3. Events
+4. Modifiers
+5. Functions
+
+::: note
+::: title
+Note
+:::
+
+It might be clearer to declare types close to their use in events or
+state variables.
+:::
+
+## Naming Conventions
+
+Naming conventions are powerful when adopted and used broadly. The use
+of different conventions can convey significant *meta* information that
+would otherwise not be immediately available.
+
+The naming recommendations given here are intended to improve the
+readability, and thus they are not rules, but rather guidelines to try
+and help convey the most information through the names of things.
+
+Lastly, consistency within a codebase should always supersede any
+conventions outlined in this document.
+
+### Naming Styles
+
+To avoid confusion, the following names will be used to refer to
+different naming styles.
+
+- `b` (single lowercase letter)
+- `B` (single uppercase letter)
+- `lowercase`
+- `UPPERCASE`
+- `UPPER_CASE_WITH_UNDERSCORES`
+- `CapitalizedWords` (or CapWords)
+- `mixedCase` (differs from CapitalizedWords by initial lowercase
+ character!)
+
+::: note
+::: title
+Note
+:::
+
+When using initialisms in CapWords, capitalize all the letters of the
+initialisms. Thus HTTPServerError is better than HttpServerError. When
+using initialisms in mixedCase, capitalize all the letters of the
+initialisms, except keep the first one lower case if it is the beginning
+of the name. Thus xmlHTTPRequest is better than XMLHTTPRequest.
+:::
+
+### Names to Avoid
+
+- `l` - Lowercase letter el
+- `O` - Uppercase letter oh
+- `I` - Uppercase letter eye
+
+Never use any of these for single letter variable names. They are often
+indistinguishable from the numerals one and zero.
+
+### Contract and Library Names
+
+- Contracts and libraries should be named using the CapWords style.
+ Examples: `SimpleToken`, `SmartBank`, `CertificateHashRepository`,
+ `Player`, `Congress`, `Owned`.
+- Contract and library names should also match their filenames.
+- If a contract file includes multiple contracts and/or libraries,
+ then the filename should match the *core contract*. This is not
+ recommended however if it can be avoided.
+
+As shown in the example below, if the contract name is `Congress` and
+the library name is `Owned`, then their associated filenames should be
+`Congress.sol` and `Owned.sol`.
+
+Yes:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.7.0 <0.9.0;
+
+// Owned.sol
+contract Owned {
+ address public owner;
+
+ constructor() {
+ owner = msg.sender;
+ }
+
+ modifier onlyOwner {
+ require(msg.sender == owner);
+ _;
+ }
+
+ function transferOwnership(address newOwner) public onlyOwner {
+ owner = newOwner;
+ }
+}
+```
+
+and in `Congress.sol`:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.4.0 <0.9.0;
+
+import "./Owned.sol";
+
+
+contract Congress is Owned, TokenRecipient {
+ //...
+}
+```
+
+No:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.7.0 <0.9.0;
+
+// owned.sol
+contract owned {
+ address public owner;
+
+ constructor() {
+ owner = msg.sender;
+ }
+
+ modifier onlyOwner {
+ require(msg.sender == owner);
+ _;
+ }
+
+ function transferOwnership(address newOwner) public onlyOwner {
+ owner = newOwner;
+ }
+}
+```
+
+and in `Congress.sol`:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity ^0.7.0;
+
+
+import "./owned.sol";
+
+
+contract Congress is owned, tokenRecipient {
+ //...
+}
+```
+
+### Struct Names
+
+Structs should be named using the CapWords style. Examples: `MyCoin`,
+`Position`, `PositionXY`.
+
+### Event Names
+
+Events should be named using the CapWords style. Examples: `Deposit`,
+`Transfer`, `Approval`, `BeforeTransfer`, `AfterTransfer`.
+
+### Function Names
+
+Functions should use mixedCase. Examples: `getBalance`, `transfer`,
+`verifyOwner`, `addMember`, `changeOwner`.
+
+### Function Argument Names
+
+Function arguments should use mixedCase. Examples: `initialSupply`,
+`account`, `recipientAddress`, `senderAddress`, `newOwner`.
+
+When writing library functions that operate on a custom struct, the
+struct should be the first argument and should always be named `self`.
+
+### Local and State Variable Names
+
+Use mixedCase. Examples: `totalSupply`, `remainingSupply`, `balancesOf`,
+`creatorAddress`, `isPreSale`, `tokenExchangeRate`.
+
+### Constants
+
+Constants should be named with all capital letters with underscores
+separating words. Examples: `MAX_BLOCKS`, `TOKEN_NAME`, `TOKEN_TICKER`,
+`CONTRACT_VERSION`.
+
+### Modifier Names
+
+Use mixedCase. Examples: `onlyBy`, `onlyAfter`, `onlyDuringThePreSale`.
+
+### Enums
+
+Enums, in the style of simple type declarations, should be named using
+the CapWords style. Examples: `TokenGroup`, `Frame`, `HashStyle`,
+`CharacterLocation`.
+
+### Avoiding Naming Collisions
+
+- `singleTrailingUnderscore_`
+
+This convention is suggested when the desired name collides with that of
+an existing state variable, function, built-in or otherwise reserved
+name.
+
+## NatSpec {#style_guide_natspec}
+
+Solidity contracts can also contain NatSpec comments. They are written
+with a triple slash (`///`) or a double asterisk block (`/** ... */`)
+and they should be used directly above function declarations or
+statements.
+
+For example, the contract from
+`a simple smart contract `{.interpreted-text
+role="ref"} with the comments added looks like the one below:
+
+```solidity
+// SPDX-License-Identifier: GPL-3.0
+pragma solidity >=0.4.16 <0.9.0;
+
+/// @author The Solidity Team
+/// @title A simple storage example
+contract SimpleStorage {
+ uint storedData;
+
+ /// Store `x`.
+ /// @param x the new value to store
+ /// @dev stores the number in the state variable `storedData`
+ function set(uint x) public {
+ storedData = x;
+ }
+
+ /// Return the stored value.
+ /// @dev retrieves the value of the state variable `storedData`
+ /// @return the stored value
+ function get() public view returns (uint) {
+ return storedData;
+ }
+}
+```
+
+It is recommended that Solidity contracts are fully annotated using
+`NatSpec `{.interpreted-text role="ref"} for all public
+interfaces (everything in the ABI).
+
+Please see the section about `NatSpec `{.interpreted-text
+role="ref"} for a detailed explanation.
diff --git a/style-guide.rst b/style-guide.rst
new file mode 100644
index 0000000..75de18a
--- /dev/null
+++ b/style-guide.rst
@@ -0,0 +1,1301 @@
+.. index:: style, coding style
+
+#############
+Style Guide
+#############
+
+************
+Introduction
+************
+
+This guide is intended to provide coding conventions for writing Solidity code.
+This guide should be thought of as an evolving document that will change over
+time as useful conventions are found and old conventions are rendered obsolete.
+
+Many projects will implement their own style guides. In the event of
+conflicts, project specific style guides take precedence.
+
+The structure and many of the recommendations within this style guide were
+taken from python's
+`pep8 style guide `_.
+
+The goal of this guide is *not* to be the right way or the best way to write
+Solidity code. The goal of this guide is *consistency*. A quote from python's
+`pep8 `_
+captures this concept well.
+
+.. note::
+
+ A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.
+
+ But most importantly: **know when to be inconsistent** -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!
+
+
+***********
+Code Layout
+***********
+
+
+Indentation
+===========
+
+Use 4 spaces per indentation level.
+
+Tabs or Spaces
+==============
+
+Spaces are the preferred indentation method.
+
+Mixing tabs and spaces should be avoided.
+
+Blank Lines
+===========
+
+Surround top level declarations in Solidity source with two blank lines.
+
+Yes:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.4.0 <0.9.0;
+
+ contract A {
+ // ...
+ }
+
+
+ contract B {
+ // ...
+ }
+
+
+ contract C {
+ // ...
+ }
+
+No:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.4.0 <0.9.0;
+
+ contract A {
+ // ...
+ }
+ contract B {
+ // ...
+ }
+
+ contract C {
+ // ...
+ }
+
+Within a contract surround function declarations with a single blank line.
+
+Blank lines may be omitted between groups of related one-liners (such as stub functions for an abstract contract)
+
+Yes:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.6.0 <0.9.0;
+
+ abstract contract A {
+ function spam() public virtual pure;
+ function ham() public virtual pure;
+ }
+
+
+ contract B is A {
+ function spam() public pure override {
+ // ...
+ }
+
+ function ham() public pure override {
+ // ...
+ }
+ }
+
+No:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.6.0 <0.9.0;
+
+ abstract contract A {
+ function spam() virtual pure public;
+ function ham() public virtual pure;
+ }
+
+
+ contract B is A {
+ function spam() public pure override {
+ // ...
+ }
+ function ham() public pure override {
+ // ...
+ }
+ }
+
+.. _maximum_line_length:
+
+Maximum Line Length
+===================
+
+Maximum suggested line length is 120 characters.
+
+Wrapped lines should conform to the following guidelines.
+
+1. The first argument should not be attached to the opening parenthesis.
+2. One, and only one, indent should be used.
+3. Each argument should fall on its own line.
+4. The terminating element, :code:`);`, should be placed on the final line by itself.
+
+Function Calls
+
+Yes:
+
+.. code-block:: solidity
+
+ thisFunctionCallIsReallyLong(
+ longArgument1,
+ longArgument2,
+ longArgument3
+ );
+
+No:
+
+.. code-block:: solidity
+
+ thisFunctionCallIsReallyLong(longArgument1,
+ longArgument2,
+ longArgument3
+ );
+
+ thisFunctionCallIsReallyLong(longArgument1,
+ longArgument2,
+ longArgument3
+ );
+
+ thisFunctionCallIsReallyLong(
+ longArgument1, longArgument2,
+ longArgument3
+ );
+
+ thisFunctionCallIsReallyLong(
+ longArgument1,
+ longArgument2,
+ longArgument3
+ );
+
+ thisFunctionCallIsReallyLong(
+ longArgument1,
+ longArgument2,
+ longArgument3);
+
+Assignment Statements
+
+Yes:
+
+.. code-block:: solidity
+
+ thisIsALongNestedMapping[being][set][toSomeValue] = someFunction(
+ argument1,
+ argument2,
+ argument3,
+ argument4
+ );
+
+No:
+
+.. code-block:: solidity
+
+ thisIsALongNestedMapping[being][set][toSomeValue] = someFunction(argument1,
+ argument2,
+ argument3,
+ argument4);
+
+Event Definitions and Event Emitters
+
+Yes:
+
+.. code-block:: solidity
+
+ event LongAndLotsOfArgs(
+ address sender,
+ address recipient,
+ uint256 publicKey,
+ uint256 amount,
+ bytes32[] options
+ );
+
+ LongAndLotsOfArgs(
+ sender,
+ recipient,
+ publicKey,
+ amount,
+ options
+ );
+
+No:
+
+.. code-block:: solidity
+
+ event LongAndLotsOfArgs(address sender,
+ address recipient,
+ uint256 publicKey,
+ uint256 amount,
+ bytes32[] options);
+
+ LongAndLotsOfArgs(sender,
+ recipient,
+ publicKey,
+ amount,
+ options);
+
+Source File Encoding
+====================
+
+UTF-8 or ASCII encoding is preferred.
+
+Imports
+=======
+
+Import statements should always be placed at the top of the file.
+
+Yes:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.4.0 <0.9.0;
+
+ import "./Owned.sol";
+
+ contract A {
+ // ...
+ }
+
+
+ contract B is Owned {
+ // ...
+ }
+
+No:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.4.0 <0.9.0;
+
+ contract A {
+ // ...
+ }
+
+
+ import "./Owned.sol";
+
+
+ contract B is Owned {
+ // ...
+ }
+
+Order of Functions
+==================
+
+Ordering helps readers identify which functions they can call and to find the constructor and fallback definitions easier.
+
+Functions should be grouped according to their visibility and ordered:
+
+- constructor
+- receive function (if exists)
+- fallback function (if exists)
+- external
+- public
+- internal
+- private
+
+Within a grouping, place the ``view`` and ``pure`` functions last.
+
+Yes:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.7.0 <0.9.0;
+ contract A {
+ constructor() {
+ // ...
+ }
+
+ receive() external payable {
+ // ...
+ }
+
+ fallback() external {
+ // ...
+ }
+
+ // External functions
+ // ...
+
+ // External functions that are view
+ // ...
+
+ // External functions that are pure
+ // ...
+
+ // Public functions
+ // ...
+
+ // Internal functions
+ // ...
+
+ // Private functions
+ // ...
+ }
+
+No:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.7.0 <0.9.0;
+ contract A {
+
+ // External functions
+ // ...
+
+ fallback() external {
+ // ...
+ }
+ receive() external payable {
+ // ...
+ }
+
+ // Private functions
+ // ...
+
+ // Public functions
+ // ...
+
+ constructor() {
+ // ...
+ }
+
+ // Internal functions
+ // ...
+ }
+
+Whitespace in Expressions
+=========================
+
+Avoid extraneous whitespace in the following situations:
+
+Immediately inside parenthesis, brackets or braces, with the exception of single line function declarations.
+
+Yes:
+
+.. code-block:: solidity
+
+ spam(ham[1], Coin({name: "ham"}));
+
+No:
+
+.. code-block:: solidity
+
+ spam( ham[ 1 ], Coin( { name: "ham" } ) );
+
+Exception:
+
+.. code-block:: solidity
+
+ function singleLine() public { spam(); }
+
+Immediately before a comma, semicolon:
+
+Yes:
+
+.. code-block:: solidity
+
+ function spam(uint i, Coin coin) public;
+
+No:
+
+.. code-block:: solidity
+
+ function spam(uint i , Coin coin) public ;
+
+More than one space around an assignment or other operator to align with another:
+
+Yes:
+
+.. code-block:: solidity
+
+ x = 1;
+ y = 2;
+ longVariable = 3;
+
+No:
+
+.. code-block:: solidity
+
+ x = 1;
+ y = 2;
+ longVariable = 3;
+
+Don't include a whitespace in the receive and fallback functions:
+
+Yes:
+
+.. code-block:: solidity
+
+ receive() external payable {
+ ...
+ }
+
+ fallback() external {
+ ...
+ }
+
+No:
+
+.. code-block:: solidity
+
+ receive () external payable {
+ ...
+ }
+
+ fallback () external {
+ ...
+ }
+
+
+Control Structures
+==================
+
+The braces denoting the body of a contract, library, functions and structs
+should:
+
+* open on the same line as the declaration
+* close on their own line at the same indentation level as the beginning of the
+ declaration.
+* The opening brace should be preceded by a single space.
+
+Yes:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.4.0 <0.9.0;
+
+ contract Coin {
+ struct Bank {
+ address owner;
+ uint balance;
+ }
+ }
+
+No:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.4.0 <0.9.0;
+
+ contract Coin
+ {
+ struct Bank {
+ address owner;
+ uint balance;
+ }
+ }
+
+The same recommendations apply to the control structures ``if``, ``else``, ``while``,
+and ``for``.
+
+Additionally there should be a single space between the control structures
+``if``, ``while``, and ``for`` and the parenthetic block representing the
+conditional, as well as a single space between the conditional parenthetic
+block and the opening brace.
+
+Yes:
+
+.. code-block:: solidity
+
+ if (...) {
+ ...
+ }
+
+ for (...) {
+ ...
+ }
+
+No:
+
+.. code-block:: solidity
+
+ if (...)
+ {
+ ...
+ }
+
+ while(...){
+ }
+
+ for (...) {
+ ...;}
+
+For control structures whose body contains a single statement, omitting the
+braces is ok *if* the statement is contained on a single line.
+
+Yes:
+
+.. code-block:: solidity
+
+ if (x < 10)
+ x += 1;
+
+No:
+
+.. code-block:: solidity
+
+ if (x < 10)
+ someArray.push(Coin({
+ name: 'spam',
+ value: 42
+ }));
+
+For ``if`` blocks which have an ``else`` or ``else if`` clause, the ``else`` should be
+placed on the same line as the ``if``'s closing brace. This is an exception compared
+to the rules of other block-like structures.
+
+Yes:
+
+.. code-block:: solidity
+
+ if (x < 3) {
+ x += 1;
+ } else if (x > 7) {
+ x -= 1;
+ } else {
+ x = 5;
+ }
+
+
+ if (x < 3)
+ x += 1;
+ else
+ x -= 1;
+
+No:
+
+.. code-block:: solidity
+
+ if (x < 3) {
+ x += 1;
+ }
+ else {
+ x -= 1;
+ }
+
+Function Declaration
+====================
+
+For short function declarations, it is recommended for the opening brace of the
+function body to be kept on the same line as the function declaration.
+
+The closing brace should be at the same indentation level as the function
+declaration.
+
+The opening brace should be preceded by a single space.
+
+Yes:
+
+.. code-block:: solidity
+
+ function increment(uint x) public pure returns (uint) {
+ return x + 1;
+ }
+
+ function increment(uint x) public pure onlyOwner returns (uint) {
+ return x + 1;
+ }
+
+No:
+
+.. code-block:: solidity
+
+ function increment(uint x) public pure returns (uint)
+ {
+ return x + 1;
+ }
+
+ function increment(uint x) public pure returns (uint){
+ return x + 1;
+ }
+
+ function increment(uint x) public pure returns (uint) {
+ return x + 1;
+ }
+
+ function increment(uint x) public pure returns (uint) {
+ return x + 1;}
+
+The modifier order for a function should be:
+
+1. Visibility
+2. Mutability
+3. Virtual
+4. Override
+5. Custom modifiers
+
+Yes:
+
+.. code-block:: solidity
+
+ function balance(uint from) public view override returns (uint) {
+ return balanceOf[from];
+ }
+
+ function shutdown() public onlyOwner {
+ selfdestruct(owner);
+ }
+
+No:
+
+.. code-block:: solidity
+
+ function balance(uint from) public override view returns (uint) {
+ return balanceOf[from];
+ }
+
+ function shutdown() onlyOwner public {
+ selfdestruct(owner);
+ }
+
+For long function declarations, it is recommended to drop each argument onto
+its own line at the same indentation level as the function body. The closing
+parenthesis and opening bracket should be placed on their own line as well at
+the same indentation level as the function declaration.
+
+Yes:
+
+.. code-block:: solidity
+
+ function thisFunctionHasLotsOfArguments(
+ address a,
+ address b,
+ address c,
+ address d,
+ address e,
+ address f
+ )
+ public
+ {
+ doSomething();
+ }
+
+No:
+
+.. code-block:: solidity
+
+ function thisFunctionHasLotsOfArguments(address a, address b, address c,
+ address d, address e, address f) public {
+ doSomething();
+ }
+
+ function thisFunctionHasLotsOfArguments(address a,
+ address b,
+ address c,
+ address d,
+ address e,
+ address f) public {
+ doSomething();
+ }
+
+ function thisFunctionHasLotsOfArguments(
+ address a,
+ address b,
+ address c,
+ address d,
+ address e,
+ address f) public {
+ doSomething();
+ }
+
+If a long function declaration has modifiers, then each modifier should be
+dropped to its own line.
+
+Yes:
+
+.. code-block:: solidity
+
+ function thisFunctionNameIsReallyLong(address x, address y, address z)
+ public
+ onlyOwner
+ priced
+ returns (address)
+ {
+ doSomething();
+ }
+
+ function thisFunctionNameIsReallyLong(
+ address x,
+ address y,
+ address z
+ )
+ public
+ onlyOwner
+ priced
+ returns (address)
+ {
+ doSomething();
+ }
+
+No:
+
+.. code-block:: solidity
+
+ function thisFunctionNameIsReallyLong(address x, address y, address z)
+ public
+ onlyOwner
+ priced
+ returns (address) {
+ doSomething();
+ }
+
+ function thisFunctionNameIsReallyLong(address x, address y, address z)
+ public onlyOwner priced returns (address)
+ {
+ doSomething();
+ }
+
+ function thisFunctionNameIsReallyLong(address x, address y, address z)
+ public
+ onlyOwner
+ priced
+ returns (address) {
+ doSomething();
+ }
+
+Multiline output parameters and return statements should follow the same style recommended for wrapping long lines found in the :ref:`Maximum Line Length ` section.
+
+Yes:
+
+.. code-block:: solidity
+
+ function thisFunctionNameIsReallyLong(
+ address a,
+ address b,
+ address c
+ )
+ public
+ returns (
+ address someAddressName,
+ uint256 LongArgument,
+ uint256 Argument
+ )
+ {
+ doSomething()
+
+ return (
+ veryLongReturnArg1,
+ veryLongReturnArg2,
+ veryLongReturnArg3
+ );
+ }
+
+No:
+
+.. code-block:: solidity
+
+ function thisFunctionNameIsReallyLong(
+ address a,
+ address b,
+ address c
+ )
+ public
+ returns (address someAddressName,
+ uint256 LongArgument,
+ uint256 Argument)
+ {
+ doSomething()
+
+ return (veryLongReturnArg1,
+ veryLongReturnArg1,
+ veryLongReturnArg1);
+ }
+
+For constructor functions on inherited contracts whose bases require arguments,
+it is recommended to drop the base constructors onto new lines in the same
+manner as modifiers if the function declaration is long or hard to read.
+
+Yes:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.7.0 <0.9.0;
+ // Base contracts just to make this compile
+ contract B {
+ constructor(uint) {
+ }
+ }
+
+
+ contract C {
+ constructor(uint, uint) {
+ }
+ }
+
+
+ contract D {
+ constructor(uint) {
+ }
+ }
+
+
+ contract A is B, C, D {
+ uint x;
+
+ constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
+ B(param1)
+ C(param2, param3)
+ D(param4)
+ {
+ // do something with param5
+ x = param5;
+ }
+ }
+
+No:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.7.0 <0.9.0;
+
+ // Base contracts just to make this compile
+ contract B {
+ constructor(uint) {
+ }
+ }
+
+
+ contract C {
+ constructor(uint, uint) {
+ }
+ }
+
+
+ contract D {
+ constructor(uint) {
+ }
+ }
+
+
+ contract A is B, C, D {
+ uint x;
+
+ constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
+ B(param1)
+ C(param2, param3)
+ D(param4) {
+ x = param5;
+ }
+ }
+
+
+ contract X is B, C, D {
+ uint x;
+
+ constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
+ B(param1)
+ C(param2, param3)
+ D(param4) {
+ x = param5;
+ }
+ }
+
+
+When declaring short functions with a single statement, it is permissible to do it on a single line.
+
+Permissible:
+
+.. code-block:: solidity
+
+ function shortFunction() public { doSomething(); }
+
+These guidelines for function declarations are intended to improve readability.
+Authors should use their best judgment as this guide does not try to cover all
+possible permutations for function declarations.
+
+Mappings
+========
+
+In variable declarations, do not separate the keyword ``mapping`` from its
+type by a space. Do not separate any nested ``mapping`` keyword from its type by
+whitespace.
+
+Yes:
+
+.. code-block:: solidity
+
+ mapping(uint => uint) map;
+ mapping(address => bool) registeredAddresses;
+ mapping(uint => mapping(bool => Data[])) public data;
+ mapping(uint => mapping(uint => s)) data;
+
+No:
+
+.. code-block:: solidity
+
+ mapping (uint => uint) map;
+ mapping( address => bool ) registeredAddresses;
+ mapping (uint => mapping (bool => Data[])) public data;
+ mapping(uint => mapping (uint => s)) data;
+
+Variable Declarations
+=====================
+
+Declarations of array variables should not have a space between the type and
+the brackets.
+
+Yes:
+
+.. code-block:: solidity
+
+ uint[] x;
+
+No:
+
+.. code-block:: solidity
+
+ uint [] x;
+
+
+Other Recommendations
+=====================
+
+* Strings should be quoted with double-quotes instead of single-quotes.
+
+Yes:
+
+.. code-block:: solidity
+
+ str = "foo";
+ str = "Hamlet says, 'To be or not to be...'";
+
+No:
+
+.. code-block:: solidity
+
+ str = 'bar';
+ str = '"Be yourself; everyone else is already taken." -Oscar Wilde';
+
+* Surround operators with a single space on either side.
+
+Yes:
+
+.. code-block:: solidity
+ :force:
+
+ x = 3;
+ x = 100 / 10;
+ x += 3 + 4;
+ x |= y && z;
+
+No:
+
+.. code-block:: solidity
+ :force:
+
+ x=3;
+ x = 100/10;
+ x += 3+4;
+ x |= y&&z;
+
+* Operators with a higher priority than others can exclude surrounding
+ whitespace in order to denote precedence. This is meant to allow for
+ improved readability for complex statements. You should always use the same
+ amount of whitespace on either side of an operator:
+
+Yes:
+
+.. code-block:: solidity
+
+ x = 2**3 + 5;
+ x = 2*y + 3*z;
+ x = (a+b) * (a-b);
+
+No:
+
+.. code-block:: solidity
+
+ x = 2** 3 + 5;
+ x = y+z;
+ x +=1;
+
+***************
+Order of Layout
+***************
+
+Layout contract elements in the following order:
+
+1. Pragma statements
+2. Import statements
+3. Interfaces
+4. Libraries
+5. Contracts
+
+Inside each contract, library or interface, use the following order:
+
+1. Type declarations
+2. State variables
+3. Events
+4. Modifiers
+5. Functions
+
+.. note::
+
+ It might be clearer to declare types close to their use in events or state
+ variables.
+
+******************
+Naming Conventions
+******************
+
+Naming conventions are powerful when adopted and used broadly. The use of
+different conventions can convey significant *meta* information that would
+otherwise not be immediately available.
+
+The naming recommendations given here are intended to improve the readability,
+and thus they are not rules, but rather guidelines to try and help convey the
+most information through the names of things.
+
+Lastly, consistency within a codebase should always supersede any conventions
+outlined in this document.
+
+
+Naming Styles
+=============
+
+To avoid confusion, the following names will be used to refer to different
+naming styles.
+
+* ``b`` (single lowercase letter)
+* ``B`` (single uppercase letter)
+* ``lowercase``
+* ``UPPERCASE``
+* ``UPPER_CASE_WITH_UNDERSCORES``
+* ``CapitalizedWords`` (or CapWords)
+* ``mixedCase`` (differs from CapitalizedWords by initial lowercase character!)
+
+.. note:: When using initialisms in CapWords, capitalize all the letters of the initialisms. Thus HTTPServerError is better than HttpServerError. When using initialisms in mixedCase, capitalize all the letters of the initialisms, except keep the first one lower case if it is the beginning of the name. Thus xmlHTTPRequest is better than XMLHTTPRequest.
+
+
+Names to Avoid
+==============
+
+* ``l`` - Lowercase letter el
+* ``O`` - Uppercase letter oh
+* ``I`` - Uppercase letter eye
+
+Never use any of these for single letter variable names. They are often
+indistinguishable from the numerals one and zero.
+
+
+Contract and Library Names
+==========================
+
+* Contracts and libraries should be named using the CapWords style. Examples: ``SimpleToken``, ``SmartBank``, ``CertificateHashRepository``, ``Player``, ``Congress``, ``Owned``.
+* Contract and library names should also match their filenames.
+* If a contract file includes multiple contracts and/or libraries, then the filename should match the *core contract*. This is not recommended however if it can be avoided.
+
+As shown in the example below, if the contract name is ``Congress`` and the library name is ``Owned``, then their associated filenames should be ``Congress.sol`` and ``Owned.sol``.
+
+Yes:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.7.0 <0.9.0;
+
+ // Owned.sol
+ contract Owned {
+ address public owner;
+
+ constructor() {
+ owner = msg.sender;
+ }
+
+ modifier onlyOwner {
+ require(msg.sender == owner);
+ _;
+ }
+
+ function transferOwnership(address newOwner) public onlyOwner {
+ owner = newOwner;
+ }
+ }
+
+and in ``Congress.sol``:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.4.0 <0.9.0;
+
+ import "./Owned.sol";
+
+
+ contract Congress is Owned, TokenRecipient {
+ //...
+ }
+
+No:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.7.0 <0.9.0;
+
+ // owned.sol
+ contract owned {
+ address public owner;
+
+ constructor() {
+ owner = msg.sender;
+ }
+
+ modifier onlyOwner {
+ require(msg.sender == owner);
+ _;
+ }
+
+ function transferOwnership(address newOwner) public onlyOwner {
+ owner = newOwner;
+ }
+ }
+
+and in ``Congress.sol``:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity ^0.7.0;
+
+
+ import "./owned.sol";
+
+
+ contract Congress is owned, tokenRecipient {
+ //...
+ }
+
+Struct Names
+==========================
+
+Structs should be named using the CapWords style. Examples: ``MyCoin``, ``Position``, ``PositionXY``.
+
+
+Event Names
+===========
+
+Events should be named using the CapWords style. Examples: ``Deposit``, ``Transfer``, ``Approval``, ``BeforeTransfer``, ``AfterTransfer``.
+
+
+Function Names
+==============
+
+Functions should use mixedCase. Examples: ``getBalance``, ``transfer``, ``verifyOwner``, ``addMember``, ``changeOwner``.
+
+
+Function Argument Names
+=======================
+
+Function arguments should use mixedCase. Examples: ``initialSupply``, ``account``, ``recipientAddress``, ``senderAddress``, ``newOwner``.
+
+When writing library functions that operate on a custom struct, the struct
+should be the first argument and should always be named ``self``.
+
+
+Local and State Variable Names
+==============================
+
+Use mixedCase. Examples: ``totalSupply``, ``remainingSupply``, ``balancesOf``, ``creatorAddress``, ``isPreSale``, ``tokenExchangeRate``.
+
+
+Constants
+=========
+
+Constants should be named with all capital letters with underscores separating
+words. Examples: ``MAX_BLOCKS``, ``TOKEN_NAME``, ``TOKEN_TICKER``, ``CONTRACT_VERSION``.
+
+
+Modifier Names
+==============
+
+Use mixedCase. Examples: ``onlyBy``, ``onlyAfter``, ``onlyDuringThePreSale``.
+
+
+Enums
+=====
+
+Enums, in the style of simple type declarations, should be named using the CapWords style. Examples: ``TokenGroup``, ``Frame``, ``HashStyle``, ``CharacterLocation``.
+
+
+Avoiding Naming Collisions
+==========================
+
+* ``singleTrailingUnderscore_``
+
+This convention is suggested when the desired name collides with that of
+an existing state variable, function, built-in or otherwise reserved name.
+
+.. _style_guide_natspec:
+
+*******
+NatSpec
+*******
+
+Solidity contracts can also contain NatSpec comments. They are written with a
+triple slash (``///``) or a double asterisk block (``/** ... */``) and
+they should be used directly above function declarations or statements.
+
+For example, the contract from :ref:`a simple smart contract ` with the comments
+added looks like the one below:
+
+.. code-block:: solidity
+
+ // SPDX-License-Identifier: GPL-3.0
+ pragma solidity >=0.4.16 <0.9.0;
+
+ /// @author The Solidity Team
+ /// @title A simple storage example
+ contract SimpleStorage {
+ uint storedData;
+
+ /// Store `x`.
+ /// @param x the new value to store
+ /// @dev stores the number in the state variable `storedData`
+ function set(uint x) public {
+ storedData = x;
+ }
+
+ /// Return the stored value.
+ /// @dev retrieves the value of the state variable `storedData`
+ /// @return the stored value
+ function get() public view returns (uint) {
+ return storedData;
+ }
+ }
+
+It is recommended that Solidity contracts are fully annotated using :ref:`NatSpec ` for all public interfaces (everything in the ABI).
+
+Please see the section about :ref:`NatSpec ` for a detailed explanation.
diff --git a/template.html b/template.html
new file mode 100644
index 0000000..7905752
--- /dev/null
+++ b/template.html
@@ -0,0 +1,62 @@
+
+
+
+
+ <%= data.pageHeadline %> - <%- data.pageTitle %>
+
+
+ <% if (data.externals && data.externals.styles) { %>
+ <% data.externals.styles.forEach(function(content) { %>
+
+ <% }) %>
+ <% } %>
+
+
+
+
+ <% if (data.repositoryUrl) { %>
+
+ <% } %>
+
+
+