diff --git a/.github/workflows/certora-prover.yml b/.github/workflows/certora-prover.yml index 154d00950..c83d54de9 100644 --- a/.github/workflows/certora-prover.yml +++ b/.github/workflows/certora-prover.yml @@ -43,7 +43,7 @@ jobs: java-version: '11' java-package: 'jre' - name: Install certora - run: pip install certora-cli==3.6.8.post3 + run: pip install certora-cli - name: Install solc run: | wget https://github.com/ethereum/solidity/releases/download/v0.8.12/solc-static-linux diff --git a/.gitignore b/.gitignore index e1019104e..92091311f 100644 --- a/.gitignore +++ b/.gitignore @@ -29,4 +29,7 @@ broadcast #script config file # script/M1_deploy.config.json -script/output/M1_deployment_data.json \ No newline at end of file +script/output/M1_deployment_data.json + +# autogenerated docs (you can generate these locally) +/docs/docgen/ \ No newline at end of file diff --git a/CVL2.py b/CVL2.py new file mode 100644 index 000000000..35df1a535 --- /dev/null +++ b/CVL2.py @@ -0,0 +1,287 @@ +#!python3 + +import argparse +import os +import re +from functools import reduce +from itertools import chain +from pathlib import Path +from sys import stderr +from typing import Any, Dict, Optional +from typing import Tuple + +METHOD_NAME_RE = r'(?P[a-zA-Z_][a-zA-Z_0-9.]*)' +sinvoke_re = re.compile(rf'(\bsinvoke\s+{METHOD_NAME_RE})\s*\(') +invoke_re = re.compile(rf'(\binvoke\s+{METHOD_NAME_RE})\s*\(') +# Some funny stuff here in order to properly parse 'if(...foo().selector)' +selector_re = re.compile(rf'[^:]\b{METHOD_NAME_RE}(?=(\s*\([^)]*\)\.selector))') +# Find the start of the methods block. Ignore methods block that may be all on one +# line - this confuses the rest of the script and is not worth it. +methods_block_re = re.compile(r'methods\s*{\s*(?://.*)?$', re.MULTILINE) +method_line_re = re.compile(rf'\s*(?:/\*.*\*/)?\s*(?Pfunction)?\s*(?P{METHOD_NAME_RE}\s*\()') +rule_prefix_re = re.compile(rf'^{METHOD_NAME_RE}+\s*(\([^)]*\))?\s*{{?\s*$') +double_sig = re.compile(rf'sig:{METHOD_NAME_RE}.sig:') + +def fixup_sinvoke(line: str) -> Tuple[str, int]: + matches = sinvoke_re.findall(line) + # stat[] += len(matches) + return (reduce(lambda l, m: l.replace(m[0], f'{m[1]}'), + matches, + line), + len(matches)) + + +def fixup_invoke(line: str) -> Tuple[str, int]: + matches = invoke_re.findall(line) + return (reduce(lambda l, m: l.replace(m[0], f'{m[1]}@withrevert'), + matches, + line), + len(matches)) + + +def fixup_selector_sig(line: str) -> Tuple[str, int]: + matches = selector_re.findall(line) + matches = list(filter(lambda m: m[0] not in ('if', 'require', 'assert'), matches)) + l, n = (reduce(lambda l, m: l.replace(m[0] + m[1], f'sig:{m[0] + m[1]}'), + matches, + line), + len(matches)) + # fix double sig + double_sig_matches = double_sig.findall(l) + for match in double_sig_matches: + l = l.replace(f'sig:{match}.sig:', f'sig:{match}.') + return l, n + + +def fixup_rule_prefix(line: str) -> Tuple[str, int]: + matches = rule_prefix_re.match(line) + if matches and matches['name'] != "methods": + return 'rule ' + line, 1 + return line, 0 + + +def fixup_static_assert(line: str) -> Tuple[str, int]: + if line.lstrip().startswith('static_assert '): + return (line.replace('static_assert', 'assert', 1), 1) + return (line, 0) + + +def fixup_static_require(line: str) -> Tuple[str, int]: + if line.lstrip().startswith('static_require '): + return (line.replace('static_require', 'require', 1), 1) + return (line, 0) + + +def find_invoke_whole(line: str) -> bool: + return 'invoke_whole(' in line + + +def methods_block_add_semicolon(line: str, next_line: Optional[str]) -> Tuple[str, int]: + l, *comment = line.split('//', 1) + l = l.rstrip() + do_nothing = (line, 0) + if not l.lstrip(): + # an empty line + return do_nothing + + if any(l.endswith(s) for s in (';', '=>', '(', '{', '/*', '/**', '*/', ',')): + # this line doesn't need a semicolon + return do_nothing + + if any(w in l.split() for w in ('if', 'else')): + # this is a branching line, skip it + return do_nothing + + if next_line is not None and (next_line.lstrip().startswith("=>") or next_line.lstrip().startswith(')')): + # the method's summary is defined in the next line, don't append a ; + # also if we have a ) in the next line it means we broke lines for the parameters + return do_nothing + + return l + ';' + (f' //{comment[0]}' if comment else ''), 1 + + +def methods_block_prepend_function(line: str) -> Tuple[str, int]: + m = method_line_re.match(line) + if m is not None and m['func'] is None: + return line.replace(m['name_w_paren'], f'function {m["name_w_paren"]}', 1), 1 + return line, 0 + + +def methods_block_add_external_visibility_no_summary(line: str) -> Tuple[str, int]: + m = method_line_re.match(line) + if m is not None and ('=>' not in line or '=> DISPATCHER' in line): + replacables = [' returns ', ' returns(', ' envfree', ' =>', ';'] + for r in replacables: + if r in line: + if all(f' {vis}{r2}' not in line for vis in ('internal', 'external') for r2 in replacables): + line = line.replace(r, f' external{r}') + return line, 1 + return line, 0 + else: + print(f"Unable to add 'external' modifier to {line}") + return line, 0 + + +def methods_block_summary_should_have_wildcard(line: str) -> Tuple[str, int]: + m = method_line_re.match(line) + if m is not None and '=>' in line and '.' not in line and ' internal ' not in line: + line = line.replace("function ", "function _.") + return line, 1 + + return line, 0 + + +def append_semicolons_to_directives(line: str) -> Tuple[str, int]: + if line.lstrip().startswith(('pragma', 'import', 'using', 'use ')) and not line.rstrip().endswith((';', '{')): + line = line.rstrip() + ';' + os.linesep + return line, 1 + return line, 0 + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument('-f', '--files', metavar='FILE', nargs='+', help='list of files to change', type=Path, + default=list()) + parser.add_argument('-d', '--dirs', metavar='DIR', nargs='+', help='the dir to search', type=Path, default=list()) + parser.add_argument('-r', '--recursive', action='store_true', help='if set dirs will be searched recursively') + args = parser.parse_args() + + if not args.dirs and not args.files: + print('No files/dirs specified', file=stderr) + return 1 + if non_existent := list(filter(lambda f: not (f.exists() and f.is_file()), args.files)): + print(f'Cannot find files {non_existent}', file=stderr) + return 1 + if non_existent := list(filter(lambda d: not (d.exists() and d.is_dir()), args.dirs)): + print(f'Cannot find dirs {non_existent}', file=stderr) + return 1 + + spec_files: chain = chain() + for d in args.dirs: + dir_files_unfiltered = (f for f in d.glob(f'{"**/" if args.recursive else ""}*') + if f.suffix in ('.cvl', '.spec')) + dir_files = filter( + lambda fname: not any(p.startswith('.certora_config') for p in fname.parts), + dir_files_unfiltered) + spec_files = chain(spec_files, dir_files) + spec_files = chain(spec_files, args.files) + + sinvoke_str = 'sinvoke foo(...) -> foo(...)' + invoke_str = 'invoke foo(...) -> foo@withrevert(...)' + static_assert_str = 'static_assert -> assert' + static_require_str = 'static_require -> require' + invoke_whole_str = "lines with 'invoke_whole'" + sig_selector_str = "selectors prepended with 'sig:'" + rule_prefix_str = "rule declarations prepended with 'rule'" + semicolon_in_directives_str = "'pragma', 'import', 'using' or 'use' directives appended with ';'" + semicolon_in_methods_str = "lines in 'methods' block appended with ';'" + prepend_function_for_methods_str = "lines in 'methods' block prepended with 'function'" + add_external_visibility_for_non_summary_str = "declarations in 'methods' block with 'external' visibility added" + summary_should_have_wildcard_str = "declarations in 'methods' block with wildcard added" + + stats: Dict[Any, Any] = {} + for fname in spec_files: + print(f"processing {fname}") + stats[fname] = {} + stats[fname][sinvoke_str] = 0 + stats[fname][invoke_str] = 0 + stats[fname][static_assert_str] = 0 + stats[fname][static_require_str] = 0 + stats[fname][sig_selector_str] = 0 + stats[fname][rule_prefix_str] = 0 + stats[fname][invoke_whole_str] = [] + stats[fname][semicolon_in_directives_str] = 0 + stats[fname][semicolon_in_methods_str] = 0 + stats[fname][prepend_function_for_methods_str] = 0 + stats[fname][add_external_visibility_for_non_summary_str] = 0 + stats[fname][summary_should_have_wildcard_str] = 0 + + flines = open(fname).readlines() + for i, l in enumerate(flines): + l, num = fixup_sinvoke(l) + stats[fname][sinvoke_str] += num + + l, num = fixup_invoke(l) + stats[fname][invoke_str] += num + + l, num = fixup_static_assert(l) + stats[fname][static_assert_str] += num + + l, num = fixup_static_require(l) + stats[fname][static_require_str] += num + + l, num = append_semicolons_to_directives(l) + stats[fname][semicolon_in_directives_str] += num + + l, num = fixup_selector_sig(l) + stats[fname][sig_selector_str] += num + flines[i] = l + + l, num = fixup_rule_prefix(l) + stats[fname][rule_prefix_str] += num + flines[i] = l + + with open(fname, 'w') as f: + f.writelines(flines) + + # methods block + contents = open(fname).read() + methods_block_declaration = methods_block_re.search(contents) + if not methods_block_declaration: + print(f"{fname} has no methods block, skipping...") + continue + try: + prev, methods_block = methods_block_re.split(contents) + except ValueError: + print(f"{fname}: Failed to find methods block - more than one 'methods' block found") + continue + + try: + methods_block, rest = re.split(r'^}', methods_block, maxsplit=1, flags=re.MULTILINE) + except ValueError: + print(f"{fname}: Failed to find methods block - couldn't find block end") + continue + + if methods_block.count("{") != methods_block.count("}"): + print(f"{fname}: Failed to find methods block - something went wrong with finding the end of the block") + continue + + # add semicolons in the methods block where it's easy to do so + methods_block = methods_block.split("\n") + for i, l in enumerate(methods_block): + next_line = methods_block[i + 1] if i + 1 < len(methods_block) else None + l, n = methods_block_add_semicolon(l, next_line) + stats[fname][semicolon_in_methods_str] += n + l, n = methods_block_prepend_function(l) + stats[fname][prepend_function_for_methods_str] += n + l, n = methods_block_add_external_visibility_no_summary(l) + stats[fname][add_external_visibility_for_non_summary_str] += n + l, n = methods_block_summary_should_have_wildcard(l) + stats[fname][summary_should_have_wildcard_str] += n + methods_block[i] = l + methods_block = "\n".join(methods_block) + + with open(fname, 'w') as f: + f.write(prev + methods_block_declaration.group(0) + methods_block + '}' + rest) + + print('Change Statistics\n-----------------') + for fname, stat in stats.items(): + if all(not n for n in stat.values()): + continue + print(f'{fname}:') + for s, n in stat.items(): + if not n: + continue + print(f'\t{s}: {n}') + + print("The following files have instances of 'invoke_whole' which need to be removed manually") + for fname in stats: + inv_whole_list = stats[fname][invoke_whole_str] + if not inv_whole_list: + continue + print(f"\t{fname} (line{'s' if len(inv_whole_list) > 1 else ''} {', '.join(str(n) for n in inv_whole_list)})") + return 0 + + +if __name__ == "__main__": + exit(main()) \ No newline at end of file diff --git a/certora/harnesses/SlasherHarness.sol b/certora/harnesses/SlasherHarness.sol index 897393e3e..d17320332 100644 --- a/certora/harnesses/SlasherHarness.sol +++ b/certora/harnesses/SlasherHarness.sol @@ -58,28 +58,28 @@ contract SlasherHarness is Slasher { return (_operatorToWhitelistedContractsByUpdate[operator].list[node][direction]); } - // uses that _HEAD = 0. Similar to StructuredLinkedList.nodeExists but slightly better defined - function nodeDoesExist(address operator, uint256 node) public returns (bool) { - if (get_next_node(operator, node) == 0 && get_previous_node(operator, node) == 0) { - // slightly stricter check than that defined in StructuredLinkedList.nodeExists - if (get_next_node(operator, 0) == node && get_previous_node(operator, 0) == node) { - return true; - } else { - return false; - } - } else { - return true; - } - } - - // uses that _PREV = false, _NEXT = true - function nodeIsWellLinked(address operator, uint256 node) public returns (bool) { - return ( - // node is not linked to itself - get_previous_node(operator, node) != node && get_next_node(operator, node) != node - && - // node is the previous node's next node and the next node's previous node - get_linked_list_entry(operator, get_previous_node(operator, node), true) == node && get_linked_list_entry(operator, get_next_node(operator, node), false) == node - ); - } + // // uses that _HEAD = 0. Similar to StructuredLinkedList.nodeExists but slightly better defined + // function nodeDoesExist(address operator, uint256 node) public returns (bool) { + // if (get_next_node(operator, node) == 0 && get_previous_node(operator, node) == 0) { + // // slightly stricter check than that defined in StructuredLinkedList.nodeExists + // if (get_next_node(operator, 0) == node && get_previous_node(operator, 0) == node) { + // return true; + // } else { + // return false; + // } + // } else { + // return true; + // } + // } + + // // uses that _PREV = false, _NEXT = true + // function nodeIsWellLinked(address operator, uint256 node) public returns (bool) { + // return ( + // // node is not linked to itself + // get_previous_node(operator, node) != node && get_next_node(operator, node) != node + // && + // // node is the previous node's next node and the next node's previous node + // get_linked_list_entry(operator, get_previous_node(operator, node), true) == node && get_linked_list_entry(operator, get_next_node(operator, node), false) == node + // ); + // } } \ No newline at end of file diff --git a/certora/scripts/core/verifyDelegationManager.sh b/certora/scripts/core/verifyDelegationManager.sh index 2906d589a..5834bd09c 100644 --- a/certora/scripts/core/verifyDelegationManager.sh +++ b/certora/scripts/core/verifyDelegationManager.sh @@ -3,6 +3,7 @@ then RULE="--rule $2" fi +solc-select use 0.8.12 certoraRun certora/harnesses/DelegationManagerHarness.sol \ lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol lib/openzeppelin-contracts/contracts/mocks/ERC1271WalletMock.sol \ @@ -11,8 +12,8 @@ certoraRun certora/harnesses/DelegationManagerHarness.sol \ --verify DelegationManagerHarness:certora/specs/core/DelegationManager.spec \ --optimistic_loop \ --send_only \ - --settings -optimisticFallback=true \ + --prover_args '-optimisticFallback true' \ $RULE \ --loop_iter 3 \ --packages @openzeppelin=lib/openzeppelin-contracts @openzeppelin-upgrades=lib/openzeppelin-contracts-upgradeable \ - --msg "DelegationManager $1 $2" \ \ No newline at end of file + --msg "DelegationManager $1 $2" \ diff --git a/certora/scripts/core/verifySlasher.sh b/certora/scripts/core/verifySlasher.sh index c1c53f2b4..a8b40a354 100644 --- a/certora/scripts/core/verifySlasher.sh +++ b/certora/scripts/core/verifySlasher.sh @@ -12,9 +12,9 @@ certoraRun certora/harnesses/SlasherHarness.sol \ --verify SlasherHarness:certora/specs/core/Slasher.spec \ --optimistic_loop \ --send_only \ - --settings -optimisticFallback=true,-recursionErrorAsAssert=false,-recursionEntryLimit=3 \ + --prover_args '-optimisticFallback true -recursionErrorAsAssert false -recursionEntryLimit 3' \ --loop_iter 3 \ --link SlasherHarness:delegation=DelegationManager \ $RULE \ --packages @openzeppelin=lib/openzeppelin-contracts @openzeppelin-upgrades=lib/openzeppelin-contracts-upgradeable \ - --msg "Slasher $1 $2" \ \ No newline at end of file + --msg "Slasher $1 $2" \ diff --git a/certora/scripts/core/verifyStrategyManager.sh b/certora/scripts/core/verifyStrategyManager.sh index 964ac6b77..fe52406c6 100644 --- a/certora/scripts/core/verifyStrategyManager.sh +++ b/certora/scripts/core/verifyStrategyManager.sh @@ -13,9 +13,9 @@ certoraRun certora/harnesses/StrategyManagerHarness.sol \ --verify StrategyManagerHarness:certora/specs/core/StrategyManager.spec \ --optimistic_loop \ --send_only \ - --settings -optimisticFallback=true \ - --settings -optimisticUnboundedHashing=true \ + --prover_args '-optimisticFallback true' \ + --optimistic_hashing \ $RULE \ - --loop_iter 3 \ + --loop_iter 2 \ --packages @openzeppelin=lib/openzeppelin-contracts @openzeppelin-upgrades=lib/openzeppelin-contracts-upgradeable \ - --msg "StrategyManager $1 $2" \ \ No newline at end of file + --msg "StrategyManager $1 $2" \ diff --git a/certora/scripts/libraries/verifyStructuredLinkedList.sh b/certora/scripts/libraries/verifyStructuredLinkedList.sh index 1527d1d87..d343945dc 100644 --- a/certora/scripts/libraries/verifyStructuredLinkedList.sh +++ b/certora/scripts/libraries/verifyStructuredLinkedList.sh @@ -3,12 +3,13 @@ then RULE="--rule $2" fi +solc-select use 0.8.12 certoraRun certora/harnesses/StructuredLinkedListHarness.sol \ --verify StructuredLinkedListHarness:certora/specs/libraries/StructuredLinkedList.spec \ --optimistic_loop \ --send_only \ - --settings -optimisticFallback=true \ + --prover_args '-optimisticFallback true' \ $RULE \ --rule_sanity \ --loop_iter 3 \ diff --git a/certora/scripts/permissions/verifyPausable.sh b/certora/scripts/permissions/verifyPausable.sh index f40cc00be..2203fcc36 100644 --- a/certora/scripts/permissions/verifyPausable.sh +++ b/certora/scripts/permissions/verifyPausable.sh @@ -3,13 +3,14 @@ then RULE="--rule $2" fi +solc-select use 0.8.12 certoraRun certora/harnesses/PausableHarness.sol \ certora/munged/permissions/PauserRegistry.sol \ --verify PausableHarness:certora/specs/permissions/Pausable.spec \ --optimistic_loop \ --send_only \ - --settings -optimisticFallback=true,-recursionErrorAsAssert=false,-recursionEntryLimit=3 \ + --prover_args '-optimisticFallback true -recursionErrorAsAssert false -recursionEntryLimit 3' \ --loop_iter 3 \ --link PausableHarness:pauserRegistry=PauserRegistry \ $RULE \ diff --git a/certora/scripts/strategies/verifyStrategyBase.sh b/certora/scripts/strategies/verifyStrategyBase.sh index 822d08a0f..0e3cadccd 100644 --- a/certora/scripts/strategies/verifyStrategyBase.sh +++ b/certora/scripts/strategies/verifyStrategyBase.sh @@ -3,6 +3,7 @@ then RULE="--rule $2" fi +solc-select use 0.8.12 certoraRun certora/munged/strategies/StrategyBase.sol \ lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol \ @@ -12,7 +13,7 @@ certoraRun certora/munged/strategies/StrategyBase.sol \ --verify StrategyBase:certora/specs/strategies/StrategyBase.spec \ --optimistic_loop \ --send_only \ - --settings -optimisticFallback=true,-recursionErrorAsAssert=false,-recursionEntryLimit=3 \ + --prover_args '-optimisticFallback true -recursionErrorAsAssert false -recursionEntryLimit 3' \ --loop_iter 3 \ --packages @openzeppelin=lib/openzeppelin-contracts @openzeppelin-upgrades=lib/openzeppelin-contracts-upgradeable \ --link StrategyBase:strategyManager=StrategyManager \ diff --git a/certora/specs/core/DelegationManager.spec b/certora/specs/core/DelegationManager.spec index 033a534a6..388ce603b 100644 --- a/certora/specs/core/DelegationManager.spec +++ b/certora/specs/core/DelegationManager.spec @@ -2,53 +2,53 @@ methods { //// External Calls // external calls to DelegationManager - undelegate(address) - decreaseDelegatedShares(address,address[],uint256[]) - increaseDelegatedShares(address,address,uint256) + function undelegate(address) external; + function decreaseDelegatedShares(address,address[],uint256[]) external; + function increaseDelegatedShares(address,address,uint256) external; // external calls to Slasher - isFrozen(address) returns (bool) => DISPATCHER(true) - canWithdraw(address,uint32,uint256) returns (bool) => DISPATCHER(true) + function _.isFrozen(address) external => DISPATCHER(true); + function _.canWithdraw(address,uint32,uint256) external => DISPATCHER(true); // external calls to StrategyManager - getDeposits(address) returns (address[],uint256[]) => DISPATCHER(true) - slasher() returns (address) => DISPATCHER(true) - deposit(address,uint256) returns (uint256) => DISPATCHER(true) - withdraw(address,address,uint256) => DISPATCHER(true) + function _.getDeposits(address) external => DISPATCHER(true); + function _.slasher() external => DISPATCHER(true); + function _.deposit(address,uint256) external => DISPATCHER(true); + function _.withdraw(address,address,uint256) external => DISPATCHER(true); // external calls to EigenPodManager - withdrawBeaconChainETH(address,address,uint256) => DISPATCHER(true) + function _.withdrawBeaconChainETH(address,address,uint256) external => DISPATCHER(true); // external calls to EigenPod - withdrawBeaconChainETH(address,uint256) => DISPATCHER(true) + function _.withdrawBeaconChainETH(address,uint256) external => DISPATCHER(true); // external calls to PauserRegistry - pauser() returns (address) => DISPATCHER(true) - unpauser() returns (address) => DISPATCHER(true) + function _.pauser() external => DISPATCHER(true); + function _.unpauser() external => DISPATCHER(true); // external calls to ERC1271 (can import OpenZeppelin mock implementation) // isValidSignature(bytes32 hash, bytes memory signature) returns (bytes4 magicValue) => DISPATCHER(true) - isValidSignature(bytes32, bytes) returns (bytes4) => DISPATCHER(true) + function _.isValidSignature(bytes32, bytes) external => DISPATCHER(true); //// Harnessed Functions // Harnessed calls - decreaseDelegatedShares(address,address,address,uint256,uint256) + function decreaseDelegatedShares(address,address,address,uint256,uint256) external; // Harmessed getters - get_operatorShares(address,address) returns(uint256) envfree + function get_operatorShares(address,address) external returns (uint256) envfree; //// Summarized Functions - _delegationReceivedHook(address,address,address[],uint256[]) => NONDET - _delegationWithdrawnHook(address,address,address[],uint256[]) => NONDET + function _._delegationReceivedHook(address,address,address[] memory, uint256[] memory) internal => NONDET; + function _._delegationWithdrawnHook(address,address,address[]memory, uint256[] memory) internal => NONDET; //envfree functions - isDelegated(address staker) returns (bool) envfree - isNotDelegated(address staker) returns (bool) envfree - isOperator(address operator) returns (bool) envfree - delegatedTo(address staker) returns (address) envfree - delegationTerms(address operator) returns (address) envfree - operatorShares(address operator, address strategy) returns (uint256) envfree - owner() returns (address) envfree - strategyManager() returns (address) envfree + function isDelegated(address staker) external returns (bool) envfree; + function isNotDelegated(address staker) external returns (bool) envfree; + function isOperator(address operator) external returns (bool) envfree; + function delegatedTo(address staker) external returns (address) envfree; + function delegationTerms(address operator) external returns (address) envfree; + function operatorShares(address operator, address strategy) external returns (uint256) envfree; + function owner() external returns (address) envfree; + function strategyManager() external returns (address) envfree; } /* @@ -133,7 +133,7 @@ rule cannotChangeDelegationWithoutUndelegating(address staker) { method f; env e; // the only way the staker can become undelegated is if `undelegate` is called - if (f.selector == undelegate(address).selector) { + if (f.selector == sig:undelegate(address).selector) { address toUndelegate; undelegate(e, toUndelegate); // either the `strategyManager` called `undelegate` with the argument `staker` (in which can the staker is now undelegated) @@ -160,7 +160,7 @@ rule canOnlyDelegateWithSpecificFunctions(address staker) { // perform arbitrary function call method f; env e; - if (f.selector == delegateTo(address).selector) { + if (f.selector == sig:delegateTo(address).selector) { address operator; delegateTo(e, operator); // we check against operator being the zero address here, since we view being delegated to the zero address as *not* being delegated @@ -169,7 +169,7 @@ rule canOnlyDelegateWithSpecificFunctions(address staker) { } else { assert (isNotDelegated(staker), "staker delegated to inappropriate address?"); } - } else if (f.selector == delegateToBySignature(address, address, uint256, bytes).selector) { + } else if (f.selector == sig:delegateToBySignature(address, address, uint256, bytes).selector) { address toDelegateFrom; address operator; uint256 expiry; @@ -177,7 +177,7 @@ rule canOnlyDelegateWithSpecificFunctions(address staker) { delegateToBySignature(e, toDelegateFrom, operator, expiry, signature); // TODO: this check could be stricter! need to filter when the block timestamp is appropriate for expiry and signature is valid assert (isNotDelegated(staker) || delegatedTo(staker) == operator, "delegateToBySignature bug?"); - } else if (f.selector == registerAsOperator(address).selector) { + } else if (f.selector == sig:registerAsOperator(address).selector) { address delegationTerms; registerAsOperator(e, delegationTerms); if (e.msg.sender == staker && delegationTerms != 0) { diff --git a/certora/specs/core/Slasher.spec b/certora/specs/core/Slasher.spec index 6e7ce1423..8b3397dc2 100644 --- a/certora/specs/core/Slasher.spec +++ b/certora/specs/core/Slasher.spec @@ -2,61 +2,60 @@ methods { //// External Calls // external calls to DelegationManager - undelegate(address) => DISPATCHER(true) - isDelegated(address) returns (bool) => DISPATCHER(true) - delegatedTo(address) returns (address) => DISPATCHER(true) - decreaseDelegatedShares(address,address[],uint256[]) => DISPATCHER(true) - increaseDelegatedShares(address,address,uint256) => DISPATCHER(true) - _delegationReceivedHook(address,address,address[],uint256[]) => NONDET - _delegationWithdrawnHook(address,address,address[],uint256[]) => NONDET + function _.undelegate(address) external => DISPATCHER(true); + function _.isDelegated(address) external => DISPATCHER(true); + function _.delegatedTo(address) external => DISPATCHER(true); + function _.decreaseDelegatedShares(address,address[],uint256[]) external => DISPATCHER(true); + function _.increaseDelegatedShares(address,address,uint256) external => DISPATCHER(true); + function _._delegationReceivedHook(address,address,address[] memory, uint256[] memory) internal => NONDET; + function _._delegationWithdrawnHook(address,address,address[] memory, uint256[] memory) internal => NONDET; // external calls to Slasher - isFrozen(address) returns (bool) envfree - canWithdraw(address,uint32,uint256) returns (bool) + function isFrozen(address) external returns (bool) envfree; + function canWithdraw(address,uint32,uint256) external returns (bool); // external calls to StrategyManager - getDeposits(address) returns (address[],uint256[]) => DISPATCHER(true) - slasher() returns (address) => DISPATCHER(true) - deposit(address,uint256) returns (uint256) => DISPATCHER(true) - withdraw(address,address,uint256) => DISPATCHER(true) + function _.getDeposits(address) external => DISPATCHER(true); + function _.slasher() external => DISPATCHER(true); + function _.deposit(address,uint256) external => DISPATCHER(true); + function _.withdraw(address,address,uint256) external => DISPATCHER(true); // external calls to EigenPodManager - withdrawBeaconChainETH(address,address,uint256) => DISPATCHER(true) + function _.withdrawBeaconChainETH(address,address,uint256) external => DISPATCHER(true); // external calls to EigenPod - withdrawBeaconChainETH(address,uint256) => DISPATCHER(true) + function _.withdrawBeaconChainETH(address,uint256) external => DISPATCHER(true); // external calls to IDelegationTerms - onDelegationWithdrawn(address,address[],uint256[]) => CONSTANT - onDelegationReceived(address,address[],uint256[]) => CONSTANT + function _.onDelegationWithdrawn(address,address[],uint256[]) external => CONSTANT; + function _.onDelegationReceived(address,address[],uint256[]) external => CONSTANT; // external calls to PauserRegistry - pauser() returns (address) => DISPATCHER(true) - unpauser() returns (address) => DISPATCHER(true) + function _.pauser() external => DISPATCHER(true); + function _.unpauser() external => DISPATCHER(true); //// Harnessed Functions // Harnessed calls // Harnessed getters - get_is_operator(address) returns (bool) envfree - get_is_delegated(address) returns (bool) envfree - get_list_exists(address) returns (bool) envfree - get_next_node_exists(address, uint256) returns (bool) envfree - get_next_node(address, uint256) returns (uint256) envfree - get_previous_node_exists(address, uint256) returns (bool) envfree - get_previous_node(address, uint256) returns (uint256) envfree - get_node_exists(address, address) returns (bool) envfree - get_list_head(address) returns (uint256) envfree - get_lastest_update_block_at_node(address, uint256) returns (uint256) envfree - get_lastest_update_block_at_head(address) returns (uint256) envfree - get_linked_list_entry(address operator, uint256 node, bool direction) returns (uint256) envfree + function get_is_operator(address) external returns (bool) envfree; + function get_is_delegated(address) external returns (bool) envfree; + function get_list_exists(address) external returns (bool) envfree; + function get_next_node_exists(address, uint256) external returns (bool) envfree; + function get_next_node(address, uint256) external returns (uint256) envfree; + function get_previous_node_exists(address, uint256) external returns (bool) envfree; + function get_previous_node(address, uint256) external returns (uint256) envfree; + function get_list_head(address) external returns (uint256) envfree; + function get_lastest_update_block_at_node(address, uint256) external returns (uint256) envfree; + function get_lastest_update_block_at_head(address) external returns (uint256) envfree; + function get_linked_list_entry(address operator, uint256 node, bool direction) external returns (uint256) envfree; // nodeDoesExist(address operator, uint256 node) returns (bool) envfree - nodeIsWellLinked(address operator, uint256 node) returns (bool) envfree + //function nodeIsWellLinked(address operator, uint256 node) external returns (bool) envfree; //// Normal Functions - owner() returns(address) envfree - contractCanSlashOperatorUntil(address, address) returns (uint32) envfree - paused(uint8) returns (bool) envfree + function owner() external returns(address) envfree; + function contractCanSlashOperatorUntilBlock(address, address) external returns (uint32) envfree; + function paused(uint8) external returns (bool) envfree; } // uses that _HEAD = 0. Similar to StructuredLinkedList.nodeExists but slightly better defined @@ -92,29 +91,29 @@ rule cantBeUnfrozen(method f) { /* verifies that `contractCanSlashOperatorUntil[operator][contractAddress]` only changes when either: the `operator` themselves calls `allowToSlash` -or +rule or the `contractAddress` calls `recordLastStakeUpdateAndRevokeSlashingAbility` */ rule canOnlyChangecontractCanSlashOperatorUntilWithSpecificFunctions(address operator, address contractAddress) { - uint256 valueBefore = contractCanSlashOperatorUntil(operator, contractAddress); + uint256 valueBefore = contractCanSlashOperatorUntilBlock(operator, contractAddress); // perform arbitrary function call method f; env e; - if (f.selector == recordLastStakeUpdateAndRevokeSlashingAbility(address, uint32).selector) { + if (f.selector == sig:recordLastStakeUpdateAndRevokeSlashingAbility(address, uint32).selector) { address operator2; uint32 serveUntil; recordLastStakeUpdateAndRevokeSlashingAbility(e, operator2, serveUntil); - uint256 valueAfter = contractCanSlashOperatorUntil(operator, contractAddress); + uint256 valueAfter = contractCanSlashOperatorUntilBlock(operator, contractAddress); if (e.msg.sender == contractAddress && operator2 == operator/* TODO: proper check */) { /* TODO: proper check */ assert (true, "failure in recordLastStakeUpdateAndRevokeSlashingAbility"); } else { assert (valueBefore == valueAfter, "bad permissions on recordLastStakeUpdateAndRevokeSlashingAbility?"); } - } else if (f.selector == optIntoSlashing(address).selector) { + } else if (f.selector == sig:optIntoSlashing(address).selector) { address arbitraryContract; optIntoSlashing(e, arbitraryContract); - uint256 valueAfter = contractCanSlashOperatorUntil(operator, contractAddress); + uint256 valueAfter = contractCanSlashOperatorUntilBlock(operator, contractAddress); // uses that the `PAUSED_OPT_INTO_SLASHING` index is 0, as an input to the `paused` function if (e.msg.sender == operator && arbitraryContract == contractAddress && get_is_operator(operator) && !paused(0)) { // uses that `MAX_CAN_SLASH_UNTIL` is equal to max_uint32 @@ -125,7 +124,7 @@ rule canOnlyChangecontractCanSlashOperatorUntilWithSpecificFunctions(address ope } else { calldataarg arg; f(e, arg); - uint256 valueAfter = contractCanSlashOperatorUntil(operator, contractAddress); + uint256 valueAfter = contractCanSlashOperatorUntilBlock(operator, contractAddress); assert(valueBefore == valueAfter, "bondedAfter value changed when it shouldn't have!"); } } diff --git a/certora/specs/core/StrategyManager.spec b/certora/specs/core/StrategyManager.spec index 73ace3bc4..c90dfe07e 100644 --- a/certora/specs/core/StrategyManager.spec +++ b/certora/specs/core/StrategyManager.spec @@ -1,79 +1,79 @@ // to allow calling ERC20 token within this spec -using ERC20 as token +using ERC20 as token; methods { //// External Calls // external calls to DelegationManager - undelegate(address) => DISPATCHER(true) - isDelegated(address) returns (bool) => DISPATCHER(true) - delegatedTo(address) returns (address) => DISPATCHER(true) - decreaseDelegatedShares(address,address[],uint256[]) => DISPATCHER(true) - increaseDelegatedShares(address,address,uint256) => DISPATCHER(true) - _delegationReceivedHook(address,address,address[],uint256[]) => NONDET - _delegationWithdrawnHook(address,address,address[],uint256[]) => NONDET + function _.undelegate(address) external => DISPATCHER(true); + function _.isDelegated(address) external => DISPATCHER(true); + function _.delegatedTo(address) external => DISPATCHER(true); + function _.decreaseDelegatedShares(address,address[],uint256[]) external => DISPATCHER(true); + function _.increaseDelegatedShares(address,address,uint256) external => DISPATCHER(true); + function _._delegationReceivedHook(address,address,address[] memory,uint256[] memory) internal => NONDET; + function _._delegationWithdrawnHook(address,address,address[] memory,uint256[] memory) internal => NONDET; // external calls to Slasher - isFrozen(address) returns (bool) => DISPATCHER(true) - canWithdraw(address,uint32,uint256) returns (bool) => DISPATCHER(true) + function _.isFrozen(address) external => DISPATCHER(true); + function _.canWithdraw(address,uint32,uint256) external => DISPATCHER(true); // external calls to StrategyManager - getDeposits(address) returns (address[],uint256[]) - slasher() returns (address) - deposit(address,uint256) returns (uint256) - withdraw(address,address,uint256) + function _.getDeposits(address) external; + function _.slasher() external; + function _.deposit(address,uint256) external; + function _.withdraw(address,address,uint256) external; // external calls to Strategy - deposit(address, uint256) returns (uint256) => DISPATCHER(true) - withdraw(address, address, uint256) => DISPATCHER(true) - totalShares() => DISPATCHER(true) + function _.deposit(address, uint256) external => DISPATCHER(true); + function _.withdraw(address, address, uint256) external => DISPATCHER(true); + function _.totalShares() external => DISPATCHER(true); // external calls to EigenPodManager - withdrawRestakedBeaconChainETH(address,address,uint256) => DISPATCHER(true) + function _.withdrawRestakedBeaconChainETH(address,address,uint256) external => DISPATCHER(true); // call made to EigenPodManager by DelayedWithdrawalRouter - getPod(address) => DISPATCHER(true) + function _.getPod(address) external => DISPATCHER(true); // external calls to EigenPod (from EigenPodManager) - withdrawRestakedBeaconChainETH(address, uint256) => DISPATCHER(true) + function _.withdrawRestakedBeaconChainETH(address, uint256) external => DISPATCHER(true); // external calls to DelayedWithdrawalRouter (from EigenPod) - createDelayedWithdrawal(address, address) => DISPATCHER(true) + function _.createDelayedWithdrawal(address, address) external => DISPATCHER(true); // external calls to IDelegationTerms - onDelegationWithdrawn(address,address[],uint256[]) => CONSTANT - onDelegationReceived(address,address[],uint256[]) => CONSTANT + function _.onDelegationWithdrawn(address,address[],uint256[]) external => CONSTANT; + function _.onDelegationReceived(address,address[],uint256[]) external => CONSTANT; // external calls to PauserRegistry - pauser() returns (address) => DISPATCHER(true) - unpauser() returns (address) => DISPATCHER(true) + function _.pauser() external => DISPATCHER(true); + function _.unpauser() external => DISPATCHER(true); // external calls to ERC20 - balanceOf(address) returns (uint256) => DISPATCHER(true) - transfer(address, uint256) returns (bool) => DISPATCHER(true) - transferFrom(address, address, uint256) returns (bool) => DISPATCHER(true) + function _.balanceOf(address) external => DISPATCHER(true); + function _.transfer(address, uint256) external => DISPATCHER(true); + function _.transferFrom(address, address, uint256) external => DISPATCHER(true); // calls to ERC20 in this spec - token.balanceOf(address) returns(uint256) envfree + function token.balanceOf(address) external returns(uint256) envfree; // external calls to ERC1271 (can import OpenZeppelin mock implementation) // isValidSignature(bytes32 hash, bytes memory signature) returns (bytes4 magicValue) => DISPATCHER(true) - isValidSignature(bytes32, bytes) returns (bytes4) => DISPATCHER(true) + function _.isValidSignature(bytes32, bytes) external => DISPATCHER(true); //// Harnessed Functions // Harnessed calls // Harnessed getters - strategy_is_in_stakers_array(address, address) returns (bool) envfree - num_times_strategy_is_in_stakers_array(address, address) returns (uint256) envfree - totalShares(address) returns (uint256) envfree + function strategy_is_in_stakers_array(address, address) external returns (bool) envfree; + function num_times_strategy_is_in_stakers_array(address, address) external returns (uint256) envfree; + function totalShares(address) external returns (uint256) envfree; //// Normal Functions - stakerStrategyListLength(address) returns (uint256) envfree - stakerStrategyList(address, uint256) returns (address) envfree - stakerStrategyShares(address, address) returns (uint256) envfree - array_exhibits_properties(address) returns (bool) envfree + function stakerStrategyListLength(address) external returns (uint256) envfree; + function stakerStrategyList(address, uint256) external returns (address) envfree; + function stakerStrategyShares(address, address) external returns (uint256) envfree; + function array_exhibits_properties(address) external returns (bool) envfree; } invariant stakerStrategyListLengthLessThanOrEqualToMax(address staker) - stakerStrategyListLength(staker) <= 32 + stakerStrategyListLength(staker) <= 32; // verifies that strategies in the staker's array of strategies are not duplicated, and that the staker has nonzero shares in each one invariant arrayExhibitsProperties(address staker) @@ -87,7 +87,7 @@ invariant arrayExhibitsProperties(address staker) // if a strategy is *not* in staker's array of strategies, then the staker should have precisely zero shares in that strategy invariant strategiesNotInArrayHaveZeroShares(address staker, uint256 index) - (index >= stakerStrategyListLength(staker)) => (stakerStrategyShares(staker, stakerStrategyList(staker, index)) == 0) + (index >= stakerStrategyListLength(staker)) => (stakerStrategyShares(staker, stakerStrategyList(staker, index)) == 0); /** * a staker's amount of shares in a strategy (i.e. `stakerStrategyShares[staker][strategy]`) should only increase when @@ -95,22 +95,22 @@ invariant strategiesNotInArrayHaveZeroShares(address staker, uint256 index) * *OR* when completing a withdrawal */ definition methodCanIncreaseShares(method f) returns bool = - f.selector == depositIntoStrategy(address,address,uint256).selector - || f.selector == depositIntoStrategyWithSignature(address,address,uint256,address,uint256,bytes).selector - || f.selector == depositBeaconChainETH(address,uint256).selector - || f.selector == completeQueuedWithdrawal((address[],uint256[],address,(address,uint96),uint32,address),address[],uint256,bool).selector; - // || f.selector == slashQueuedWithdrawal(address,bytes,address[],uint256[]).selector - // || f.selector == slashShares(address,address,address[],address[],uint256[],uint256[]).selector; + f.selector == sig:depositIntoStrategy(address,address,uint256).selector + || f.selector == sig:depositIntoStrategyWithSignature(address,address,uint256,address,uint256,bytes).selector + || f.selector == sig:depositBeaconChainETH(address,uint256).selector + || f.selector == sig:completeQueuedWithdrawal(IStrategyManager.QueuedWithdrawal,address[],uint256,bool).selector; + // || f.selector == sig:slashQueuedWithdrawal(address,bytes,address[],uint256[]).selector + // || f.selector == sig:slashShares(address,address,address[],address[],uint256[],uint256[]).selector; /** * a staker's amount of shares in a strategy (i.e. `stakerStrategyShares[staker][strategy]`) should only decrease when * `queueWithdrawal`, `slashShares`, or `recordOvercommittedBeaconChainETH` has been called */ definition methodCanDecreaseShares(method f) returns bool = - f.selector == queueWithdrawal(uint256[],address[],uint256[],address,bool).selector - || f.selector == slashShares(address,address,address[],address[],uint256[],uint256[]).selector - || f.selector == slashSharesSinglet(address,address,address,address,uint256,uint256).selector - || f.selector == recordOvercommittedBeaconChainETH(address,uint256,uint256).selector; + f.selector == sig:queueWithdrawal(uint256[],address[],uint256[],address,bool).selector + || f.selector == sig:slashShares(address,address,address[],address[],uint256[],uint256[]).selector + || f.selector == sig:slashSharesSinglet(address,address,address,address,uint256,uint256).selector + || f.selector == sig:recordOvercommittedBeaconChainETH(address,uint256,uint256).selector; rule sharesAmountsChangeOnlyWhenAppropriateFunctionsCalled(address staker, address strategy) { uint256 sharesBefore = stakerStrategyShares(staker, strategy); @@ -139,7 +139,7 @@ hook Sstore stakerStrategyShares[KEY address staker][KEY address strategy] uint2 * only later is `totalShares` decremented (when `completeQueuedWithdrawal` is called). */ invariant totalSharesGeqSumOfShares(address strategy) - totalShares(strategy) >= sumOfSharesInStrategy[strategy] + to_mathint(totalShares(strategy)) >= sumOfSharesInStrategy[strategy] // preserved block since does not apply for 'beaconChainETH' { preserved { // 0xbeaC0eeEeeeeEEeEeEEEEeeEEeEeeeEeeEEBEaC0 converted to decimal (this is the address of the virtual 'beaconChainETH' strategy) @@ -159,8 +159,8 @@ rule safeApprovalUse(address user) { calldataarg args; // need special case for `slashShares` function since otherwise this rule fails by making the user address one of the slashed strategy(s) if ( - f.selector == slashShares(address,address,address[],address[],uint256[],uint256[]).selector - || f.selector == slashSharesSinglet(address,address,address,address,uint256,uint256).selector + f.selector == sig:slashShares(address,address,address[],address[],uint256[],uint256[]).selector + || f.selector == sig:slashSharesSinglet(address,address,address,address,uint256,uint256).selector ) { address slashedAddress; address recipient; diff --git a/certora/specs/libraries/StructuredLinkedList.spec b/certora/specs/libraries/StructuredLinkedList.spec index 12a58f443..c4d22cd16 100644 --- a/certora/specs/libraries/StructuredLinkedList.spec +++ b/certora/specs/libraries/StructuredLinkedList.spec @@ -1,15 +1,15 @@ methods { - listExists() returns (bool) envfree - nodeExists(uint256) returns (bool) envfree - sizeOf() returns (uint256) envfree - getHead() returns (uint256) envfree - getNode(uint256) returns (bool, uint256, uint256) envfree - getAdjacent(uint256,bool) returns (bool, uint256) envfree - getAdjacentStrict(uint256,bool) returns (uint256) envfree - getNextNode(uint256) returns (bool, uint256) envfree - getPreviousNode(uint256) returns (bool, uint256) envfree - insert(uint256,uint256,bool) envfree - remove(uint256) envfree + function listExists() external returns (bool) envfree; + function nodeExists(uint256) external returns (bool) envfree; + function sizeOf() external returns (uint256) envfree; + function getHead() external returns (uint256) envfree; + function getNode(uint256) external returns (bool, uint256, uint256) envfree; + function getAdjacent(uint256,bool) external returns (bool, uint256) envfree; + function getAdjacentStrict(uint256,bool) external returns (uint256) envfree; + function getNextNode(uint256) external returns (bool, uint256) envfree; + function getPreviousNode(uint256) external returns (bool, uint256) envfree; + function insert(uint256,uint256,bool) external envfree; + function remove(uint256) external envfree; } ghost mapping(uint256 => bool) connectsToHead { @@ -168,7 +168,7 @@ function safeAssumptions() { invariant zeroEmpty() isEmpty(0) - filtered { f -> f.selector != insertSorted(address, uint256, uint256).selector } + filtered { f -> f.selector != sig:insertSorted(address, uint256, uint256).selector } rule zeroEmptyPreservedInsertSorted(address _id, uint256 _value) { address prev; @@ -198,7 +198,7 @@ invariant headWellFormed() invariant tailWellFormed() isTailWellFormed() - filtered { f -> f.selector != insertSorted(address, uint256, uint256).selector } + filtered { f -> f.selector != sig:insertSorted(address, uint256, uint256).selector } { preserved remove(address _id) { requireInvariant zeroEmpty(); requireInvariant twoWayLinked(getPrev(_id), _id); @@ -235,7 +235,7 @@ invariant tipsZero() invariant noPrevIsHead(address addr) hasNoPrevIsHead(addr) - filtered { f -> f.selector != insertSorted(address, uint256, uint256).selector } + filtered { f -> f.selector != sig:insertSorted(address, uint256, uint256).selector } { preserved remove(address _id) { safeAssumptions(); requireInvariant twoWayLinked(_id, getNext(_id)); @@ -264,7 +264,7 @@ rule noPrevIsHeadPreservedInsertSorted(address _id, uint256 _value) { invariant noNextIsTail(address addr) hasNoNextIsTail(addr) - filtered { f -> f.selector != insertSorted(address, uint256, uint256).selector } + filtered { f -> f.selector != sig:insertSorted(address, uint256, uint256).selector } { preserved remove(address _id) { safeAssumptions(); requireInvariant twoWayLinked(_id, getNext(_id)); @@ -293,7 +293,7 @@ rule noNextisTailPreservedInsertSorted(address _id, uint256 _value) { invariant linkedIsInDLL(address addr) isLinked(addr) => isInDLL(addr) - filtered { f -> f.selector != insertSorted(address, uint256, uint256).selector } + filtered { f -> f.selector != sig:insertSorted(address, uint256, uint256).selector } { preserved remove(address _id) { safeAssumptions(); requireInvariant twoWayLinked(_id, getNext(_id)); @@ -323,7 +323,7 @@ rule linkedIsInDllPreservedInsertSorted(address _id, uint256 _value) { invariant twoWayLinked(address first, address second) isTwoWayLinked(first, second) - filtered { f -> f.selector != insertSorted(address, uint256, uint256).selector } + filtered { f -> f.selector != sig:insertSorted(address, uint256, uint256).selector } { preserved remove(address _id) { safeAssumptions(); requireInvariant twoWayLinked(getPrev(_id), _id); @@ -349,8 +349,8 @@ rule twoWayLinkedPreservedInsertSorted(address _id, uint256 _value) { invariant forwardLinked(address addr) isInDLL(addr) => isForwardLinkedBetween(getHead(), addr) - filtered { f -> f.selector != remove(address).selector && - f.selector != insertSorted(address, uint256, uint256).selector } + filtered { f -> f.selector != sig:remove(address).selector && + f.selector != sig:insertSorted(address, uint256, uint256).selector } rule forwardLinkedPreservedInsertSorted(address _id, uint256 _value) { address addr; address prev; diff --git a/certora/specs/permissions/Pausable.spec b/certora/specs/permissions/Pausable.spec index 9d57d4ffb..fd0137927 100644 --- a/certora/specs/permissions/Pausable.spec +++ b/certora/specs/permissions/Pausable.spec @@ -1,29 +1,27 @@ methods { // external calls to PauserRegistry - isPauser(address) returns (bool) => DISPATCHER(true) - unpauser() returns (address) => DISPATCHER(true) + function _.pauser() external => DISPATCHER(true); + function _.unpauser() external => DISPATCHER(true); // envfree functions - paused() returns (uint256) envfree - paused(uint8 index) returns (bool) envfree - pauserRegistry() returns (address) envfree + function paused() external returns (uint256) envfree; + function paused(uint8 index) external returns (bool) envfree; + function pauserRegistry() external returns (address) envfree; // harnessed functions - isPauser(address) returns (bool) envfree - unpauser() returns (address) envfree - bitwise_not(uint256) returns (uint256) envfree - bitwise_and(uint256, uint256) returns (uint256) envfree + function isPauser(address) external returns (bool) envfree; + function unpauser() external returns (address) envfree; + function bitwise_not(uint256) external returns (uint256) envfree; + function bitwise_and(uint256, uint256) external returns (uint256) envfree; } rule onlyPauserCanPauseAndOnlyUnpauserCanUnpause() { method f; env e; uint256 pausedStatusBefore = paused(); - address pauser; - require(isPauser(pauser)); address unpauser = unpauser(); - if (f.selector == pause(uint256).selector) { + if (f.selector == sig:pause(uint256).selector) { uint256 newPausedStatus; pause(e, newPausedStatus); uint256 pausedStatusAfter = paused(); @@ -32,7 +30,7 @@ rule onlyPauserCanPauseAndOnlyUnpauserCanUnpause() { } else { assert(pausedStatusAfter == pausedStatusBefore, "pausedStatusAfter != pausedStatusBefore"); } - } else if (f.selector == pauseAll().selector) { + } else if (f.selector == sig:pauseAll().selector) { pauseAll(e); uint256 pausedStatusAfter = paused(); if (isPauser(e.msg.sender)) { @@ -42,7 +40,7 @@ rule onlyPauserCanPauseAndOnlyUnpauserCanUnpause() { } else { assert(pausedStatusAfter == pausedStatusBefore, "pausedStatusAfter != pausedStatusBefore"); } - } else if (f.selector == unpause(uint256).selector) { + } else if (f.selector == sig:unpause(uint256).selector) { uint256 newPausedStatus; unpause(e, newPausedStatus); uint256 pausedStatusAfter = paused(); diff --git a/certora/specs/strategies/StrategyBase.spec b/certora/specs/strategies/StrategyBase.spec index fc0110687..e33fbf86e 100644 --- a/certora/specs/strategies/StrategyBase.spec +++ b/certora/specs/strategies/StrategyBase.spec @@ -1,29 +1,29 @@ -using StrategyManager as strategyManager +using StrategyManager as strategyManager; methods { // external calls to StrategyManager - stakerStrategyShares(address, address) returns (uint256) => DISPATCHER(true) + function _.stakerStrategyShares(address, address) external => DISPATCHER(true); // external calls to PauserRegistry - pauser() returns (address) => DISPATCHER(true) - unpauser() returns (address) => DISPATCHER(true) + function _.pauser() external => DISPATCHER(true); + function _.unpauser() external => DISPATCHER(true); // external calls to ERC20 - balanceOf(address) returns (uint256) => DISPATCHER(true) - transfer(address, uint256) returns (bool) => DISPATCHER(true) - transferFrom(address, address, uint256) returns (bool) => DISPATCHER(true) + function _.balanceOf(address) external => DISPATCHER(true); + function _.transfer(address, uint256) external => DISPATCHER(true); + function _.transferFrom(address, address, uint256) external => DISPATCHER(true); // external calls from StrategyManager to Slasher - isFrozen(address) returns (bool) => DISPATCHER(true) - canWithdraw(address,uint32,uint256) returns (bool) => DISPATCHER(true) + function _.isFrozen(address) external => DISPATCHER(true); + function _.canWithdraw(address,uint32,uint256) external => DISPATCHER(true); // envfree functions - totalShares() returns (uint256) envfree - underlyingToken() returns (address) envfree - sharesToUnderlyingView(uint256) returns (uint256) envfree - sharesToUnderlying(uint256) returns (uint256) envfree - underlyingToSharesView(uint256) returns (uint256) envfree - underlyingToShares(uint256) returns (uint256) envfree - shares(address) returns (uint256) envfree + function totalShares() external returns (uint256) envfree; + function underlyingToken() external returns (address) envfree; + function sharesToUnderlyingView(uint256) external returns (uint256) envfree; + function sharesToUnderlying(uint256) external returns (uint256) envfree; + function underlyingToSharesView(uint256) external returns (uint256) envfree; + function underlyingToShares(uint256) external returns (uint256) envfree; + function shares(address) external returns (uint256) envfree; } // // idea based on OpenZeppelin invariant -- see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/formal-verification/certora/specs/ERC20.spec#L8-L22 diff --git a/docs/docgen/core/DelegationManager.md b/docs/docgen/core/DelegationManager.md deleted file mode 100644 index a397526f8..000000000 --- a/docs/docgen/core/DelegationManager.md +++ /dev/null @@ -1,208 +0,0 @@ -# Solidity API - -## DelegationManager - -This is the contract for delegation in EigenLayer. The main functionalities of this contract are -- enabling anyone to register as an operator in EigenLayer -- allowing new operators to provide a DelegationTerms-type contract, which may mediate their interactions with stakers who delegate to them -- enabling any staker to delegate its stake to the operator of its choice -- enabling a staker to undelegate its assets from an operator (performed as part of the withdrawal process, initiated through the StrategyManager) - -### PAUSED_NEW_DELEGATION - -```solidity -uint8 PAUSED_NEW_DELEGATION -``` - -### ERC1271_MAGICVALUE - -```solidity -bytes4 ERC1271_MAGICVALUE -``` - -### ORIGINAL_CHAIN_ID - -```solidity -uint256 ORIGINAL_CHAIN_ID -``` - -### onlyStrategyManager - -```solidity -modifier onlyStrategyManager() -``` - -Simple permission for functions that are only callable by the StrategyManager contract. - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager, contract ISlasher _slasher) public -``` - -### OnDelegationReceivedCallFailure - -```solidity -event OnDelegationReceivedCallFailure(contract IDelegationTerms delegationTerms, bytes32 returnData) -``` - -_Emitted when a low-level call to `delegationTerms.onDelegationReceived` fails, returning `returnData`_ - -### OnDelegationWithdrawnCallFailure - -```solidity -event OnDelegationWithdrawnCallFailure(contract IDelegationTerms delegationTerms, bytes32 returnData) -``` - -_Emitted when a low-level call to `delegationTerms.onDelegationWithdrawn` fails, returning `returnData`_ - -### RegisterAsOperator - -```solidity -event RegisterAsOperator(address operator, contract IDelegationTerms delegationTerms) -``` - -_Emitted when an entity registers itself as an operator in the DelegationManager_ - -### initialize - -```solidity -function initialize(address initialOwner, contract IPauserRegistry _pauserRegistry, uint256 initialPausedStatus) external -``` - -### registerAsOperator - -```solidity -function registerAsOperator(contract IDelegationTerms dt) external -``` - -This will be called by an operator to register itself as an operator that stakers can choose to delegate to. - -_An operator can set `dt` equal to their own address (or another EOA address), in the event that they want to split payments -in a more 'trustful' manner. -In the present design, once set, there is no way for an operator to ever modify the address of their DelegationTerms contract._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| dt | contract IDelegationTerms | is the `DelegationTerms` contract that the operator has for those who delegate to them. | - -### delegateTo - -```solidity -function delegateTo(address operator) external -``` - -@notice This will be called by a staker to delegate its assets to some operator. - @param operator is the operator to whom staker (msg.sender) is delegating its assets - -### delegateToBySignature - -```solidity -function delegateToBySignature(address staker, address operator, uint256 expiry, bytes signature) external -``` - -Delegates from `staker` to `operator`. - -_requires that: -1) if `staker` is an EOA, then `signature` is valid ECDSA signature from `staker`, indicating their intention for this action -2) if `staker` is a contract, then `signature` must will be checked according to EIP-1271_ - -### undelegate - -```solidity -function undelegate(address staker) external -``` - -Undelegates `staker` from the operator who they are delegated to. -Callable only by the StrategyManager - -_Should only ever be called in the event that the `staker` has no active deposits in EigenLayer._ - -### increaseDelegatedShares - -```solidity -function increaseDelegatedShares(address staker, contract IStrategy strategy, uint256 shares) external -``` - -Increases the `staker`'s delegated shares in `strategy` by `shares, typically called when the staker has further deposits into EigenLayer - -_Callable only by the StrategyManager_ - -### decreaseDelegatedShares - -```solidity -function decreaseDelegatedShares(address staker, contract IStrategy[] strategies, uint256[] shares) external -``` - -Decreases the `staker`'s delegated shares in each entry of `strategies` by its respective `shares[i]`, typically called when the staker withdraws from EigenLayer - -_Callable only by the StrategyManager_ - -### _delegationReceivedHook - -```solidity -function _delegationReceivedHook(contract IDelegationTerms dt, address staker, contract IStrategy[] strategies, uint256[] shares) internal -``` - -Makes a low-level call to `dt.onDelegationReceived(staker, strategies, shares)`, ignoring reverts and with a gas budget -equal to `LOW_LEVEL_GAS_BUDGET` (a constant defined in this contract). - -_*If* the low-level call fails, then this function emits the event `OnDelegationReceivedCallFailure(dt, returnData)`, where -`returnData` is *only the first 32 bytes* returned by the call to `dt`._ - -### _delegationWithdrawnHook - -```solidity -function _delegationWithdrawnHook(contract IDelegationTerms dt, address staker, contract IStrategy[] strategies, uint256[] shares) internal -``` - -Makes a low-level call to `dt.onDelegationWithdrawn(staker, strategies, shares)`, ignoring reverts and with a gas budget -equal to `LOW_LEVEL_GAS_BUDGET` (a constant defined in this contract). - -_*If* the low-level call fails, then this function emits the event `OnDelegationReceivedCallFailure(dt, returnData)`, where -`returnData` is *only the first 32 bytes* returned by the call to `dt`._ - -### _delegate - -```solidity -function _delegate(address staker, address operator) internal -``` - -Internal function implementing the delegation *from* `staker` *to* `operator`. - -_Ensures that the operator has registered as a delegate (`address(dt) != address(0)`), verifies that `staker` is not already -delegated, and records the new delegation._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| staker | address | The address to delegate *from* -- this address is delegating control of its own assets. | -| operator | address | The address to delegate *to* -- this address is being given power to place the `staker`'s assets at risk on services | - -### isDelegated - -```solidity -function isDelegated(address staker) public view returns (bool) -``` - -Returns 'true' if `staker` *is* actively delegated, and 'false' otherwise. - -### isNotDelegated - -```solidity -function isNotDelegated(address staker) public view returns (bool) -``` - -Returns 'true' if `staker` is *not* actively delegated, and 'false' otherwise. - -### isOperator - -```solidity -function isOperator(address operator) public view returns (bool) -``` - -Returns if an operator can be delegated to, i.e. it has called `registerAsOperator`. - diff --git a/docs/docgen/core/DelegationManagerStorage.md b/docs/docgen/core/DelegationManagerStorage.md deleted file mode 100644 index 58b0fe0f9..000000000 --- a/docs/docgen/core/DelegationManagerStorage.md +++ /dev/null @@ -1,102 +0,0 @@ -# Solidity API - -## DelegationManagerStorage - -This storage contract is separate from the logic to simplify the upgrade process. - -### LOW_LEVEL_GAS_BUDGET - -```solidity -uint256 LOW_LEVEL_GAS_BUDGET -``` - -Gas budget provided in calls to DelegationTerms contracts - -### DOMAIN_TYPEHASH - -```solidity -bytes32 DOMAIN_TYPEHASH -``` - -The EIP-712 typehash for the contract's domain - -### DELEGATION_TYPEHASH - -```solidity -bytes32 DELEGATION_TYPEHASH -``` - -The EIP-712 typehash for the delegation struct used by the contract - -### DOMAIN_SEPARATOR - -```solidity -bytes32 DOMAIN_SEPARATOR -``` - -EIP-712 Domain separator - -### strategyManager - -```solidity -contract IStrategyManager strategyManager -``` - -The StrategyManager contract for EigenLayer - -### slasher - -```solidity -contract ISlasher slasher -``` - -The Slasher contract for EigenLayer - -### operatorShares - -```solidity -mapping(address => mapping(contract IStrategy => uint256)) operatorShares -``` - -Mapping: operator => strategy => total number of shares in the strategy delegated to the operator - -### delegationTerms - -```solidity -mapping(address => contract IDelegationTerms) delegationTerms -``` - -Mapping: operator => delegation terms contract - -### delegatedTo - -```solidity -mapping(address => address) delegatedTo -``` - -Mapping: staker => operator whom the staker has delegated to - -### nonces - -```solidity -mapping(address => uint256) nonces -``` - -Mapping: delegator => number of signed delegation nonce (used in delegateToBySignature) - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager, contract ISlasher _slasher) internal -``` - -### __gap - -```solidity -uint256[46] __gap -``` - -_This empty reserved space is put in place to allow future versions to add new -variables without shifting down storage in the inheritance chain. -See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps_ - diff --git a/docs/docgen/core/Slasher.md b/docs/docgen/core/Slasher.md deleted file mode 100644 index 8fa9dd3ae..000000000 --- a/docs/docgen/core/Slasher.md +++ /dev/null @@ -1,470 +0,0 @@ -# Solidity API - -## Slasher - -This contract specifies details on slashing. The functionalities are: -- adding contracts who have permission to perform slashing, -- revoking permission for slashing from specified contracts, -- tracking historic stake updates to ensure that withdrawals can only be completed once no middlewares have slashing rights -over the funds being withdrawn - -### HEAD - -```solidity -uint256 HEAD -``` - -### PAUSED_OPT_INTO_SLASHING - -```solidity -uint8 PAUSED_OPT_INTO_SLASHING -``` - -### PAUSED_FIRST_STAKE_UPDATE - -```solidity -uint8 PAUSED_FIRST_STAKE_UPDATE -``` - -### PAUSED_NEW_FREEZING - -```solidity -uint8 PAUSED_NEW_FREEZING -``` - -### strategyManager - -```solidity -contract IStrategyManager strategyManager -``` - -The central StrategyManager contract of EigenLayer - -### delegation - -```solidity -contract IDelegationManager delegation -``` - -The DelegationManager contract of EigenLayer - -### _whitelistedContractDetails - -```solidity -mapping(address => mapping(address => struct ISlasher.MiddlewareDetails)) _whitelistedContractDetails -``` - -### frozenStatus - -```solidity -mapping(address => bool) frozenStatus -``` - -### MAX_CAN_SLASH_UNTIL - -```solidity -uint32 MAX_CAN_SLASH_UNTIL -``` - -### _operatorToWhitelistedContractsByUpdate - -```solidity -mapping(address => struct StructuredLinkedList.List) _operatorToWhitelistedContractsByUpdate -``` - -operator => a linked list of the addresses of the whitelisted middleware with permission to slash the operator, i.e. which -the operator is serving. Sorted by the block at which they were last updated (content of updates below) in ascending order. -This means the 'HEAD' (i.e. start) of the linked list will have the stalest 'updateBlock' value. - -### _operatorToMiddlewareTimes - -```solidity -mapping(address => struct ISlasher.MiddlewareTimes[]) _operatorToMiddlewareTimes -``` - -operator => - [ - ( - the least recent update block of all of the middlewares it's serving/served, - latest time that the stake bonded at that update needed to serve until - ) - ] - -### MiddlewareTimesAdded - -```solidity -event MiddlewareTimesAdded(address operator, uint256 index, uint32 stalestUpdateBlock, uint32 latestServeUntilBlock) -``` - -Emitted when a middleware times is added to `operator`'s array. - -### OptedIntoSlashing - -```solidity -event OptedIntoSlashing(address operator, address contractAddress) -``` - -Emitted when `operator` begins to allow `contractAddress` to slash them. - -### SlashingAbilityRevoked - -```solidity -event SlashingAbilityRevoked(address operator, address contractAddress, uint32 contractCanSlashOperatorUntilBlock) -``` - -Emitted when `contractAddress` signals that it will no longer be able to slash `operator` after the `contractCanSlashOperatorUntilBlock`. - -### OperatorFrozen - -```solidity -event OperatorFrozen(address slashedOperator, address slashingContract) -``` - -Emitted when `slashingContract` 'freezes' the `slashedOperator`. - -_The `slashingContract` must have permission to slash the `slashedOperator`, i.e. `canSlash(slasherOperator, slashingContract)` must return 'true'._ - -### FrozenStatusReset - -```solidity -event FrozenStatusReset(address previouslySlashedAddress) -``` - -Emitted when `previouslySlashedAddress` is 'unfrozen', allowing them to again move deposited funds within EigenLayer. - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager, contract IDelegationManager _delegation) public -``` - -### onlyRegisteredForService - -```solidity -modifier onlyRegisteredForService(address operator) -``` - -Ensures that the operator has opted into slashing by the caller, and that the caller has never revoked its slashing ability. - -### initialize - -```solidity -function initialize(address initialOwner, contract IPauserRegistry _pauserRegistry, uint256 initialPausedStatus) external -``` - -### optIntoSlashing - -```solidity -function optIntoSlashing(address contractAddress) external -``` - -Gives the `contractAddress` permission to slash the funds of the caller. - -_Typically, this function must be called prior to registering for a middleware._ - -### freezeOperator - -```solidity -function freezeOperator(address toBeFrozen) external -``` - -Used for 'slashing' a certain operator. - -_Technically the operator is 'frozen' (hence the name of this function), and then subject to slashing pending a decision by a human-in-the-loop. -The operator must have previously given the caller (which should be a contract) the ability to slash them, through a call to `optIntoSlashing`._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| toBeFrozen | address | The operator to be frozen. | - -### resetFrozenStatus - -```solidity -function resetFrozenStatus(address[] frozenAddresses) external -``` - -Removes the 'frozen' status from each of the `frozenAddresses` - -_Callable only by the contract owner (i.e. governance)._ - -### recordFirstStakeUpdate - -```solidity -function recordFirstStakeUpdate(address operator, uint32 serveUntilBlock) external -``` - -this function is a called by middlewares during an operator's registration to make sure the operator's stake at registration - is slashable until serveUntilBlock - -_adds the middleware's slashing contract to the operator's linked list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | the operator whose stake update is being recorded | -| serveUntilBlock | uint32 | the block until which the operator's stake at the current block is slashable | - -### recordStakeUpdate - -```solidity -function recordStakeUpdate(address operator, uint32 updateBlock, uint32 serveUntilBlock, uint256 insertAfter) external -``` - -this function is a called by middlewares during a stake update for an operator (perhaps to free pending withdrawals) - to make sure the operator's stake at updateBlock is slashable until serveUntilBlock - -_insertAfter should be calculated offchain before making the transaction that calls this. this is subject to race conditions, - but it is anticipated to be rare and not detrimental._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | the operator whose stake update is being recorded | -| updateBlock | uint32 | the block for which the stake update is being recorded | -| serveUntilBlock | uint32 | the block until which the operator's stake at updateBlock is slashable | -| insertAfter | uint256 | the element of the operators linked list that the currently updating middleware should be inserted after | - -### recordLastStakeUpdateAndRevokeSlashingAbility - -```solidity -function recordLastStakeUpdateAndRevokeSlashingAbility(address operator, uint32 serveUntilBlock) external -``` - -this function is a called by middlewares during an operator's deregistration to make sure the operator's stake at deregistration - is slashable until serveUntilBlock - -_removes the middleware's slashing contract to the operator's linked list and revokes the middleware's (i.e. caller's) ability to -slash `operator` once `serveUntilBlock` is reached_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | the operator whose stake update is being recorded | -| serveUntilBlock | uint32 | the block until which the operator's stake at the current block is slashable | - -### contractCanSlashOperatorUntilBlock - -```solidity -function contractCanSlashOperatorUntilBlock(address operator, address serviceContract) external view returns (uint32) -``` - -Returns the block until which `serviceContract` is allowed to slash the `operator`. - -### latestUpdateBlock - -```solidity -function latestUpdateBlock(address operator, address serviceContract) external view returns (uint32) -``` - -Returns the block at which the `serviceContract` last updated its view of the `operator`'s stake - -### whitelistedContractDetails - -```solidity -function whitelistedContractDetails(address operator, address serviceContract) external view returns (struct ISlasher.MiddlewareDetails) -``` - -### isFrozen - -```solidity -function isFrozen(address staker) external view returns (bool) -``` - -Used to determine whether `staker` is actively 'frozen'. If a staker is frozen, then they are potentially subject to -slashing of their funds, and cannot cannot deposit or withdraw from the strategyManager until the slashing process is completed -and the staker's status is reset (to 'unfrozen'). - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| staker | address | The staker of interest. | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | Returns 'true' if `staker` themselves has their status set to frozen, OR if the staker is delegated to an operator who has their status set to frozen. Otherwise returns 'false'. | - -### canSlash - -```solidity -function canSlash(address toBeSlashed, address slashingContract) public view returns (bool) -``` - -Returns true if `slashingContract` is currently allowed to slash `toBeSlashed`. - -### canWithdraw - -```solidity -function canWithdraw(address operator, uint32 withdrawalStartBlock, uint256 middlewareTimesIndex) external view returns (bool) -``` - -Returns 'true' if `operator` can currently complete a withdrawal started at the `withdrawalStartBlock`, with `middlewareTimesIndex` used -to specify the index of a `MiddlewareTimes` struct in the operator's list (i.e. an index in `_operatorToMiddlewareTimes[operator]`). The specified -struct is consulted as proof of the `operator`'s ability (or lack thereof) to complete the withdrawal. -This function will return 'false' if the operator cannot currently complete a withdrawal started at the `withdrawalStartBlock`, *or* in the event -that an incorrect `middlewareTimesIndex` is supplied, even if one or more correct inputs exist. - -_The correct `middlewareTimesIndex` input should be computable off-chain._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | Either the operator who queued the withdrawal themselves, or if the withdrawing party is a staker who delegated to an operator, this address is the operator *who the staker was delegated to* at the time of the `withdrawalStartBlock`. | -| withdrawalStartBlock | uint32 | The block number at which the withdrawal was initiated. | -| middlewareTimesIndex | uint256 | Indicates an index in `_operatorToMiddlewareTimes[operator]` to consult as proof of the `operator`'s ability to withdraw | - -### operatorToMiddlewareTimes - -```solidity -function operatorToMiddlewareTimes(address operator, uint256 arrayIndex) external view returns (struct ISlasher.MiddlewareTimes) -``` - -Getter function for fetching `_operatorToMiddlewareTimes[operator][arrayIndex]`. - -### middlewareTimesLength - -```solidity -function middlewareTimesLength(address operator) external view returns (uint256) -``` - -Getter function for fetching `_operatorToMiddlewareTimes[operator].length`. - -### getMiddlewareTimesIndexBlock - -```solidity -function getMiddlewareTimesIndexBlock(address operator, uint32 index) external view returns (uint32) -``` - -Getter function for fetching `_operatorToMiddlewareTimes[operator][index].stalestUpdateBlock`. - -### getMiddlewareTimesIndexServeUntilBlock - -```solidity -function getMiddlewareTimesIndexServeUntilBlock(address operator, uint32 index) external view returns (uint32) -``` - -Getter function for fetching `_operatorToMiddlewareTimes[operator][index].latestServeUntilBlock`. - -### operatorWhitelistedContractsLinkedListSize - -```solidity -function operatorWhitelistedContractsLinkedListSize(address operator) external view returns (uint256) -``` - -Getter function for fetching `_operatorToWhitelistedContractsByUpdate[operator].size`. - -### operatorWhitelistedContractsLinkedListEntry - -```solidity -function operatorWhitelistedContractsLinkedListEntry(address operator, address node) external view returns (bool, uint256, uint256) -``` - -Getter function for fetching a single node in the operator's linked list (`_operatorToWhitelistedContractsByUpdate[operator]`). - -### getCorrectValueForInsertAfter - -```solidity -function getCorrectValueForInsertAfter(address operator, uint32 updateBlock) public view returns (uint256) -``` - -A search routine for finding the correct input value of `insertAfter` to `recordStakeUpdate` / `_updateMiddlewareList`. - -_Used within this contract only as a fallback in the case when an incorrect value of `insertAfter` is supplied as an input to `_updateMiddlewareList`. -The return value should *either* be 'HEAD' (i.e. zero) in the event that the node being inserted in the linked list has an `updateBlock` -that is less than the HEAD of the list, *or* the return value should specify the last `node` in the linked list for which -`_whitelistedContractDetails[operator][node].latestUpdateBlock <= updateBlock`, -i.e. the node such that the *next* node either doesn't exist, -OR -`_whitelistedContractDetails[operator][nextNode].latestUpdateBlock > updateBlock`._ - -### getPreviousWhitelistedContractByUpdate - -```solidity -function getPreviousWhitelistedContractByUpdate(address operator, uint256 node) external view returns (bool, uint256) -``` - -gets the node previous to the given node in the operators middleware update linked list - -_used in offchain libs for updating stakes_ - -### _optIntoSlashing - -```solidity -function _optIntoSlashing(address operator, address contractAddress) internal -``` - -### _revokeSlashingAbility - -```solidity -function _revokeSlashingAbility(address operator, address contractAddress, uint32 serveUntilBlock) internal -``` - -### _freezeOperator - -```solidity -function _freezeOperator(address toBeFrozen, address slashingContract) internal -``` - -### _resetFrozenStatus - -```solidity -function _resetFrozenStatus(address previouslySlashedAddress) internal -``` - -### _recordUpdateAndAddToMiddlewareTimes - -```solidity -function _recordUpdateAndAddToMiddlewareTimes(address operator, uint32 updateBlock, uint32 serveUntilBlock) internal -``` - -records the most recent updateBlock for the currently updating middleware and appends an entry to the operator's list of - MiddlewareTimes if relavent information has updated - -_this function is only called during externally called stake updates by middleware contracts that can slash operator_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | the entity whose stake update is being recorded | -| updateBlock | uint32 | the block number for which the currently updating middleware is updating the serveUntilBlock for | -| serveUntilBlock | uint32 | the block until which the operator's stake at updateBlock is slashable | - -### _updateMiddlewareList - -```solidity -function _updateMiddlewareList(address operator, uint32 updateBlock, uint256 insertAfter) internal -``` - -A routine for updating the `operator`'s linked list of middlewares, inside `recordStakeUpdate`. - -### _addressToUint - -```solidity -function _addressToUint(address addr) internal pure returns (uint256) -``` - -### _uintToAddress - -```solidity -function _uintToAddress(uint256 x) internal pure returns (address) -``` - -### __gap - -```solidity -uint256[46] __gap -``` - -_This empty reserved space is put in place to allow future versions to add new -variables without shifting down storage in the inheritance chain. -See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps_ - diff --git a/docs/docgen/core/StrategyManager.md b/docs/docgen/core/StrategyManager.md deleted file mode 100644 index 4ddd4764c..000000000 --- a/docs/docgen/core/StrategyManager.md +++ /dev/null @@ -1,666 +0,0 @@ -# Solidity API - -## StrategyManager - -This contract is for managing deposits in different strategies. The main -functionalities are: -- adding and removing strategies that any delegator can deposit into -- enabling deposit of assets into specified strategy(s) -- enabling withdrawal of assets from specified strategy(s) -- recording deposit of ETH into settlement layer -- slashing of assets for permissioned strategies - -### GWEI_TO_WEI - -```solidity -uint256 GWEI_TO_WEI -``` - -### PAUSED_DEPOSITS - -```solidity -uint8 PAUSED_DEPOSITS -``` - -### PAUSED_WITHDRAWALS - -```solidity -uint8 PAUSED_WITHDRAWALS -``` - -### ORIGINAL_CHAIN_ID - -```solidity -uint256 ORIGINAL_CHAIN_ID -``` - -### ERC1271_MAGICVALUE - -```solidity -bytes4 ERC1271_MAGICVALUE -``` - -### Deposit - -```solidity -event Deposit(address depositor, contract IERC20 token, contract IStrategy strategy, uint256 shares) -``` - -Emitted when a new deposit occurs on behalf of `depositor`. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | Is the staker who is depositing funds into EigenLayer. | -| token | contract IERC20 | Is the token that `depositor` deposited. | -| strategy | contract IStrategy | Is the strategy that `depositor` has deposited into. | -| shares | uint256 | Is the number of new shares `depositor` has been granted in `strategy`. | - -### ShareWithdrawalQueued - -```solidity -event ShareWithdrawalQueued(address depositor, uint96 nonce, contract IStrategy strategy, uint256 shares) -``` - -Emitted when a new withdrawal occurs on behalf of `depositor`. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | Is the staker who is queuing a withdrawal from EigenLayer. | -| nonce | uint96 | Is the withdrawal's unique identifier (to the depositor). | -| strategy | contract IStrategy | Is the strategy that `depositor` has queued to withdraw from. | -| shares | uint256 | Is the number of shares `depositor` has queued to withdraw. | - -### WithdrawalQueued - -```solidity -event WithdrawalQueued(address depositor, uint96 nonce, address withdrawer, address delegatedAddress, bytes32 withdrawalRoot) -``` - -Emitted when a new withdrawal is queued by `depositor`. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | Is the staker who is withdrawing funds from EigenLayer. | -| nonce | uint96 | Is the withdrawal's unique identifier (to the depositor). | -| withdrawer | address | Is the party specified by `staker` who will be able to complete the queued withdrawal and receive the withdrawn funds. | -| delegatedAddress | address | Is the party who the `staker` was delegated to at the time of creating the queued withdrawal | -| withdrawalRoot | bytes32 | Is a hash of the input data for the withdrawal. | - -### WithdrawalCompleted - -```solidity -event WithdrawalCompleted(address depositor, uint96 nonce, address withdrawer, bytes32 withdrawalRoot) -``` - -Emitted when a queued withdrawal is completed - -### StrategyWhitelisterChanged - -```solidity -event StrategyWhitelisterChanged(address previousAddress, address newAddress) -``` - -Emitted when the `strategyWhitelister` is changed - -### StrategyAddedToDepositWhitelist - -```solidity -event StrategyAddedToDepositWhitelist(contract IStrategy strategy) -``` - -Emitted when a strategy is added to the approved list of strategies for deposit - -### StrategyRemovedFromDepositWhitelist - -```solidity -event StrategyRemovedFromDepositWhitelist(contract IStrategy strategy) -``` - -Emitted when a strategy is removed from the approved list of strategies for deposit - -### WithdrawalDelayBlocksSet - -```solidity -event WithdrawalDelayBlocksSet(uint256 previousValue, uint256 newValue) -``` - -Emitted when the `withdrawalDelayBlocks` variable is modified from `previousValue` to `newValue`. - -### onlyNotFrozen - -```solidity -modifier onlyNotFrozen(address staker) -``` - -### onlyFrozen - -```solidity -modifier onlyFrozen(address staker) -``` - -### onlyEigenPodManager - -```solidity -modifier onlyEigenPodManager() -``` - -### onlyStrategyWhitelister - -```solidity -modifier onlyStrategyWhitelister() -``` - -### onlyStrategiesWhitelistedForDeposit - -```solidity -modifier onlyStrategiesWhitelistedForDeposit(contract IStrategy strategy) -``` - -### constructor - -```solidity -constructor(contract IDelegationManager _delegation, contract IEigenPodManager _eigenPodManager, contract ISlasher _slasher) public -``` - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _delegation | contract IDelegationManager | The delegation contract of EigenLayer. | -| _eigenPodManager | contract IEigenPodManager | The contract that keeps track of EigenPod stakes for restaking beacon chain ether. | -| _slasher | contract ISlasher | The primary slashing contract of EigenLayer. | - -### initialize - -```solidity -function initialize(address initialOwner, address initialStrategyWhitelister, contract IPauserRegistry _pauserRegistry, uint256 initialPausedStatus, uint256 _withdrawalDelayBlocks) external -``` - -Initializes the strategy manager contract. Sets the `pauserRegistry` (currently **not** modifiable after being set), -and transfers contract ownership to the specified `initialOwner`. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| initialOwner | address | Ownership of this contract is transferred to this address. | -| initialStrategyWhitelister | address | The initial value of `strategyWhitelister` to set. | -| _pauserRegistry | contract IPauserRegistry | Used for access control of pausing. | -| initialPausedStatus | uint256 | The initial value of `_paused` to set. | -| _withdrawalDelayBlocks | uint256 | The initial value of `withdrawalDelayBlocks` to set. | - -### depositBeaconChainETH - -```solidity -function depositBeaconChainETH(address staker, uint256 amount) external -``` - -Deposits `amount` of beaconchain ETH into this contract on behalf of `staker` - -_Only callable by EigenPodManager._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| staker | address | is the entity that is restaking in eigenlayer, | -| amount | uint256 | is the amount of beaconchain ETH being restaked, | - -### recordOvercommittedBeaconChainETH - -```solidity -function recordOvercommittedBeaconChainETH(address overcommittedPodOwner, uint256 beaconChainETHStrategyIndex, uint256 amount) external -``` - -Records an overcommitment event on behalf of a staker. The staker's beaconChainETH shares are decremented by `amount`. - -_Only callable by EigenPodManager._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| overcommittedPodOwner | address | is the pod owner to be slashed | -| beaconChainETHStrategyIndex | uint256 | is the index of the beaconChainETHStrategy in case it must be removed, | -| amount | uint256 | is the amount to decrement the slashedAddress's beaconChainETHStrategy shares | - -### depositIntoStrategy - -```solidity -function depositIntoStrategy(contract IStrategy strategy, contract IERC20 token, uint256 amount) external returns (uint256 shares) -``` - -Deposits `amount` of `token` into the specified `strategy`, with the resultant shares credited to `msg.sender` - -_The `msg.sender` must have previously approved this contract to transfer at least `amount` of `token` on their behalf. -Cannot be called by an address that is 'frozen' (this function will revert if the `msg.sender` is frozen). - -WARNING: Depositing tokens that allow reentrancy (eg. ERC-777) into a strategy is not recommended. This can lead to attack vectors - where the token balance and corresponding strategy shares are not in sync upon reentrancy._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategy | contract IStrategy | is the specified strategy where deposit is to be made, | -| token | contract IERC20 | is the denomination in which the deposit is to be made, | -| amount | uint256 | is the amount of token to be deposited in the strategy by the depositor | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| shares | uint256 | The amount of new shares in the `strategy` created as part of the action. | - -### depositIntoStrategyWithSignature - -```solidity -function depositIntoStrategyWithSignature(contract IStrategy strategy, contract IERC20 token, uint256 amount, address staker, uint256 expiry, bytes signature) external returns (uint256 shares) -``` - -Used for depositing an asset into the specified strategy with the resultant shares credited to `staker`, -who must sign off on the action. -Note that the assets are transferred out/from the `msg.sender`, not from the `staker`; this function is explicitly designed -purely to help one address deposit 'for' another. - -_The `msg.sender` must have previously approved this contract to transfer at least `amount` of `token` on their behalf. -A signature is required for this function to eliminate the possibility of griefing attacks, specifically those -targeting stakers who may be attempting to undelegate. -Cannot be called on behalf of a staker that is 'frozen' (this function will revert if the `staker` is frozen). - - WARNING: Depositing tokens that allow reentrancy (eg. ERC-777) into a strategy is not recommended. This can lead to attack vectors - where the token balance and corresponding strategy shares are not in sync upon reentrancy_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategy | contract IStrategy | is the specified strategy where deposit is to be made, | -| token | contract IERC20 | is the denomination in which the deposit is to be made, | -| amount | uint256 | is the amount of token to be deposited in the strategy by the depositor | -| staker | address | the staker that the deposited assets will be credited to | -| expiry | uint256 | the timestamp at which the signature expires | -| signature | bytes | is a valid signature from the `staker`. either an ECDSA signature if the `staker` is an EOA, or data to forward following EIP-1271 if the `staker` is a contract | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| shares | uint256 | The amount of new shares in the `strategy` created as part of the action. | - -### undelegate - -```solidity -function undelegate() external -``` - -Called by a staker to undelegate entirely from EigenLayer. The staker must first withdraw all of their existing deposits -(through use of the `queueWithdrawal` function), or else otherwise have never deposited in EigenLayer prior to delegating. - -### queueWithdrawal - -```solidity -function queueWithdrawal(uint256[] strategyIndexes, contract IStrategy[] strategies, uint256[] shares, address withdrawer, bool undelegateIfPossible) external returns (bytes32) -``` - -Called by a staker to queue a withdrawal of the given amount of `shares` from each of the respective given `strategies`. - -_Stakers will complete their withdrawal by calling the 'completeQueuedWithdrawal' function. -User shares are decreased in this function, but the total number of shares in each strategy remains the same. -The total number of shares is decremented in the 'completeQueuedWithdrawal' function instead, which is where -the funds are actually sent to the user through use of the strategies' 'withdrawal' function. This ensures -that the value per share reported by each strategy will remain consistent, and that the shares will continue -to accrue gains during the enforced withdrawal waiting period. -Strategies are removed from `stakerStrategyList` by swapping the last entry with the entry to be removed, then -popping off the last entry in `stakerStrategyList`. The simplest way to calculate the correct `strategyIndexes` to input -is to order the strategies *for which `msg.sender` is withdrawing 100% of their shares* from highest index in -`stakerStrategyList` to lowest index -Note that if the withdrawal includes shares in the enshrined 'beaconChainETH' strategy, then it must *only* include shares in this strategy, and -`withdrawer` must match the caller's address. The first condition is because slashing of queued withdrawals cannot be guaranteed -for Beacon Chain ETH (since we cannot trigger a withdrawal from the beacon chain through a smart contract) and the second condition is because shares in -the enshrined 'beaconChainETH' strategy technically represent non-fungible positions (deposits to the Beacon Chain, each pointed at a specific EigenPod)._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategyIndexes | uint256[] | is a list of the indices in `stakerStrategyList[msg.sender]` that correspond to the strategies for which `msg.sender` is withdrawing 100% of their shares | -| strategies | contract IStrategy[] | The Strategies to withdraw from | -| shares | uint256[] | The amount of shares to withdraw from each of the respective Strategies in the `strategies` array | -| withdrawer | address | The address that can complete the withdrawal and will receive any withdrawn funds or shares upon completing the withdrawal | -| undelegateIfPossible | bool | If this param is marked as 'true' *and the withdrawal will result in `msg.sender` having no shares in any Strategy,* then this function will also make an internal call to `undelegate(msg.sender)` to undelegate the `msg.sender`. | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bytes32 | The 'withdrawalRoot' of the newly created Queued Withdrawal | - -### completeQueuedWithdrawal - -```solidity -function completeQueuedWithdrawal(struct IStrategyManager.QueuedWithdrawal queuedWithdrawal, contract IERC20[] tokens, uint256 middlewareTimesIndex, bool receiveAsTokens) external -``` - -Used to complete the specified `queuedWithdrawal`. The function caller must match `queuedWithdrawal.withdrawer` - -_middlewareTimesIndex should be calculated off chain before calling this function by finding the first index that satisfies `slasher.canWithdraw`_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| queuedWithdrawal | struct IStrategyManager.QueuedWithdrawal | The QueuedWithdrawal to complete. | -| tokens | contract IERC20[] | Array in which the i-th entry specifies the `token` input to the 'withdraw' function of the i-th Strategy in the `strategies` array of the `queuedWithdrawal`. This input can be provided with zero length if `receiveAsTokens` is set to 'false' (since in that case, this input will be unused) | -| middlewareTimesIndex | uint256 | is the index in the operator that the staker who triggered the withdrawal was delegated to's middleware times array | -| receiveAsTokens | bool | If true, the shares specified in the queued withdrawal will be withdrawn from the specified strategies themselves and sent to the caller, through calls to `queuedWithdrawal.strategies[i].withdraw`. If false, then the shares in the specified strategies will simply be transferred to the caller directly. | - -### completeQueuedWithdrawals - -```solidity -function completeQueuedWithdrawals(struct IStrategyManager.QueuedWithdrawal[] queuedWithdrawals, contract IERC20[][] tokens, uint256[] middlewareTimesIndexes, bool[] receiveAsTokens) external -``` - -Used to complete the specified `queuedWithdrawals`. The function caller must match `queuedWithdrawals[...].withdrawer` - -_Array-ified version of `completeQueuedWithdrawal` -middlewareTimesIndex should be calculated off chain before calling this function by finding the first index that satisfies `slasher.canWithdraw`_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| queuedWithdrawals | struct IStrategyManager.QueuedWithdrawal[] | The QueuedWithdrawals to complete. | -| tokens | contract IERC20[][] | Array of tokens for each QueuedWithdrawal. See `completeQueuedWithdrawal` for the usage of a single array. | -| middlewareTimesIndexes | uint256[] | One index to reference per QueuedWithdrawal. See `completeQueuedWithdrawal` for the usage of a single index. | -| receiveAsTokens | bool[] | If true, the shares specified in the queued withdrawal will be withdrawn from the specified strategies themselves and sent to the caller, through calls to `queuedWithdrawal.strategies[i].withdraw`. If false, then the shares in the specified strategies will simply be transferred to the caller directly. | - -### slashShares - -```solidity -function slashShares(address slashedAddress, address recipient, contract IStrategy[] strategies, contract IERC20[] tokens, uint256[] strategyIndexes, uint256[] shareAmounts) external -``` - -Slashes the shares of a 'frozen' operator (or a staker delegated to one) - -_strategies are removed from `stakerStrategyList` by swapping the last entry with the entry to be removed, then -popping off the last entry in `stakerStrategyList`. The simplest way to calculate the correct `strategyIndexes` to input -is to order the strategies *for which `msg.sender` is withdrawing 100% of their shares* from highest index in -`stakerStrategyList` to lowest index_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| slashedAddress | address | is the frozen address that is having its shares slashed | -| recipient | address | is the address that will receive the slashed funds, which could e.g. be a harmed party themself, or a MerkleDistributor-type contract that further sub-divides the slashed funds. | -| strategies | contract IStrategy[] | Strategies to slash | -| tokens | contract IERC20[] | The tokens to use as input to the `withdraw` function of each of the provided `strategies` | -| strategyIndexes | uint256[] | is a list of the indices in `stakerStrategyList[msg.sender]` that correspond to the strategies for which `msg.sender` is withdrawing 100% of their shares | -| shareAmounts | uint256[] | The amount of shares to slash in each of the provided `strategies` | - -### slashQueuedWithdrawal - -```solidity -function slashQueuedWithdrawal(address recipient, struct IStrategyManager.QueuedWithdrawal queuedWithdrawal, contract IERC20[] tokens, uint256[] indicesToSkip) external -``` - -Slashes an existing queued withdrawal that was created by a 'frozen' operator (or a staker delegated to one) - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| recipient | address | The funds in the slashed withdrawal are withdrawn as tokens to this address. | -| queuedWithdrawal | struct IStrategyManager.QueuedWithdrawal | The previously queued withdrawal to be slashed | -| tokens | contract IERC20[] | Array in which the i-th entry specifies the `token` input to the 'withdraw' function of the i-th Strategy in the `strategies` array of the `queuedWithdrawal`. | -| indicesToSkip | uint256[] | Optional input parameter -- indices in the `strategies` array to skip (i.e. not call the 'withdraw' function on). This input exists so that, e.g., if the slashed QueuedWithdrawal contains a malicious strategy in the `strategies` array which always reverts on calls to its 'withdraw' function, then the malicious strategy can be skipped (with the shares in effect "burned"), while the non-malicious strategies are still called as normal. | - -### setWithdrawalDelayBlocks - -```solidity -function setWithdrawalDelayBlocks(uint256 _withdrawalDelayBlocks) external -``` - -Owner-only function for modifying the value of the `withdrawalDelayBlocks` variable. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _withdrawalDelayBlocks | uint256 | new value of `withdrawalDelayBlocks`. | - -### setStrategyWhitelister - -```solidity -function setStrategyWhitelister(address newStrategyWhitelister) external -``` - -Owner-only function to change the `strategyWhitelister` address. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newStrategyWhitelister | address | new address for the `strategyWhitelister`. | - -### addStrategiesToDepositWhitelist - -```solidity -function addStrategiesToDepositWhitelist(contract IStrategy[] strategiesToWhitelist) external -``` - -Owner-only function that adds the provided Strategies to the 'whitelist' of strategies that stakers can deposit into - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategiesToWhitelist | contract IStrategy[] | Strategies that will be added to the `strategyIsWhitelistedForDeposit` mapping (if they aren't in it already) | - -### removeStrategiesFromDepositWhitelist - -```solidity -function removeStrategiesFromDepositWhitelist(contract IStrategy[] strategiesToRemoveFromWhitelist) external -``` - -Owner-only function that removes the provided Strategies from the 'whitelist' of strategies that stakers can deposit into - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategiesToRemoveFromWhitelist | contract IStrategy[] | Strategies that will be removed to the `strategyIsWhitelistedForDeposit` mapping (if they are in it) | - -### _addShares - -```solidity -function _addShares(address depositor, contract IStrategy strategy, uint256 shares) internal -``` - -This function adds `shares` for a given `strategy` to the `depositor` and runs through the necessary update logic. - -_In particular, this function calls `delegation.increaseDelegatedShares(depositor, strategy, shares)` to ensure that all -delegated shares are tracked, increases the stored share amount in `stakerStrategyShares[depositor][strategy]`, and adds `strategy` -to the `depositor`'s list of strategies, if it is not in the list already._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | The address to add shares to | -| strategy | contract IStrategy | The Strategy in which the `depositor` is receiving shares | -| shares | uint256 | The amount of shares to grant to the `depositor` | - -### _depositIntoStrategy - -```solidity -function _depositIntoStrategy(address depositor, contract IStrategy strategy, contract IERC20 token, uint256 amount) internal returns (uint256 shares) -``` - -Internal function in which `amount` of ERC20 `token` is transferred from `msg.sender` to the Strategy-type contract -`strategy`, with the resulting shares credited to `depositor`. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | The address that will be credited with the new shares. | -| strategy | contract IStrategy | The Strategy contract to deposit into. | -| token | contract IERC20 | The ERC20 token to deposit. | -| amount | uint256 | The amount of `token` to deposit. | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| shares | uint256 | The amount of *new* shares in `strategy` that have been credited to the `depositor`. | - -### _removeShares - -```solidity -function _removeShares(address depositor, uint256 strategyIndex, contract IStrategy strategy, uint256 shareAmount) internal returns (bool) -``` - -Decreases the shares that `depositor` holds in `strategy` by `shareAmount`. - -_If the amount of shares represents all of the depositor`s shares in said strategy, -then the strategy is removed from stakerStrategyList[depositor] and 'true' is returned. Otherwise 'false' is returned._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | The address to decrement shares from | -| strategyIndex | uint256 | The `strategyIndex` input for the internal `_removeStrategyFromStakerStrategyList`. Used only in the case that the removal of the depositor's shares results in them having zero remaining shares in the `strategy` | -| strategy | contract IStrategy | The strategy for which the `depositor`'s shares are being decremented | -| shareAmount | uint256 | The amount of shares to decrement | - -### _removeStrategyFromStakerStrategyList - -```solidity -function _removeStrategyFromStakerStrategyList(address depositor, uint256 strategyIndex, contract IStrategy strategy) internal -``` - -Removes `strategy` from `depositor`'s dynamic array of strategies, i.e. from `stakerStrategyList[depositor]` - -_the provided `strategyIndex` input is optimistically used to find the strategy quickly in the list. If the specified -index is incorrect, then we revert to a brute-force search._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | The user whose array will have an entry removed | -| strategyIndex | uint256 | Preferably the index of `strategy` in `stakerStrategyList[depositor]`. If the input is incorrect, then a brute-force fallback routine will be used to find the correct input | -| strategy | contract IStrategy | The Strategy to remove from `stakerStrategyList[depositor]` | - -### _completeQueuedWithdrawal - -```solidity -function _completeQueuedWithdrawal(struct IStrategyManager.QueuedWithdrawal queuedWithdrawal, contract IERC20[] tokens, uint256 middlewareTimesIndex, bool receiveAsTokens) internal -``` - -Internal function for completing the given `queuedWithdrawal`. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| queuedWithdrawal | struct IStrategyManager.QueuedWithdrawal | The QueuedWithdrawal to complete | -| tokens | contract IERC20[] | The ERC20 tokens to provide as inputs to `Strategy.withdraw`. Only relevant if `receiveAsTokens = true` | -| middlewareTimesIndex | uint256 | Passed on as an input to the `slasher.canWithdraw` function, to ensure the withdrawal is completable. | -| receiveAsTokens | bool | If marked 'true', then calls will be passed on to the `Strategy.withdraw` function for each strategy. If marked 'false', then the shares will simply be internally transferred to the `msg.sender`. | - -### _undelegate - -```solidity -function _undelegate(address depositor) internal -``` - -If the `depositor` has no existing shares, then they can `undelegate` themselves. -This allows people a "hard reset" in their relationship with EigenLayer after withdrawing all of their stake. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | The address to undelegate. Passed on as an input to the `delegation.undelegate` function. | - -### _withdrawBeaconChainETH - -```solidity -function _withdrawBeaconChainETH(address staker, address recipient, uint256 amount) internal -``` - -### _setWithdrawalDelayBlocks - -```solidity -function _setWithdrawalDelayBlocks(uint256 _withdrawalDelayBlocks) internal -``` - -internal function for changing the value of `withdrawalDelayBlocks`. Also performs sanity check and emits an event. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _withdrawalDelayBlocks | uint256 | The new value for `withdrawalDelayBlocks` to take. | - -### _setStrategyWhitelister - -```solidity -function _setStrategyWhitelister(address newStrategyWhitelister) internal -``` - -Internal function for modifying the `strategyWhitelister`. Used inside of the `setStrategyWhitelister` and `initialize` functions. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newStrategyWhitelister | address | The new address for the `strategyWhitelister` to take. | - -### getDeposits - -```solidity -function getDeposits(address depositor) external view returns (contract IStrategy[], uint256[]) -``` - -Get all details on the depositor's deposits and corresponding shares - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | The staker of interest, whose deposits this function will fetch | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | contract IStrategy[] | (depositor's strategies, shares in these strategies) | -| [1] | uint256[] | | - -### stakerStrategyListLength - -```solidity -function stakerStrategyListLength(address staker) external view returns (uint256) -``` - -Simple getter function that returns `stakerStrategyList[staker].length`. - -### calculateWithdrawalRoot - -```solidity -function calculateWithdrawalRoot(struct IStrategyManager.QueuedWithdrawal queuedWithdrawal) public pure returns (bytes32) -``` - -Returns the keccak256 hash of `queuedWithdrawal`. - diff --git a/docs/docgen/core/StrategyManagerStorage.md b/docs/docgen/core/StrategyManagerStorage.md deleted file mode 100644 index 10b7dfc9d..000000000 --- a/docs/docgen/core/StrategyManagerStorage.md +++ /dev/null @@ -1,160 +0,0 @@ -# Solidity API - -## StrategyManagerStorage - -This storage contract is separate from the logic to simplify the upgrade process. - -### DOMAIN_TYPEHASH - -```solidity -bytes32 DOMAIN_TYPEHASH -``` - -The EIP-712 typehash for the contract's domain - -### DEPOSIT_TYPEHASH - -```solidity -bytes32 DEPOSIT_TYPEHASH -``` - -The EIP-712 typehash for the deposit struct used by the contract - -### DOMAIN_SEPARATOR - -```solidity -bytes32 DOMAIN_SEPARATOR -``` - -EIP-712 Domain separator - -### nonces - -```solidity -mapping(address => uint256) nonces -``` - -### MAX_STAKER_STRATEGY_LIST_LENGTH - -```solidity -uint8 MAX_STAKER_STRATEGY_LIST_LENGTH -``` - -### delegation - -```solidity -contract IDelegationManager delegation -``` - -Returns the single, central Delegation contract of EigenLayer - -### eigenPodManager - -```solidity -contract IEigenPodManager eigenPodManager -``` - -### slasher - -```solidity -contract ISlasher slasher -``` - -Returns the single, central Slasher contract of EigenLayer - -### strategyWhitelister - -```solidity -address strategyWhitelister -``` - -Permissioned role, which can be changed by the contract owner. Has the ability to edit the strategy whitelist - -### withdrawalDelayBlocks - -```solidity -uint256 withdrawalDelayBlocks -``` - -Minimum delay enforced by this contract for completing queued withdrawals. Measured in blocks, and adjustable by this contract's owner, -up to a maximum of `MAX_WITHDRAWAL_DELAY_BLOCKS`. Minimum value is 0 (i.e. no delay enforced). - -_Note that the withdrawal delay is not enforced on withdrawals of 'beaconChainETH', as the EigenPods have their own separate delay mechanic -and we want to avoid stacking multiple enforced delays onto a single withdrawal._ - -### MAX_WITHDRAWAL_DELAY_BLOCKS - -```solidity -uint256 MAX_WITHDRAWAL_DELAY_BLOCKS -``` - -### stakerStrategyShares - -```solidity -mapping(address => mapping(contract IStrategy => uint256)) stakerStrategyShares -``` - -Mapping: staker => Strategy => number of shares which they currently hold - -### stakerStrategyList - -```solidity -mapping(address => contract IStrategy[]) stakerStrategyList -``` - -Mapping: staker => array of strategies in which they have nonzero shares - -### withdrawalRootPending - -```solidity -mapping(bytes32 => bool) withdrawalRootPending -``` - -Mapping: hash of withdrawal inputs, aka 'withdrawalRoot' => whether the withdrawal is pending - -### numWithdrawalsQueued - -```solidity -mapping(address => uint256) numWithdrawalsQueued -``` - -Mapping: staker => cumulative number of queued withdrawals they have ever initiated. only increments (doesn't decrement) - -### strategyIsWhitelistedForDeposit - -```solidity -mapping(contract IStrategy => bool) strategyIsWhitelistedForDeposit -``` - -Mapping: strategy => whether or not stakers are allowed to deposit into it - -### beaconChainETHSharesToDecrementOnWithdrawal - -```solidity -mapping(address => uint256) beaconChainETHSharesToDecrementOnWithdrawal -``` - -### beaconChainETHStrategy - -```solidity -contract IStrategy beaconChainETHStrategy -``` - -returns the enshrined, virtual 'beaconChainETH' Strategy - -### constructor - -```solidity -constructor(contract IDelegationManager _delegation, contract IEigenPodManager _eigenPodManager, contract ISlasher _slasher) internal -``` - -### __gap - -```solidity -uint256[40] __gap -``` - -_This empty reserved space is put in place to allow future versions to add new -variables without shifting down storage in the inheritance chain. -See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps_ - diff --git a/docs/docgen/interfaces/IBLSPublicKeyCompendium.md b/docs/docgen/interfaces/IBLSPublicKeyCompendium.md deleted file mode 100644 index 2c365a74d..000000000 --- a/docs/docgen/interfaces/IBLSPublicKeyCompendium.md +++ /dev/null @@ -1,40 +0,0 @@ -# Solidity API - -## IBLSPublicKeyCompendium - -### operatorToPubkeyHash - -```solidity -function operatorToPubkeyHash(address operator) external view returns (bytes32) -``` - -mapping from operator address to pubkey hash. -Returns *zero* if the `operator` has never registered, and otherwise returns the hash of the public key of the operator. - -### pubkeyHashToOperator - -```solidity -function pubkeyHashToOperator(bytes32 pubkeyHash) external view returns (address) -``` - -mapping from pubkey hash to operator address. -Returns *zero* if no operator has ever registered the public key corresponding to `pubkeyHash`, -and otherwise returns the (unique) registered operator who owns the BLS public key that is the preimage of `pubkeyHash`. - -### registerBLSPublicKey - -```solidity -function registerBLSPublicKey(uint256 s, struct BN254.G1Point rPoint, struct BN254.G1Point pubkeyG1, struct BN254.G2Point pubkeyG2) external -``` - -Called by an operator to register themselves as the owner of a BLS public key and reveal their G1 and G2 public key. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| s | uint256 | is the field element of the operator's Schnorr signature | -| rPoint | struct BN254.G1Point | is the group element of the operator's Schnorr signature | -| pubkeyG1 | struct BN254.G1Point | is the the G1 pubkey of the operator | -| pubkeyG2 | struct BN254.G2Point | is the G2 with the same private key as the pubkeyG1 | - diff --git a/docs/docgen/interfaces/IBLSRegistry.md b/docs/docgen/interfaces/IBLSRegistry.md deleted file mode 100644 index 8c78a3731..000000000 --- a/docs/docgen/interfaces/IBLSRegistry.md +++ /dev/null @@ -1,84 +0,0 @@ -# Solidity API - -## IBLSRegistry - -Adds BLS-specific functions to the base interface. - -### ApkUpdate - -```solidity -struct ApkUpdate { - bytes32 apkHash; - uint32 blockNumber; -} -``` - -### getCorrectApkHash - -```solidity -function getCorrectApkHash(uint256 index, uint32 blockNumber) external returns (bytes32) -``` - -get hash of a historical aggregated public key corresponding to a given index; -called by checkSignatures in BLSSignatureChecker.sol. - -### apkUpdates - -```solidity -function apkUpdates(uint256 index) external view returns (struct IBLSRegistry.ApkUpdate) -``` - -returns the `ApkUpdate` struct at `index` in the list of APK updates - -### apkHashes - -```solidity -function apkHashes(uint256 index) external view returns (bytes32) -``` - -returns the APK hash that resulted from the `index`th APK update - -### apkUpdateBlockNumbers - -```solidity -function apkUpdateBlockNumbers(uint256 index) external view returns (uint32) -``` - -returns the block number at which the `index`th APK update occurred - -### operatorWhitelister - -```solidity -function operatorWhitelister() external view returns (address) -``` - -### operatorWhitelistEnabled - -```solidity -function operatorWhitelistEnabled() external view returns (bool) -``` - -### whitelisted - -```solidity -function whitelisted(address) external view returns (bool) -``` - -### setOperatorWhitelistStatus - -```solidity -function setOperatorWhitelistStatus(bool _operatorWhitelistEnabled) external -``` - -### addToOperatorWhitelist - -```solidity -function addToOperatorWhitelist(address[]) external -``` - -### removeFromWhitelist - -```solidity -function removeFromWhitelist(address[] operators) external -``` - diff --git a/docs/docgen/interfaces/IBeaconChainOracle.md b/docs/docgen/interfaces/IBeaconChainOracle.md deleted file mode 100644 index 5c5aa2aac..000000000 --- a/docs/docgen/interfaces/IBeaconChainOracle.md +++ /dev/null @@ -1,129 +0,0 @@ -# Solidity API - -## IBeaconChainOracle - -### latestConfirmedOracleBlockNumber - -```solidity -function latestConfirmedOracleBlockNumber() external view returns (uint64) -``` - -Largest blockNumber that has been confirmed by the oracle. - -### beaconStateRootAtBlockNumber - -```solidity -function beaconStateRootAtBlockNumber(uint64 blockNumber) external view returns (bytes32) -``` - -Mapping: Beacon Chain blockNumber => the Beacon Chain state root at the specified blockNumber. - -_This will return `bytes32(0)` if the state root at the specified blockNumber is not yet confirmed._ - -### isOracleSigner - -```solidity -function isOracleSigner(address _oracleSigner) external view returns (bool) -``` - -Mapping: address => whether or not the address is in the set of oracle signers. - -### hasVoted - -```solidity -function hasVoted(uint64 blockNumber, address oracleSigner) external view returns (bool) -``` - -Mapping: Beacon Chain blockNumber => oracle signer address => whether or not the oracle signer has voted on the state root at the blockNumber. - -### stateRootVotes - -```solidity -function stateRootVotes(uint64 blockNumber, bytes32 stateRoot) external view returns (uint256) -``` - -Mapping: Beacon Chain blockNumber => state root => total number of oracle signer votes for the state root at the blockNumber. - -### totalOracleSigners - -```solidity -function totalOracleSigners() external view returns (uint256) -``` - -Total number of members of the set of oracle signers. - -### threshold - -```solidity -function threshold() external view returns (uint256) -``` - -Number of oracle signers that must vote for a state root in order for the state root to be confirmed. -Adjustable by this contract's owner through use of the `setThreshold` function. - -_We note that there is an edge case -- when the threshold is adjusted downward, if a state root already has enough votes to meet the *new* threshold, -the state root must still receive one additional vote from an oracle signer to be confirmed. This behavior is intended, to minimize unexpected root confirmations._ - -### setThreshold - -```solidity -function setThreshold(uint256 _threshold) external -``` - -Owner-only function used to modify the value of the `threshold` variable. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _threshold | uint256 | Desired new value for the `threshold` variable. Function will revert if this is set to zero. | - -### addOracleSigners - -```solidity -function addOracleSigners(address[] _oracleSigners) external -``` - -Owner-only function used to add a signer to the set of oracle signers. - -_Function will have no effect on the i-th input address if `_oracleSigners[i]`is already in the set of oracle signers._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _oracleSigners | address[] | Array of address to be added to the set. | - -### removeOracleSigners - -```solidity -function removeOracleSigners(address[] _oracleSigners) external -``` - -Owner-only function used to remove a signer from the set of oracle signers. - -_Function will have no effect on the i-th input address if `_oracleSigners[i]`is already not in the set of oracle signers._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _oracleSigners | address[] | Array of address to be removed from the set. | - -### voteForBeaconChainStateRoot - -```solidity -function voteForBeaconChainStateRoot(uint64 blockNumber, bytes32 stateRoot) external -``` - -Called by a member of the set of oracle signers to assert that the Beacon Chain state root is `stateRoot` at `blockNumber`. - -_The state root will be finalized once the total number of votes *for this exact state root at this exact blockNumber* meets the `threshold` value._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| blockNumber | uint64 | The Beacon Chain blockNumber of interest. | -| stateRoot | bytes32 | The Beacon Chain state root that the caller asserts was the correct root, at the specified `blockNumber`. | - diff --git a/docs/docgen/interfaces/IDelayedService.md b/docs/docgen/interfaces/IDelayedService.md deleted file mode 100644 index 07bbe5552..000000000 --- a/docs/docgen/interfaces/IDelayedService.md +++ /dev/null @@ -1,19 +0,0 @@ -# Solidity API - -## IDelayedService - -Specifically, this interface is designed for services that consult stake amounts up to `BLOCK_STALE_MEASURE` -blocks in the past. This may be necessary due to, e.g., network processing & communication delays, or to avoid race conditions -that could be present with coordinating aggregate operator signatures while service operators are registering & de-registering. - -_To clarify edge cases, the middleware can look `BLOCK_STALE_MEASURE` blocks into the past, i.e. it may trust stakes from the interval -[block.number - BLOCK_STALE_MEASURE, block.number] (specifically, *inclusive* of the block that is `BLOCK_STALE_MEASURE` before the current one)_ - -### BLOCK_STALE_MEASURE - -```solidity -function BLOCK_STALE_MEASURE() external view returns (uint32) -``` - -The maximum amount of blocks in the past that the service will consider stake amounts to still be 'valid'. - diff --git a/docs/docgen/interfaces/IDelayedWithdrawalRouter.md b/docs/docgen/interfaces/IDelayedWithdrawalRouter.md deleted file mode 100644 index 31708eb16..000000000 --- a/docs/docgen/interfaces/IDelayedWithdrawalRouter.md +++ /dev/null @@ -1,118 +0,0 @@ -# Solidity API - -## IDelayedWithdrawalRouter - -### DelayedWithdrawal - -```solidity -struct DelayedWithdrawal { - uint224 amount; - uint32 blockCreated; -} -``` - -### UserDelayedWithdrawals - -```solidity -struct UserDelayedWithdrawals { - uint256 delayedWithdrawalsCompleted; - struct IDelayedWithdrawalRouter.DelayedWithdrawal[] delayedWithdrawals; -} -``` - -### createDelayedWithdrawal - -```solidity -function createDelayedWithdrawal(address podOwner, address recipient) external payable -``` - -Creates an delayed withdrawal for `msg.value` to the `recipient`. - -_Only callable by the `podOwner`'s EigenPod contract._ - -### claimDelayedWithdrawals - -```solidity -function claimDelayedWithdrawals(address recipient, uint256 maxNumberOfWithdrawalsToClaim) external -``` - -Called in order to withdraw delayed withdrawals made to the `recipient` that have passed the `withdrawalDelayBlocks` period. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| recipient | address | The address to claim delayedWithdrawals for. | -| maxNumberOfWithdrawalsToClaim | uint256 | Used to limit the maximum number of withdrawals to loop through claiming. | - -### claimDelayedWithdrawals - -```solidity -function claimDelayedWithdrawals(uint256 maxNumberOfWithdrawalsToClaim) external -``` - -Called in order to withdraw delayed withdrawals made to the caller that have passed the `withdrawalDelayBlocks` period. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| maxNumberOfWithdrawalsToClaim | uint256 | Used to limit the maximum number of withdrawals to loop through claiming. | - -### setWithdrawalDelayBlocks - -```solidity -function setWithdrawalDelayBlocks(uint256 newValue) external -``` - -Owner-only function for modifying the value of the `withdrawalDelayBlocks` variable. - -### userWithdrawals - -```solidity -function userWithdrawals(address user) external view returns (struct IDelayedWithdrawalRouter.UserDelayedWithdrawals) -``` - -Getter function for the mapping `_userWithdrawals` - -### claimableUserDelayedWithdrawals - -```solidity -function claimableUserDelayedWithdrawals(address user) external view returns (struct IDelayedWithdrawalRouter.DelayedWithdrawal[]) -``` - -Getter function to get all delayedWithdrawals that are currently claimable by the `user` - -### userDelayedWithdrawalByIndex - -```solidity -function userDelayedWithdrawalByIndex(address user, uint256 index) external view returns (struct IDelayedWithdrawalRouter.DelayedWithdrawal) -``` - -Getter function for fetching the delayedWithdrawal at the `index`th entry from the `_userWithdrawals[user].delayedWithdrawals` array - -### userWithdrawalsLength - -```solidity -function userWithdrawalsLength(address user) external view returns (uint256) -``` - -Getter function for fetching the length of the delayedWithdrawals array of a specific user - -### canClaimDelayedWithdrawal - -```solidity -function canClaimDelayedWithdrawal(address user, uint256 index) external view returns (bool) -``` - -Convenience function for checking whether or not the delayedWithdrawal at the `index`th entry from the `_userWithdrawals[user].delayedWithdrawals` array is currently claimable - -### withdrawalDelayBlocks - -```solidity -function withdrawalDelayBlocks() external view returns (uint256) -``` - -Delay enforced by this contract for completing any delayedWithdrawal. Measured in blocks, and adjustable by this contract's owner, -up to a maximum of `MAX_WITHDRAWAL_DELAY_BLOCKS`. Minimum value is 0 (i.e. no delay enforced). - diff --git a/docs/docgen/interfaces/IDelegationManager.md b/docs/docgen/interfaces/IDelegationManager.md deleted file mode 100644 index 4c031f801..000000000 --- a/docs/docgen/interfaces/IDelegationManager.md +++ /dev/null @@ -1,128 +0,0 @@ -# Solidity API - -## IDelegationManager - -This is the contract for delegation in EigenLayer. The main functionalities of this contract are -- enabling anyone to register as an operator in EigenLayer -- allowing new operators to provide a DelegationTerms-type contract, which may mediate their interactions with stakers who delegate to them -- enabling any staker to delegate its stake to the operator of its choice -- enabling a staker to undelegate its assets from an operator (performed as part of the withdrawal process, initiated through the StrategyManager) - -### registerAsOperator - -```solidity -function registerAsOperator(contract IDelegationTerms dt) external -``` - -This will be called by an operator to register itself as an operator that stakers can choose to delegate to. - -_An operator can set `dt` equal to their own address (or another EOA address), in the event that they want to split payments -in a more 'trustful' manner. -In the present design, once set, there is no way for an operator to ever modify the address of their DelegationTerms contract._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| dt | contract IDelegationTerms | is the `DelegationTerms` contract that the operator has for those who delegate to them. | - -### delegateTo - -```solidity -function delegateTo(address operator) external -``` - -@notice This will be called by a staker to delegate its assets to some operator. - @param operator is the operator to whom staker (msg.sender) is delegating its assets - -### delegateToBySignature - -```solidity -function delegateToBySignature(address staker, address operator, uint256 expiry, bytes signature) external -``` - -Delegates from `staker` to `operator`. - -_requires that: -1) if `staker` is an EOA, then `signature` is valid ECDSA signature from `staker`, indicating their intention for this action -2) if `staker` is a contract, then `signature` must will be checked according to EIP-1271_ - -### undelegate - -```solidity -function undelegate(address staker) external -``` - -Undelegates `staker` from the operator who they are delegated to. -Callable only by the StrategyManager - -_Should only ever be called in the event that the `staker` has no active deposits in EigenLayer._ - -### delegatedTo - -```solidity -function delegatedTo(address staker) external view returns (address) -``` - -returns the address of the operator that `staker` is delegated to. - -### delegationTerms - -```solidity -function delegationTerms(address operator) external view returns (contract IDelegationTerms) -``` - -returns the DelegationTerms of the `operator`, which may mediate their interactions with stakers who delegate to them. - -### operatorShares - -```solidity -function operatorShares(address operator, contract IStrategy strategy) external view returns (uint256) -``` - -returns the total number of shares in `strategy` that are delegated to `operator`. - -### increaseDelegatedShares - -```solidity -function increaseDelegatedShares(address staker, contract IStrategy strategy, uint256 shares) external -``` - -Increases the `staker`'s delegated shares in `strategy` by `shares, typically called when the staker has further deposits into EigenLayer - -_Callable only by the StrategyManager_ - -### decreaseDelegatedShares - -```solidity -function decreaseDelegatedShares(address staker, contract IStrategy[] strategies, uint256[] shares) external -``` - -Decreases the `staker`'s delegated shares in each entry of `strategies` by its respective `shares[i]`, typically called when the staker withdraws from EigenLayer - -_Callable only by the StrategyManager_ - -### isDelegated - -```solidity -function isDelegated(address staker) external view returns (bool) -``` - -Returns 'true' if `staker` *is* actively delegated, and 'false' otherwise. - -### isNotDelegated - -```solidity -function isNotDelegated(address staker) external view returns (bool) -``` - -Returns 'true' if `staker` is *not* actively delegated, and 'false' otherwise. - -### isOperator - -```solidity -function isOperator(address operator) external view returns (bool) -``` - -Returns if an operator can be delegated to, i.e. it has called `registerAsOperator`. - diff --git a/docs/docgen/interfaces/IDelegationTerms.md b/docs/docgen/interfaces/IDelegationTerms.md deleted file mode 100644 index b0f207b3e..000000000 --- a/docs/docgen/interfaces/IDelegationTerms.md +++ /dev/null @@ -1,24 +0,0 @@ -# Solidity API - -## IDelegationTerms - -The gas budget provided to this contract in calls from EigenLayer contracts is limited. - -### payForService - -```solidity -function payForService(contract IERC20 token, uint256 amount) external payable -``` - -### onDelegationWithdrawn - -```solidity -function onDelegationWithdrawn(address delegator, contract IStrategy[] stakerStrategyList, uint256[] stakerShares) external returns (bytes) -``` - -### onDelegationReceived - -```solidity -function onDelegationReceived(address delegator, contract IStrategy[] stakerStrategyList, uint256[] stakerShares) external returns (bytes) -``` - diff --git a/docs/docgen/interfaces/IETHPOSDeposit.md b/docs/docgen/interfaces/IETHPOSDeposit.md deleted file mode 100644 index b7fbbcfde..000000000 --- a/docs/docgen/interfaces/IETHPOSDeposit.md +++ /dev/null @@ -1,60 +0,0 @@ -# Solidity API - -## IETHPOSDeposit - -This is the Ethereum 2.0 deposit contract interface. -For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs - -### DepositEvent - -```solidity -event DepositEvent(bytes pubkey, bytes withdrawal_credentials, bytes amount, bytes signature, bytes index) -``` - -A processed deposit event. - -### deposit - -```solidity -function deposit(bytes pubkey, bytes withdrawal_credentials, bytes signature, bytes32 deposit_data_root) external payable -``` - -Submit a Phase 0 DepositData object. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| pubkey | bytes | A BLS12-381 public key. | -| withdrawal_credentials | bytes | Commitment to a public key for withdrawals. | -| signature | bytes | A BLS12-381 signature. | -| deposit_data_root | bytes32 | The SHA-256 hash of the SSZ-encoded DepositData object. Used as a protection against malformed input. | - -### get_deposit_root - -```solidity -function get_deposit_root() external view returns (bytes32) -``` - -Query the current deposit root hash. - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bytes32 | The deposit root hash. | - -### get_deposit_count - -```solidity -function get_deposit_count() external view returns (bytes) -``` - -Query the current deposit count. - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bytes | The deposit count encoded as a little endian 64-bit number. | - diff --git a/docs/docgen/interfaces/IEigenPod.md b/docs/docgen/interfaces/IEigenPod.md deleted file mode 100644 index a1d497b0f..000000000 --- a/docs/docgen/interfaces/IEigenPod.md +++ /dev/null @@ -1,215 +0,0 @@ -# Solidity API - -## IEigenPod - -The main functionalities are: -- creating new ETH validators with their withdrawal credentials pointed to this contract -- proving from beacon chain state roots that withdrawal credentials are pointed to this contract -- proving from beacon chain state roots the balances of ETH validators with their withdrawal credentials - pointed to this contract -- updating aggregate balances in the EigenPodManager -- withdrawing eth when withdrawals are initiated - -_Note that all beacon chain balances are stored as gwei within the beacon chain datastructures. We choose - to account balances in terms of gwei in the EigenPod contract and convert to wei when making calls to other contracts_ - -### VALIDATOR_STATUS - -```solidity -enum VALIDATOR_STATUS { - INACTIVE, - ACTIVE, - OVERCOMMITTED, - WITHDRAWN -} -``` - -### PartialWithdrawalClaim - -```solidity -struct PartialWithdrawalClaim { - enum IEigenPod.PARTIAL_WITHDRAWAL_CLAIM_STATUS status; - uint32 creationBlockNumber; - uint32 fraudproofPeriodEndBlockNumber; - uint64 partialWithdrawalAmountGwei; -} -``` - -### PARTIAL_WITHDRAWAL_CLAIM_STATUS - -```solidity -enum PARTIAL_WITHDRAWAL_CLAIM_STATUS { - REDEEMED, - PENDING, - FAILED -} -``` - -### REQUIRED_BALANCE_GWEI - -```solidity -function REQUIRED_BALANCE_GWEI() external view returns (uint64) -``` - -The amount of eth, in gwei, that is restaked per validator - -### REQUIRED_BALANCE_WEI - -```solidity -function REQUIRED_BALANCE_WEI() external view returns (uint256) -``` - -The amount of eth, in wei, that is restaked per validator - -### validatorStatus - -```solidity -function validatorStatus(uint40 validatorIndex) external view returns (enum IEigenPod.VALIDATOR_STATUS) -``` - -this is a mapping of validator indices to a Validator struct containing pertinent info about the validator - -### restakedExecutionLayerGwei - -```solidity -function restakedExecutionLayerGwei() external view returns (uint64) -``` - -the amount of execution layer ETH in this contract that is staked in EigenLayer (i.e. withdrawn from beaconchain but not EigenLayer), - -### initialize - -```solidity -function initialize(address owner) external -``` - -Used to initialize the pointers to contracts crucial to the pod's functionality, in beacon proxy construction from EigenPodManager - -### stake - -```solidity -function stake(bytes pubkey, bytes signature, bytes32 depositDataRoot) external payable -``` - -Called by EigenPodManager when the owner wants to create another ETH validator. - -### withdrawRestakedBeaconChainETH - -```solidity -function withdrawRestakedBeaconChainETH(address recipient, uint256 amount) external -``` - -Transfers `amountWei` in ether from this contract to the specified `recipient` address -Called by EigenPodManager to withdrawBeaconChainETH that has been added to the EigenPod's balance due to a withdrawal from the beacon chain. - -_Called during withdrawal or slashing. -Note that this function is marked as non-reentrant to prevent the recipient calling back into it_ - -### eigenPodManager - -```solidity -function eigenPodManager() external view returns (contract IEigenPodManager) -``` - -The single EigenPodManager for EigenLayer - -### podOwner - -```solidity -function podOwner() external view returns (address) -``` - -The owner of this EigenPod - -### hasRestaked - -```solidity -function hasRestaked() external view returns (bool) -``` - -an indicator of whether or not the podOwner has ever "fully restaked" by successfully calling `verifyCorrectWithdrawalCredentials`. - -### mostRecentWithdrawalBlockNumber - -```solidity -function mostRecentWithdrawalBlockNumber() external view returns (uint64) -``` - -block number of the most recent withdrawal - -### provenPartialWithdrawal - -```solidity -function provenPartialWithdrawal(uint40 validatorIndex, uint64 slot) external view returns (bool) -``` - -mapping that tracks proven partial withdrawals - -### verifyWithdrawalCredentialsAndBalance - -```solidity -function verifyWithdrawalCredentialsAndBalance(uint64 oracleBlockNumber, uint40 validatorIndex, struct BeaconChainProofs.ValidatorFieldsAndBalanceProofs proofs, bytes32[] validatorFields) external -``` - -This function verifies that the withdrawal credentials of the podOwner are pointed to -this contract. It also verifies the current (not effective) balance of the validator. It verifies the provided proof of the ETH validator against the beacon chain state -root, marks the validator as 'active' in EigenLayer, and credits the restaked ETH in Eigenlayer. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| oracleBlockNumber | uint64 | is the Beacon Chain blockNumber whose state root the `proof` will be proven against. | -| validatorIndex | uint40 | is the index of the validator being proven, refer to consensus specs | -| proofs | struct BeaconChainProofs.ValidatorFieldsAndBalanceProofs | is the bytes that prove the ETH validator's balance and withdrawal credentials against a beacon chain state root | -| validatorFields | bytes32[] | are the fields of the "Validator Container", refer to consensus specs for details: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator | - -### verifyOvercommittedStake - -```solidity -function verifyOvercommittedStake(uint40 validatorIndex, struct BeaconChainProofs.ValidatorFieldsAndBalanceProofs proofs, bytes32[] validatorFields, uint256 beaconChainETHStrategyIndex, uint64 oracleBlockNumber) external -``` - -This function records an overcommitment of stake to EigenLayer on behalf of a certain ETH validator. - If successful, the overcommitted balance is penalized (available for withdrawal whenever the pod's balance allows). - The ETH validator's shares in the enshrined beaconChainETH strategy are also removed from the StrategyManager and undelegated. - -_For more details on the Beacon Chain spec, see: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| validatorIndex | uint40 | is the index of the validator being proven, refer to consensus specs | -| proofs | struct BeaconChainProofs.ValidatorFieldsAndBalanceProofs | is the proof of the validator's balance and validatorFields in the balance tree and the balanceRoot to prove for | -| validatorFields | bytes32[] | are the fields of the "Validator Container", refer to consensus specs | -| beaconChainETHStrategyIndex | uint256 | is the index of the beaconChainETHStrategy for the pod owner for the callback to the StrategyManager in case it must be removed from the list of the podOwners strategies | -| oracleBlockNumber | uint64 | The oracleBlockNumber whose state root the `proof` will be proven against. Must be within `VERIFY_OVERCOMMITTED_WINDOW_BLOCKS` of the current block. | - -### verifyAndProcessWithdrawal - -```solidity -function verifyAndProcessWithdrawal(struct BeaconChainProofs.WithdrawalProofs withdrawalProofs, bytes validatorFieldsProof, bytes32[] validatorFields, bytes32[] withdrawalFields, uint256 beaconChainETHStrategyIndex, uint64 oracleBlockNumber) external -``` - -This function records a full withdrawal on behalf of one of the Ethereum validators for this EigenPod - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| withdrawalProofs | struct BeaconChainProofs.WithdrawalProofs | is the information needed to check the veracity of the block number and withdrawal being proven | -| validatorFieldsProof | bytes | is the proof of the validator's fields in the validator tree | -| validatorFields | bytes32[] | are the fields of the validator being proven | -| withdrawalFields | bytes32[] | are the fields of the withdrawal being proven | -| beaconChainETHStrategyIndex | uint256 | is the index of the beaconChainETHStrategy for the pod owner for the callback to the EigenPodManager to the StrategyManager in case it must be removed from the podOwner's list of strategies | -| oracleBlockNumber | uint64 | | - -### withdrawBeforeRestaking - -```solidity -function withdrawBeforeRestaking() external -``` - -Called by the pod owner to withdraw the balance of the pod when `hasRestaked` is set to false - diff --git a/docs/docgen/interfaces/IEigenPodManager.md b/docs/docgen/interfaces/IEigenPodManager.md deleted file mode 100644 index d20647bdf..000000000 --- a/docs/docgen/interfaces/IEigenPodManager.md +++ /dev/null @@ -1,155 +0,0 @@ -# Solidity API - -## IEigenPodManager - -### createPod - -```solidity -function createPod() external -``` - -Creates an EigenPod for the sender. - -_Function will revert if the `msg.sender` already has an EigenPod._ - -### stake - -```solidity -function stake(bytes pubkey, bytes signature, bytes32 depositDataRoot) external payable -``` - -Stakes for a new beacon chain validator on the sender's EigenPod. -Also creates an EigenPod for the sender if they don't have one already. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| pubkey | bytes | The 48 bytes public key of the beacon chain validator. | -| signature | bytes | The validator's signature of the deposit data. | -| depositDataRoot | bytes32 | The root/hash of the deposit data for the validator's deposit. | - -### restakeBeaconChainETH - -```solidity -function restakeBeaconChainETH(address podOwner, uint256 amount) external -``` - -Deposits/Restakes beacon chain ETH in EigenLayer on behalf of the owner of an EigenPod. - -_Callable only by the podOwner's EigenPod contract._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| podOwner | address | The owner of the pod whose balance must be deposited. | -| amount | uint256 | The amount of ETH to 'deposit' (i.e. be credited to the podOwner). | - -### recordOvercommittedBeaconChainETH - -```solidity -function recordOvercommittedBeaconChainETH(address podOwner, uint256 beaconChainETHStrategyIndex, uint256 amount) external -``` - -Removes beacon chain ETH from EigenLayer on behalf of the owner of an EigenPod, when the - balance of a validator is lower than how much stake they have committed to EigenLayer - -_Callable only by the podOwner's EigenPod contract._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| podOwner | address | The owner of the pod whose balance must be removed. | -| beaconChainETHStrategyIndex | uint256 | is the index of the beaconChainETHStrategy for the pod owner for the callback to the StrategyManager in case it must be removed from the list of the podOwner's strategies | -| amount | uint256 | The amount of ETH to remove. | - -### withdrawRestakedBeaconChainETH - -```solidity -function withdrawRestakedBeaconChainETH(address podOwner, address recipient, uint256 amount) external -``` - -Withdraws ETH from an EigenPod. The ETH must have first been withdrawn from the beacon chain. - -_Callable only by the StrategyManager contract._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| podOwner | address | The owner of the pod whose balance must be withdrawn. | -| recipient | address | The recipient of the withdrawn ETH. | -| amount | uint256 | The amount of ETH to withdraw. | - -### updateBeaconChainOracle - -```solidity -function updateBeaconChainOracle(contract IBeaconChainOracle newBeaconChainOracle) external -``` - -Updates the oracle contract that provides the beacon chain state root - -_Callable only by the owner of this contract (i.e. governance)_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newBeaconChainOracle | contract IBeaconChainOracle | is the new oracle contract being pointed to | - -### ownerToPod - -```solidity -function ownerToPod(address podOwner) external view returns (contract IEigenPod) -``` - -Returns the address of the `podOwner`'s EigenPod if it has been deployed. - -### getPod - -```solidity -function getPod(address podOwner) external view returns (contract IEigenPod) -``` - -Returns the address of the `podOwner`'s EigenPod (whether it is deployed yet or not). - -### beaconChainOracle - -```solidity -function beaconChainOracle() external view returns (contract IBeaconChainOracle) -``` - -Oracle contract that provides updates to the beacon chain's state - -### getBeaconChainStateRoot - -```solidity -function getBeaconChainStateRoot(uint64 blockNumber) external view returns (bytes32) -``` - -Returns the Beacon Chain state root at `blockNumber`. Reverts if the Beacon Chain state root at `blockNumber` has not yet been finalized. - -### strategyManager - -```solidity -function strategyManager() external view returns (contract IStrategyManager) -``` - -EigenLayer's StrategyManager contract - -### slasher - -```solidity -function slasher() external view returns (contract ISlasher) -``` - -EigenLayer's Slasher contract - -### hasPod - -```solidity -function hasPod(address podOwner) external view returns (bool) -``` - diff --git a/docs/docgen/interfaces/IPausable.md b/docs/docgen/interfaces/IPausable.md deleted file mode 100644 index 69619507f..000000000 --- a/docs/docgen/interfaces/IPausable.md +++ /dev/null @@ -1,83 +0,0 @@ -# Solidity API - -## IPausable - -Contracts that inherit from this contract may define their own `pause` and `unpause` (and/or related) functions. -These functions should be permissioned as "onlyPauser" which defers to a `PauserRegistry` for determining access control. - -_Pausability is implemented using a uint256, which allows up to 256 different single bit-flags; each bit can potentially pause different functionality. -Inspiration for this was taken from the NearBridge design here https://etherscan.io/address/0x3FEFc5A4B1c02f21cBc8D3613643ba0635b9a873#code. -For the `pause` and `unpause` functions we've implemented, if you pause, you can only flip (any number of) switches to on/1 (aka "paused"), and if you unpause, -you can only flip (any number of) switches to off/0 (aka "paused"). -If you want a pauseXYZ function that just flips a single bit / "pausing flag", it will: -1) 'bit-wise and' (aka `&`) a flag with the current paused state (as a uint256) -2) update the paused state to this new value -We note as well that we have chosen to identify flags by their *bit index* as opposed to their numerical value, so, e.g. defining `DEPOSITS_PAUSED = 3` -indicates specifically that if the *third bit* of `_paused` is flipped -- i.e. it is a '1' -- then deposits should be paused_ - -### pauserRegistry - -```solidity -function pauserRegistry() external view returns (contract IPauserRegistry) -``` - -Address of the `PauserRegistry` contract that this contract defers to for determining access control (for pausing). - -### pause - -```solidity -function pause(uint256 newPausedStatus) external -``` - -This function is used to pause an EigenLayer contract's functionality. -It is permissioned to the `pauser` address, which is expected to be a low threshold multisig. - -_This function can only pause functionality, and thus cannot 'unflip' any bit in `_paused` from 1 to 0._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newPausedStatus | uint256 | represents the new value for `_paused` to take, which means it may flip several bits at once. | - -### pauseAll - -```solidity -function pauseAll() external -``` - -Alias for `pause(type(uint256).max)`. - -### unpause - -```solidity -function unpause(uint256 newPausedStatus) external -``` - -This function is used to unpause an EigenLayer contract's functionality. -It is permissioned to the `unpauser` address, which is expected to be a high threshold multisig or governance contract. - -_This function can only unpause functionality, and thus cannot 'flip' any bit in `_paused` from 0 to 1._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newPausedStatus | uint256 | represents the new value for `_paused` to take, which means it may flip several bits at once. | - -### paused - -```solidity -function paused() external view returns (uint256) -``` - -Returns the current paused status as a uint256. - -### paused - -```solidity -function paused(uint8 index) external view returns (bool) -``` - -Returns 'true' if the `indexed`th bit of `_paused` is 1, and 'false' otherwise - diff --git a/docs/docgen/interfaces/IPauserRegistry.md b/docs/docgen/interfaces/IPauserRegistry.md deleted file mode 100644 index 5a7002e32..000000000 --- a/docs/docgen/interfaces/IPauserRegistry.md +++ /dev/null @@ -1,20 +0,0 @@ -# Solidity API - -## IPauserRegistry - -### pauser - -```solidity -function pauser() external view returns (address) -``` - -Unique address that holds the pauser role. - -### unpauser - -```solidity -function unpauser() external view returns (address) -``` - -Unique address that holds the unpauser role. Capable of changing *both* the pauser and unpauser addresses. - diff --git a/docs/docgen/interfaces/IPaymentManager.md b/docs/docgen/interfaces/IPaymentManager.md deleted file mode 100644 index df975704e..000000000 --- a/docs/docgen/interfaces/IPaymentManager.md +++ /dev/null @@ -1,268 +0,0 @@ -# Solidity API - -## IPaymentManager - -### DissectionType - -```solidity -enum DissectionType { - INVALID, - FIRST_HALF, - SECOND_HALF -} -``` - -### PaymentStatus - -```solidity -enum PaymentStatus { - REDEEMED, - COMMITTED, - CHALLENGED -} -``` - -### ChallengeStatus - -```solidity -enum ChallengeStatus { - RESOLVED, - OPERATOR_TURN, - CHALLENGER_TURN, - OPERATOR_TURN_ONE_STEP, - CHALLENGER_TURN_ONE_STEP -} -``` - -### Payment - -```solidity -struct Payment { - uint32 fromTaskNumber; - uint32 toTaskNumber; - uint32 confirmAt; - uint96 amount; - enum IPaymentManager.PaymentStatus status; - uint256 challengeAmount; -} -``` - -### PaymentChallenge - -```solidity -struct PaymentChallenge { - address operator; - address challenger; - address serviceManager; - uint32 fromTaskNumber; - uint32 toTaskNumber; - uint96 amount1; - uint96 amount2; - uint32 settleAt; - enum IPaymentManager.ChallengeStatus status; -} -``` - -### TotalStakes - -```solidity -struct TotalStakes { - uint256 signedStakeFirstQuorum; - uint256 signedStakeSecondQuorum; -} -``` - -### depositFutureFees - -```solidity -function depositFutureFees(address depositFor, uint256 amount) external -``` - -deposit one-time fees by the `msg.sender` with this contract to pay for future tasks of this middleware - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositFor | address | could be the `msg.sender` themselves, or a different address for whom `msg.sender` is depositing these future fees | -| amount | uint256 | is amount of futures fees being deposited | - -### setAllowance - -```solidity -function setAllowance(address allowed, uint256 amount) external -``` - -Allows the `allowed` address to spend up to `amount` of the `msg.sender`'s funds that have been deposited in this contract - -### takeFee - -```solidity -function takeFee(address initiator, address payer, uint256 feeAmount) external -``` - -Used for deducting the fees from the payer to the middleware - -### setPaymentChallengeAmount - -```solidity -function setPaymentChallengeAmount(uint256 _paymentChallengeAmount) external -``` - -Modifies the `paymentChallengeAmount` amount. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _paymentChallengeAmount | uint256 | The new value for `paymentChallengeAmount` to take. | - -### commitPayment - -```solidity -function commitPayment(uint32 toTaskNumber, uint96 amount) external -``` - -This is used by an operator to make a claim on the amount that they deserve for their service from their last payment until `toTaskNumber` - -_Once this payment is recorded, a fraud proof period commences during which a challenger can dispute the proposed payment._ - -### redeemPayment - -```solidity -function redeemPayment() external -``` - -Called by an operator to redeem a payment that they previously 'committed' to by calling `commitPayment`. - -_This function can only be called after the challenge window for the payment claim has completed._ - -### initPaymentChallenge - -```solidity -function initPaymentChallenge(address operator, uint96 amount1, uint96 amount2) external -``` - -This function is called by a fraud prover to challenge a payment, initiating an interactive-type fraudproof. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | is the operator against whose payment claim the fraudproof is being made | -| amount1 | uint96 | is the reward amount the challenger in that round claims is for the first half of tasks | -| amount2 | uint96 | is the reward amount the challenger in that round claims is for the second half of tasks | - -### performChallengeBisectionStep - -```solidity -function performChallengeBisectionStep(address operator, bool secondHalf, uint96 amount1, uint96 amount2) external -``` - -Perform a single bisection step in an existing interactive payment challenge. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | The middleware operator who was challenged (used to look up challenge details) | -| secondHalf | bool | If true, then the caller wishes to challenge the amount claimed as payment in the *second half* of the previous bisection step. If false then the *first half* is indicated instead. | -| amount1 | uint96 | The amount that the caller asserts the operator is entitled to, for the first half *of the challenged half* of the previous bisection. | -| amount2 | uint96 | The amount that the caller asserts the operator is entitled to, for the second half *of the challenged half* of the previous bisection. | - -### resolveChallenge - -```solidity -function resolveChallenge(address operator) external -``` - -resolve an existing PaymentChallenge for an operator - -### paymentFraudproofInterval - -```solidity -function paymentFraudproofInterval() external view returns (uint256) -``` - -Challenge window for submitting fraudproof in the case of an incorrect payment claim by a registered operator. - -### paymentChallengeAmount - -```solidity -function paymentChallengeAmount() external view returns (uint256) -``` - -Specifies the payment that has to be made as a guarantee for fraudproof during payment challenges. - -### paymentToken - -```solidity -function paymentToken() external view returns (contract IERC20) -``` - -the ERC20 token that will be used by the disperser to pay the service fees to middleware nodes. - -### paymentChallengeToken - -```solidity -function paymentChallengeToken() external view returns (contract IERC20) -``` - -Token used for placing a guarantee on challenges & payment commits - -### getChallengeStatus - -```solidity -function getChallengeStatus(address operator) external view returns (enum IPaymentManager.ChallengeStatus) -``` - -Returns the ChallengeStatus for the `operator`'s payment claim. - -### getAmount1 - -```solidity -function getAmount1(address operator) external view returns (uint96) -``` - -Returns the 'amount1' for the `operator`'s payment claim. - -### getAmount2 - -```solidity -function getAmount2(address operator) external view returns (uint96) -``` - -Returns the 'amount2' for the `operator`'s payment claim. - -### getToTaskNumber - -```solidity -function getToTaskNumber(address operator) external view returns (uint48) -``` - -Returns the 'toTaskNumber' for the `operator`'s payment claim. - -### getFromTaskNumber - -```solidity -function getFromTaskNumber(address operator) external view returns (uint48) -``` - -Returns the 'fromTaskNumber' for the `operator`'s payment claim. - -### getDiff - -```solidity -function getDiff(address operator) external view returns (uint48) -``` - -Returns the task number difference for the `operator`'s payment claim. - -### getPaymentChallengeAmount - -```solidity -function getPaymentChallengeAmount(address) external view returns (uint256) -``` - -Returns the active guarantee amount of the `operator` placed on their payment claim. - diff --git a/docs/docgen/interfaces/IQuorumRegistry.md b/docs/docgen/interfaces/IQuorumRegistry.md deleted file mode 100644 index fd90f7ab1..000000000 --- a/docs/docgen/interfaces/IQuorumRegistry.md +++ /dev/null @@ -1,220 +0,0 @@ -# Solidity API - -## IQuorumRegistry - -This contract does not currently support n-quorums where n >= 3. -Note in particular the presence of only `firstQuorumStake` and `secondQuorumStake` in the `OperatorStake` struct. - -### Status - -```solidity -enum Status { - INACTIVE, - ACTIVE -} -``` - -### Operator - -```solidity -struct Operator { - bytes32 pubkeyHash; - uint32 fromTaskNumber; - enum IQuorumRegistry.Status status; -} -``` - -### OperatorIndex - -```solidity -struct OperatorIndex { - uint32 toBlockNumber; - uint32 index; -} -``` - -### OperatorStake - -```solidity -struct OperatorStake { - uint32 updateBlockNumber; - uint32 nextUpdateBlockNumber; - uint96 firstQuorumStake; - uint96 secondQuorumStake; -} -``` - -### getLengthOfTotalStakeHistory - -```solidity -function getLengthOfTotalStakeHistory() external view returns (uint256) -``` - -### getTotalStakeFromIndex - -```solidity -function getTotalStakeFromIndex(uint256 index) external view returns (struct IQuorumRegistry.OperatorStake) -``` - -Returns the `index`-th entry in the dynamic array of total stake, `totalStakeHistory`. - -_Function will revert in the event that `index` is out-of-bounds._ - -### getOperatorPubkeyHash - -```solidity -function getOperatorPubkeyHash(address operator) external view returns (bytes32) -``` - -Returns the stored pubkeyHash for the specified `operator`. - -### getFromTaskNumberForOperator - -```solidity -function getFromTaskNumberForOperator(address operator) external view returns (uint32) -``` - -Returns task number from when `operator` has been registered. - -### getStakeFromPubkeyHashAndIndex - -```solidity -function getStakeFromPubkeyHashAndIndex(bytes32 pubkeyHash, uint256 index) external view returns (struct IQuorumRegistry.OperatorStake) -``` - -Returns the stake weight corresponding to `pubkeyHash`, at the -`index`-th entry in the `pubkeyHashToStakeHistory[pubkeyHash]` array. - -_Function will revert if `index` is out-of-bounds._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| pubkeyHash | bytes32 | Hash of the public key of the operator of interest. | -| index | uint256 | Array index for lookup, within the dynamic array `pubkeyHashToStakeHistory[pubkeyHash]`. | - -### checkOperatorActiveAtBlockNumber - -```solidity -function checkOperatorActiveAtBlockNumber(address operator, uint256 blockNumber, uint256 stakeHistoryIndex) external view returns (bool) -``` - -Checks that the `operator` was active at the `blockNumber`, using the specified `stakeHistoryIndex` as proof. - -_In order for this function to return 'true', the inputs must satisfy all of the following list: -1) `pubkeyHashToStakeHistory[pubkeyHash][index].updateBlockNumber <= blockNumber` -2) `pubkeyHashToStakeHistory[pubkeyHash][index].nextUpdateBlockNumber` must be either `0` (signifying no next update) or -is must be strictly greater than `blockNumber` -3) `pubkeyHashToStakeHistory[pubkeyHash][index].firstQuorumStake > 0` -or `pubkeyHashToStakeHistory[pubkeyHash][index].secondQuorumStake > 0`, i.e. the operator had nonzero stake -Note that a return value of 'false' does not guarantee that the `operator` was inactive at `blockNumber`, since a -bad `stakeHistoryIndex` can be supplied in order to obtain a response of 'false'._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | is the operator of interest | -| blockNumber | uint256 | is the block number of interest | -| stakeHistoryIndex | uint256 | specifies an index in `pubkeyHashToStakeHistory[pubkeyHash]`, where `pubkeyHash` is looked up in `registry[operator].pubkeyHash` | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | 'true' if it is successfully proven that the `operator` was active at the `blockNumber`, and 'false' otherwise | - -### checkOperatorInactiveAtBlockNumber - -```solidity -function checkOperatorInactiveAtBlockNumber(address operator, uint256 blockNumber, uint256 stakeHistoryIndex) external view returns (bool) -``` - -Checks that the `operator` was inactive at the `blockNumber`, using the specified `stakeHistoryIndex` as proof. - -_In order for this function to return 'true', the inputs must satisfy all of the following list: -1) `pubkeyHashToStakeHistory[pubkeyHash][index].updateBlockNumber <= blockNumber` -2) `pubkeyHashToStakeHistory[pubkeyHash][index].nextUpdateBlockNumber` must be either `0` (signifying no next update) or -is must be strictly greater than `blockNumber` -3) `pubkeyHashToStakeHistory[pubkeyHash][index].firstQuorumStake > 0` -or `pubkeyHashToStakeHistory[pubkeyHash][index].secondQuorumStake > 0`, i.e. the operator had nonzero stake -Note that a return value of 'false' does not guarantee that the `operator` was active at `blockNumber`, since a -bad `stakeHistoryIndex` can be supplied in order to obtain a response of 'false'._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | is the operator of interest | -| blockNumber | uint256 | is the block number of interest | -| stakeHistoryIndex | uint256 | specifies an index in `pubkeyHashToStakeHistory[pubkeyHash]`, where `pubkeyHash` is looked up in `registry[operator].pubkeyHash` | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | 'true' if it is successfully proven that the `operator` was inactive at the `blockNumber`, and 'false' otherwise | - -### getOperatorIndex - -```solidity -function getOperatorIndex(address operator, uint32 blockNumber, uint32 index) external view returns (uint32) -``` - -Looks up the `operator`'s index in the dynamic array `operatorList` at the specified `blockNumber`. - -_Function will revert in the event that the specified `index` input does not identify the appropriate entry in the -array `pubkeyHashToIndexHistory[pubkeyHash]` to pull the info from._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | | -| blockNumber | uint32 | Is the desired block number at which we wish to query the operator's position in the `operatorList` array | -| index | uint32 | Used to specify the entry within the dynamic array `pubkeyHashToIndexHistory[pubkeyHash]` to read data from, where `pubkeyHash` is looked up from `operator`'s registration info | - -### getTotalOperators - -```solidity -function getTotalOperators(uint32 blockNumber, uint32 index) external view returns (uint32) -``` - -Looks up the number of total operators at the specified `blockNumber`. - -_This function will revert if the provided `index` is out of bounds._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| blockNumber | uint32 | | -| index | uint32 | Input used to specify the entry within the dynamic array `totalOperatorsHistory` to read data from. | - -### numOperators - -```solidity -function numOperators() external view returns (uint32) -``` - -Returns the current number of operators of this service. - -### operatorStakes - -```solidity -function operatorStakes(address operator) external view returns (uint96, uint96) -``` - -Returns the most recent stake weights for the `operator` - -_Function returns weights of **0** in the event that the operator has no stake history_ - -### totalStake - -```solidity -function totalStake() external view returns (uint96, uint96) -``` - -Returns the stake amounts from the latest entry in `totalStakeHistory`. - diff --git a/docs/docgen/interfaces/IRegistry.md b/docs/docgen/interfaces/IRegistry.md deleted file mode 100644 index 49a8a221c..000000000 --- a/docs/docgen/interfaces/IRegistry.md +++ /dev/null @@ -1,15 +0,0 @@ -# Solidity API - -## IRegistry - -Functions related to the registration process itself have been intentionally excluded -because their function signatures may vary significantly. - -### isActiveOperator - -```solidity -function isActiveOperator(address operator) external view returns (bool) -``` - -Returns 'true' if `operator` is registered as an active operator, and 'false' otherwise. - diff --git a/docs/docgen/interfaces/ISafe.md b/docs/docgen/interfaces/ISafe.md deleted file mode 100644 index 24b5c8bbc..000000000 --- a/docs/docgen/interfaces/ISafe.md +++ /dev/null @@ -1,37 +0,0 @@ -# Solidity API - -## ISafe - -### Operation - -```solidity -enum Operation { - Call, - DelegateCall -} -``` - -### setup - -```solidity -function setup(address[] _owners, uint256 _threshold, address to, bytes data, address fallbackHandler, address paymentToken, uint256 payment, address payable paymentReceiver) external -``` - -### execTransaction - -```solidity -function execTransaction(address to, uint256 value, bytes data, enum ISafe.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes signatures) external payable returns (bytes) -``` - -### checkSignatures - -```solidity -function checkSignatures(bytes32 dataHash, bytes signatures) external view -``` - -### approveHash - -```solidity -function approveHash(bytes32 hashToApprove) external -``` - diff --git a/docs/docgen/interfaces/IServiceManager.md b/docs/docgen/interfaces/IServiceManager.md deleted file mode 100644 index daa191bde..000000000 --- a/docs/docgen/interfaces/IServiceManager.md +++ /dev/null @@ -1,58 +0,0 @@ -# Solidity API - -## IServiceManager - -### taskNumber - -```solidity -function taskNumber() external view returns (uint32) -``` - -Returns the current 'taskNumber' for the middleware - -### freezeOperator - -```solidity -function freezeOperator(address operator) external -``` - -Permissioned function that causes the ServiceManager to freeze the operator on EigenLayer, through a call to the Slasher contract - -### recordFirstStakeUpdate - -```solidity -function recordFirstStakeUpdate(address operator, uint32 serveUntilBlock) external -``` - -Permissioned function to have the ServiceManager forward a call to the slasher, recording an initial stake update (on operator registration) - -### recordStakeUpdate - -```solidity -function recordStakeUpdate(address operator, uint32 updateBlock, uint32 serveUntilBlock, uint256 prevElement) external -``` - -Permissioned function to have the ServiceManager forward a call to the slasher, recording a stake update - -### recordLastStakeUpdateAndRevokeSlashingAbility - -```solidity -function recordLastStakeUpdateAndRevokeSlashingAbility(address operator, uint32 serveUntilBlock) external -``` - -Permissioned function to have the ServiceManager forward a call to the slasher, recording a final stake update (on operator deregistration) - -### latestServeUntilBlock - -```solidity -function latestServeUntilBlock() external view returns (uint32) -``` - -Returns the latest block until which operators must serve. - -### owner - -```solidity -function owner() external view returns (address) -``` - diff --git a/docs/docgen/interfaces/ISlasher.md b/docs/docgen/interfaces/ISlasher.md deleted file mode 100644 index b01db6c95..000000000 --- a/docs/docgen/interfaces/ISlasher.md +++ /dev/null @@ -1,249 +0,0 @@ -# Solidity API - -## ISlasher - -See the `Slasher` contract itself for implementation details. - -### MiddlewareTimes - -```solidity -struct MiddlewareTimes { - uint32 stalestUpdateBlock; - uint32 latestServeUntilBlock; -} -``` - -### MiddlewareDetails - -```solidity -struct MiddlewareDetails { - uint32 contractCanSlashOperatorUntilBlock; - uint32 latestUpdateBlock; -} -``` - -### optIntoSlashing - -```solidity -function optIntoSlashing(address contractAddress) external -``` - -Gives the `contractAddress` permission to slash the funds of the caller. - -_Typically, this function must be called prior to registering for a middleware._ - -### freezeOperator - -```solidity -function freezeOperator(address toBeFrozen) external -``` - -Used for 'slashing' a certain operator. - -_Technically the operator is 'frozen' (hence the name of this function), and then subject to slashing pending a decision by a human-in-the-loop. -The operator must have previously given the caller (which should be a contract) the ability to slash them, through a call to `optIntoSlashing`._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| toBeFrozen | address | The operator to be frozen. | - -### resetFrozenStatus - -```solidity -function resetFrozenStatus(address[] frozenAddresses) external -``` - -Removes the 'frozen' status from each of the `frozenAddresses` - -_Callable only by the contract owner (i.e. governance)._ - -### recordFirstStakeUpdate - -```solidity -function recordFirstStakeUpdate(address operator, uint32 serveUntilBlock) external -``` - -this function is a called by middlewares during an operator's registration to make sure the operator's stake at registration - is slashable until serveUntil - -_adds the middleware's slashing contract to the operator's linked list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | the operator whose stake update is being recorded | -| serveUntilBlock | uint32 | the block until which the operator's stake at the current block is slashable | - -### recordStakeUpdate - -```solidity -function recordStakeUpdate(address operator, uint32 updateBlock, uint32 serveUntilBlock, uint256 insertAfter) external -``` - -this function is a called by middlewares during a stake update for an operator (perhaps to free pending withdrawals) - to make sure the operator's stake at updateBlock is slashable until serveUntil - -_insertAfter should be calculated offchain before making the transaction that calls this. this is subject to race conditions, - but it is anticipated to be rare and not detrimental._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | the operator whose stake update is being recorded | -| updateBlock | uint32 | the block for which the stake update is being recorded | -| serveUntilBlock | uint32 | the block until which the operator's stake at updateBlock is slashable | -| insertAfter | uint256 | the element of the operators linked list that the currently updating middleware should be inserted after | - -### recordLastStakeUpdateAndRevokeSlashingAbility - -```solidity -function recordLastStakeUpdateAndRevokeSlashingAbility(address operator, uint32 serveUntilBlock) external -``` - -this function is a called by middlewares during an operator's deregistration to make sure the operator's stake at deregistration - is slashable until serveUntil - -_removes the middleware's slashing contract to the operator's linked list and revokes the middleware's (i.e. caller's) ability to -slash `operator` once `serveUntil` is reached_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | the operator whose stake update is being recorded | -| serveUntilBlock | uint32 | the block until which the operator's stake at the current block is slashable | - -### isFrozen - -```solidity -function isFrozen(address staker) external view returns (bool) -``` - -Used to determine whether `staker` is actively 'frozen'. If a staker is frozen, then they are potentially subject to -slashing of their funds, and cannot cannot deposit or withdraw from the strategyManager until the slashing process is completed -and the staker's status is reset (to 'unfrozen'). - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| staker | address | The staker of interest. | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | Returns 'true' if `staker` themselves has their status set to frozen, OR if the staker is delegated to an operator who has their status set to frozen. Otherwise returns 'false'. | - -### canSlash - -```solidity -function canSlash(address toBeSlashed, address slashingContract) external view returns (bool) -``` - -Returns true if `slashingContract` is currently allowed to slash `toBeSlashed`. - -### contractCanSlashOperatorUntilBlock - -```solidity -function contractCanSlashOperatorUntilBlock(address operator, address serviceContract) external view returns (uint32) -``` - -Returns the block until which `serviceContract` is allowed to slash the `operator`. - -### latestUpdateBlock - -```solidity -function latestUpdateBlock(address operator, address serviceContract) external view returns (uint32) -``` - -Returns the block at which the `serviceContract` last updated its view of the `operator`'s stake - -### getCorrectValueForInsertAfter - -```solidity -function getCorrectValueForInsertAfter(address operator, uint32 updateBlock) external view returns (uint256) -``` - -A search routine for finding the correct input value of `insertAfter` to `recordStakeUpdate` / `_updateMiddlewareList`. - -### canWithdraw - -```solidity -function canWithdraw(address operator, uint32 withdrawalStartBlock, uint256 middlewareTimesIndex) external returns (bool) -``` - -Returns 'true' if `operator` can currently complete a withdrawal started at the `withdrawalStartBlock`, with `middlewareTimesIndex` used -to specify the index of a `MiddlewareTimes` struct in the operator's list (i.e. an index in `operatorToMiddlewareTimes[operator]`). The specified -struct is consulted as proof of the `operator`'s ability (or lack thereof) to complete the withdrawal. -This function will return 'false' if the operator cannot currently complete a withdrawal started at the `withdrawalStartBlock`, *or* in the event -that an incorrect `middlewareTimesIndex` is supplied, even if one or more correct inputs exist. - -_The correct `middlewareTimesIndex` input should be computable off-chain._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | Either the operator who queued the withdrawal themselves, or if the withdrawing party is a staker who delegated to an operator, this address is the operator *who the staker was delegated to* at the time of the `withdrawalStartBlock`. | -| withdrawalStartBlock | uint32 | The block number at which the withdrawal was initiated. | -| middlewareTimesIndex | uint256 | Indicates an index in `operatorToMiddlewareTimes[operator]` to consult as proof of the `operator`'s ability to withdraw | - -### operatorToMiddlewareTimes - -```solidity -function operatorToMiddlewareTimes(address operator, uint256 arrayIndex) external view returns (struct ISlasher.MiddlewareTimes) -``` - -operator => - [ - ( - the least recent update block of all of the middlewares it's serving/served, - latest time that the stake bonded at that update needed to serve until - ) - ] - -### middlewareTimesLength - -```solidity -function middlewareTimesLength(address operator) external view returns (uint256) -``` - -Getter function for fetching `operatorToMiddlewareTimes[operator].length` - -### getMiddlewareTimesIndexBlock - -```solidity -function getMiddlewareTimesIndexBlock(address operator, uint32 index) external view returns (uint32) -``` - -Getter function for fetching `operatorToMiddlewareTimes[operator][index].stalestUpdateBlock`. - -### getMiddlewareTimesIndexServeUntilBlock - -```solidity -function getMiddlewareTimesIndexServeUntilBlock(address operator, uint32 index) external view returns (uint32) -``` - -Getter function for fetching `operatorToMiddlewareTimes[operator][index].latestServeUntil`. - -### operatorWhitelistedContractsLinkedListSize - -```solidity -function operatorWhitelistedContractsLinkedListSize(address operator) external view returns (uint256) -``` - -Getter function for fetching `_operatorToWhitelistedContractsByUpdate[operator].size`. - -### operatorWhitelistedContractsLinkedListEntry - -```solidity -function operatorWhitelistedContractsLinkedListEntry(address operator, address node) external view returns (bool, uint256, uint256) -``` - -Getter function for fetching a single node in the operator's linked list (`_operatorToWhitelistedContractsByUpdate[operator]`). - diff --git a/docs/docgen/interfaces/IStrategy.md b/docs/docgen/interfaces/IStrategy.md deleted file mode 100644 index 7753401b9..000000000 --- a/docs/docgen/interfaces/IStrategy.md +++ /dev/null @@ -1,183 +0,0 @@ -# Solidity API - -## IStrategy - -Custom `Strategy` implementations may expand extensively on this interface. - -### deposit - -```solidity -function deposit(contract IERC20 token, uint256 amount) external returns (uint256) -``` - -Used to deposit tokens into this Strategy - -_This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's -`depositIntoStrategy` function, and individual share balances are recorded in the strategyManager as well._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| token | contract IERC20 | is the ERC20 token being deposited | -| amount | uint256 | is the amount of token being deposited | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | newShares is the number of new shares issued at the current exchange ratio. | - -### withdraw - -```solidity -function withdraw(address depositor, contract IERC20 token, uint256 amountShares) external -``` - -Used to withdraw tokens from this Strategy, to the `depositor`'s address - -_This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's -other functions, and individual share balances are recorded in the strategyManager as well._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | is the address to receive the withdrawn funds | -| token | contract IERC20 | is the ERC20 token being transferred out | -| amountShares | uint256 | is the amount of shares being withdrawn | - -### sharesToUnderlying - -```solidity -function sharesToUnderlying(uint256 amountShares) external returns (uint256) -``` - -Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy. -In contrast to `sharesToUnderlyingView`, this function **may** make state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountShares | uint256 | is the amount of shares to calculate its conversion into the underlying token | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of underlying tokens corresponding to the input `amountShares` | - -### underlyingToShares - -```solidity -function underlyingToShares(uint256 amountUnderlying) external returns (uint256) -``` - -Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy. -In contrast to `underlyingToSharesView`, this function **may** make state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountUnderlying | uint256 | is the amount of `underlyingToken` to calculate its conversion into strategy shares | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of underlying tokens corresponding to the input `amountShares` | - -### userUnderlying - -```solidity -function userUnderlying(address user) external returns (uint256) -``` - -convenience function for fetching the current underlying value of all of the `user`'s shares in -this strategy. In contrast to `userUnderlyingView`, this function **may** make state modifications - -### sharesToUnderlyingView - -```solidity -function sharesToUnderlyingView(uint256 amountShares) external view returns (uint256) -``` - -Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy. -In contrast to `sharesToUnderlying`, this function guarantees no state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountShares | uint256 | is the amount of shares to calculate its conversion into the underlying token | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of shares corresponding to the input `amountUnderlying` | - -### underlyingToSharesView - -```solidity -function underlyingToSharesView(uint256 amountUnderlying) external view returns (uint256) -``` - -Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy. -In contrast to `underlyingToShares`, this function guarantees no state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountUnderlying | uint256 | is the amount of `underlyingToken` to calculate its conversion into strategy shares | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of shares corresponding to the input `amountUnderlying` | - -### userUnderlyingView - -```solidity -function userUnderlyingView(address user) external view returns (uint256) -``` - -convenience function for fetching the current underlying value of all of the `user`'s shares in -this strategy. In contrast to `userUnderlying`, this function guarantees no state modifications - -### underlyingToken - -```solidity -function underlyingToken() external view returns (contract IERC20) -``` - -The underlying token for shares in this Strategy - -### totalShares - -```solidity -function totalShares() external view returns (uint256) -``` - -The total number of extant shares in this Strategy - -### explanation - -```solidity -function explanation() external view returns (string) -``` - -Returns either a brief string explaining the strategy's goal & purpose, or a link to metadata that explains in more detail. - diff --git a/docs/docgen/interfaces/IStrategyManager.md b/docs/docgen/interfaces/IStrategyManager.md deleted file mode 100644 index 52c17f208..000000000 --- a/docs/docgen/interfaces/IStrategyManager.md +++ /dev/null @@ -1,345 +0,0 @@ -# Solidity API - -## IStrategyManager - -See the `StrategyManager` contract itself for implementation details. - -### WithdrawerAndNonce - -```solidity -struct WithdrawerAndNonce { - address withdrawer; - uint96 nonce; -} -``` - -### QueuedWithdrawal - -```solidity -struct QueuedWithdrawal { - contract IStrategy[] strategies; - uint256[] shares; - address depositor; - struct IStrategyManager.WithdrawerAndNonce withdrawerAndNonce; - uint32 withdrawalStartBlock; - address delegatedAddress; -} -``` - -### depositIntoStrategy - -```solidity -function depositIntoStrategy(contract IStrategy strategy, contract IERC20 token, uint256 amount) external returns (uint256 shares) -``` - -Deposits `amount` of `token` into the specified `strategy`, with the resultant shares credited to `msg.sender` - -_The `msg.sender` must have previously approved this contract to transfer at least `amount` of `token` on their behalf. -Cannot be called by an address that is 'frozen' (this function will revert if the `msg.sender` is frozen). - -WARNING: Depositing tokens that allow reentrancy (eg. ERC-777) into a strategy is not recommended. This can lead to attack vectors - where the token balance and corresponding strategy shares are not in sync upon reentrancy._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategy | contract IStrategy | is the specified strategy where deposit is to be made, | -| token | contract IERC20 | is the denomination in which the deposit is to be made, | -| amount | uint256 | is the amount of token to be deposited in the strategy by the depositor | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| shares | uint256 | The amount of new shares in the `strategy` created as part of the action. | - -### depositBeaconChainETH - -```solidity -function depositBeaconChainETH(address staker, uint256 amount) external -``` - -Deposits `amount` of beaconchain ETH into this contract on behalf of `staker` - -_Only callable by EigenPodManager._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| staker | address | is the entity that is restaking in eigenlayer, | -| amount | uint256 | is the amount of beaconchain ETH being restaked, | - -### recordOvercommittedBeaconChainETH - -```solidity -function recordOvercommittedBeaconChainETH(address overcommittedPodOwner, uint256 beaconChainETHStrategyIndex, uint256 amount) external -``` - -Records an overcommitment event on behalf of a staker. The staker's beaconChainETH shares are decremented by `amount`. - -_Only callable by EigenPodManager._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| overcommittedPodOwner | address | is the pod owner to be slashed | -| beaconChainETHStrategyIndex | uint256 | is the index of the beaconChainETHStrategy in case it must be removed, | -| amount | uint256 | is the amount to decrement the slashedAddress's beaconChainETHStrategy shares | - -### depositIntoStrategyWithSignature - -```solidity -function depositIntoStrategyWithSignature(contract IStrategy strategy, contract IERC20 token, uint256 amount, address staker, uint256 expiry, bytes signature) external returns (uint256 shares) -``` - -Used for depositing an asset into the specified strategy with the resultant shares credited to `staker`, -who must sign off on the action. -Note that the assets are transferred out/from the `msg.sender`, not from the `staker`; this function is explicitly designed -purely to help one address deposit 'for' another. - -_The `msg.sender` must have previously approved this contract to transfer at least `amount` of `token` on their behalf. -A signature is required for this function to eliminate the possibility of griefing attacks, specifically those -targeting stakers who may be attempting to undelegate. -Cannot be called on behalf of a staker that is 'frozen' (this function will revert if the `staker` is frozen). - - WARNING: Depositing tokens that allow reentrancy (eg. ERC-777) into a strategy is not recommended. This can lead to attack vectors - where the token balance and corresponding strategy shares are not in sync upon reentrancy_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategy | contract IStrategy | is the specified strategy where deposit is to be made, | -| token | contract IERC20 | is the denomination in which the deposit is to be made, | -| amount | uint256 | is the amount of token to be deposited in the strategy by the depositor | -| staker | address | the staker that the deposited assets will be credited to | -| expiry | uint256 | the timestamp at which the signature expires | -| signature | bytes | is a valid signature from the `staker`. either an ECDSA signature if the `staker` is an EOA, or data to forward following EIP-1271 if the `staker` is a contract | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| shares | uint256 | The amount of new shares in the `strategy` created as part of the action. | - -### stakerStrategyShares - -```solidity -function stakerStrategyShares(address user, contract IStrategy strategy) external view returns (uint256 shares) -``` - -Returns the current shares of `user` in `strategy` - -### getDeposits - -```solidity -function getDeposits(address depositor) external view returns (contract IStrategy[], uint256[]) -``` - -Get all details on the depositor's deposits and corresponding shares - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | contract IStrategy[] | (depositor's strategies, shares in these strategies) | -| [1] | uint256[] | | - -### stakerStrategyListLength - -```solidity -function stakerStrategyListLength(address staker) external view returns (uint256) -``` - -Simple getter function that returns `stakerStrategyList[staker].length`. - -### queueWithdrawal - -```solidity -function queueWithdrawal(uint256[] strategyIndexes, contract IStrategy[] strategies, uint256[] shares, address withdrawer, bool undelegateIfPossible) external returns (bytes32) -``` - -Called by a staker to queue a withdrawal of the given amount of `shares` from each of the respective given `strategies`. - -_Stakers will complete their withdrawal by calling the 'completeQueuedWithdrawal' function. -User shares are decreased in this function, but the total number of shares in each strategy remains the same. -The total number of shares is decremented in the 'completeQueuedWithdrawal' function instead, which is where -the funds are actually sent to the user through use of the strategies' 'withdrawal' function. This ensures -that the value per share reported by each strategy will remain consistent, and that the shares will continue -to accrue gains during the enforced withdrawal waiting period. -Strategies are removed from `stakerStrategyList` by swapping the last entry with the entry to be removed, then -popping off the last entry in `stakerStrategyList`. The simplest way to calculate the correct `strategyIndexes` to input -is to order the strategies *for which `msg.sender` is withdrawing 100% of their shares* from highest index in -`stakerStrategyList` to lowest index -Note that if the withdrawal includes shares in the enshrined 'beaconChainETH' strategy, then it must *only* include shares in this strategy, and -`withdrawer` must match the caller's address. The first condition is because slashing of queued withdrawals cannot be guaranteed -for Beacon Chain ETH (since we cannot trigger a withdrawal from the beacon chain through a smart contract) and the second condition is because shares in -the enshrined 'beaconChainETH' strategy technically represent non-fungible positions (deposits to the Beacon Chain, each pointed at a specific EigenPod)._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategyIndexes | uint256[] | is a list of the indices in `stakerStrategyList[msg.sender]` that correspond to the strategies for which `msg.sender` is withdrawing 100% of their shares | -| strategies | contract IStrategy[] | The Strategies to withdraw from | -| shares | uint256[] | The amount of shares to withdraw from each of the respective Strategies in the `strategies` array | -| withdrawer | address | The address that can complete the withdrawal and will receive any withdrawn funds or shares upon completing the withdrawal | -| undelegateIfPossible | bool | If this param is marked as 'true' *and the withdrawal will result in `msg.sender` having no shares in any Strategy,* then this function will also make an internal call to `undelegate(msg.sender)` to undelegate the `msg.sender`. | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bytes32 | The 'withdrawalRoot' of the newly created Queued Withdrawal | - -### completeQueuedWithdrawal - -```solidity -function completeQueuedWithdrawal(struct IStrategyManager.QueuedWithdrawal queuedWithdrawal, contract IERC20[] tokens, uint256 middlewareTimesIndex, bool receiveAsTokens) external -``` - -Used to complete the specified `queuedWithdrawal`. The function caller must match `queuedWithdrawal.withdrawer` - -_middlewareTimesIndex should be calculated off chain before calling this function by finding the first index that satisfies `slasher.canWithdraw`_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| queuedWithdrawal | struct IStrategyManager.QueuedWithdrawal | The QueuedWithdrawal to complete. | -| tokens | contract IERC20[] | Array in which the i-th entry specifies the `token` input to the 'withdraw' function of the i-th Strategy in the `strategies` array of the `queuedWithdrawal`. This input can be provided with zero length if `receiveAsTokens` is set to 'false' (since in that case, this input will be unused) | -| middlewareTimesIndex | uint256 | is the index in the operator that the staker who triggered the withdrawal was delegated to's middleware times array | -| receiveAsTokens | bool | If true, the shares specified in the queued withdrawal will be withdrawn from the specified strategies themselves and sent to the caller, through calls to `queuedWithdrawal.strategies[i].withdraw`. If false, then the shares in the specified strategies will simply be transferred to the caller directly. | - -### completeQueuedWithdrawals - -```solidity -function completeQueuedWithdrawals(struct IStrategyManager.QueuedWithdrawal[] queuedWithdrawals, contract IERC20[][] tokens, uint256[] middlewareTimesIndexes, bool[] receiveAsTokens) external -``` - -Used to complete the specified `queuedWithdrawals`. The function caller must match `queuedWithdrawals[...].withdrawer` - -_Array-ified version of `completeQueuedWithdrawal` -middlewareTimesIndex should be calculated off chain before calling this function by finding the first index that satisfies `slasher.canWithdraw`_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| queuedWithdrawals | struct IStrategyManager.QueuedWithdrawal[] | The QueuedWithdrawals to complete. | -| tokens | contract IERC20[][] | Array of tokens for each QueuedWithdrawal. See `completeQueuedWithdrawal` for the usage of a single array. | -| middlewareTimesIndexes | uint256[] | One index to reference per QueuedWithdrawal. See `completeQueuedWithdrawal` for the usage of a single index. | -| receiveAsTokens | bool[] | If true, the shares specified in the queued withdrawal will be withdrawn from the specified strategies themselves and sent to the caller, through calls to `queuedWithdrawal.strategies[i].withdraw`. If false, then the shares in the specified strategies will simply be transferred to the caller directly. | - -### slashShares - -```solidity -function slashShares(address slashedAddress, address recipient, contract IStrategy[] strategies, contract IERC20[] tokens, uint256[] strategyIndexes, uint256[] shareAmounts) external -``` - -Slashes the shares of a 'frozen' operator (or a staker delegated to one) - -_strategies are removed from `stakerStrategyList` by swapping the last entry with the entry to be removed, then -popping off the last entry in `stakerStrategyList`. The simplest way to calculate the correct `strategyIndexes` to input -is to order the strategies *for which `msg.sender` is withdrawing 100% of their shares* from highest index in -`stakerStrategyList` to lowest index_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| slashedAddress | address | is the frozen address that is having its shares slashed | -| recipient | address | is the address that will receive the slashed funds, which could e.g. be a harmed party themself, or a MerkleDistributor-type contract that further sub-divides the slashed funds. | -| strategies | contract IStrategy[] | Strategies to slash | -| tokens | contract IERC20[] | The tokens to use as input to the `withdraw` function of each of the provided `strategies` | -| strategyIndexes | uint256[] | is a list of the indices in `stakerStrategyList[msg.sender]` that correspond to the strategies for which `msg.sender` is withdrawing 100% of their shares | -| shareAmounts | uint256[] | The amount of shares to slash in each of the provided `strategies` | - -### slashQueuedWithdrawal - -```solidity -function slashQueuedWithdrawal(address recipient, struct IStrategyManager.QueuedWithdrawal queuedWithdrawal, contract IERC20[] tokens, uint256[] indicesToSkip) external -``` - -Slashes an existing queued withdrawal that was created by a 'frozen' operator (or a staker delegated to one) - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| recipient | address | The funds in the slashed withdrawal are withdrawn as tokens to this address. | -| queuedWithdrawal | struct IStrategyManager.QueuedWithdrawal | The previously queued withdrawal to be slashed | -| tokens | contract IERC20[] | Array in which the i-th entry specifies the `token` input to the 'withdraw' function of the i-th Strategy in the `strategies` array of the `queuedWithdrawal`. | -| indicesToSkip | uint256[] | Optional input parameter -- indices in the `strategies` array to skip (i.e. not call the 'withdraw' function on). This input exists so that, e.g., if the slashed QueuedWithdrawal contains a malicious strategy in the `strategies` array which always reverts on calls to its 'withdraw' function, then the malicious strategy can be skipped (with the shares in effect "burned"), while the non-malicious strategies are still called as normal. | - -### calculateWithdrawalRoot - -```solidity -function calculateWithdrawalRoot(struct IStrategyManager.QueuedWithdrawal queuedWithdrawal) external pure returns (bytes32) -``` - -Returns the keccak256 hash of `queuedWithdrawal`. - -### addStrategiesToDepositWhitelist - -```solidity -function addStrategiesToDepositWhitelist(contract IStrategy[] strategiesToWhitelist) external -``` - -Owner-only function that adds the provided Strategies to the 'whitelist' of strategies that stakers can deposit into - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategiesToWhitelist | contract IStrategy[] | Strategies that will be added to the `strategyIsWhitelistedForDeposit` mapping (if they aren't in it already) | - -### removeStrategiesFromDepositWhitelist - -```solidity -function removeStrategiesFromDepositWhitelist(contract IStrategy[] strategiesToRemoveFromWhitelist) external -``` - -Owner-only function that removes the provided Strategies from the 'whitelist' of strategies that stakers can deposit into - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| strategiesToRemoveFromWhitelist | contract IStrategy[] | Strategies that will be removed to the `strategyIsWhitelistedForDeposit` mapping (if they are in it) | - -### delegation - -```solidity -function delegation() external view returns (contract IDelegationManager) -``` - -Returns the single, central Delegation contract of EigenLayer - -### slasher - -```solidity -function slasher() external view returns (contract ISlasher) -``` - -Returns the single, central Slasher contract of EigenLayer - -### beaconChainETHStrategy - -```solidity -function beaconChainETHStrategy() external view returns (contract IStrategy) -``` - -returns the enshrined, virtual 'beaconChainETH' Strategy - -### withdrawalDelayBlocks - -```solidity -function withdrawalDelayBlocks() external view returns (uint256) -``` - -Returns the number of blocks that must pass between the time a withdrawal is queued and the time it can be completed - diff --git a/docs/docgen/interfaces/IVoteWeigher.md b/docs/docgen/interfaces/IVoteWeigher.md deleted file mode 100644 index 10e91a839..000000000 --- a/docs/docgen/interfaces/IVoteWeigher.md +++ /dev/null @@ -1,34 +0,0 @@ -# Solidity API - -## IVoteWeigher - -Note that `NUMBER_OF_QUORUMS` is expected to remain constant, as suggested by its uppercase formatting. - -### weightOfOperator - -```solidity -function weightOfOperator(address operator, uint256 quorumNumber) external returns (uint96) -``` - -This function computes the total weight of the @param operator in the quorum @param quorumNumber. - -_returns zero in the case that `quorumNumber` is greater than or equal to `NUMBER_OF_QUORUMS`_ - -### NUMBER_OF_QUORUMS - -```solidity -function NUMBER_OF_QUORUMS() external view returns (uint256) -``` - -Number of quorums that are being used by the middleware. - -### quorumBips - -```solidity -function quorumBips(uint256 quorumNumber) external view returns (uint256) -``` - -This defines the earnings split between different quorums. Mapping is quorumNumber => BIPS which the quorum earns, out of the total earnings. - -_The sum of all entries, i.e. sum(quorumBips[0] through quorumBips[NUMBER_OF_QUORUMS - 1]) should *always* be 10,000!_ - diff --git a/docs/docgen/interfaces/IWhitelister.md b/docs/docgen/interfaces/IWhitelister.md deleted file mode 100644 index a8b97e4a1..000000000 --- a/docs/docgen/interfaces/IWhitelister.md +++ /dev/null @@ -1,46 +0,0 @@ -# Solidity API - -## IWhitelister - -### whitelist - -```solidity -function whitelist(address operator) external -``` - -### getStaker - -```solidity -function getStaker(address operator) external returns (address) -``` - -### depositIntoStrategy - -```solidity -function depositIntoStrategy(address staker, contract IStrategy strategy, contract IERC20 token, uint256 amount) external returns (bytes) -``` - -### queueWithdrawal - -```solidity -function queueWithdrawal(address staker, uint256[] strategyIndexes, contract IStrategy[] strategies, uint256[] shares, address withdrawer, bool undelegateIfPossible) external returns (bytes) -``` - -### completeQueuedWithdrawal - -```solidity -function completeQueuedWithdrawal(address staker, struct IStrategyManager.QueuedWithdrawal queuedWithdrawal, contract IERC20[] tokens, uint256 middlewareTimesIndex, bool receiveAsTokens) external returns (bytes) -``` - -### transfer - -```solidity -function transfer(address staker, address token, address to, uint256 amount) external returns (bytes) -``` - -### callAddress - -```solidity -function callAddress(address to, bytes data) external payable returns (bytes) -``` - diff --git a/docs/docgen/libraries/BN254.md b/docs/docgen/libraries/BN254.md deleted file mode 100644 index 56e3f320a..000000000 --- a/docs/docgen/libraries/BN254.md +++ /dev/null @@ -1,215 +0,0 @@ -# Solidity API - -## BN254 - -Contains BN254 parameters, common operations (addition, scalar mul, pairing), and BLS signature functionality. - -### FP_MODULUS - -```solidity -uint256 FP_MODULUS -``` - -### FR_MODULUS - -```solidity -uint256 FR_MODULUS -``` - -### G1Point - -```solidity -struct G1Point { - uint256 X; - uint256 Y; -} -``` - -### G2Point - -```solidity -struct G2Point { - uint256[2] X; - uint256[2] Y; -} -``` - -### G2x1 - -```solidity -uint256 G2x1 -``` - -_Generator point in F_q2 is of the form: (x0 + ix1, y0 + iy1)._ - -### G2x0 - -```solidity -uint256 G2x0 -``` - -### G2y1 - -```solidity -uint256 G2y1 -``` - -### G2y0 - -```solidity -uint256 G2y0 -``` - -### generatorG2 - -```solidity -function generatorG2() internal pure returns (struct BN254.G2Point) -``` - -returns the G2 generator - -_mind the ordering of the 1s and 0s! - this is because of the (unknown to us) convention used in the bn254 pairing precompile contract - "Elements a * i + b of F_p^2 are encoded as two elements of F_p, (a, b)." - https://github.com/ethereum/EIPs/blob/master/EIPS/eip-197.md#encoding_ - -### nG2x1 - -```solidity -uint256 nG2x1 -``` - -_Generator point in F_q2 is of the form: (x0 + ix1, y0 + iy1)._ - -### nG2x0 - -```solidity -uint256 nG2x0 -``` - -### nG2y1 - -```solidity -uint256 nG2y1 -``` - -### nG2y0 - -```solidity -uint256 nG2y0 -``` - -### negGeneratorG2 - -```solidity -function negGeneratorG2() internal pure returns (struct BN254.G2Point) -``` - -### powersOfTauMerkleRoot - -```solidity -bytes32 powersOfTauMerkleRoot -``` - -### negate - -```solidity -function negate(struct BN254.G1Point p) internal pure returns (struct BN254.G1Point) -``` - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| p | struct BN254.G1Point | Some point in G1. | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | struct BN254.G1Point | The negation of `p`, i.e. p.plus(p.negate()) should be zero. | - -### plus - -```solidity -function plus(struct BN254.G1Point p1, struct BN254.G1Point p2) internal view returns (struct BN254.G1Point r) -``` - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| r | struct BN254.G1Point | the sum of two points of G1 | - -### scalar_mul - -```solidity -function scalar_mul(struct BN254.G1Point p, uint256 s) internal view returns (struct BN254.G1Point r) -``` - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| r | struct BN254.G1Point | the product of a point on G1 and a scalar, i.e. p == p.scalar_mul(1) and p.plus(p) == p.scalar_mul(2) for all points p. | - -### pairing - -```solidity -function pairing(struct BN254.G1Point a1, struct BN254.G2Point a2, struct BN254.G1Point b1, struct BN254.G2Point b2) internal view returns (bool) -``` - -@return The result of computing the pairing check - e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 - For example, - pairing([P1(), P1().negate()], [P2(), P2()]) should return true. - -### safePairing - -```solidity -function safePairing(struct BN254.G1Point a1, struct BN254.G2Point a2, struct BN254.G1Point b1, struct BN254.G2Point b2, uint256 pairingGas) internal view returns (bool, bool) -``` - -This function is functionally the same as pairing(), however it specifies a gas limit - the user can set, as a precompile may use the entire gas budget if it reverts. - -### hashG1Point - -```solidity -function hashG1Point(struct BN254.G1Point pk) internal pure returns (bytes32) -``` - -_used for BLS signatures_ - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bytes32 | the keccak256 hash of the G1 Point | - -### hashToG1 - -```solidity -function hashToG1(bytes32 _x) internal view returns (uint256, uint256) -``` - -adapted from https://github.com/HarryR/solcrypto/blob/master/contracts/altbn128.sol - -### findYFromX - -```solidity -function findYFromX(uint256 x) internal view returns (uint256, uint256) -``` - -Given X, find Y - - where y = sqrt(x^3 + b) - -Returns: (x^3 + b), y - -### expMod - -```solidity -function expMod(uint256 _base, uint256 _exponent, uint256 _modulus) internal view returns (uint256 retval) -``` - diff --git a/docs/docgen/libraries/BeaconChainProofs.md b/docs/docgen/libraries/BeaconChainProofs.md deleted file mode 100644 index f76d081cb..000000000 --- a/docs/docgen/libraries/BeaconChainProofs.md +++ /dev/null @@ -1,427 +0,0 @@ -# Solidity API - -## BeaconChainProofs - -### NUM_BEACON_BLOCK_HEADER_FIELDS - -```solidity -uint256 NUM_BEACON_BLOCK_HEADER_FIELDS -``` - -### BEACON_BLOCK_HEADER_FIELD_TREE_HEIGHT - -```solidity -uint256 BEACON_BLOCK_HEADER_FIELD_TREE_HEIGHT -``` - -### NUM_BEACON_BLOCK_BODY_FIELDS - -```solidity -uint256 NUM_BEACON_BLOCK_BODY_FIELDS -``` - -### BEACON_BLOCK_BODY_FIELD_TREE_HEIGHT - -```solidity -uint256 BEACON_BLOCK_BODY_FIELD_TREE_HEIGHT -``` - -### NUM_BEACON_STATE_FIELDS - -```solidity -uint256 NUM_BEACON_STATE_FIELDS -``` - -### BEACON_STATE_FIELD_TREE_HEIGHT - -```solidity -uint256 BEACON_STATE_FIELD_TREE_HEIGHT -``` - -### NUM_ETH1_DATA_FIELDS - -```solidity -uint256 NUM_ETH1_DATA_FIELDS -``` - -### ETH1_DATA_FIELD_TREE_HEIGHT - -```solidity -uint256 ETH1_DATA_FIELD_TREE_HEIGHT -``` - -### NUM_VALIDATOR_FIELDS - -```solidity -uint256 NUM_VALIDATOR_FIELDS -``` - -### VALIDATOR_FIELD_TREE_HEIGHT - -```solidity -uint256 VALIDATOR_FIELD_TREE_HEIGHT -``` - -### NUM_EXECUTION_PAYLOAD_HEADER_FIELDS - -```solidity -uint256 NUM_EXECUTION_PAYLOAD_HEADER_FIELDS -``` - -### EXECUTION_PAYLOAD_HEADER_FIELD_TREE_HEIGHT - -```solidity -uint256 EXECUTION_PAYLOAD_HEADER_FIELD_TREE_HEIGHT -``` - -### NUM_EXECUTION_PAYLOAD_FIELDS - -```solidity -uint256 NUM_EXECUTION_PAYLOAD_FIELDS -``` - -### EXECUTION_PAYLOAD_FIELD_TREE_HEIGHT - -```solidity -uint256 EXECUTION_PAYLOAD_FIELD_TREE_HEIGHT -``` - -### HISTORICAL_ROOTS_TREE_HEIGHT - -```solidity -uint256 HISTORICAL_ROOTS_TREE_HEIGHT -``` - -### HISTORICAL_BATCH_TREE_HEIGHT - -```solidity -uint256 HISTORICAL_BATCH_TREE_HEIGHT -``` - -### STATE_ROOTS_TREE_HEIGHT - -```solidity -uint256 STATE_ROOTS_TREE_HEIGHT -``` - -### BLOCK_ROOTS_TREE_HEIGHT - -```solidity -uint256 BLOCK_ROOTS_TREE_HEIGHT -``` - -### NUM_WITHDRAWAL_FIELDS - -```solidity -uint256 NUM_WITHDRAWAL_FIELDS -``` - -### WITHDRAWAL_FIELD_TREE_HEIGHT - -```solidity -uint256 WITHDRAWAL_FIELD_TREE_HEIGHT -``` - -### VALIDATOR_TREE_HEIGHT - -```solidity -uint256 VALIDATOR_TREE_HEIGHT -``` - -### BALANCE_TREE_HEIGHT - -```solidity -uint256 BALANCE_TREE_HEIGHT -``` - -### WITHDRAWALS_TREE_HEIGHT - -```solidity -uint256 WITHDRAWALS_TREE_HEIGHT -``` - -### EXECUTION_PAYLOAD_INDEX - -```solidity -uint256 EXECUTION_PAYLOAD_INDEX -``` - -### STATE_ROOT_INDEX - -```solidity -uint256 STATE_ROOT_INDEX -``` - -### PROPOSER_INDEX_INDEX - -```solidity -uint256 PROPOSER_INDEX_INDEX -``` - -### SLOT_INDEX - -```solidity -uint256 SLOT_INDEX -``` - -### BODY_ROOT_INDEX - -```solidity -uint256 BODY_ROOT_INDEX -``` - -### STATE_ROOTS_INDEX - -```solidity -uint256 STATE_ROOTS_INDEX -``` - -### BLOCK_ROOTS_INDEX - -```solidity -uint256 BLOCK_ROOTS_INDEX -``` - -### HISTORICAL_ROOTS_INDEX - -```solidity -uint256 HISTORICAL_ROOTS_INDEX -``` - -### ETH_1_ROOT_INDEX - -```solidity -uint256 ETH_1_ROOT_INDEX -``` - -### VALIDATOR_TREE_ROOT_INDEX - -```solidity -uint256 VALIDATOR_TREE_ROOT_INDEX -``` - -### BALANCE_INDEX - -```solidity -uint256 BALANCE_INDEX -``` - -### EXECUTION_PAYLOAD_HEADER_INDEX - -```solidity -uint256 EXECUTION_PAYLOAD_HEADER_INDEX -``` - -### HISTORICAL_BATCH_STATE_ROOT_INDEX - -```solidity -uint256 HISTORICAL_BATCH_STATE_ROOT_INDEX -``` - -### VALIDATOR_WITHDRAWAL_CREDENTIALS_INDEX - -```solidity -uint256 VALIDATOR_WITHDRAWAL_CREDENTIALS_INDEX -``` - -### VALIDATOR_BALANCE_INDEX - -```solidity -uint256 VALIDATOR_BALANCE_INDEX -``` - -### VALIDATOR_SLASHED_INDEX - -```solidity -uint256 VALIDATOR_SLASHED_INDEX -``` - -### VALIDATOR_WITHDRAWABLE_EPOCH_INDEX - -```solidity -uint256 VALIDATOR_WITHDRAWABLE_EPOCH_INDEX -``` - -### BLOCK_NUMBER_INDEX - -```solidity -uint256 BLOCK_NUMBER_INDEX -``` - -### WITHDRAWALS_ROOT_INDEX - -```solidity -uint256 WITHDRAWALS_ROOT_INDEX -``` - -### WITHDRAWALS_INDEX - -```solidity -uint256 WITHDRAWALS_INDEX -``` - -### WITHDRAWAL_VALIDATOR_INDEX_INDEX - -```solidity -uint256 WITHDRAWAL_VALIDATOR_INDEX_INDEX -``` - -### WITHDRAWAL_VALIDATOR_AMOUNT_INDEX - -```solidity -uint256 WITHDRAWAL_VALIDATOR_AMOUNT_INDEX -``` - -### HISTORICALBATCH_STATEROOTS_INDEX - -```solidity -uint256 HISTORICALBATCH_STATEROOTS_INDEX -``` - -### SLOTS_PER_EPOCH - -```solidity -uint256 SLOTS_PER_EPOCH -``` - -### UINT64_MASK - -```solidity -bytes8 UINT64_MASK -``` - -### WithdrawalProofs - -```solidity -struct WithdrawalProofs { - bytes blockHeaderProof; - bytes withdrawalProof; - bytes slotProof; - bytes executionPayloadProof; - bytes blockNumberProof; - uint64 blockHeaderRootIndex; - uint64 withdrawalIndex; - bytes32 blockHeaderRoot; - bytes32 blockBodyRoot; - bytes32 slotRoot; - bytes32 blockNumberRoot; - bytes32 executionPayloadRoot; -} -``` - -### ValidatorFieldsAndBalanceProofs - -```solidity -struct ValidatorFieldsAndBalanceProofs { - bytes validatorFieldsProof; - bytes validatorBalanceProof; - bytes32 balanceRoot; -} -``` - -### ValidatorFieldsProof - -```solidity -struct ValidatorFieldsProof { - bytes validatorProof; - uint40 validatorIndex; -} -``` - -### computePhase0BeaconBlockHeaderRoot - -```solidity -function computePhase0BeaconBlockHeaderRoot(bytes32[5] blockHeaderFields) internal pure returns (bytes32) -``` - -### computePhase0BeaconStateRoot - -```solidity -function computePhase0BeaconStateRoot(bytes32[21] beaconStateFields) internal pure returns (bytes32) -``` - -### computePhase0ValidatorRoot - -```solidity -function computePhase0ValidatorRoot(bytes32[8] validatorFields) internal pure returns (bytes32) -``` - -### computePhase0Eth1DataRoot - -```solidity -function computePhase0Eth1DataRoot(bytes32[3] eth1DataFields) internal pure returns (bytes32) -``` - -### getBalanceFromBalanceRoot - -```solidity -function getBalanceFromBalanceRoot(uint40 validatorIndex, bytes32 balanceRoot) internal pure returns (uint64) -``` - -This function is parses the balanceRoot to get the uint64 balance of a validator. During merkleization of the -beacon state balance tree, four uint64 values (making 32 bytes) are grouped together and treated as a single leaf in the merkle tree. Thus the -validatorIndex mod 4 is used to determine which of the four uint64 values to extract from the balanceRoot. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| validatorIndex | uint40 | is the index of the validator being proven for. | -| balanceRoot | bytes32 | is the combination of 4 validator balances being proven for. | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint64 | The validator's balance, in Gwei | - -### verifyValidatorFields - -```solidity -function verifyValidatorFields(uint40 validatorIndex, bytes32 beaconStateRoot, bytes proof, bytes32[] validatorFields) internal view -``` - -This function verifies merkle proofs of the fields of a certain validator against a beacon chain state root - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| validatorIndex | uint40 | the index of the proven validator | -| beaconStateRoot | bytes32 | is the beacon chain state root to be proven against. | -| proof | bytes | is the data used in proving the validator's fields | -| validatorFields | bytes32[] | the claimed fields of the validator | - -### verifyValidatorBalance - -```solidity -function verifyValidatorBalance(uint40 validatorIndex, bytes32 beaconStateRoot, bytes proof, bytes32 balanceRoot) internal view -``` - -This function verifies merkle proofs of the balance of a certain validator against a beacon chain state root - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| validatorIndex | uint40 | the index of the proven validator | -| beaconStateRoot | bytes32 | is the beacon chain state root to be proven against. | -| proof | bytes | is the proof of the balance against the beacon chain state root | -| balanceRoot | bytes32 | is the serialized balance used to prove the balance of the validator (refer to `getBalanceFromBalanceRoot` above for detailed explanation) | - -### verifyWithdrawalProofs - -```solidity -function verifyWithdrawalProofs(bytes32 beaconStateRoot, struct BeaconChainProofs.WithdrawalProofs proofs, bytes32[] withdrawalFields) internal view -``` - -This function verifies the slot and the withdrawal fields for a given withdrawal - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| beaconStateRoot | bytes32 | is the beacon chain state root to be proven against. | -| proofs | struct BeaconChainProofs.WithdrawalProofs | is the provided set of merkle proofs | -| withdrawalFields | bytes32[] | is the serialized withdrawal container to be proven | - diff --git a/docs/docgen/libraries/BytesLib.md b/docs/docgen/libraries/BytesLib.md deleted file mode 100644 index 6d3aa5055..000000000 --- a/docs/docgen/libraries/BytesLib.md +++ /dev/null @@ -1,88 +0,0 @@ -# Solidity API - -## BytesLib - -### concat - -```solidity -function concat(bytes _preBytes, bytes _postBytes) internal pure returns (bytes) -``` - -### concatStorage - -```solidity -function concatStorage(bytes _preBytes, bytes _postBytes) internal -``` - -### slice - -```solidity -function slice(bytes _bytes, uint256 _start, uint256 _length) internal pure returns (bytes) -``` - -### toAddress - -```solidity -function toAddress(bytes _bytes, uint256 _start) internal pure returns (address) -``` - -### toUint8 - -```solidity -function toUint8(bytes _bytes, uint256 _start) internal pure returns (uint8) -``` - -### toUint16 - -```solidity -function toUint16(bytes _bytes, uint256 _start) internal pure returns (uint16) -``` - -### toUint32 - -```solidity -function toUint32(bytes _bytes, uint256 _start) internal pure returns (uint32) -``` - -### toUint64 - -```solidity -function toUint64(bytes _bytes, uint256 _start) internal pure returns (uint64) -``` - -### toUint96 - -```solidity -function toUint96(bytes _bytes, uint256 _start) internal pure returns (uint96) -``` - -### toUint128 - -```solidity -function toUint128(bytes _bytes, uint256 _start) internal pure returns (uint128) -``` - -### toUint256 - -```solidity -function toUint256(bytes _bytes, uint256 _start) internal pure returns (uint256) -``` - -### toBytes32 - -```solidity -function toBytes32(bytes _bytes, uint256 _start) internal pure returns (bytes32) -``` - -### equal - -```solidity -function equal(bytes _preBytes, bytes _postBytes) internal pure returns (bool) -``` - -### equalStorage - -```solidity -function equalStorage(bytes _preBytes, bytes _postBytes) internal view returns (bool) -``` - diff --git a/docs/docgen/libraries/Endian.md b/docs/docgen/libraries/Endian.md deleted file mode 100644 index b0f8941c0..000000000 --- a/docs/docgen/libraries/Endian.md +++ /dev/null @@ -1,27 +0,0 @@ -# Solidity API - -## Endian - -### fromLittleEndianUint64 - -```solidity -function fromLittleEndianUint64(bytes32 lenum) internal pure returns (uint64 n) -``` - -Converts a little endian-formatted uint64 to a big endian-formatted uint64 - -_Note that the input is formatted as a 'bytes32' type (i.e. 256 bits), but it is immediately truncated to a uint64 (i.e. 64 bits) -through a right-shift/shr operation._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| lenum | bytes32 | little endian-formatted uint64 input, provided as 'bytes32' type | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| n | uint64 | The big endian-formatted uint64 | - diff --git a/docs/docgen/libraries/Merkle.md b/docs/docgen/libraries/Merkle.md deleted file mode 100644 index 52b4f8ad0..000000000 --- a/docs/docgen/libraries/Merkle.md +++ /dev/null @@ -1,85 +0,0 @@ -# Solidity API - -## Merkle - -_These functions deal with verification of Merkle Tree proofs. - -The tree and the proofs can be generated using our -https://github.com/OpenZeppelin/merkle-tree[JavaScript library]. -You will find a quickstart guide in the readme. - -WARNING: You should avoid using leaf values that are 64 bytes long prior to -hashing, or use a hash function other than keccak256 for hashing leaves. -This is because the concatenation of a sorted pair of internal nodes in -the merkle tree could be reinterpreted as a leaf value. -OpenZeppelin's JavaScript library generates merkle trees that are safe -against this attack out of the box._ - -### verifyInclusionKeccak - -```solidity -function verifyInclusionKeccak(bytes proof, bytes32 root, bytes32 leaf, uint256 index) internal pure returns (bool) -``` - -_Returns the rebuilt hash obtained by traversing a Merkle tree up -from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt -hash matches the root of the tree. The tree is built assuming `leaf` is -the 0 indexed `index`'th leaf from the bottom left of the tree. - -Note this is for a Merkle tree using the keccak/sha3 hash function_ - -### processInclusionProofKeccak - -```solidity -function processInclusionProofKeccak(bytes proof, bytes32 leaf, uint256 index) internal pure returns (bytes32) -``` - -_Returns the rebuilt hash obtained by traversing a Merkle tree up -from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt -hash matches the root of the tree. The tree is built assuming `leaf` is -the 0 indexed `index`'th leaf from the bottom left of the tree. - -_Available since v4.4._ - -Note this is for a Merkle tree using the keccak/sha3 hash function_ - -### verifyInclusionSha256 - -```solidity -function verifyInclusionSha256(bytes proof, bytes32 root, bytes32 leaf, uint256 index) internal view returns (bool) -``` - -_Returns the rebuilt hash obtained by traversing a Merkle tree up -from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt -hash matches the root of the tree. The tree is built assuming `leaf` is -the 0 indexed `index`'th leaf from the bottom left of the tree. - -Note this is for a Merkle tree using the sha256 hash function_ - -### processInclusionProofSha256 - -```solidity -function processInclusionProofSha256(bytes proof, bytes32 leaf, uint256 index) internal view returns (bytes32) -``` - -_Returns the rebuilt hash obtained by traversing a Merkle tree up -from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt -hash matches the root of the tree. The tree is built assuming `leaf` is -the 0 indexed `index`'th leaf from the bottom left of the tree. - -_Available since v4.4._ - -Note this is for a Merkle tree using the sha256 hash function_ - -### merkleizeSha256 - -```solidity -function merkleizeSha256(bytes32[] leaves) internal pure returns (bytes32) -``` - -this function returns the merkle root of a tree created from a set of leaves using sha256 as its hash function - @param leaves the leaves of the merkle tree - - @notice requires the leaves.length is a power of 2 - @return The computed Merkle root of the tree. - diff --git a/docs/docgen/libraries/MiddlewareUtils.md b/docs/docgen/libraries/MiddlewareUtils.md deleted file mode 100644 index 5bc3e6d83..000000000 --- a/docs/docgen/libraries/MiddlewareUtils.md +++ /dev/null @@ -1,12 +0,0 @@ -# Solidity API - -## MiddlewareUtils - -### computeSignatoryRecordHash - -```solidity -function computeSignatoryRecordHash(uint32 globalDataStoreId, bytes32[] nonSignerPubkeyHashes, uint256 signedStakeFirstQuorum, uint256 signedStakeSecondQuorum) internal pure returns (bytes32) -``` - -Finds the `signatoryRecordHash`, used for fraudproofs. - diff --git a/docs/docgen/libraries/StructuredLinkedList.md b/docs/docgen/libraries/StructuredLinkedList.md deleted file mode 100644 index 8d034c870..000000000 --- a/docs/docgen/libraries/StructuredLinkedList.md +++ /dev/null @@ -1,442 +0,0 @@ -# Solidity API - -## StructuredLinkedList - -Adapted from https://github.com/vittominacori/solidity-linked-list/blob/master/contracts/StructuredLinkedList.sol - -_An utility library for using sorted linked list data structures in your Solidity project._ - -### _NULL - -```solidity -uint256 _NULL -``` - -### _HEAD - -```solidity -uint256 _HEAD -``` - -### _PREV - -```solidity -bool _PREV -``` - -### _NEXT - -```solidity -bool _NEXT -``` - -### List - -```solidity -struct List { - uint256 size; - mapping(uint256 => mapping(bool => uint256)) list; -} -``` - -### listExists - -```solidity -function listExists(struct StructuredLinkedList.List self) internal view returns (bool) -``` - -_Checks if the list exists_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool true if list exists, false otherwise | - -### nodeExists - -```solidity -function nodeExists(struct StructuredLinkedList.List self, uint256 _node) internal view returns (bool) -``` - -_Checks if the node exists_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | a node to search for | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool true if node exists, false otherwise | - -### sizeOf - -```solidity -function sizeOf(struct StructuredLinkedList.List self) internal view returns (uint256) -``` - -_Returns the number of elements in the list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | uint256 | - -### getHead - -```solidity -function getHead(struct StructuredLinkedList.List self) internal view returns (uint256) -``` - -_Gets the head of the list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | uint256 the head of the list | - -### getNode - -```solidity -function getNode(struct StructuredLinkedList.List self, uint256 _node) internal view returns (bool, uint256, uint256) -``` - -_Returns the links of a node as a tuple_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | id of the node to get | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool, uint256, uint256 true if node exists or false otherwise, previous node, next node | -| [1] | uint256 | | -| [2] | uint256 | | - -### getAdjacent - -```solidity -function getAdjacent(struct StructuredLinkedList.List self, uint256 _node, bool _direction) internal view returns (bool, uint256) -``` - -_Returns the link of a node `_node` in direction `_direction`._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | id of the node to step from | -| _direction | bool | direction to step in | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool, uint256 true if node exists or false otherwise, node in _direction | -| [1] | uint256 | | - -### getNextNode - -```solidity -function getNextNode(struct StructuredLinkedList.List self, uint256 _node) internal view returns (bool, uint256) -``` - -_Returns the link of a node `_node` in direction `_NEXT`._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | id of the node to step from | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool, uint256 true if node exists or false otherwise, next node | -| [1] | uint256 | | - -### getPreviousNode - -```solidity -function getPreviousNode(struct StructuredLinkedList.List self, uint256 _node) internal view returns (bool, uint256) -``` - -_Returns the link of a node `_node` in direction `_PREV`._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | id of the node to step from | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool, uint256 true if node exists or false otherwise, previous node | -| [1] | uint256 | | - -### insertAfter - -```solidity -function insertAfter(struct StructuredLinkedList.List self, uint256 _node, uint256 _new) internal returns (bool) -``` - -_Insert node `_new` beside existing node `_node` in direction `_NEXT`._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | existing node | -| _new | uint256 | new node to insert | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool true if success, false otherwise | - -### insertBefore - -```solidity -function insertBefore(struct StructuredLinkedList.List self, uint256 _node, uint256 _new) internal returns (bool) -``` - -_Insert node `_new` beside existing node `_node` in direction `_PREV`._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | existing node | -| _new | uint256 | new node to insert | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool true if success, false otherwise | - -### remove - -```solidity -function remove(struct StructuredLinkedList.List self, uint256 _node) internal returns (uint256) -``` - -_Removes an entry from the linked list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | node to remove from the list | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | uint256 the removed node | - -### pushFront - -```solidity -function pushFront(struct StructuredLinkedList.List self, uint256 _node) internal returns (bool) -``` - -_Pushes an entry to the head of the linked list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | new entry to push to the head | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool true if success, false otherwise | - -### pushBack - -```solidity -function pushBack(struct StructuredLinkedList.List self, uint256 _node) internal returns (bool) -``` - -_Pushes an entry to the tail of the linked list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | new entry to push to the tail | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool true if success, false otherwise | - -### popFront - -```solidity -function popFront(struct StructuredLinkedList.List self) internal returns (uint256) -``` - -_Pops the first entry from the head of the linked list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | uint256 the removed node | - -### popBack - -```solidity -function popBack(struct StructuredLinkedList.List self) internal returns (uint256) -``` - -_Pops the first entry from the tail of the linked list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | uint256 the removed node | - -### _push - -```solidity -function _push(struct StructuredLinkedList.List self, uint256 _node, bool _direction) private returns (bool) -``` - -_Pushes an entry to the head of the linked list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | new entry to push to the head | -| _direction | bool | push to the head (_NEXT) or tail (_PREV) | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool true if success, false otherwise | - -### _pop - -```solidity -function _pop(struct StructuredLinkedList.List self, bool _direction) private returns (uint256) -``` - -_Pops the first entry from the linked list_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _direction | bool | pop from the head (_NEXT) or the tail (_PREV) | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | uint256 the removed node | - -### _insert - -```solidity -function _insert(struct StructuredLinkedList.List self, uint256 _node, uint256 _new, bool _direction) private returns (bool) -``` - -_Insert node `_new` beside existing node `_node` in direction `_direction`._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | existing node | -| _new | uint256 | new node to insert | -| _direction | bool | direction to insert node in | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | bool true if success, false otherwise | - -### _createLink - -```solidity -function _createLink(struct StructuredLinkedList.List self, uint256 _node, uint256 _link, bool _direction) private -``` - -_Creates a bidirectional link between two nodes on direction `_direction`_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| self | struct StructuredLinkedList.List | stored linked list from contract | -| _node | uint256 | existing node | -| _link | uint256 | node to link to in the _direction | -| _direction | bool | direction to insert node in | - diff --git a/docs/docgen/middleware/BLSPublicKeyCompendium.md b/docs/docgen/middleware/BLSPublicKeyCompendium.md deleted file mode 100644 index 3d26ecbb5..000000000 --- a/docs/docgen/middleware/BLSPublicKeyCompendium.md +++ /dev/null @@ -1,51 +0,0 @@ -# Solidity API - -## BLSPublicKeyCompendium - -### ZERO_PK_HASH - -```solidity -bytes32 ZERO_PK_HASH -``` - -### operatorToPubkeyHash - -```solidity -mapping(address => bytes32) operatorToPubkeyHash -``` - -mapping from operator address to pubkey hash - -### pubkeyHashToOperator - -```solidity -mapping(bytes32 => address) pubkeyHashToOperator -``` - -mapping from pubkey hash to operator address - -### NewPubkeyRegistration - -```solidity -event NewPubkeyRegistration(address operator, struct BN254.G1Point pubkeyG1, struct BN254.G2Point pubkeyG2) -``` - -Emitted when `operator` registers with the public key `pk`. - -### registerBLSPublicKey - -```solidity -function registerBLSPublicKey(uint256 s, struct BN254.G1Point rPoint, struct BN254.G1Point pubkeyG1, struct BN254.G2Point pubkeyG2) external -``` - -Called by an operator to register themselves as the owner of a BLS public key and reveal their G1 and G2 public key. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| s | uint256 | is the field element of the operator's Schnorr signature | -| rPoint | struct BN254.G1Point | is the group element of the operator's Schnorr signature | -| pubkeyG1 | struct BN254.G1Point | is the the G1 pubkey of the operator | -| pubkeyG2 | struct BN254.G2Point | is the G2 with the same private key as the pubkeyG1 | - diff --git a/docs/docgen/middleware/BLSRegistry.md b/docs/docgen/middleware/BLSRegistry.md deleted file mode 100644 index 977e8030b..000000000 --- a/docs/docgen/middleware/BLSRegistry.md +++ /dev/null @@ -1,303 +0,0 @@ -# Solidity API - -## BLSRegistry - -This contract is used for -- registering new operators -- committing to and finalizing de-registration as an operator -- updating the stakes of the operator - -### ZERO_PK_HASH - -```solidity -bytes32 ZERO_PK_HASH -``` - -### pubkeyCompendium - -```solidity -contract IBLSPublicKeyCompendium pubkeyCompendium -``` - -contract used for looking up operators' BLS public keys - -### _apkUpdates - -```solidity -struct IBLSRegistry.ApkUpdate[] _apkUpdates -``` - -list of keccak256(apk_x, apk_y) of operators, and the block numbers at which the aggregate -pubkeys were updated. This occurs whenever a new operator registers or deregisters. - -### apk - -```solidity -struct BN254.G1Point apk -``` - -used for storing current aggregate public key - -_Initialized value of APK is the point at infinity: (0, 0)_ - -### operatorWhitelister - -```solidity -address operatorWhitelister -``` - -the address that can whitelist people - -### operatorWhitelistEnabled - -```solidity -bool operatorWhitelistEnabled -``` - -toggle of whether the operator whitelist is on or off - -### whitelisted - -```solidity -mapping(address => bool) whitelisted -``` - -operator => are they whitelisted (can they register with the middleware) - -### Registration - -```solidity -event Registration(address operator, bytes32 pkHash, struct BN254.G1Point pk, uint32 apkHashIndex, bytes32 apkHash, string socket) -``` - -Emitted upon the registration of a new operator for the middleware - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | Address of the new operator | -| pkHash | bytes32 | The keccak256 hash of the operator's public key | -| pk | struct BN254.G1Point | The operator's public key itself | -| apkHashIndex | uint32 | The index of the latest (i.e. the new) APK update | -| apkHash | bytes32 | The keccak256 hash of the new Aggregate Public Key | -| socket | string | | - -### OperatorWhitelisterTransferred - -```solidity -event OperatorWhitelisterTransferred(address previousAddress, address newAddress) -``` - -Emitted when the `operatorWhitelister` role is transferred. - -### onlyOperatorWhitelister - -```solidity -modifier onlyOperatorWhitelister() -``` - -Modifier that restricts a function to only be callable by the `whitelister` role. - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager, contract IServiceManager _serviceManager, uint8 _NUMBER_OF_QUORUMS, contract IBLSPublicKeyCompendium _pubkeyCompendium) public -``` - -### initialize - -```solidity -function initialize(address _operatorWhitelister, bool _operatorWhitelistEnabled, uint256[] _quorumBips, struct VoteWeigherBaseStorage.StrategyAndWeightingMultiplier[] _firstQuorumStrategiesConsideredAndMultipliers, struct VoteWeigherBaseStorage.StrategyAndWeightingMultiplier[] _secondQuorumStrategiesConsideredAndMultipliers) public virtual -``` - -Initialize the APK, the payment split between quorums, and the quorum strategies + multipliers. - -### setOperatorWhitelister - -```solidity -function setOperatorWhitelister(address _operatorWhitelister) external -``` - -Called by the service manager owner to transfer the whitelister role to another address - -### setOperatorWhitelistStatus - -```solidity -function setOperatorWhitelistStatus(bool _operatorWhitelistEnabled) external -``` - -Callable only by the service manager owner, this function toggles the whitelist on or off - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _operatorWhitelistEnabled | bool | true if turning whitelist on, false otherwise | - -### addToOperatorWhitelist - -```solidity -function addToOperatorWhitelist(address[] operators) external -``` - -Called by the whitelister, adds a list of operators to the whitelist - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operators | address[] | the operators to add to the whitelist | - -### removeFromWhitelist - -```solidity -function removeFromWhitelist(address[] operators) external -``` - -Called by the whitelister, removes a list of operators to the whitelist - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operators | address[] | the operators to remove from the whitelist | - -### registerOperator - -```solidity -function registerOperator(uint8 operatorType, struct BN254.G1Point pk, string socket) external virtual -``` - -called for registering as an operator - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operatorType | uint8 | specifies whether the operator want to register as staker for one or both quorums | -| pk | struct BN254.G1Point | is the operator's G1 public key | -| socket | string | is the socket address of the operator | - -### _registerOperator - -```solidity -function _registerOperator(address operator, uint8 operatorType, struct BN254.G1Point pk, string socket) internal -``` - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | is the node who is registering to be a operator | -| operatorType | uint8 | specifies whether the operator want to register as staker for one or both quorums | -| pk | struct BN254.G1Point | is the operator's G1 public key | -| socket | string | is the socket address of the operator | - -### deregisterOperator - -```solidity -function deregisterOperator(struct BN254.G1Point pkToRemove, uint32 index) external virtual returns (bool) -``` - -Used by an operator to de-register itself from providing service to the middleware. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| pkToRemove | struct BN254.G1Point | is the sender's pubkey in affine coordinates | -| index | uint32 | is the sender's location in the dynamic array `operatorList` | - -### _deregisterOperator - -```solidity -function _deregisterOperator(address operator, struct BN254.G1Point pkToRemove, uint32 index) internal -``` - -Used to process de-registering an operator from providing service to the middleware. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | The operator to be deregistered | -| pkToRemove | struct BN254.G1Point | is the sender's pubkey | -| index | uint32 | is the sender's location in the dynamic array `operatorList` | - -### updateStakes - -```solidity -function updateStakes(address[] operators, uint256[] prevElements) external -``` - -Used for updating information on deposits of nodes. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operators | address[] | are the nodes whose deposit information is getting updated | -| prevElements | uint256[] | are the elements before this middleware in the operator's linked list within the slasher | - -### _processApkUpdate - -```solidity -function _processApkUpdate(struct BN254.G1Point newApk) internal returns (bytes32) -``` - -Updates the stored APK to `newApk`, calculates its hash, and pushes new entries to the `_apkUpdates` array - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newApk | struct BN254.G1Point | The updated APK. This will be the `apk` after this function runs! | - -### _setOperatorWhitelister - -```solidity -function _setOperatorWhitelister(address _operatorWhitelister) internal -``` - -### getCorrectApkHash - -```solidity -function getCorrectApkHash(uint256 index, uint32 blockNumber) external view returns (bytes32) -``` - -get hash of a historical aggregated public key corresponding to a given index; -called by checkSignatures in BLSSignatureChecker.sol. - -### getApkUpdatesLength - -```solidity -function getApkUpdatesLength() external view returns (uint256) -``` - -returns the total number of APK updates that have ever occurred (including one for initializing the pubkey as the generator) - -### apkUpdates - -```solidity -function apkUpdates(uint256 index) external view returns (struct IBLSRegistry.ApkUpdate) -``` - -returns the `ApkUpdate` struct at `index` in the list of APK updates - -### apkHashes - -```solidity -function apkHashes(uint256 index) external view returns (bytes32) -``` - -returns the APK hash that resulted from the `index`th APK update - -### apkUpdateBlockNumbers - -```solidity -function apkUpdateBlockNumbers(uint256 index) external view returns (uint32) -``` - -returns the block number at which the `index`th APK update occurred - diff --git a/docs/docgen/middleware/BLSSignatureChecker.md b/docs/docgen/middleware/BLSSignatureChecker.md deleted file mode 100644 index 79c818bc0..000000000 --- a/docs/docgen/middleware/BLSSignatureChecker.md +++ /dev/null @@ -1,193 +0,0 @@ -# Solidity API - -## BLSSignatureChecker - -This is the contract for checking the validity of aggregate operator signatures. - -### SignatoryTotals - -```solidity -struct SignatoryTotals { - uint256 signedStakeFirstQuorum; - uint256 signedStakeSecondQuorum; - uint256 totalStakeFirstQuorum; - uint256 totalStakeSecondQuorum; -} -``` - -### SignatoryRecord - -```solidity -event SignatoryRecord(bytes32 msgHash, uint32 taskNumber, uint256 signedStakeFirstQuorum, uint256 signedStakeSecondQuorum, bytes32[] pubkeyHashes) -``` - -used for recording the event that signature has been checked in checkSignatures function. - -### registry - -```solidity -contract IQuorumRegistry registry -``` - -### constructor - -```solidity -constructor(contract IQuorumRegistry _registry) internal -``` - -### BYTE_LENGTH_totalStakeIndex - -```solidity -uint256 BYTE_LENGTH_totalStakeIndex -``` - -### BYTE_LENGTH_referenceBlockNumber - -```solidity -uint256 BYTE_LENGTH_referenceBlockNumber -``` - -### BYTE_LENGTH_taskNumberToConfirm - -```solidity -uint256 BYTE_LENGTH_taskNumberToConfirm -``` - -### BYTE_LENGTH_numberNonSigners - -```solidity -uint256 BYTE_LENGTH_numberNonSigners -``` - -### BYTE_LENGTH_G1_POINT - -```solidity -uint256 BYTE_LENGTH_G1_POINT -``` - -### BYTE_LENGTH_G2_POINT - -```solidity -uint256 BYTE_LENGTH_G2_POINT -``` - -### BYTE_LENGTH_stakeIndex - -```solidity -uint256 BYTE_LENGTH_stakeIndex -``` - -### BYTE_LENGTH_NON_SIGNER_INFO - -```solidity -uint256 BYTE_LENGTH_NON_SIGNER_INFO -``` - -### BYTE_LENGTH_apkIndex - -```solidity -uint256 BYTE_LENGTH_apkIndex -``` - -### BIT_SHIFT_totalStakeIndex - -```solidity -uint256 BIT_SHIFT_totalStakeIndex -``` - -### BIT_SHIFT_referenceBlockNumber - -```solidity -uint256 BIT_SHIFT_referenceBlockNumber -``` - -### BIT_SHIFT_taskNumberToConfirm - -```solidity -uint256 BIT_SHIFT_taskNumberToConfirm -``` - -### BIT_SHIFT_numberNonSigners - -```solidity -uint256 BIT_SHIFT_numberNonSigners -``` - -### BIT_SHIFT_stakeIndex - -```solidity -uint256 BIT_SHIFT_stakeIndex -``` - -### BIT_SHIFT_apkIndex - -```solidity -uint256 BIT_SHIFT_apkIndex -``` - -### CALLDATA_OFFSET_totalStakeIndex - -```solidity -uint256 CALLDATA_OFFSET_totalStakeIndex -``` - -### CALLDATA_OFFSET_referenceBlockNumber - -```solidity -uint256 CALLDATA_OFFSET_referenceBlockNumber -``` - -### CALLDATA_OFFSET_taskNumberToConfirm - -```solidity -uint256 CALLDATA_OFFSET_taskNumberToConfirm -``` - -### CALLDATA_OFFSET_numberNonSigners - -```solidity -uint256 CALLDATA_OFFSET_numberNonSigners -``` - -### CALLDATA_OFFSET_NonsignerPubkeys - -```solidity -uint256 CALLDATA_OFFSET_NonsignerPubkeys -``` - -### checkSignatures - -```solidity -function checkSignatures(bytes data) public returns (uint32 taskNumberToConfirm, uint32 referenceBlockNumber, bytes32 msgHash, struct BLSSignatureChecker.SignatoryTotals signedTotals, bytes32 compressedSignatoryRecord) -``` - -_This calldata is of the format: -< -bytes32 msgHash, the taskHash for which disperser is calling checkSignatures -uint48 index of the totalStake corresponding to the dataStoreId in the 'totalStakeHistory' array of the BLSRegistry -uint32 blockNumber, the blockNumber at which the task was initated -uint32 taskNumberToConfirm -uint32 numberOfNonSigners, -{uint256[2] pubkeyG1, uint32 stakeIndex}[numberOfNonSigners] the G1 public key and the index to query of `pubkeyHashToStakeHistory` for each nonsigner, -uint32 apkIndex, the index in the `apkUpdates` array at which we want to load the aggregate public key -uint256[2] apkG1 (G1 aggregate public key, including nonSigners), -uint256[4] apkG2 (G2 aggregate public key, not including nonSigners), -uint256[2] sigma, the aggregate signature itself -> - -Before signature verification, the function verifies operator stake information. This includes ensuring that the provided `referenceBlockNumber` -is correct, i.e., ensure that the stake returned from the specified block number is recent enough and that the stake is either the most recent update -for the total stake (or the operator) or latest before the referenceBlockNumber. -The next step involves computing the aggregated pub key of all the operators that are not part of the quorum for this specific taskNumber. -We use a loop to iterate through the `nonSignerPK` array, loading each individual public key from calldata. Before the loop, we isolate the first public key -calldataload - this implementation saves us one ecAdd operation, which would be performed in the i=0 iteration otherwise. -Within the loop, each non-signer public key is loaded from the calldata into memory. The most recent staking-related information is retrieved and is subtracted -from the total stake of validators in the quorum. Then the aggregate public key and the aggregate non-signer public key is subtracted from it. -Finally the siganture is verified by computing the elliptic curve pairing._ - -### _validateOperatorStake - -```solidity -function _validateOperatorStake(struct IQuorumRegistry.OperatorStake opStake, uint32 referenceBlockNumber) internal pure -``` - diff --git a/docs/docgen/middleware/PaymentManager.md b/docs/docgen/middleware/PaymentManager.md deleted file mode 100644 index b61ce3c51..000000000 --- a/docs/docgen/middleware/PaymentManager.md +++ /dev/null @@ -1,456 +0,0 @@ -# Solidity API - -## PaymentManager - -This contract is used for doing interactive payment challenges. -The contract is marked as abstract since it does not implement the `respondToPaymentChallengeFinal` -function -- see DataLayerPaymentManager for an example - -### PAUSED_NEW_PAYMENT_COMMIT - -```solidity -uint8 PAUSED_NEW_PAYMENT_COMMIT -``` - -### PAUSED_REDEEM_PAYMENT - -```solidity -uint8 PAUSED_REDEEM_PAYMENT -``` - -### paymentFraudproofInterval - -```solidity -uint256 paymentFraudproofInterval -``` - -Challenge window for submitting fraudproof in the case of an incorrect payment claim by a registered operator. - -### MAX_BIPS - -```solidity -uint256 MAX_BIPS -``` - -Constant used as a divisor in dealing with BIPS amounts - -### LOW_LEVEL_GAS_BUDGET - -```solidity -uint256 LOW_LEVEL_GAS_BUDGET -``` - -Gas budget provided in calls to DelegationTerms contracts - -### delegationManager - -```solidity -contract IDelegationManager delegationManager -``` - -The global EigenLayer Delegation contract, which is primarily used by -stakers to delegate their stake to operators who serve as middleware nodes. - -_For more details, see DelegationManager.sol._ - -### serviceManager - -```solidity -contract IServiceManager serviceManager -``` - -The ServiceManager contract for this middleware, where tasks are created / initiated. - -### registry - -```solidity -contract IQuorumRegistry registry -``` - -The Registry contract for this middleware, where operators register and deregister. - -### paymentToken - -```solidity -contract IERC20 paymentToken -``` - -the ERC20 token that will be used by the disperser to pay the service fees to middleware nodes. - -### paymentChallengeToken - -```solidity -contract IERC20 paymentChallengeToken -``` - -Token used for placing a guarantee on challenges & payment commits - -### paymentChallengeAmount - -```solidity -uint256 paymentChallengeAmount -``` - -Specifies the payment that has to be made as a guarantee for fraudproof during payment challenges. - -### operatorToPayment - -```solidity -mapping(address => struct IPaymentManager.Payment) operatorToPayment -``` - -mapping between the operator and its current committed payment or last redeemed payment - -### operatorToPaymentChallenge - -```solidity -mapping(address => struct IPaymentManager.PaymentChallenge) operatorToPaymentChallenge -``` - -mapping from operator => PaymentChallenge - -### depositsOf - -```solidity -mapping(address => uint256) depositsOf -``` - -Deposits of future fees to be drawn against when paying for service from the middleware - -### allowances - -```solidity -mapping(address => mapping(address => uint256)) allowances -``` - -depositors => addresses approved to spend deposits => allowance - -### PaymentChallengeAmountSet - -```solidity -event PaymentChallengeAmountSet(uint256 previousValue, uint256 newValue) -``` - -Emitted when the `paymentChallengeAmount` variable is modified - -### PaymentCommit - -```solidity -event PaymentCommit(address operator, uint32 fromTaskNumber, uint32 toTaskNumber, uint256 fee) -``` - -Emitted when an operator commits to a payment by calling the `commitPayment` function - -### PaymentChallengeInit - -```solidity -event PaymentChallengeInit(address operator, address challenger) -``` - -Emitted when a new challenge is created through a call to the `initPaymentChallenge` function - -### PaymentRedemption - -```solidity -event PaymentRedemption(address operator, uint256 fee) -``` - -Emitted when an operator redeems a payment by calling the `redeemPayment` function - -### PaymentBreakdown - -```solidity -event PaymentBreakdown(address operator, uint32 fromTaskNumber, uint32 toTaskNumber, uint96 amount1, uint96 amount2) -``` - -Emitted when a bisection step is performed in a challenge, through a call to the `performChallengeBisectionStep` function - -### PaymentChallengeResolution - -```solidity -event PaymentChallengeResolution(address operator, bool operatorWon) -``` - -Emitted upon successful resolution of a payment challenge, within a call to `resolveChallenge` - -### OnPayForServiceCallFailure - -```solidity -event OnPayForServiceCallFailure(contract IDelegationTerms delegationTerms, bytes32 returnData) -``` - -_Emitted when a low-level call to `delegationTerms.payForService` fails, returning `returnData`_ - -### onlyServiceManager - -```solidity -modifier onlyServiceManager() -``` - -when applied to a function, ensures that the function is only callable by the `serviceManager` - -### onlyRegistry - -```solidity -modifier onlyRegistry() -``` - -when applied to a function, ensures that the function is only callable by the `registry` - -### onlyServiceManagerOwner - -```solidity -modifier onlyServiceManagerOwner() -``` - -when applied to a function, ensures that the function is only callable by the owner of the `serviceManager` - -### constructor - -```solidity -constructor(contract IDelegationManager _delegationManager, contract IServiceManager _serviceManager, contract IQuorumRegistry _registry, contract IERC20 _paymentToken, contract IERC20 _paymentChallengeToken) internal -``` - -### initialize - -```solidity -function initialize(contract IPauserRegistry _pauserReg, uint256 _paymentChallengeAmount) public -``` - -### depositFutureFees - -```solidity -function depositFutureFees(address depositFor, uint256 amount) external -``` - -deposit one-time fees by the `msg.sender` with this contract to pay for future tasks of this middleware - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositFor | address | could be the `msg.sender` themselves, or a different address for whom `msg.sender` is depositing these future fees | -| amount | uint256 | is amount of futures fees being deposited | - -### setAllowance - -```solidity -function setAllowance(address allowed, uint256 amount) external -``` - -Allows the `allowed` address to spend up to `amount` of the `msg.sender`'s funds that have been deposited in this contract - -### setPaymentChallengeAmount - -```solidity -function setPaymentChallengeAmount(uint256 _paymentChallengeAmount) external virtual -``` - -Modifies the `paymentChallengeAmount` amount. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _paymentChallengeAmount | uint256 | The new value for `paymentChallengeAmount` to take. | - -### takeFee - -```solidity -function takeFee(address initiator, address payer, uint256 feeAmount) external virtual -``` - -Used for deducting the fees from the payer to the middleware - -### commitPayment - -```solidity -function commitPayment(uint32 toTaskNumber, uint96 amount) external -``` - -This is used by an operator to make a claim on the amount that they deserve for their service from their last payment until `toTaskNumber` - -_Once this payment is recorded, a fraud proof period commences during which a challenger can dispute the proposed payment._ - -### redeemPayment - -```solidity -function redeemPayment() external -``` - -Called by an operator to redeem a payment that they previously 'committed' to by calling `commitPayment`. - -_This function can only be called after the challenge window for the payment claim has completed._ - -### _payForServiceHook - -```solidity -function _payForServiceHook(contract IDelegationTerms dt, uint256 amount) internal -``` - -### initPaymentChallenge - -```solidity -function initPaymentChallenge(address operator, uint96 amount1, uint96 amount2) external -``` - -This function is called by a fraud prover to challenge a payment, initiating an interactive-type fraudproof. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | is the operator against whose payment claim the fraudproof is being made | -| amount1 | uint96 | is the reward amount the challenger in that round claims is for the first half of tasks | -| amount2 | uint96 | is the reward amount the challenger in that round claims is for the second half of tasks | - -### performChallengeBisectionStep - -```solidity -function performChallengeBisectionStep(address operator, bool secondHalf, uint96 amount1, uint96 amount2) external -``` - -Perform a single bisection step in an existing interactive payment challenge. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | The middleware operator who was challenged (used to look up challenge details) | -| secondHalf | bool | If true, then the caller wishes to challenge the amount claimed as payment in the *second half* of the previous bisection step. If false then the *first half* is indicated instead. | -| amount1 | uint96 | The amount that the caller asserts the operator is entitled to, for the first half *of the challenged half* of the previous bisection. | -| amount2 | uint96 | The amount that the caller asserts the operator is entitled to, for the second half *of the challenged half* of the previous bisection. | - -### _updateStatus - -```solidity -function _updateStatus(address operator, uint32 diff) internal returns (bool) -``` - -This function is used for updating the status of the challenge in terms of who has to respon -to the interactive challenge mechanism next - is it going to be challenger or the operator. - -_If the challenge is over only one task, then the challenge is marked specially as a one step challenge – -the smallest unit over which a challenge can be proposed – and 'true' is returned. -Otherwise status is updated normally and 'false' is returned._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | is the operator whose payment claim is being challenged | -| diff | uint32 | is the number of tasks across which payment is being challenged in this iteration | - -### _updateChallengeAmounts - -```solidity -function _updateChallengeAmounts(address operator, enum IPaymentManager.DissectionType dissectionType, uint96 amount1, uint96 amount2) internal -``` - -Used to update challenge amounts when the operator (or challenger) breaks down the challenged amount (single bisection step) - -### resolveChallenge - -```solidity -function resolveChallenge(address operator) external -``` - -resolve an existing PaymentChallenge for an operator - -### _resolve - -```solidity -function _resolve(struct IPaymentManager.PaymentChallenge challenge, address winner) internal -``` - -Resolves a single payment challenge, paying the winner. - -_If challenger is proven correct, then they are refunded their own challengeAmount plus the challengeAmount put up by the operator. -If operator is proven correct, then the challenger's challengeAmount is transferred to them, since the operator still hasn't been -proven right, and thus their challengeAmount is still required in case they are challenged again._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| challenge | struct IPaymentManager.PaymentChallenge | The challenge that is being resolved. | -| winner | address | Address of the winner of the challenge. | - -### getChallengeStatus - -```solidity -function getChallengeStatus(address operator) external view returns (enum IPaymentManager.ChallengeStatus) -``` - -Returns the ChallengeStatus for the `operator`'s payment claim. - -### getAmount1 - -```solidity -function getAmount1(address operator) external view returns (uint96) -``` - -Returns the 'amount1' for the `operator`'s payment claim. - -### getAmount2 - -```solidity -function getAmount2(address operator) external view returns (uint96) -``` - -Returns the 'amount2' for the `operator`'s payment claim. - -### getToTaskNumber - -```solidity -function getToTaskNumber(address operator) external view returns (uint48) -``` - -Returns the 'toTaskNumber' for the `operator`'s payment claim. - -### getFromTaskNumber - -```solidity -function getFromTaskNumber(address operator) external view returns (uint48) -``` - -Returns the 'fromTaskNumber' for the `operator`'s payment claim. - -### getDiff - -```solidity -function getDiff(address operator) external view returns (uint48) -``` - -Returns the task number difference for the `operator`'s payment claim. - -### getPaymentChallengeAmount - -```solidity -function getPaymentChallengeAmount(address operator) external view returns (uint256) -``` - -Returns the active challengeAmount of the `operator` placed on their payment claim. - -### _taskNumber - -```solidity -function _taskNumber() internal view returns (uint32) -``` - -Convenience function for fetching the current taskNumber from the `serviceManager` - -### _setPaymentChallengeAmount - -```solidity -function _setPaymentChallengeAmount(uint256 _paymentChallengeAmount) internal -``` - -Modifies the `paymentChallengeAmount` amount. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _paymentChallengeAmount | uint256 | The new value for `paymentChallengeAmount` to take. | - diff --git a/docs/docgen/middleware/RegistryBase.md b/docs/docgen/middleware/RegistryBase.md deleted file mode 100644 index bb7241808..000000000 --- a/docs/docgen/middleware/RegistryBase.md +++ /dev/null @@ -1,461 +0,0 @@ -# Solidity API - -## RegistryBase - -This contract is used for -- registering new operators -- committing to and finalizing de-registration as an operator -- updating the stakes of the operator - -_This contract is missing key functions. See `BLSRegistry` or `ECDSARegistry` for examples that inherit from this contract._ - -### minimumStakeFirstQuorum - -```solidity -uint128 minimumStakeFirstQuorum -``` - -In order to register, an operator must have at least `minimumStakeFirstQuorum` or `minimumStakeSecondQuorum`, as -evaluated by this contract's 'VoteWeigher' logic. - -### minimumStakeSecondQuorum - -```solidity -uint128 minimumStakeSecondQuorum -``` - -### registry - -```solidity -mapping(address => struct IQuorumRegistry.Operator) registry -``` - -used for storing Operator info on each operator while registration - -### operatorList - -```solidity -address[] operatorList -``` - -used for storing the list of current and past registered operators - -### totalStakeHistory - -```solidity -struct IQuorumRegistry.OperatorStake[] totalStakeHistory -``` - -array of the history of the total stakes -- marked as internal since getTotalStakeFromIndex is a getter for this - -### totalOperatorsHistory - -```solidity -struct IQuorumRegistry.OperatorIndex[] totalOperatorsHistory -``` - -array of the history of the number of operators, and the taskNumbers at which the number of operators changed - -### pubkeyHashToStakeHistory - -```solidity -mapping(bytes32 => struct IQuorumRegistry.OperatorStake[]) pubkeyHashToStakeHistory -``` - -mapping from operator's pubkeyhash to the history of their stake updates - -### pubkeyHashToIndexHistory - -```solidity -mapping(bytes32 => struct IQuorumRegistry.OperatorIndex[]) pubkeyHashToIndexHistory -``` - -mapping from operator's pubkeyhash to the history of their index in the array of all operators - -### SocketUpdate - -```solidity -event SocketUpdate(address operator, string socket) -``` - -emitted when `operator` updates their socket address to `socket` - -### StakeUpdate - -```solidity -event StakeUpdate(address operator, uint96 firstQuorumStake, uint96 secondQuorumStake, uint32 updateBlockNumber, uint32 prevUpdateBlockNumber) -``` - -emitted whenever the stake of `operator` is updated - -### Deregistration - -```solidity -event Deregistration(address operator, address swapped) -``` - -Emitted whenever an operator deregisters. -The `swapped` address is the address returned by an internal call to the `_popRegistrant` function. - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager, contract IServiceManager _serviceManager, uint8 _NUMBER_OF_QUORUMS) internal -``` - -Irrevocably sets the (immutable) `delegation` & `strategyManager` addresses, and `NUMBER_OF_QUORUMS` variable. - -### _initialize - -```solidity -function _initialize(uint256[] _quorumBips, struct VoteWeigherBaseStorage.StrategyAndWeightingMultiplier[] _firstQuorumStrategiesConsideredAndMultipliers, struct VoteWeigherBaseStorage.StrategyAndWeightingMultiplier[] _secondQuorumStrategiesConsideredAndMultipliers) internal virtual -``` - -Adds empty first entries to the dynamic arrays `totalStakeHistory` and `totalOperatorsHistory`, -to record an initial condition of zero operators with zero total stake. -Adds `_firstQuorumStrategiesConsideredAndMultipliers` and `_secondQuorumStrategiesConsideredAndMultipliers` to the dynamic arrays -`strategiesConsideredAndMultipliers[0]` and `strategiesConsideredAndMultipliers[1]` (i.e. to the weighing functions of the quorums) - -### getOperatorIndex - -```solidity -function getOperatorIndex(address operator, uint32 blockNumber, uint32 index) external view returns (uint32) -``` - -Looks up the `operator`'s index in the dynamic array `operatorList` at the specified `blockNumber`. - -_Function will revert in the event that the specified `index` input does not identify the appropriate entry in the -array `pubkeyHashToIndexHistory[pubkeyHash]` to pull the info from._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | | -| blockNumber | uint32 | Is the desired block number at which we wish to query the operator's position in the `operatorList` array | -| index | uint32 | Used to specify the entry within the dynamic array `pubkeyHashToIndexHistory[pubkeyHash]` to read data from, where `pubkeyHash` is looked up from `operator`'s registration info | - -### getTotalOperators - -```solidity -function getTotalOperators(uint32 blockNumber, uint32 index) external view returns (uint32) -``` - -Looks up the number of total operators at the specified `blockNumber`. - -_This function will revert if the provided `index` is out of bounds._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| blockNumber | uint32 | | -| index | uint32 | Input used to specify the entry within the dynamic array `totalOperatorsHistory` to read data from. | - -### isActiveOperator - -```solidity -function isActiveOperator(address operator) external view virtual returns (bool) -``` - -Returns whether or not the `operator` is currently an active operator, i.e. is "registered". - -### getOperatorPubkeyHash - -```solidity -function getOperatorPubkeyHash(address operator) public view returns (bytes32) -``` - -Returns the stored pubkeyHash for the specified `operator`. - -### getStakeFromPubkeyHashAndIndex - -```solidity -function getStakeFromPubkeyHashAndIndex(bytes32 pubkeyHash, uint256 index) external view returns (struct IQuorumRegistry.OperatorStake) -``` - -Returns the stake weight corresponding to `pubkeyHash`, at the -`index`-th entry in the `pubkeyHashToStakeHistory[pubkeyHash]` array. - -_Function will revert if `index` is out-of-bounds._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| pubkeyHash | bytes32 | Hash of the public key of the operator of interest. | -| index | uint256 | Array index for lookup, within the dynamic array `pubkeyHashToStakeHistory[pubkeyHash]`. | - -### checkOperatorActiveAtBlockNumber - -```solidity -function checkOperatorActiveAtBlockNumber(address operator, uint256 blockNumber, uint256 stakeHistoryIndex) external view returns (bool) -``` - -Checks that the `operator` was active at the `blockNumber`, using the specified `stakeHistoryIndex` as proof. - -_In order for this function to return 'true', the inputs must satisfy all of the following list: -1) `pubkeyHashToStakeHistory[pubkeyHash][index].updateBlockNumber <= blockNumber` -2) `pubkeyHashToStakeHistory[pubkeyHash][index].nextUpdateBlockNumber` must be either `0` (signifying no next update) or -is must be strictly greater than `blockNumber` -3) `pubkeyHashToStakeHistory[pubkeyHash][index].firstQuorumStake > 0` -or `pubkeyHashToStakeHistory[pubkeyHash][index].secondQuorumStake > 0`, i.e. the operator had nonzero stake -Note that a return value of 'false' does not guarantee that the `operator` was inactive at `blockNumber`, since a -bad `stakeHistoryIndex` can be supplied in order to obtain a response of 'false'._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | is the operator of interest | -| blockNumber | uint256 | is the block number of interest | -| stakeHistoryIndex | uint256 | specifies an index in `pubkeyHashToStakeHistory[pubkeyHash]`, where `pubkeyHash` is looked up in `registry[operator].pubkeyHash` | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | 'true' if it is successfully proven that the `operator` was active at the `blockNumber`, and 'false' otherwise | - -### checkOperatorInactiveAtBlockNumber - -```solidity -function checkOperatorInactiveAtBlockNumber(address operator, uint256 blockNumber, uint256 stakeHistoryIndex) external view returns (bool) -``` - -Checks that the `operator` was inactive at the `blockNumber`, using the specified `stakeHistoryIndex` as proof. - -_In order for this function to return 'true', the inputs must satisfy all of the following list: -1) `pubkeyHashToStakeHistory[pubkeyHash][index].updateBlockNumber <= blockNumber` -2) `pubkeyHashToStakeHistory[pubkeyHash][index].nextUpdateBlockNumber` must be either `0` (signifying no next update) or -is must be strictly greater than `blockNumber` -3) `pubkeyHashToStakeHistory[pubkeyHash][index].firstQuorumStake > 0` -or `pubkeyHashToStakeHistory[pubkeyHash][index].secondQuorumStake > 0`, i.e. the operator had nonzero stake -Note that a return value of 'false' does not guarantee that the `operator` was active at `blockNumber`, since a -bad `stakeHistoryIndex` can be supplied in order to obtain a response of 'false'._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | is the operator of interest | -| blockNumber | uint256 | is the block number of interest | -| stakeHistoryIndex | uint256 | specifies an index in `pubkeyHashToStakeHistory[pubkeyHash]`, where `pubkeyHash` is looked up in `registry[operator].pubkeyHash` | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | bool | 'true' if it is successfully proven that the `operator` was inactive at the `blockNumber`, and 'false' otherwise | - -### getMostRecentStakeByOperator - -```solidity -function getMostRecentStakeByOperator(address operator) public view returns (struct IQuorumRegistry.OperatorStake) -``` - -Returns the most recent stake weight for the `operator` - -_Function returns an OperatorStake struct with **every entry equal to 0** in the event that the operator has no stake history_ - -### getStakeHistoryLength - -```solidity -function getStakeHistoryLength(bytes32 pubkeyHash) external view returns (uint256) -``` - -### firstQuorumStakedByOperator - -```solidity -function firstQuorumStakedByOperator(address operator) external view returns (uint96) -``` - -### secondQuorumStakedByOperator - -```solidity -function secondQuorumStakedByOperator(address operator) external view returns (uint96) -``` - -### operatorStakes - -```solidity -function operatorStakes(address operator) public view returns (uint96, uint96) -``` - -Returns the most recent stake weights for the `operator` - -_Function returns weights of **0** in the event that the operator has no stake history_ - -### totalStake - -```solidity -function totalStake() external view returns (uint96, uint96) -``` - -Returns the stake amounts from the latest entry in `totalStakeHistory`. - -### getLengthOfPubkeyHashStakeHistory - -```solidity -function getLengthOfPubkeyHashStakeHistory(bytes32 pubkeyHash) external view returns (uint256) -``` - -### getLengthOfPubkeyHashIndexHistory - -```solidity -function getLengthOfPubkeyHashIndexHistory(bytes32 pubkeyHash) external view returns (uint256) -``` - -### getLengthOfTotalStakeHistory - -```solidity -function getLengthOfTotalStakeHistory() external view returns (uint256) -``` - -### getLengthOfTotalOperatorsHistory - -```solidity -function getLengthOfTotalOperatorsHistory() external view returns (uint256) -``` - -### getTotalStakeFromIndex - -```solidity -function getTotalStakeFromIndex(uint256 index) external view returns (struct IQuorumRegistry.OperatorStake) -``` - -Returns the `index`-th entry in the dynamic array of total stake, `totalStakeHistory`. - -_Function will revert in the event that `index` is out-of-bounds._ - -### getFromTaskNumberForOperator - -```solidity -function getFromTaskNumberForOperator(address operator) external view returns (uint32) -``` - -Returns task number from when `operator` has been registered. - -### numOperators - -```solidity -function numOperators() public view returns (uint32) -``` - -Returns the current number of operators of this service. - -### setMinimumStakeFirstQuorum - -```solidity -function setMinimumStakeFirstQuorum(uint128 _minimumStakeFirstQuorum) external -``` - -Adjusts the `minimumStakeFirstQuorum` -- i.e. the node stake (weight) requirement for inclusion in the 1st quorum. - -### setMinimumStakeSecondQuorum - -```solidity -function setMinimumStakeSecondQuorum(uint128 _minimumStakeSecondQuorum) external -``` - -Adjusts the `minimumStakeSecondQuorum` -- i.e. the node stake (weight) requirement for inclusion in the 2nd quorum. - -### updateSocket - -```solidity -function updateSocket(string newSocket) external -``` - -### _updateTotalOperatorsHistory - -```solidity -function _updateTotalOperatorsHistory() internal -``` - -Called when the total number of operators has changed. -Sets the `toBlockNumber` field on the last entry *so far* in thedynamic array `totalOperatorsHistory` to the current `block.number`, -recording that the previous entry is *no longer the latest* and the block number at which the next was added. -Pushes a new entry to `totalOperatorsHistory`, with `index` field set equal to the new amount of operators, recording the new number -of total operators (and leaving the `toBlockNumber` field at zero, signaling that this is the latest entry in the array) - -### _removeOperator - -```solidity -function _removeOperator(address operator, bytes32 pubkeyHash, uint32 index) internal virtual -``` - -Remove the operator from active status. Removes the operator with the given `pubkeyHash` from the `index` in `operatorList`, -updates operatorList and index histories, and performs other necessary updates for removing operator - -### _removeOperatorStake - -```solidity -function _removeOperatorStake(bytes32 pubkeyHash) internal returns (uint32) -``` - -Removes the stakes of the operator with pubkeyHash `pubkeyHash` - -### _popRegistrant - -```solidity -function _popRegistrant(uint32 index) internal returns (address swappedOperator) -``` - -Removes the registrant at the given `index` from the `operatorList` - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| swappedOperator | address | is the operator who was swapped with the removed operator in the operatorList, or the *zero address* in the case that the removed operator was already the list operator in the operatorList. | - -### _addRegistrant - -```solidity -function _addRegistrant(address operator, bytes32 pubkeyHash, struct IQuorumRegistry.OperatorStake _operatorStake) internal virtual -``` - -Adds the Operator `operator` with the given `pubkeyHash` to the `operatorList` and performs necessary related updates. - -### _registrationStakeEvaluation - -```solidity -function _registrationStakeEvaluation(address operator, uint8 operatorType) internal returns (struct IQuorumRegistry.OperatorStake) -``` - -Used inside of inheriting contracts to validate the registration of `operator` and find their `OperatorStake`. - -_This function does **not** update the stored state of the operator's stakes -- storage updates are performed elsewhere._ - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | struct IQuorumRegistry.OperatorStake | The newly calculated `OperatorStake` for `operator`, stored in memory but not yet committed to storage. | - -### _updateOperatorStake - -```solidity -function _updateOperatorStake(address operator, bytes32 pubkeyHash, struct IQuorumRegistry.OperatorStake currentOperatorStake, uint256 insertAfter) internal returns (struct IQuorumRegistry.OperatorStake updatedOperatorStake) -``` - -Finds the updated stake for `operator`, stores it and records the update. - -_**DOES NOT UPDATE `totalStake` IN ANY WAY** -- `totalStake` updates must be done elsewhere._ - -### _recordTotalStakeUpdate - -```solidity -function _recordTotalStakeUpdate(struct IQuorumRegistry.OperatorStake _totalStake) internal -``` - -Records that the `totalStake` is now equal to the input param @_totalStake - -### _deregistrationCheck - -```solidity -function _deregistrationCheck(address operator, uint32 index) internal view -``` - -Verify that the `operator` is an active operator and that they've provided the correct `index` - diff --git a/docs/docgen/middleware/VoteWeigherBase.md b/docs/docgen/middleware/VoteWeigherBase.md deleted file mode 100644 index 378e3ffbd..000000000 --- a/docs/docgen/middleware/VoteWeigherBase.md +++ /dev/null @@ -1,120 +0,0 @@ -# Solidity API - -## VoteWeigherBase - -This contract is used for -- computing the total weight of an operator for any of the quorums that are considered -by the middleware -- addition and removal of strategies and the associated weighting criteria that are assigned -by the middleware for each of the quorum(s) -@dev - -### StrategyAddedToQuorum - -```solidity -event StrategyAddedToQuorum(uint256 quorumNumber, contract IStrategy strategy) -``` - -emitted when `strategy` has been added to the array at `strategiesConsideredAndMultipliers[quorumNumber]` - -### StrategyRemovedFromQuorum - -```solidity -event StrategyRemovedFromQuorum(uint256 quorumNumber, contract IStrategy strategy) -``` - -emitted when `strategy` has removed from the array at `strategiesConsideredAndMultipliers[quorumNumber]` - -### onlyServiceManagerOwner - -```solidity -modifier onlyServiceManagerOwner() -``` - -when applied to a function, ensures that the function is only callable by the current `owner` of the `serviceManager` - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager, contract IServiceManager _serviceManager, uint8 _NUMBER_OF_QUORUMS) internal -``` - -Sets the (immutable) `strategyManager` and `serviceManager` addresses, as well as the (immutable) `NUMBER_OF_QUORUMS` variable - -### _initialize - -```solidity -function _initialize(uint256[] _quorumBips) internal virtual -``` - -Set the split in earnings between the different quorums. - -### weightOfOperator - -```solidity -function weightOfOperator(address operator, uint256 quorumNumber) public virtual returns (uint96) -``` - -This function computes the total weight of the @param operator in the quorum @param quorumNumber. - -_returns zero in the case that `quorumNumber` is greater than or equal to `NUMBER_OF_QUORUMS`_ - -### addStrategiesConsideredAndMultipliers - -```solidity -function addStrategiesConsideredAndMultipliers(uint256 quorumNumber, struct VoteWeigherBaseStorage.StrategyAndWeightingMultiplier[] _newStrategiesConsideredAndMultipliers) external virtual -``` - -Adds new strategies and the associated multipliers to the @param quorumNumber. - -### removeStrategiesConsideredAndMultipliers - -```solidity -function removeStrategiesConsideredAndMultipliers(uint256 quorumNumber, contract IStrategy[] _strategiesToRemove, uint256[] indicesToRemove) external virtual -``` - -This function is used for removing strategies and their associated weights from the -mapping strategiesConsideredAndMultipliers for a specific @param quorumNumber. - -_higher indices should be *first* in the list of @param indicesToRemove, since otherwise -the removal of lower index entries will cause a shift in the indices of the other strategiesToRemove_ - -### modifyStrategyWeights - -```solidity -function modifyStrategyWeights(uint256 quorumNumber, uint256[] strategyIndices, uint96[] newMultipliers) external virtual -``` - -This function is used for modifying the weights of strategies that are already in the -mapping strategiesConsideredAndMultipliers for a specific @param quorumNumber. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| quorumNumber | uint256 | | -| strategyIndices | uint256[] | is a correctness-check input -- the supplied values must match the indices of the strategiesToModifyWeightsOf in strategiesConsideredAndMultipliers[quorumNumber] | -| newMultipliers | uint96[] | | - -### strategiesConsideredAndMultipliersLength - -```solidity -function strategiesConsideredAndMultipliersLength(uint256 quorumNumber) public view returns (uint256) -``` - -Returns the length of the dynamic array stored in `strategiesConsideredAndMultipliers[quorumNumber]`. - -_Reverts if `quorumNumber` < `NUMBER_OF_QUORUMS`, i.e. the input is out of bounds._ - -### _addStrategiesConsideredAndMultipliers - -```solidity -function _addStrategiesConsideredAndMultipliers(uint256 quorumNumber, struct VoteWeigherBaseStorage.StrategyAndWeightingMultiplier[] _newStrategiesConsideredAndMultipliers) internal -``` - -Adds `_newStrategiesConsideredAndMultipliers` to the `quorumNumber`-th quorum. - -_Checks to make sure that the *same* strategy cannot be added multiple times (checks against both against existing and new strategies). -This function has no check to make sure that the strategies for a single quorum have the same underlying asset. This is a concious choice, -since a middleware may want, e.g., a stablecoin quorum that accepts USDC, USDT, DAI, etc. as underlying assets and trades them as "equivalent"._ - diff --git a/docs/docgen/middleware/VoteWeigherBaseStorage.md b/docs/docgen/middleware/VoteWeigherBaseStorage.md deleted file mode 100644 index cca96e8ef..000000000 --- a/docs/docgen/middleware/VoteWeigherBaseStorage.md +++ /dev/null @@ -1,104 +0,0 @@ -# Solidity API - -## VoteWeigherBaseStorage - -This storage contract is separate from the logic to simplify the upgrade process. - -### StrategyAndWeightingMultiplier - -```solidity -struct StrategyAndWeightingMultiplier { - contract IStrategy strategy; - uint96 multiplier; -} -``` - -### WEIGHTING_DIVISOR - -```solidity -uint256 WEIGHTING_DIVISOR -``` - -Constant used as a divisor in calculating weights. - -### MAX_WEIGHING_FUNCTION_LENGTH - -```solidity -uint8 MAX_WEIGHING_FUNCTION_LENGTH -``` - -Maximum length of dynamic arrays in the `strategiesConsideredAndMultipliers` mapping. - -### MAX_BIPS - -```solidity -uint256 MAX_BIPS -``` - -Constant used as a divisor in dealing with BIPS amounts. - -### delegation - -```solidity -contract IDelegationManager delegation -``` - -The address of the Delegation contract for EigenLayer. - -### strategyManager - -```solidity -contract IStrategyManager strategyManager -``` - -The address of the StrategyManager contract for EigenLayer. - -### slasher - -```solidity -contract ISlasher slasher -``` - -The address of the Slasher contract for EigenLayer. - -### serviceManager - -```solidity -contract IServiceManager serviceManager -``` - -The ServiceManager contract for this middleware, where tasks are created / initiated. - -### NUMBER_OF_QUORUMS - -```solidity -uint256 NUMBER_OF_QUORUMS -``` - -Number of quorums that are being used by the middleware. - -### strategiesConsideredAndMultipliers - -```solidity -mapping(uint256 => struct VoteWeigherBaseStorage.StrategyAndWeightingMultiplier[]) strategiesConsideredAndMultipliers -``` - -mapping from quorum number to the list of strategies considered and their -corresponding multipliers for that specific quorum - -### quorumBips - -```solidity -mapping(uint256 => uint256) quorumBips -``` - -This defines the earnings split between different quorums. Mapping is quorumNumber => BIPS which the quorum earns, out of the total earnings. - -_The sum of all entries, i.e. sum(quorumBips[0] through quorumBips[NUMBER_OF_QUORUMS - 1]) should *always* be 10,000!_ - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager, contract IServiceManager _serviceManager, uint8 _NUMBER_OF_QUORUMS) internal -``` - diff --git a/docs/docgen/middleware/example/ECDSARegistry.md b/docs/docgen/middleware/example/ECDSARegistry.md deleted file mode 100644 index 15486642f..000000000 --- a/docs/docgen/middleware/example/ECDSARegistry.md +++ /dev/null @@ -1,205 +0,0 @@ -# Solidity API - -## ECDSARegistry - -This contract is used for -- registering new operators -- committing to and finalizing de-registration as an operator -- updating the stakes of the operator - -### operatorWhitelister - -```solidity -address operatorWhitelister -``` - -the address that can whitelist people - -### operatorWhitelistEnabled - -```solidity -bool operatorWhitelistEnabled -``` - -toggle of whether the operator whitelist is on or off - -### whitelisted - -```solidity -mapping(address => bool) whitelisted -``` - -operator => are they whitelisted (can they register with the middleware) - -### Registration - -```solidity -event Registration(address operator, string socket) -``` - -Emitted upon the registration of a new operator for the middleware - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | Address of the new operator | -| socket | string | The ip:port of the operator | - -### OperatorWhitelisterTransferred - -```solidity -event OperatorWhitelisterTransferred(address previousAddress, address newAddress) -``` - -Emitted when the `operatorWhitelister` role is transferred. - -### onlyOperatorWhitelister - -```solidity -modifier onlyOperatorWhitelister() -``` - -Modifier that restricts a function to only be callable by the `whitelister` role. - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager, contract IServiceManager _serviceManager) public -``` - -### initialize - -```solidity -function initialize(address _operatorWhitelister, bool _operatorWhitelistEnabled, uint256[] _quorumBips, struct VoteWeigherBaseStorage.StrategyAndWeightingMultiplier[] _quorumStrategiesConsideredAndMultipliers) public virtual -``` - -Initialize whitelister and the quorum strategies + multipliers. - -### setOperatorWhitelister - -```solidity -function setOperatorWhitelister(address _operatorWhitelister) external -``` - -Called by the service manager owner to transfer the whitelister role to another address - -### setOperatorWhitelistStatus - -```solidity -function setOperatorWhitelistStatus(bool _operatorWhitelistEnabled) external -``` - -Callable only by the service manager owner, this function toggles the whitelist on or off - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _operatorWhitelistEnabled | bool | true if turning whitelist on, false otherwise | - -### addToOperatorWhitelist - -```solidity -function addToOperatorWhitelist(address[] operators) external -``` - -Called by the operatorWhitelister, adds a list of operators to the whitelist - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operators | address[] | the operators to add to the whitelist | - -### removeFromWhitelist - -```solidity -function removeFromWhitelist(address[] operators) external -``` - -Called by the operatorWhitelister, removes a list of operators to the whitelist - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operators | address[] | the operators to remove from the whitelist | - -### registerOperator - -```solidity -function registerOperator(string socket) external virtual -``` - -called for registering as an operator - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| socket | string | is the socket address of the operator | - -### _registerOperator - -```solidity -function _registerOperator(address operator, string socket) internal -``` - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | is the node who is registering to be a operator | -| socket | string | is the socket address of the operator | - -### deregisterOperator - -```solidity -function deregisterOperator(uint32 index) external virtual returns (bool) -``` - -Used by an operator to de-register itself from providing service to the middleware. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| index | uint32 | is the sender's location in the dynamic array `operatorList` | - -### _deregisterOperator - -```solidity -function _deregisterOperator(address operator, uint32 index) internal -``` - -Used to process de-registering an operator from providing service to the middleware. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operator | address | The operator to be deregistered | -| index | uint32 | is the sender's location in the dynamic array `operatorList` | - -### updateStakes - -```solidity -function updateStakes(address[] operators, uint256[] prevElements) external -``` - -Used for updating information on deposits of nodes. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| operators | address[] | are the nodes whose deposit information is getting updated | -| prevElements | uint256[] | are the elements before this middleware in the operator's linked list within the slasher | - -### _setOperatorWhitelister - -```solidity -function _setOperatorWhitelister(address _operatorWhitelister) internal -``` - diff --git a/docs/docgen/middleware/example/HashThreshold.md b/docs/docgen/middleware/example/HashThreshold.md deleted file mode 100644 index 99cc3011d..000000000 --- a/docs/docgen/middleware/example/HashThreshold.md +++ /dev/null @@ -1,151 +0,0 @@ -# Solidity API - -## HashThreshold - -### disputePeriodBlocks - -```solidity -uint32 disputePeriodBlocks -``` - -### numZeroes - -```solidity -uint8 numZeroes -``` - -### slasher - -```solidity -contract ISlasher slasher -``` - -### registry - -```solidity -contract ECDSARegistry registry -``` - -### CertifiedMessageMetadata - -```solidity -struct CertifiedMessageMetadata { - bytes32 signaturesHash; - uint32 validAfterBlock; -} -``` - -### taskNumber - -```solidity -uint32 taskNumber -``` - -Returns the current 'taskNumber' for the middleware - -### latestServeUntilBlock - -```solidity -uint32 latestServeUntilBlock -``` - -Returns the latest block until which operators must serve. - -### certifiedMessageMetadatas - -```solidity -mapping(bytes32 => struct HashThreshold.CertifiedMessageMetadata) certifiedMessageMetadatas -``` - -### MessageCertified - -```solidity -event MessageCertified(bytes32) -``` - -### onlyRegistry - -```solidity -modifier onlyRegistry() -``` - -### constructor - -```solidity -constructor(contract ISlasher _slasher, contract ECDSARegistry _registry) public -``` - -### owner - -```solidity -function owner() public view returns (address) -``` - -### decaHash - -```solidity -function decaHash(bytes32 message) public pure returns (bytes32) -``` - -### submitSignatures - -```solidity -function submitSignatures(bytes32 message, bytes signatures) external -``` - -This function is called by anyone to certify a message. Signers are certifying that the decahashed message starts with at least `numZeros` 0s. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| message | bytes32 | The message to certify | -| signatures | bytes | The signatures of the message, certifying it | - -### slashSigners - -```solidity -function slashSigners(bytes32 message, bytes signatures) external -``` - -This function is called by anyone to slash the signers of an invalid message that has been certified. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| message | bytes32 | The message to slash the signers of | -| signatures | bytes | The signatures that certified the message | - -### freezeOperator - -```solidity -function freezeOperator(address operator) external -``` - -Permissioned function that causes the ServiceManager to freeze the operator on EigenLayer, through a call to the Slasher contract - -### recordFirstStakeUpdate - -```solidity -function recordFirstStakeUpdate(address operator, uint32 serveUntilBlock) external -``` - -Permissioned function to have the ServiceManager forward a call to the slasher, recording an initial stake update (on operator registration) - -### recordLastStakeUpdateAndRevokeSlashingAbility - -```solidity -function recordLastStakeUpdateAndRevokeSlashingAbility(address operator, uint32 serveUntilBlock) external -``` - -Permissioned function to have the ServiceManager forward a call to the slasher, recording a final stake update (on operator deregistration) - -### recordStakeUpdate - -```solidity -function recordStakeUpdate(address operator, uint32 updateBlock, uint32 serveUntilBlock, uint256 prevElement) external -``` - -Permissioned function to have the ServiceManager forward a call to the slasher, recording a stake update - diff --git a/docs/docgen/operators/MerkleDelegationTerms.md b/docs/docgen/operators/MerkleDelegationTerms.md deleted file mode 100644 index 166437dd8..000000000 --- a/docs/docgen/operators/MerkleDelegationTerms.md +++ /dev/null @@ -1,129 +0,0 @@ -# Solidity API - -## MerkleDelegationTerms - -This contract specifies the delegation terms of a given operator. When a staker delegates its stake to an operator, -it has to agrees to the terms set in the operator's 'Delegation Terms' contract. Payments to an operator are routed through -their specified 'Delegation Terms' contract for subsequent distribution of earnings to individual stakers. -There are also hooks that call into an operator's DelegationTerms contract when a staker delegates to or undelegates from -the operator. - -_This contract uses a system in which the operator posts roots of a *sparse Merkle tree*. Each leaf of the tree is expected -to contain the **cumulative** earnings of a staker. This will reduce the total number of actions that stakers who claim only rarely -have to take, while allowing stakers to claim their earnings as often as new Merkle roots are posted._ - -### TokenAndAmount - -```solidity -struct TokenAndAmount { - contract IERC20 token; - uint256 amount; -} -``` - -### MerkleRootAndTreeHeight - -```solidity -struct MerkleRootAndTreeHeight { - bytes32 root; - uint256 height; -} -``` - -### MAX_HEIGHT - -```solidity -uint256 MAX_HEIGHT -``` - -### cumulativeClaimedByStakerOfToken - -```solidity -mapping(address => mapping(contract IERC20 => uint256)) cumulativeClaimedByStakerOfToken -``` - -staker => token => cumulative amount *claimed* - -### merkleRoots - -```solidity -struct MerkleDelegationTerms.MerkleRootAndTreeHeight[] merkleRoots -``` - -Array of Merkle roots with heights, each posted by the operator (contract owner) - -### NewMerkleRootPosted - -```solidity -event NewMerkleRootPosted(bytes32 newRoot, uint256 height) -``` - -### operatorWithdrawal - -```solidity -function operatorWithdrawal(struct MerkleDelegationTerms.TokenAndAmount[] tokensAndAmounts) external -``` - -Used by the operator to withdraw tokens directly from this contract. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| tokensAndAmounts | struct MerkleDelegationTerms.TokenAndAmount[] | ERC20 tokens to withdraw and the amount of each respective ERC20 token to withdraw. | - -### postMerkleRoot - -```solidity -function postMerkleRoot(bytes32 newRoot, uint256 height) external -``` - -Used by the operator to post an updated root of the stakers' all-time earnings - -### proveEarningsAndWithdraw - -```solidity -function proveEarningsAndWithdraw(struct MerkleDelegationTerms.TokenAndAmount[] tokensAndAmounts, bytes proof, uint256 nodeIndex, uint256 rootIndex) external -``` - -Called by a staker to prove the inclusion of their earnings in a Merkle root (posted by the operator) and claim them. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| tokensAndAmounts | struct MerkleDelegationTerms.TokenAndAmount[] | ERC20 tokens to withdraw and the amount of each respective ERC20 token to withdraw. | -| proof | bytes | Merkle proof showing that a leaf containing `(msg.sender, tokensAndAmounts)` was included in the `rootIndex`-th Merkle root posted by the operator. | -| nodeIndex | uint256 | Specifies the node inside the Merkle tree corresponding to the specified root, `merkleRoots[rootIndex].root`. | -| rootIndex | uint256 | Specifies the Merkle root to look up, using `merkleRoots[rootIndex]` | - -### calculateLeafHash - -```solidity -function calculateLeafHash(address staker, struct MerkleDelegationTerms.TokenAndAmount[] tokensAndAmounts) public pure returns (bytes32) -``` - -Helper function for calculating a leaf in a Merkle tree formatted as `(address staker, TokenAndAmount[] calldata tokensAndAmounts)` - -### payForService - -```solidity -function payForService(contract IERC20, uint256) external payable -``` - -### onDelegationReceived - -```solidity -function onDelegationReceived(address, contract IStrategy[], uint256[]) external pure returns (bytes) -``` - -Hook for receiving new delegation - -### onDelegationWithdrawn - -```solidity -function onDelegationWithdrawn(address, contract IStrategy[], uint256[]) external pure returns (bytes) -``` - -Hook for withdrawing delegation - diff --git a/docs/docgen/permissions/Pausable.md b/docs/docgen/permissions/Pausable.md deleted file mode 100644 index 37277bc16..000000000 --- a/docs/docgen/permissions/Pausable.md +++ /dev/null @@ -1,167 +0,0 @@ -# Solidity API - -## Pausable - -Contracts that inherit from this contract may define their own `pause` and `unpause` (and/or related) functions. -These functions should be permissioned as "onlyPauser" which defers to a `PauserRegistry` for determining access control. - -_Pausability is implemented using a uint256, which allows up to 256 different single bit-flags; each bit can potentially pause different functionality. -Inspiration for this was taken from the NearBridge design here https://etherscan.io/address/0x3FEFc5A4B1c02f21cBc8D3613643ba0635b9a873#code. -For the `pause` and `unpause` functions we've implemented, if you pause, you can only flip (any number of) switches to on/1 (aka "paused"), and if you unpause, -you can only flip (any number of) switches to off/0 (aka "paused"). -If you want a pauseXYZ function that just flips a single bit / "pausing flag", it will: -1) 'bit-wise and' (aka `&`) a flag with the current paused state (as a uint256) -2) update the paused state to this new value -We note as well that we have chosen to identify flags by their *bit index* as opposed to their numerical value, so, e.g. defining `DEPOSITS_PAUSED = 3` -indicates specifically that if the *third bit* of `_paused` is flipped -- i.e. it is a '1' -- then deposits should be paused_ - -### pauserRegistry - -```solidity -contract IPauserRegistry pauserRegistry -``` - -Address of the `PauserRegistry` contract that this contract defers to for determining access control (for pausing). - -### _paused - -```solidity -uint256 _paused -``` - -_whether or not the contract is currently paused_ - -### UNPAUSE_ALL - -```solidity -uint256 UNPAUSE_ALL -``` - -### PAUSE_ALL - -```solidity -uint256 PAUSE_ALL -``` - -### Paused - -```solidity -event Paused(address account, uint256 newPausedStatus) -``` - -Emitted when the pause is triggered by `account`, and changed to `newPausedStatus`. - -### Unpaused - -```solidity -event Unpaused(address account, uint256 newPausedStatus) -``` - -Emitted when the pause is lifted by `account`, and changed to `newPausedStatus`. - -### onlyPauser - -```solidity -modifier onlyPauser() -``` - -@notice - -### onlyUnpauser - -```solidity -modifier onlyUnpauser() -``` - -### whenNotPaused - -```solidity -modifier whenNotPaused() -``` - -Throws if the contract is paused, i.e. if any of the bits in `_paused` is flipped to 1. - -### onlyWhenNotPaused - -```solidity -modifier onlyWhenNotPaused(uint8 index) -``` - -Throws if the `indexed`th bit of `_paused` is 1, i.e. if the `index`th pause switch is flipped. - -### _initializePauser - -```solidity -function _initializePauser(contract IPauserRegistry _pauserRegistry, uint256 initPausedStatus) internal -``` - -One-time function for setting the `pauserRegistry` and initializing the value of `_paused`. - -### pause - -```solidity -function pause(uint256 newPausedStatus) external -``` - -This function is used to pause an EigenLayer contract's functionality. -It is permissioned to the `pauser` address, which is expected to be a low threshold multisig. - -_This function can only pause functionality, and thus cannot 'unflip' any bit in `_paused` from 1 to 0._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newPausedStatus | uint256 | represents the new value for `_paused` to take, which means it may flip several bits at once. | - -### pauseAll - -```solidity -function pauseAll() external -``` - -Alias for `pause(type(uint256).max)`. - -### unpause - -```solidity -function unpause(uint256 newPausedStatus) external -``` - -This function is used to unpause an EigenLayer contract's functionality. -It is permissioned to the `unpauser` address, which is expected to be a high threshold multisig or governance contract. - -_This function can only unpause functionality, and thus cannot 'flip' any bit in `_paused` from 0 to 1._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newPausedStatus | uint256 | represents the new value for `_paused` to take, which means it may flip several bits at once. | - -### paused - -```solidity -function paused() public view virtual returns (uint256) -``` - -Returns the current paused status as a uint256. - -### paused - -```solidity -function paused(uint8 index) public view virtual returns (bool) -``` - -Returns 'true' if the `indexed`th bit of `_paused` is 1, and 'false' otherwise - -### __gap - -```solidity -uint256[48] __gap -``` - -_This empty reserved space is put in place to allow future versions to add new -variables without shifting down storage in the inheritance chain. -See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps_ - diff --git a/docs/docgen/permissions/PauserRegistry.md b/docs/docgen/permissions/PauserRegistry.md deleted file mode 100644 index 28c4a6f46..000000000 --- a/docs/docgen/permissions/PauserRegistry.md +++ /dev/null @@ -1,72 +0,0 @@ -# Solidity API - -## PauserRegistry - -### pauser - -```solidity -address pauser -``` - -Unique address that holds the pauser role. - -### unpauser - -```solidity -address unpauser -``` - -Unique address that holds the unpauser role. Capable of changing *both* the pauser and unpauser addresses. - -### PauserChanged - -```solidity -event PauserChanged(address previousPauser, address newPauser) -``` - -### UnpauserChanged - -```solidity -event UnpauserChanged(address previousUnpauser, address newUnpauser) -``` - -### onlyUnpauser - -```solidity -modifier onlyUnpauser() -``` - -### constructor - -```solidity -constructor(address _pauser, address _unpauser) public -``` - -### setPauser - -```solidity -function setPauser(address newPauser) external -``` - -Sets new pauser - only callable by unpauser, as the unpauser is expected to be kept more secure, e.g. being a multisig with a higher threshold - -### setUnpauser - -```solidity -function setUnpauser(address newUnpauser) external -``` - -Sets new unpauser - only callable by unpauser, as the unpauser is expected to be kept more secure, e.g. being a multisig with a higher threshold - -### _setPauser - -```solidity -function _setPauser(address newPauser) internal -``` - -### _setUnpauser - -```solidity -function _setUnpauser(address newUnpauser) internal -``` - diff --git a/docs/docgen/pods/BeaconChainOracle.md b/docs/docgen/pods/BeaconChainOracle.md deleted file mode 100644 index 4b809cca6..000000000 --- a/docs/docgen/pods/BeaconChainOracle.md +++ /dev/null @@ -1,202 +0,0 @@ -# Solidity API - -## BeaconChainOracle - -The owner of this contract can edit a set of 'oracle signers', as well as changing the threshold number of oracle signers that must vote for a - particular state root at a specified blockNumber before the state root is considered 'confirmed'. - -### MINIMUM_THRESHOLD - -```solidity -uint256 MINIMUM_THRESHOLD -``` - -The minimum value which the `threshold` variable is allowed to take. - -### totalOracleSigners - -```solidity -uint256 totalOracleSigners -``` - -Total number of members of the set of oracle signers. - -### threshold - -```solidity -uint256 threshold -``` - -Number of oracle signers that must vote for a state root in order for the state root to be confirmed. -Adjustable by this contract's owner through use of the `setThreshold` function. - -_We note that there is an edge case -- when the threshold is adjusted downward, if a state root already has enough votes to meet the *new* threshold, -the state root must still receive one additional vote from an oracle signer to be confirmed. This behavior is intended, to minimize unexpected root confirmations._ - -### latestConfirmedOracleBlockNumber - -```solidity -uint64 latestConfirmedOracleBlockNumber -``` - -Largest blockNumber that has been confirmed by the oracle. - -### beaconStateRootAtBlockNumber - -```solidity -mapping(uint64 => bytes32) beaconStateRootAtBlockNumber -``` - -Mapping: Beacon Chain blockNumber => the Beacon Chain state root at the specified blockNumber. - -_This will return `bytes32(0)` if the state root at the specified blockNumber is not yet confirmed._ - -### isOracleSigner - -```solidity -mapping(address => bool) isOracleSigner -``` - -Mapping: address => whether or not the address is in the set of oracle signers. - -### hasVoted - -```solidity -mapping(uint64 => mapping(address => bool)) hasVoted -``` - -Mapping: Beacon Chain blockNumber => oracle signer address => whether or not the oracle signer has voted on the state root at the blockNumber. - -### stateRootVotes - -```solidity -mapping(uint64 => mapping(bytes32 => uint256)) stateRootVotes -``` - -Mapping: Beacon Chain blockNumber => state root => total number of oracle signer votes for the state root at the blockNumber. - -### ThresholdModified - -```solidity -event ThresholdModified(uint256 previousValue, uint256 newValue) -``` - -Emitted when the value of the `threshold` variable is changed from `previousValue` to `newValue`. - -### StateRootConfirmed - -```solidity -event StateRootConfirmed(uint64 blockNumber, bytes32 stateRoot) -``` - -Emitted when the beacon chain state root at `blockNumber` is confirmed to be `stateRoot`. - -### OracleSignerAdded - -```solidity -event OracleSignerAdded(address addedOracleSigner) -``` - -Emitted when `addedOracleSigner` is added to the set of oracle signers. - -### OracleSignerRemoved - -```solidity -event OracleSignerRemoved(address removedOracleSigner) -``` - -Emitted when `removedOracleSigner` is removed from the set of oracle signers. - -### onlyOracleSigner - -```solidity -modifier onlyOracleSigner() -``` - -Modifier that restricts functions to only be callable by members of the oracle signer set - -### constructor - -```solidity -constructor(address initialOwner, uint256 initialThreshold, address[] initialOracleSigners) public -``` - -### setThreshold - -```solidity -function setThreshold(uint256 _threshold) external -``` - -Owner-only function used to modify the value of the `threshold` variable. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _threshold | uint256 | Desired new value for the `threshold` variable. Function will revert if this is set to zero. | - -### addOracleSigners - -```solidity -function addOracleSigners(address[] _oracleSigners) external -``` - -Owner-only function used to add a signer to the set of oracle signers. - -_Function will have no effect on the i-th input address if `_oracleSigners[i]`is already in the set of oracle signers._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _oracleSigners | address[] | Array of address to be added to the set. | - -### removeOracleSigners - -```solidity -function removeOracleSigners(address[] _oracleSigners) external -``` - -Owner-only function used to remove a signer from the set of oracle signers. - -_Function will have no effect on the i-th input address if `_oracleSigners[i]`is already not in the set of oracle signers._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| _oracleSigners | address[] | Array of address to be removed from the set. | - -### voteForBeaconChainStateRoot - -```solidity -function voteForBeaconChainStateRoot(uint64 blockNumber, bytes32 stateRoot) external -``` - -Called by a member of the set of oracle signers to assert that the Beacon Chain state root is `stateRoot` at `blockNumber`. - -_The state root will be confirmed once the total number of votes *for this exact state root at this exact blockNumber* meets the `threshold` value._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| blockNumber | uint64 | The Beacon Chain blockNumber of interest. | -| stateRoot | bytes32 | The Beacon Chain state root that the caller asserts was the correct root, at the specified `blockNumber`. | - -### _setThreshold - -```solidity -function _setThreshold(uint256 _threshold) internal -``` - -Internal function used for modifying the value of the `threshold` variable, used in the constructor and the `setThreshold` function - -### _addOracleSigners - -```solidity -function _addOracleSigners(address[] _oracleSigners) internal -``` - -Internal counterpart of the `addOracleSigners` function. Also used in the constructor. - diff --git a/docs/docgen/pods/DelayedWithdrawalRouter.md b/docs/docgen/pods/DelayedWithdrawalRouter.md deleted file mode 100644 index 095dd3f80..000000000 --- a/docs/docgen/pods/DelayedWithdrawalRouter.md +++ /dev/null @@ -1,201 +0,0 @@ -# Solidity API - -## DelayedWithdrawalRouter - -### WithdrawalDelayBlocksSet - -```solidity -event WithdrawalDelayBlocksSet(uint256 previousValue, uint256 newValue) -``` - -Emitted when the `withdrawalDelayBlocks` variable is modified from `previousValue` to `newValue`. - -### PAUSED_DELAYED_WITHDRAWAL_CLAIMS - -```solidity -uint8 PAUSED_DELAYED_WITHDRAWAL_CLAIMS -``` - -### withdrawalDelayBlocks - -```solidity -uint256 withdrawalDelayBlocks -``` - -Delay enforced by this contract for completing any delayedWithdrawal. Measured in blocks, and adjustable by this contract's owner, -up to a maximum of `MAX_WITHDRAWAL_DELAY_BLOCKS`. Minimum value is 0 (i.e. no delay enforced). - -### MAX_WITHDRAWAL_DELAY_BLOCKS - -```solidity -uint256 MAX_WITHDRAWAL_DELAY_BLOCKS -``` - -### eigenPodManager - -```solidity -contract IEigenPodManager eigenPodManager -``` - -The EigenPodManager contract of EigenLayer. - -### _userWithdrawals - -```solidity -mapping(address => struct IDelayedWithdrawalRouter.UserDelayedWithdrawals) _userWithdrawals -``` - -Mapping: user => struct storing all delayedWithdrawal info. Marked as internal with an external getter function named `userWithdrawals` - -### DelayedWithdrawalCreated - -```solidity -event DelayedWithdrawalCreated(address podOwner, address recipient, uint256 amount, uint256 index) -``` - -event for delayedWithdrawal creation - -### DelayedWithdrawalsClaimed - -```solidity -event DelayedWithdrawalsClaimed(address recipient, uint256 amountClaimed, uint256 delayedWithdrawalsCompleted) -``` - -event for the claiming of delayedWithdrawals - -### onlyEigenPod - -```solidity -modifier onlyEigenPod(address podOwner) -``` - -Modifier used to permission a function to only be called by the EigenPod of the specified `podOwner` - -### constructor - -```solidity -constructor(contract IEigenPodManager _eigenPodManager) public -``` - -### initialize - -```solidity -function initialize(address initOwner, contract IPauserRegistry _pauserRegistry, uint256 initPausedStatus, uint256 _withdrawalDelayBlocks) external -``` - -### createDelayedWithdrawal - -```solidity -function createDelayedWithdrawal(address podOwner, address recipient) external payable -``` - -Creates a delayed withdrawal for `msg.value` to the `recipient`. - -_Only callable by the `podOwner`'s EigenPod contract._ - -### claimDelayedWithdrawals - -```solidity -function claimDelayedWithdrawals(address recipient, uint256 maxNumberOfDelayedWithdrawalsToClaim) external -``` - -Called in order to withdraw delayed withdrawals made to the `recipient` that have passed the `withdrawalDelayBlocks` period. - -_WARNING: Note that the caller of this function cannot control where the funds are sent, but they can control when the - funds are sent once the withdrawal becomes claimable._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| recipient | address | The address to claim delayedWithdrawals for. | -| maxNumberOfDelayedWithdrawalsToClaim | uint256 | Used to limit the maximum number of delayedWithdrawals to loop through claiming. | - -### claimDelayedWithdrawals - -```solidity -function claimDelayedWithdrawals(uint256 maxNumberOfDelayedWithdrawalsToClaim) external -``` - -Called in order to withdraw delayed withdrawals made to the caller that have passed the `withdrawalDelayBlocks` period. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| maxNumberOfDelayedWithdrawalsToClaim | uint256 | Used to limit the maximum number of delayedWithdrawals to loop through claiming. | - -### setWithdrawalDelayBlocks - -```solidity -function setWithdrawalDelayBlocks(uint256 newValue) external -``` - -Owner-only function for modifying the value of the `withdrawalDelayBlocks` variable. - -### userWithdrawals - -```solidity -function userWithdrawals(address user) external view returns (struct IDelayedWithdrawalRouter.UserDelayedWithdrawals) -``` - -Getter function for the mapping `_userWithdrawals` - -### claimableUserDelayedWithdrawals - -```solidity -function claimableUserDelayedWithdrawals(address user) external view returns (struct IDelayedWithdrawalRouter.DelayedWithdrawal[]) -``` - -Getter function to get all delayedWithdrawals that are currently claimable by the `user` - -### userDelayedWithdrawalByIndex - -```solidity -function userDelayedWithdrawalByIndex(address user, uint256 index) external view returns (struct IDelayedWithdrawalRouter.DelayedWithdrawal) -``` - -Getter function for fetching the delayedWithdrawal at the `index`th entry from the `_userWithdrawals[user].delayedWithdrawals` array - -### userWithdrawalsLength - -```solidity -function userWithdrawalsLength(address user) external view returns (uint256) -``` - -Getter function for fetching the length of the delayedWithdrawals array of a specific user - -### canClaimDelayedWithdrawal - -```solidity -function canClaimDelayedWithdrawal(address user, uint256 index) external view returns (bool) -``` - -Convenience function for checking whether or not the delayedWithdrawal at the `index`th entry from the `_userWithdrawals[user].delayedWithdrawals` array is currently claimable - -### _claimDelayedWithdrawals - -```solidity -function _claimDelayedWithdrawals(address recipient, uint256 maxNumberOfDelayedWithdrawalsToClaim) internal -``` - -internal function used in both of the overloaded `claimDelayedWithdrawals` functions - -### _setWithdrawalDelayBlocks - -```solidity -function _setWithdrawalDelayBlocks(uint256 newValue) internal -``` - -internal function for changing the value of `withdrawalDelayBlocks`. Also performs sanity check and emits an event. - -### __gap - -```solidity -uint256[48] __gap -``` - -_This empty reserved space is put in place to allow future versions to add new -variables without shifting down storage in the inheritance chain. -See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps_ - diff --git a/docs/docgen/pods/EigenPod.md b/docs/docgen/pods/EigenPod.md deleted file mode 100644 index 766f56474..000000000 --- a/docs/docgen/pods/EigenPod.md +++ /dev/null @@ -1,345 +0,0 @@ -# Solidity API - -## EigenPod - -The main functionalities are: -- creating new ETH validators with their withdrawal credentials pointed to this contract -- proving from beacon chain state roots that withdrawal credentials are pointed to this contract -- proving from beacon chain state roots the balances of ETH validators with their withdrawal credentials - pointed to this contract -- updating aggregate balances in the EigenPodManager -- withdrawing eth when withdrawals are initiated - -_Note that all beacon chain balances are stored as gwei within the beacon chain datastructures. We choose - to account balances in terms of gwei in the EigenPod contract and convert to wei when making calls to other contracts_ - -### GWEI_TO_WEI - -```solidity -uint256 GWEI_TO_WEI -``` - -### VERIFY_OVERCOMMITTED_WINDOW_BLOCKS - -```solidity -uint256 VERIFY_OVERCOMMITTED_WINDOW_BLOCKS -``` - -Maximum "staleness" of a Beacon Chain state root against which `verifyOvercommittedStake` may be proven. 7 days in blocks. - -### ethPOS - -```solidity -contract IETHPOSDeposit ethPOS -``` - -This is the beacon chain deposit contract - -### delayedWithdrawalRouter - -```solidity -contract IDelayedWithdrawalRouter delayedWithdrawalRouter -``` - -Contract used for withdrawal routing, to provide an extra "safety net" mechanism - -### eigenPodManager - -```solidity -contract IEigenPodManager eigenPodManager -``` - -The single EigenPodManager for EigenLayer - -### REQUIRED_BALANCE_GWEI - -```solidity -uint64 REQUIRED_BALANCE_GWEI -``` - -The amount of eth, in gwei, that is restaked per validator - -### REQUIRED_BALANCE_WEI - -```solidity -uint256 REQUIRED_BALANCE_WEI -``` - -The amount of eth, in wei, that is restaked per ETH validator into EigenLayer - -### podOwner - -```solidity -address podOwner -``` - -The owner of this EigenPod - -### mostRecentWithdrawalBlockNumber - -```solidity -uint64 mostRecentWithdrawalBlockNumber -``` - -The latest block number at which the pod owner withdrew the balance of the pod. - -_This variable is only updated when the `withdraw` function is called, which can only occur before `hasRestaked` is set to true for this pod. -Proofs for this pod are only valid against Beacon Chain state roots corresponding to blocks after the stored `mostRecentWithdrawalBlockNumber`._ - -### restakedExecutionLayerGwei - -```solidity -uint64 restakedExecutionLayerGwei -``` - -the amount of execution layer ETH in this contract that is staked in EigenLayer (i.e. withdrawn from the Beacon Chain but not from EigenLayer), - -### hasRestaked - -```solidity -bool hasRestaked -``` - -an indicator of whether or not the podOwner has ever "fully restaked" by successfully calling `verifyCorrectWithdrawalCredentials`. - -### validatorStatus - -```solidity -mapping(uint40 => enum IEigenPod.VALIDATOR_STATUS) validatorStatus -``` - -this is a mapping of validator indices to a Validator struct containing pertinent info about the validator - -### provenPartialWithdrawal - -```solidity -mapping(uint40 => mapping(uint64 => bool)) provenPartialWithdrawal -``` - -This is a mapping of validatorIndex to withdrawalIndex to whether or not they have proven a withdrawal for that index - -### EigenPodStaked - -```solidity -event EigenPodStaked(bytes pubkey) -``` - -Emitted when an ETH validator stakes via this eigenPod - -### ValidatorRestaked - -```solidity -event ValidatorRestaked(uint40 validatorIndex) -``` - -Emitted when an ETH validator's withdrawal credentials are successfully verified to be pointed to this eigenPod - -### ValidatorOvercommitted - -```solidity -event ValidatorOvercommitted(uint40 validatorIndex) -``` - -Emitted when an ETH validator is proven to have a balance less than `REQUIRED_BALANCE_GWEI` in the beacon chain - -### FullWithdrawalRedeemed - -```solidity -event FullWithdrawalRedeemed(uint40 validatorIndex, address recipient, uint64 withdrawalAmountGwei) -``` - -Emitted when an ETH validator is prove to have withdrawn from the beacon chain - -### PartialWithdrawalRedeemed - -```solidity -event PartialWithdrawalRedeemed(uint40 validatorIndex, address recipient, uint64 partialWithdrawalAmountGwei) -``` - -Emitted when a partial withdrawal claim is successfully redeemed - -### RestakedBeaconChainETHWithdrawn - -```solidity -event RestakedBeaconChainETHWithdrawn(address recipient, uint256 amount) -``` - -Emitted when restaked beacon chain ETH is withdrawn from the eigenPod. - -### onlyEigenPodManager - -```solidity -modifier onlyEigenPodManager() -``` - -### onlyEigenPodOwner - -```solidity -modifier onlyEigenPodOwner() -``` - -### onlyNotFrozen - -```solidity -modifier onlyNotFrozen() -``` - -### hasNeverRestaked - -```solidity -modifier hasNeverRestaked() -``` - -### proofIsForValidBlockNumber - -```solidity -modifier proofIsForValidBlockNumber(uint64 blockNumber) -``` - -Checks that `blockNumber` is strictly greater than the value stored in `mostRecentWithdrawalBlockNumber` - -### onlyWhenNotPaused - -```solidity -modifier onlyWhenNotPaused(uint8 index) -``` - -Based on 'Pausable' code, but uses the storage of the EigenPodManager instead of this contract. This construction -is necessary for enabling pausing all EigenPods at the same time (due to EigenPods being Beacon Proxies). -Modifier throws if the `indexed`th bit of `_paused` in the EigenPodManager is 1, i.e. if the `index`th pause switch is flipped. - -### constructor - -```solidity -constructor(contract IETHPOSDeposit _ethPOS, contract IDelayedWithdrawalRouter _delayedWithdrawalRouter, contract IEigenPodManager _eigenPodManager, uint256 _REQUIRED_BALANCE_WEI) public -``` - -### initialize - -```solidity -function initialize(address _podOwner) external -``` - -Used to initialize the pointers to addresses crucial to the pod's functionality. Called on construction by the EigenPodManager. - -### stake - -```solidity -function stake(bytes pubkey, bytes signature, bytes32 depositDataRoot) external payable -``` - -Called by EigenPodManager when the owner wants to create another ETH validator. - -### verifyWithdrawalCredentialsAndBalance - -```solidity -function verifyWithdrawalCredentialsAndBalance(uint64 oracleBlockNumber, uint40 validatorIndex, struct BeaconChainProofs.ValidatorFieldsAndBalanceProofs proofs, bytes32[] validatorFields) external -``` - -This function verifies that the withdrawal credentials of the podOwner are pointed to -this contract. It also verifies the current (not effective) balance of the validator. It verifies the provided proof of the ETH validator against the beacon chain state -root, marks the validator as 'active' in EigenLayer, and credits the restaked ETH in Eigenlayer. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| oracleBlockNumber | uint64 | is the Beacon Chain blockNumber whose state root the `proof` will be proven against. | -| validatorIndex | uint40 | is the index of the validator being proven, refer to consensus specs | -| proofs | struct BeaconChainProofs.ValidatorFieldsAndBalanceProofs | is the bytes that prove the ETH validator's balance and withdrawal credentials against a beacon chain state root | -| validatorFields | bytes32[] | are the fields of the "Validator Container", refer to consensus specs for details: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator | - -### verifyOvercommittedStake - -```solidity -function verifyOvercommittedStake(uint40 validatorIndex, struct BeaconChainProofs.ValidatorFieldsAndBalanceProofs proofs, bytes32[] validatorFields, uint256 beaconChainETHStrategyIndex, uint64 oracleBlockNumber) external -``` - -This function records an overcommitment of stake to EigenLayer on behalf of a certain ETH validator. - If successful, the overcommitted balance is penalized (available for withdrawal whenever the pod's balance allows). - The ETH validator's shares in the enshrined beaconChainETH strategy are also removed from the StrategyManager and undelegated. - -_For more details on the Beacon Chain spec, see: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| validatorIndex | uint40 | is the index of the validator being proven, refer to consensus specs | -| proofs | struct BeaconChainProofs.ValidatorFieldsAndBalanceProofs | is the proof of the validator's balance and validatorFields in the balance tree and the balanceRoot to prove for | -| validatorFields | bytes32[] | are the fields of the "Validator Container", refer to consensus specs | -| beaconChainETHStrategyIndex | uint256 | is the index of the beaconChainETHStrategy for the pod owner for the callback to the StrategyManager in case it must be removed from the list of the podOwner's strategies | -| oracleBlockNumber | uint64 | The oracleBlockNumber whose state root the `proof` will be proven against. Must be within `VERIFY_OVERCOMMITTED_WINDOW_BLOCKS` of the current block. | - -### verifyAndProcessWithdrawal - -```solidity -function verifyAndProcessWithdrawal(struct BeaconChainProofs.WithdrawalProofs withdrawalProofs, bytes validatorFieldsProof, bytes32[] validatorFields, bytes32[] withdrawalFields, uint256 beaconChainETHStrategyIndex, uint64 oracleBlockNumber) external -``` - -This function records a full withdrawal on behalf of one of the Ethereum validators for this EigenPod - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| withdrawalProofs | struct BeaconChainProofs.WithdrawalProofs | is the information needed to check the veracity of the block number and withdrawal being proven | -| validatorFieldsProof | bytes | is the information needed to check the veracity of the validator fields being proven | -| validatorFields | bytes32[] | are the fields of the validator being proven | -| withdrawalFields | bytes32[] | are the fields of the withdrawal being proven | -| beaconChainETHStrategyIndex | uint256 | is the index of the beaconChainETHStrategy for the pod owner for the callback to the EigenPodManager to the StrategyManager in case it must be removed from the podOwner's list of strategies | -| oracleBlockNumber | uint64 | is the Beacon Chain blockNumber whose state root the `proof` will be proven against. | - -### _processFullWithdrawal - -```solidity -function _processFullWithdrawal(uint64 withdrawalAmountGwei, uint40 validatorIndex, uint256 beaconChainETHStrategyIndex, address recipient, enum IEigenPod.VALIDATOR_STATUS status) internal -``` - -### _processPartialWithdrawal - -```solidity -function _processPartialWithdrawal(uint64 withdrawalHappenedSlot, uint64 partialWithdrawalAmountGwei, uint40 validatorIndex, address recipient) internal -``` - -### withdrawRestakedBeaconChainETH - -```solidity -function withdrawRestakedBeaconChainETH(address recipient, uint256 amountWei) external -``` - -Transfers `amountWei` in ether from this contract to the specified `recipient` address -Called by EigenPodManager to withdrawBeaconChainETH that has been added to the EigenPod's balance due to a withdrawal from the beacon chain. - -_Called during withdrawal or slashing._ - -### withdrawBeforeRestaking - -```solidity -function withdrawBeforeRestaking() external -``` - -Called by the pod owner to withdraw the balance of the pod when `hasRestaked` is set to false - -### _podWithdrawalCredentials - -```solidity -function _podWithdrawalCredentials() internal view returns (bytes) -``` - -### _sendETH - -```solidity -function _sendETH(address recipient, uint256 amountWei) internal -``` - -### __gap - -```solidity -uint256[46] __gap -``` - -_This empty reserved space is put in place to allow future versions to add new -variables without shifting down storage in the inheritance chain. -See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps_ - diff --git a/docs/docgen/pods/EigenPodManager.md b/docs/docgen/pods/EigenPodManager.md deleted file mode 100644 index c2482ee6b..000000000 --- a/docs/docgen/pods/EigenPodManager.md +++ /dev/null @@ -1,260 +0,0 @@ -# Solidity API - -## EigenPodManager - -The main functionalities are: -- creating EigenPods -- staking for new validators on EigenPods -- keeping track of the balances of all validators of EigenPods, and their stake in EigenLayer -- withdrawing eth when withdrawals are initiated - -### beaconProxyBytecode - -```solidity -bytes beaconProxyBytecode -``` - -Stored code of type(BeaconProxy).creationCode - -_Maintained as a constant to solve an edge case - changes to OpenZeppelin's BeaconProxy code should not cause -addresses of EigenPods that are pre-computed with Create2 to change, even upon upgrading this contract, changing compiler version, etc._ - -### ethPOS - -```solidity -contract IETHPOSDeposit ethPOS -``` - -The ETH2 Deposit Contract - -### eigenPodBeacon - -```solidity -contract IBeacon eigenPodBeacon -``` - -Beacon proxy to which the EigenPods point - -### strategyManager - -```solidity -contract IStrategyManager strategyManager -``` - -EigenLayer's StrategyManager contract - -### slasher - -```solidity -contract ISlasher slasher -``` - -EigenLayer's Slasher contract - -### beaconChainOracle - -```solidity -contract IBeaconChainOracle beaconChainOracle -``` - -Oracle contract that provides updates to the beacon chain's state - -### ownerToPod - -```solidity -mapping(address => contract IEigenPod) ownerToPod -``` - -Pod owner to deployed EigenPod address - -### BeaconOracleUpdated - -```solidity -event BeaconOracleUpdated(address newOracleAddress) -``` - -Emitted to notify the update of the beaconChainOracle address - -### PodDeployed - -```solidity -event PodDeployed(address eigenPod, address podOwner) -``` - -Emitted to notify the deployment of an EigenPod - -### BeaconChainETHDeposited - -```solidity -event BeaconChainETHDeposited(address podOwner, uint256 amount) -``` - -Emitted to notify a deposit of beacon chain ETH recorded in the strategy manager - -### onlyEigenPod - -```solidity -modifier onlyEigenPod(address podOwner) -``` - -### onlyStrategyManager - -```solidity -modifier onlyStrategyManager() -``` - -### constructor - -```solidity -constructor(contract IETHPOSDeposit _ethPOS, contract IBeacon _eigenPodBeacon, contract IStrategyManager _strategyManager, contract ISlasher _slasher) public -``` - -### initialize - -```solidity -function initialize(contract IBeaconChainOracle _beaconChainOracle, address initialOwner, contract IPauserRegistry _pauserRegistry, uint256 _initPausedStatus) external -``` - -### createPod - -```solidity -function createPod() external -``` - -Creates an EigenPod for the sender. - -_Function will revert if the `msg.sender` already has an EigenPod._ - -### stake - -```solidity -function stake(bytes pubkey, bytes signature, bytes32 depositDataRoot) external payable -``` - -Stakes for a new beacon chain validator on the sender's EigenPod. -Also creates an EigenPod for the sender if they don't have one already. - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| pubkey | bytes | The 48 bytes public key of the beacon chain validator. | -| signature | bytes | The validator's signature of the deposit data. | -| depositDataRoot | bytes32 | The root/hash of the deposit data for the validator's deposit. | - -### restakeBeaconChainETH - -```solidity -function restakeBeaconChainETH(address podOwner, uint256 amount) external -``` - -Deposits/Restakes beacon chain ETH in EigenLayer on behalf of the owner of an EigenPod. - -_Callable only by the podOwner's EigenPod contract._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| podOwner | address | The owner of the pod whose balance must be deposited. | -| amount | uint256 | The amount of ETH to 'deposit' (i.e. be credited to the podOwner). | - -### recordOvercommittedBeaconChainETH - -```solidity -function recordOvercommittedBeaconChainETH(address podOwner, uint256 beaconChainETHStrategyIndex, uint256 amount) external -``` - -Removes beacon chain ETH from EigenLayer on behalf of the owner of an EigenPod, when the - balance of a validator is lower than how much stake they have committed to EigenLayer - -_Callable only by the podOwner's EigenPod contract._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| podOwner | address | The owner of the pod whose balance must be removed. | -| beaconChainETHStrategyIndex | uint256 | is the index of the beaconChainETHStrategy for the pod owner for the callback to the StrategyManager in case it must be removed from the list of the podOwner's strategies | -| amount | uint256 | The amount of beacon chain ETH to decrement from the podOwner's shares in the strategyManager. | - -### withdrawRestakedBeaconChainETH - -```solidity -function withdrawRestakedBeaconChainETH(address podOwner, address recipient, uint256 amount) external -``` - -Withdraws ETH from an EigenPod. The ETH must have first been withdrawn from the beacon chain. - -_Callable only by the StrategyManager contract._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| podOwner | address | The owner of the pod whose balance must be withdrawn. | -| recipient | address | The recipient of the withdrawn ETH. | -| amount | uint256 | The amount of ETH to withdraw. | - -### updateBeaconChainOracle - -```solidity -function updateBeaconChainOracle(contract IBeaconChainOracle newBeaconChainOracle) external -``` - -Updates the oracle contract that provides the beacon chain state root - -_Callable only by the owner of this contract (i.e. governance)_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newBeaconChainOracle | contract IBeaconChainOracle | is the new oracle contract being pointed to | - -### _deployPod - -```solidity -function _deployPod() internal returns (contract IEigenPod) -``` - -### _updateBeaconChainOracle - -```solidity -function _updateBeaconChainOracle(contract IBeaconChainOracle newBeaconChainOracle) internal -``` - -### getPod - -```solidity -function getPod(address podOwner) public view returns (contract IEigenPod) -``` - -Returns the address of the `podOwner`'s EigenPod (whether it is deployed yet or not). - -### hasPod - -```solidity -function hasPod(address podOwner) public view returns (bool) -``` - -Returns 'true' if the `podOwner` has created an EigenPod, and 'false' otherwise. - -### getBeaconChainStateRoot - -```solidity -function getBeaconChainStateRoot(uint64 blockNumber) external view returns (bytes32) -``` - -Returns the Beacon Chain state root at `blockNumber`. Reverts if the Beacon Chain state root at `blockNumber` has not yet been finalized. - -### __gap - -```solidity -uint256[48] __gap -``` - -_This empty reserved space is put in place to allow future versions to add new -variables without shifting down storage in the inheritance chain. -See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps_ - diff --git a/docs/docgen/pods/EigenPodPausingConstants.md b/docs/docgen/pods/EigenPodPausingConstants.md deleted file mode 100644 index 5483e7081..000000000 --- a/docs/docgen/pods/EigenPodPausingConstants.md +++ /dev/null @@ -1,44 +0,0 @@ -# Solidity API - -## EigenPodPausingConstants - -### PAUSED_NEW_EIGENPODS - -```solidity -uint8 PAUSED_NEW_EIGENPODS -``` - -Index for flag that pauses creation of new EigenPods when set. See EigenPodManager code for details. - -### PAUSED_WITHDRAW_RESTAKED_ETH - -```solidity -uint8 PAUSED_WITHDRAW_RESTAKED_ETH -``` - -Index for flag that pauses the `withdrawRestakedBeaconChainETH` function *of the EigenPodManager* when set. See EigenPodManager code for details. - -### PAUSED_EIGENPODS_VERIFY_CREDENTIALS - -```solidity -uint8 PAUSED_EIGENPODS_VERIFY_CREDENTIALS -``` - -Index for flag that pauses the `verifyCorrectWithdrawalCredentials` function *of the EigenPods* when set. see EigenPod code for details. - -### PAUSED_EIGENPODS_VERIFY_OVERCOMMITTED - -```solidity -uint8 PAUSED_EIGENPODS_VERIFY_OVERCOMMITTED -``` - -Index for flag that pauses the `verifyOvercommittedStake` function *of the EigenPods* when set. see EigenPod code for details. - -### PAUSED_EIGENPODS_VERIFY_WITHDRAWAL - -```solidity -uint8 PAUSED_EIGENPODS_VERIFY_WITHDRAWAL -``` - -Index for flag that pauses the `verifyBeaconChainFullWithdrawal` function *of the EigenPods* when set. see EigenPod code for details. - diff --git a/docs/docgen/strategies/StrategyBase.md b/docs/docgen/strategies/StrategyBase.md deleted file mode 100644 index 9280a7d47..000000000 --- a/docs/docgen/strategies/StrategyBase.md +++ /dev/null @@ -1,300 +0,0 @@ -# Solidity API - -## StrategyBase - -Simple, basic, "do-nothing" Strategy that holds a single underlying token and returns it on withdrawals. -Implements minimal versions of the IStrategy functions, this contract is designed to be inherited by -more complex strategies, which can then override its functions as necessary. -This contract functions similarly to an ERC4626 vault, only without issuing a token. -To mitigate against the common "inflation attack" vector, we have chosen to use the 'virtual shares' mitigation route, -similar to [OpenZeppelin](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol). -We acknowledge that this mitigation has the known downside of the virtual shares causing some losses to users, which are pronounced -particularly in the case of the share exchange rate changing signficantly, either positively or negatively. -For a fairly thorough discussion of this issue and our chosen mitigation strategy, we recommend reading through -[this thread](https://github.com/OpenZeppelin/openzeppelin-contracts/issues/3706) on the OpenZeppelin repo. -We specifically use a share offset of `SHARES_OFFSET` and a balance offset of `BALANCE_OFFSET`. - -_Note that some functions have their mutability restricted; developers inheriting from this contract cannot broaden -the mutability without modifying this contract itself. -This contract is expressly *not* intended for use with 'fee-on-transfer'-type tokens. -Setting the `underlyingToken` to be a fee-on-transfer token may result in improper accounting._ - -### PAUSED_DEPOSITS - -```solidity -uint8 PAUSED_DEPOSITS -``` - -### PAUSED_WITHDRAWALS - -```solidity -uint8 PAUSED_WITHDRAWALS -``` - -### SHARES_OFFSET - -```solidity -uint256 SHARES_OFFSET -``` - -virtual shares used as part of the mitigation of the common 'share inflation' attack vector. -Constant value chosen to reasonably reduce attempted share inflation by the first depositor, while still -incurring reasonably small losses to depositors - -### BALANCE_OFFSET - -```solidity -uint256 BALANCE_OFFSET -``` - -virtual balance used as part of the mitigation of the common 'share inflation' attack vector -Constant value chosen to reasonably reduce attempted share inflation by the first depositor, while still -incurring reasonably small losses to depositors - -### strategyManager - -```solidity -contract IStrategyManager strategyManager -``` - -EigenLayer's StrategyManager contract - -### underlyingToken - -```solidity -contract IERC20 underlyingToken -``` - -The underlying token for shares in this Strategy - -### totalShares - -```solidity -uint256 totalShares -``` - -The total number of extant shares in this Strategy - -### onlyStrategyManager - -```solidity -modifier onlyStrategyManager() -``` - -Simply checks that the `msg.sender` is the `strategyManager`, which is an address stored immutably at construction. - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager) public -``` - -Since this contract is designed to be initializable, the constructor simply sets `strategyManager`, the only immutable variable. - -### initialize - -```solidity -function initialize(contract IERC20 _underlyingToken, contract IPauserRegistry _pauserRegistry) public virtual -``` - -### _initializeStrategyBase - -```solidity -function _initializeStrategyBase(contract IERC20 _underlyingToken, contract IPauserRegistry _pauserRegistry) internal -``` - -Sets the `underlyingToken` and `pauserRegistry` for the strategy. - -### deposit - -```solidity -function deposit(contract IERC20 token, uint256 amount) external virtual returns (uint256 newShares) -``` - -Used to deposit tokens into this Strategy - -_This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's -`depositIntoStrategy` function, and individual share balances are recorded in the strategyManager as well. -Note that the assumption is made that `amount` of `token` has already been transferred directly to this contract -(as performed in the StrategyManager's deposit functions). In particular, setting the `underlyingToken` of this contract -to be a fee-on-transfer token will break the assumption that the amount this contract *received* of the token is equal to -the amount that was input when the transfer was performed (i.e. the amount transferred 'out' of the depositor's balance)._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| token | contract IERC20 | is the ERC20 token being deposited | -| amount | uint256 | is the amount of token being deposited | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| newShares | uint256 | is the number of new shares issued at the current exchange ratio. | - -### withdraw - -```solidity -function withdraw(address depositor, contract IERC20 token, uint256 amountShares) external virtual -``` - -Used to withdraw tokens from this Strategy, to the `depositor`'s address - -_This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's -other functions, and individual share balances are recorded in the strategyManager as well._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | is the address to receive the withdrawn funds | -| token | contract IERC20 | is the ERC20 token being transferred out | -| amountShares | uint256 | is the amount of shares being withdrawn | - -### explanation - -```solidity -function explanation() external pure virtual returns (string) -``` - -Currently returns a brief string explaining the strategy's goal & purpose, but for more complex -strategies, may be a link to metadata that explains in more detail. - -### sharesToUnderlyingView - -```solidity -function sharesToUnderlyingView(uint256 amountShares) public view virtual returns (uint256) -``` - -Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy. -In contrast to `sharesToUnderlying`, this function guarantees no state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountShares | uint256 | is the amount of shares to calculate its conversion into the underlying token | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of underlying tokens corresponding to the input `amountShares` | - -### sharesToUnderlying - -```solidity -function sharesToUnderlying(uint256 amountShares) public view virtual returns (uint256) -``` - -Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy. -In contrast to `sharesToUnderlyingView`, this function **may** make state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountShares | uint256 | is the amount of shares to calculate its conversion into the underlying token | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of underlying tokens corresponding to the input `amountShares` | - -### underlyingToSharesView - -```solidity -function underlyingToSharesView(uint256 amountUnderlying) public view virtual returns (uint256) -``` - -Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy. -In contrast to `underlyingToShares`, this function guarantees no state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountUnderlying | uint256 | is the amount of `underlyingToken` to calculate its conversion into strategy shares | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of shares corresponding to the input `amountUnderlying` | - -### underlyingToShares - -```solidity -function underlyingToShares(uint256 amountUnderlying) external view virtual returns (uint256) -``` - -Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy. -In contrast to `underlyingToSharesView`, this function **may** make state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountUnderlying | uint256 | is the amount of `underlyingToken` to calculate its conversion into strategy shares | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of shares corresponding to the input `amountUnderlying` | - -### userUnderlyingView - -```solidity -function userUnderlyingView(address user) external view virtual returns (uint256) -``` - -convenience function for fetching the current underlying value of all of the `user`'s shares in -this strategy. In contrast to `userUnderlying`, this function guarantees no state modifications - -### userUnderlying - -```solidity -function userUnderlying(address user) external virtual returns (uint256) -``` - -convenience function for fetching the current underlying value of all of the `user`'s shares in -this strategy. In contrast to `userUnderlyingView`, this function **may** make state modifications - -### shares - -```solidity -function shares(address user) public view virtual returns (uint256) -``` - -convenience function for fetching the current total shares of `user` in this strategy, by -querying the `strategyManager` contract - -### _tokenBalance - -```solidity -function _tokenBalance() internal view virtual returns (uint256) -``` - -Internal function used to fetch this contract's current balance of `underlyingToken`. - -### __gap - -```solidity -uint256[48] __gap -``` - -_This empty reserved space is put in place to allow future versions to add new -variables without shifting down storage in the inheritance chain. -See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps_ - diff --git a/docs/docgen/strategies/StrategyWrapper.md b/docs/docgen/strategies/StrategyWrapper.md deleted file mode 100644 index e39108b02..000000000 --- a/docs/docgen/strategies/StrategyWrapper.md +++ /dev/null @@ -1,222 +0,0 @@ -# Solidity API - -## StrategyWrapper - -Simple, basic, "do-nothing" Strategy that holds a single underlying token and returns it on withdrawals. -Assumes shares are always 1-to-1 with the underlyingToken. - -_Unlike `StrategyBase`, this contract is *not* designed to be inherited from. -This contract is expressly *not* intended for use with 'fee-on-transfer'-type tokens. -Setting the `underlyingToken` to be a fee-on-transfer token may result in improper accounting._ - -### strategyManager - -```solidity -contract IStrategyManager strategyManager -``` - -EigenLayer's StrategyManager contract - -### underlyingToken - -```solidity -contract IERC20 underlyingToken -``` - -The underlying token for shares in this Strategy - -### totalShares - -```solidity -uint256 totalShares -``` - -The total number of extant shares in this Strategy - -### onlyStrategyManager - -```solidity -modifier onlyStrategyManager() -``` - -### constructor - -```solidity -constructor(contract IStrategyManager _strategyManager, contract IERC20 _underlyingToken) public -``` - -### deposit - -```solidity -function deposit(contract IERC20 token, uint256 amount) external returns (uint256) -``` - -Used to deposit tokens into this Strategy - -_This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's -`depositIntoStrategy` function, and individual share balances are recorded in the strategyManager as well. -Note that the assumption is made that `amount` of `token` has already been transferred directly to this contract -(as performed in the StrategyManager's deposit functions). In particular, setting the `underlyingToken` of this contract -to be a fee-on-transfer token will break the assumption that the amount this contract *received* of the token is equal to -the amount that was input when the transfer was performed (i.e. the amount transferred 'out' of the depositor's balance)._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| token | contract IERC20 | is the ERC20 token being deposited | -| amount | uint256 | is the amount of token being deposited | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | newShares is the number of new shares issued at the current exchange ratio. | - -### withdraw - -```solidity -function withdraw(address depositor, contract IERC20 token, uint256 amountShares) external -``` - -Used to withdraw tokens from this Strategy, to the `depositor`'s address - -_This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's -other functions, and individual share balances are recorded in the strategyManager as well._ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| depositor | address | is the address to receive the withdrawn funds | -| token | contract IERC20 | is the ERC20 token being transferred out | -| amountShares | uint256 | is the amount of shares being withdrawn | - -### explanation - -```solidity -function explanation() external pure returns (string) -``` - -Currently returns a brief string explaining the strategy's goal & purpose, but for more complex -strategies, may be a link to metadata that explains in more detail. - -### sharesToUnderlyingView - -```solidity -function sharesToUnderlyingView(uint256 amountShares) public pure returns (uint256) -``` - -Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy. -In contrast to `sharesToUnderlying`, this function guarantees no state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountShares | uint256 | is the amount of shares to calculate its conversion into the underlying token | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of underlying tokens corresponding to the input `amountShares` | - -### sharesToUnderlying - -```solidity -function sharesToUnderlying(uint256 amountShares) public pure returns (uint256) -``` - -Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy. -In contrast to `sharesToUnderlyingView`, this function **may** make state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountShares | uint256 | is the amount of shares to calculate its conversion into the underlying token | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of underlying tokens corresponding to the input `amountShares` | - -### underlyingToSharesView - -```solidity -function underlyingToSharesView(uint256 amountUnderlying) external pure returns (uint256) -``` - -Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy. -In contrast to `underlyingToShares`, this function guarantees no state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountUnderlying | uint256 | is the amount of `underlyingToken` to calculate its conversion into strategy shares | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of shares corresponding to the input `amountUnderlying` | - -### underlyingToShares - -```solidity -function underlyingToShares(uint256 amountUnderlying) external pure returns (uint256) -``` - -Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy. -In contrast to `underlyingToSharesView`, this function **may** make state modifications - -_Implementation for these functions in particular may vary significantly for different strategies_ - -#### Parameters - -| Name | Type | Description | -| ---- | ---- | ----------- | -| amountUnderlying | uint256 | is the amount of `underlyingToken` to calculate its conversion into strategy shares | - -#### Return Values - -| Name | Type | Description | -| ---- | ---- | ----------- | -| [0] | uint256 | The amount of shares corresponding to the input `amountUnderlying` | - -### userUnderlyingView - -```solidity -function userUnderlyingView(address user) external view returns (uint256) -``` - -convenience function for fetching the current underlying value of all of the `user`'s shares in -this strategy. In contrast to `userUnderlying`, this function guarantees no state modifications - -### userUnderlying - -```solidity -function userUnderlying(address user) external view returns (uint256) -``` - -convenience function for fetching the current underlying value of all of the `user`'s shares in -this strategy. In contrast to `userUnderlyingView`, this function **may** make state modifications - -### shares - -```solidity -function shares(address user) public view returns (uint256) -``` - -convenience function for fetching the current total shares of `user` in this strategy, by -querying the `strategyManager` contract - diff --git a/src/contracts/core/Slasher.sol b/src/contracts/core/Slasher.sol index 0e657b8b3..4793eedd5 100644 --- a/src/contracts/core/Slasher.sol +++ b/src/contracts/core/Slasher.sol @@ -316,7 +316,7 @@ contract Slasher is Initializable, OwnableUpgradeable, ISlasher, Pausable { } /// @notice Getter function for fetching `_operatorToMiddlewareTimes[operator][index].stalestUpdateBlock`. - function getMiddlewareTimesIndexBlock(address operator, uint32 index) external view returns (uint32) { + function getMiddlewareTimesIndexStalestUpdateBlock(address operator, uint32 index) external view returns (uint32) { return _operatorToMiddlewareTimes[operator][index].stalestUpdateBlock; } diff --git a/src/contracts/interfaces/IBLSPublicKeyCompendium.sol b/src/contracts/interfaces/IBLSPublicKeyCompendium.sol index 3d692d7b9..8833f1840 100644 --- a/src/contracts/interfaces/IBLSPublicKeyCompendium.sol +++ b/src/contracts/interfaces/IBLSPublicKeyCompendium.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "../libraries/BN254.sol"; @@ -24,10 +24,9 @@ interface IBLSPublicKeyCompendium { /** * @notice Called by an operator to register themselves as the owner of a BLS public key and reveal their G1 and G2 public key. - * @param s is the field element of the operator's Schnorr signature - * @param rPoint is the group element of the operator's Schnorr signature - * @param pubkeyG1 is the the G1 pubkey of the operator - * @param pubkeyG2 is the G2 with the same private key as the pubkeyG1 + * @param signedMessageHash is the registration message hash signed by the private key of the operator + * @param pubkeyG1 is the corresponding G1 public key of the operator + * @param pubkeyG2 is the corresponding G2 public key of the operator */ - function registerBLSPublicKey(uint256 s, BN254.G1Point memory rPoint, BN254.G1Point memory pubkeyG1, BN254.G2Point memory pubkeyG2) external; + function registerBLSPublicKey(BN254.G1Point memory signedMessageHash, BN254.G1Point memory pubkeyG1, BN254.G2Point memory pubkeyG2) external; } diff --git a/src/contracts/interfaces/IBLSRegistry.sol b/src/contracts/interfaces/IBLSRegistry.sol new file mode 100644 index 000000000..de856a84d --- /dev/null +++ b/src/contracts/interfaces/IBLSRegistry.sol @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: BUSL-1.1 +pragma solidity >=0.5.0; + +import "./IQuorumRegistry.sol"; + +/** + * @title Minimal interface extension to `IQuorumRegistry`. + * @author Layr Labs, Inc. + * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service + * @notice Adds BLS-specific functions to the base interface. + */ +interface IBLSRegistry is IQuorumRegistry { + /// @notice Data structure used to track the history of the Aggregate Public Key of all operators + struct ApkUpdate { + // keccak256(apk_x0, apk_x1, apk_y0, apk_y1) + bytes32 apkHash; + // block number at which the update occurred + uint32 blockNumber; + } + + /** + * @notice get hash of a historical aggregated public key corresponding to a given index; + * called by checkSignatures in BLSSignatureChecker.sol. + */ + function getCorrectApkHash(uint256 index, uint32 blockNumber) external returns (bytes32); + + /// @notice returns the `ApkUpdate` struct at `index` in the list of APK updates + function apkUpdates(uint256 index) external view returns (ApkUpdate memory); + + /// @notice returns the APK hash that resulted from the `index`th APK update + function apkHashes(uint256 index) external view returns (bytes32); + + /// @notice returns the block number at which the `index`th APK update occurred + function apkUpdateBlockNumbers(uint256 index) external view returns (uint32); + + function operatorWhitelister() external view returns(address); + + function operatorWhitelistEnabled() external view returns(bool); + + function whitelisted(address) external view returns(bool); + + function setOperatorWhitelistStatus(bool _operatorWhitelistEnabled) external; + + function addToOperatorWhitelist(address[] calldata) external; + + function removeFromWhitelist(address[] calldata operators) external; +} \ No newline at end of file diff --git a/src/contracts/interfaces/IBLSSignatureChecker.sol b/src/contracts/interfaces/IBLSSignatureChecker.sol new file mode 100644 index 000000000..52b4e4273 --- /dev/null +++ b/src/contracts/interfaces/IBLSSignatureChecker.sol @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: BUSL-1.1 +pragma solidity =0.8.12; + +import "../interfaces/IBLSRegistryCoordinatorWithIndices.sol"; +import "../libraries/MiddlewareUtils.sol"; +import "../libraries/BN254.sol"; +import "../libraries/BitmapUtils.sol"; + +/** + * @title Used for checking BLS aggregate signatures from the operators of a EigenLayer AVS with the RegistryCoordinator/BLSPubkeyRegistry/StakeRegistry architechture. + * @author Layr Labs, Inc. + * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service + * @notice This is the contract for checking the validity of aggregate operator signatures. + */ +interface IBLSSignatureChecker { + // DATA STRUCTURES + + struct NonSignerStakesAndSignature { + uint32[] nonSignerQuorumBitmapIndices; + BN254.G1Point[] nonSignerPubkeys; + BN254.G1Point[] quorumApks; + BN254.G2Point apkG2; + BN254.G1Point sigma; + uint32[] quorumApkIndices; + uint32[] totalStakeIndices; + uint32[][] nonSignerStakeIndices; // nonSignerStakeIndices[quorumNumberIndex][nonSignerIndex] + } + + /** + * @notice this data structure is used for recording the details on the total stake of the registered + * operators and those operators who are part of the quorum for a particular taskNumber + */ + + struct QuorumStakeTotals { + // total stake of the operators in each quorum + uint96[] signedStakeForQuorum; + // total amount staked by all operators in each quorum + uint96[] totalStakeForQuorum; + } + + // CONSTANTS & IMMUTABLES + + function registryCoordinator() external view returns (IRegistryCoordinator); + function stakeRegistry() external view returns (IStakeRegistry); + function blsPubkeyRegistry() external view returns (IBLSPubkeyRegistry); + + /** + * @notice This function is called by disperser when it has aggregated all the signatures of the operators + * that are part of the quorum for a particular taskNumber and is asserting them into onchain. The function + * checks that the claim for aggregated signatures are valid. + * + * The thesis of this procedure entails: + * - getting the aggregated pubkey of all registered nodes at the time of pre-commit by the + * disperser (represented by apk in the parameters), + * - subtracting the pubkeys of all the signers not in the quorum (nonSignerPubkeys) and storing + * the output in apk to get aggregated pubkey of all operators that are part of quorum. + * - use this aggregated pubkey to verify the aggregated signature under BLS scheme. + * + * @dev Before signature verification, the function verifies operator stake information. This includes ensuring that the provided `referenceBlockNumber` + * is correct, i.e., ensure that the stake returned from the specified block number is recent enough and that the stake is either the most recent update + * for the total stake (or the operator) or latest before the referenceBlockNumber. + */ + function checkSignatures( + bytes32 msgHash, + bytes calldata quorumNumbers, + uint32 referenceBlockNumber, + NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) + external + view + returns ( + QuorumStakeTotals memory, + bytes32 + ); +} \ No newline at end of file diff --git a/src/contracts/interfaces/IBeaconChainOracle.sol b/src/contracts/interfaces/IBeaconChainOracle.sol index 6bdff804d..fdc551ba7 100644 --- a/src/contracts/interfaces/IBeaconChainOracle.sol +++ b/src/contracts/interfaces/IBeaconChainOracle.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; /** * @title Interface for the BeaconStateOracle contract. diff --git a/src/contracts/interfaces/IDelayedService.sol b/src/contracts/interfaces/IDelayedService.sol index 1f905b399..2de542012 100644 --- a/src/contracts/interfaces/IDelayedService.sol +++ b/src/contracts/interfaces/IDelayedService.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; /** * @title Interface for a middleware / service that may look at past stake amounts. diff --git a/src/contracts/interfaces/IDelayedWithdrawalRouter.sol b/src/contracts/interfaces/IDelayedWithdrawalRouter.sol index 093009aae..c2f12dce1 100644 --- a/src/contracts/interfaces/IDelayedWithdrawalRouter.sol +++ b/src/contracts/interfaces/IDelayedWithdrawalRouter.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; interface IDelayedWithdrawalRouter { // struct used to pack data into a single storage slot diff --git a/src/contracts/interfaces/IDelegationManager.sol b/src/contracts/interfaces/IDelegationManager.sol index b2d7715c2..2992beb1b 100644 --- a/src/contracts/interfaces/IDelegationManager.sol +++ b/src/contracts/interfaces/IDelegationManager.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "./IDelegationTerms.sol"; diff --git a/src/contracts/interfaces/IDelegationTerms.sol b/src/contracts/interfaces/IDelegationTerms.sol index 803cdfcde..6b70c7784 100644 --- a/src/contracts/interfaces/IDelegationTerms.sol +++ b/src/contracts/interfaces/IDelegationTerms.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "./IStrategy.sol"; diff --git a/src/contracts/interfaces/IETHPOSDeposit.sol b/src/contracts/interfaces/IETHPOSDeposit.sol index cb6676d55..5fc09a5cc 100644 --- a/src/contracts/interfaces/IETHPOSDeposit.sol +++ b/src/contracts/interfaces/IETHPOSDeposit.sol @@ -9,7 +9,7 @@ // SPDX-License-Identifier: CC0-1.0 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; // This interface is designed to be compatible with the Vyper version. /// @notice This is the Ethereum 2.0 deposit contract interface. diff --git a/src/contracts/interfaces/IEigenPod.sol b/src/contracts/interfaces/IEigenPod.sol index a44cb339d..886fee8bc 100644 --- a/src/contracts/interfaces/IEigenPod.sol +++ b/src/contracts/interfaces/IEigenPod.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "../libraries/BeaconChainProofs.sol"; import "./IEigenPodManager.sol"; diff --git a/src/contracts/interfaces/IEigenPodManager.sol b/src/contracts/interfaces/IEigenPodManager.sol index 3455262f2..4912ab742 100644 --- a/src/contracts/interfaces/IEigenPodManager.sol +++ b/src/contracts/interfaces/IEigenPodManager.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "./IStrategyManager.sol"; import "./IEigenPod.sol"; diff --git a/src/contracts/interfaces/IPausable.sol b/src/contracts/interfaces/IPausable.sol index 11450067a..e81241357 100644 --- a/src/contracts/interfaces/IPausable.sol +++ b/src/contracts/interfaces/IPausable.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "../interfaces/IPauserRegistry.sol"; diff --git a/src/contracts/interfaces/IPauserRegistry.sol b/src/contracts/interfaces/IPauserRegistry.sol index 7a3a986f7..732a7eb33 100644 --- a/src/contracts/interfaces/IPauserRegistry.sol +++ b/src/contracts/interfaces/IPauserRegistry.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; /** * @title Interface for the `PauserRegistry` contract. diff --git a/src/contracts/interfaces/IPaymentManager.sol b/src/contracts/interfaces/IPaymentManager.sol index 4618c186a..a1cb4cee0 100644 --- a/src/contracts/interfaces/IPaymentManager.sol +++ b/src/contracts/interfaces/IPaymentManager.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; diff --git a/src/contracts/interfaces/IQuorumRegistry.sol b/src/contracts/interfaces/IQuorumRegistry.sol new file mode 100644 index 000000000..871874f87 --- /dev/null +++ b/src/contracts/interfaces/IQuorumRegistry.sol @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: BUSL-1.1 +pragma solidity >=0.5.0; + +import "./IRegistry.sol"; + +/** + * @title Interface for a `Registry`-type contract that uses either 1 or 2 quorums. + * @author Layr Labs, Inc. + * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service + * @notice This contract does not currently support n-quorums where n >= 3. + * Note in particular the presence of only `firstQuorumStake` and `secondQuorumStake` in the `OperatorStake` struct. + */ +interface IQuorumRegistry is IRegistry { + // DATA STRUCTURES + enum Status + { + // default is inactive + INACTIVE, + ACTIVE + } + + /** + * @notice Data structure for storing info on operators to be used for: + * - sending data by the sequencer + * - payment and associated challenges + */ + struct Operator { + // hash of pubkey of the operator + bytes32 pubkeyHash; + // start taskNumber from which the operator has been registered + uint32 fromTaskNumber; + // indicates whether the operator is actively registered for serving the middleware or not + Status status; + } + + // struct used to give definitive ordering to operators at each blockNumber + struct OperatorIndex { + // blockNumber number at which operator index changed + // note that the operator's index is different *for this block number*, i.e. the *new* index is *inclusive* of this value + uint32 toBlockNumber; + // index of the operator in array of operators, or the total number of operators if in the 'totalOperatorsHistory' + uint32 index; + } + + /// @notice struct used to store the stakes of an individual operator or the sum of all operators' stakes, for storage + struct OperatorStake { + // the block number at which the stake amounts were updated and stored + uint32 updateBlockNumber; + // the block number at which the *next update* occurred. + /// @notice This entry has the value **0** until another update takes place. + uint32 nextUpdateBlockNumber; + // stake weight for the first quorum + uint96 firstQuorumStake; + // stake weight for the second quorum. Will always be zero in the event that only one quorum is used + uint96 secondQuorumStake; + } + + function getLengthOfTotalStakeHistory() external view returns (uint256); + + /** + * @notice Returns the `index`-th entry in the dynamic array of total stake, `totalStakeHistory`. + * @dev Function will revert in the event that `index` is out-of-bounds. + */ + function getTotalStakeFromIndex(uint256 index) external view returns (OperatorStake memory); + + /// @notice Returns the stored pubkeyHash for the specified `operator`. + function getOperatorPubkeyHash(address operator) external view returns (bytes32); + + /// @notice Returns task number from when `operator` has been registered. + function getFromTaskNumberForOperator(address operator) external view returns (uint32); + + /** + * @notice Returns the stake weight corresponding to `pubkeyHash`, at the + * `index`-th entry in the `pubkeyHashToStakeHistory[pubkeyHash]` array. + * @param pubkeyHash Hash of the public key of the operator of interest. + * @param index Array index for lookup, within the dynamic array `pubkeyHashToStakeHistory[pubkeyHash]`. + * @dev Function will revert if `index` is out-of-bounds. + */ + function getStakeFromPubkeyHashAndIndex(bytes32 pubkeyHash, uint256 index) + external + view + returns (OperatorStake memory); + + /** + * @notice Checks that the `operator` was active at the `blockNumber`, using the specified `stakeHistoryIndex` as proof. + * @param operator is the operator of interest + * @param blockNumber is the block number of interest + * @param stakeHistoryIndex specifies an index in `pubkeyHashToStakeHistory[pubkeyHash]`, where `pubkeyHash` is looked up + * in `registry[operator].pubkeyHash` + * @return 'true' if it is successfully proven that the `operator` was active at the `blockNumber`, and 'false' otherwise + * @dev In order for this function to return 'true', the inputs must satisfy all of the following list: + * 1) `pubkeyHashToStakeHistory[pubkeyHash][index].updateBlockNumber <= blockNumber` + * 2) `pubkeyHashToStakeHistory[pubkeyHash][index].nextUpdateBlockNumber` must be either `0` (signifying no next update) or + * is must be strictly greater than `blockNumber` + * 3) `pubkeyHashToStakeHistory[pubkeyHash][index].firstQuorumStake > 0` + * or `pubkeyHashToStakeHistory[pubkeyHash][index].secondQuorumStake > 0`, i.e. the operator had nonzero stake + * @dev Note that a return value of 'false' does not guarantee that the `operator` was inactive at `blockNumber`, since a + * bad `stakeHistoryIndex` can be supplied in order to obtain a response of 'false'. + */ + function checkOperatorActiveAtBlockNumber( + address operator, + uint256 blockNumber, + uint256 stakeHistoryIndex + ) external view returns (bool); + + /** + * @notice Checks that the `operator` was inactive at the `blockNumber`, using the specified `stakeHistoryIndex` as proof. + * @param operator is the operator of interest + * @param blockNumber is the block number of interest + * @param stakeHistoryIndex specifies an index in `pubkeyHashToStakeHistory[pubkeyHash]`, where `pubkeyHash` is looked up + * in `registry[operator].pubkeyHash` + * @return 'true' if it is successfully proven that the `operator` was inactive at the `blockNumber`, and 'false' otherwise + * @dev In order for this function to return 'true', the inputs must satisfy all of the following list: + * 1) `pubkeyHashToStakeHistory[pubkeyHash][index].updateBlockNumber <= blockNumber` + * 2) `pubkeyHashToStakeHistory[pubkeyHash][index].nextUpdateBlockNumber` must be either `0` (signifying no next update) or + * is must be strictly greater than `blockNumber` + * 3) `pubkeyHashToStakeHistory[pubkeyHash][index].firstQuorumStake > 0` + * or `pubkeyHashToStakeHistory[pubkeyHash][index].secondQuorumStake > 0`, i.e. the operator had nonzero stake + * @dev Note that a return value of 'false' does not guarantee that the `operator` was active at `blockNumber`, since a + * bad `stakeHistoryIndex` can be supplied in order to obtain a response of 'false'. + */ + function checkOperatorInactiveAtBlockNumber( + address operator, + uint256 blockNumber, + uint256 stakeHistoryIndex + ) external view returns (bool); + + /** + * @notice Looks up the `operator`'s index in the dynamic array `operatorList` at the specified `blockNumber`. + * @param index Used to specify the entry within the dynamic array `pubkeyHashToIndexHistory[pubkeyHash]` to + * read data from, where `pubkeyHash` is looked up from `operator`'s registration info + * @param blockNumber Is the desired block number at which we wish to query the operator's position in the `operatorList` array + * @dev Function will revert in the event that the specified `index` input does not identify the appropriate entry in the + * array `pubkeyHashToIndexHistory[pubkeyHash]` to pull the info from. + */ + function getOperatorIndex(address operator, uint32 blockNumber, uint32 index) external view returns (uint32); + + /** + * @notice Looks up the number of total operators at the specified `blockNumber`. + * @param index Input used to specify the entry within the dynamic array `totalOperatorsHistory` to read data from. + * @dev This function will revert if the provided `index` is out of bounds. + */ + function getTotalOperators(uint32 blockNumber, uint32 index) external view returns (uint32); + + /// @notice Returns the current number of operators of this service. + function numOperators() external view returns (uint32); + + /** + * @notice Returns the most recent stake weights for the `operator` + * @dev Function returns weights of **0** in the event that the operator has no stake history + */ + function operatorStakes(address operator) external view returns (uint96, uint96); + + /// @notice Returns the stake amounts from the latest entry in `totalStakeHistory`. + function totalStake() external view returns (uint96, uint96); +} diff --git a/src/contracts/interfaces/IRegistry.sol b/src/contracts/interfaces/IRegistry.sol index a917f0f61..49e7d5456 100644 --- a/src/contracts/interfaces/IRegistry.sol +++ b/src/contracts/interfaces/IRegistry.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "./IRegistryCoordinator.sol"; diff --git a/src/contracts/interfaces/IServiceManager.sol b/src/contracts/interfaces/IServiceManager.sol index 953ab3844..2ee90cb0e 100644 --- a/src/contracts/interfaces/IServiceManager.sol +++ b/src/contracts/interfaces/IServiceManager.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IDelegationManager.sol"; diff --git a/src/contracts/interfaces/ISlasher.sol b/src/contracts/interfaces/ISlasher.sol index 63612f29d..c15b2ee47 100644 --- a/src/contracts/interfaces/ISlasher.sol +++ b/src/contracts/interfaces/ISlasher.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; /** * @title Interface for the primary 'slashing' contract for EigenLayer. @@ -126,7 +126,7 @@ interface ISlasher { function middlewareTimesLength(address operator) external view returns (uint256); /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator][index].stalestUpdateBlock`. - function getMiddlewareTimesIndexBlock(address operator, uint32 index) external view returns(uint32); + function getMiddlewareTimesIndexStalestUpdateBlock(address operator, uint32 index) external view returns(uint32); /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator][index].latestServeUntil`. function getMiddlewareTimesIndexServeUntilBlock(address operator, uint32 index) external view returns(uint32); diff --git a/src/contracts/interfaces/IStrategy.sol b/src/contracts/interfaces/IStrategy.sol index 80bc9a323..3d65a2023 100644 --- a/src/contracts/interfaces/IStrategy.sol +++ b/src/contracts/interfaces/IStrategy.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; diff --git a/src/contracts/interfaces/IStrategyManager.sol b/src/contracts/interfaces/IStrategyManager.sol index 49313727d..48b1c623b 100644 --- a/src/contracts/interfaces/IStrategyManager.sol +++ b/src/contracts/interfaces/IStrategyManager.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "./IStrategy.sol"; import "./ISlasher.sol"; diff --git a/src/contracts/interfaces/IVoteWeigher.sol b/src/contracts/interfaces/IVoteWeigher.sol index d8604bf89..dfdf6e55c 100644 --- a/src/contracts/interfaces/IVoteWeigher.sol +++ b/src/contracts/interfaces/IVoteWeigher.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity >=0.5.0; import "../interfaces/IStrategyManager.sol"; import "../interfaces/IServiceManager.sol"; diff --git a/src/contracts/interfaces/IWhitelister.sol b/src/contracts/interfaces/IWhitelister.sol new file mode 100644 index 000000000..a3f2fdf57 --- /dev/null +++ b/src/contracts/interfaces/IWhitelister.sol @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: BUSL-1.1 +pragma solidity >=0.5.0; + +import "../../contracts/interfaces/IStrategyManager.sol"; +import "../../contracts/interfaces/IStrategy.sol"; +import "../../contracts/interfaces/IDelegationManager.sol"; +import "../../contracts/interfaces/IBLSRegistry.sol"; +import "../../../script/whitelist/Staker.sol"; + +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; +import "@openzeppelin/contracts/utils/Create2.sol"; + + +interface IWhitelister { + + function whitelist(address operator) external; + + function getStaker(address operator) external returns (address); + + function depositIntoStrategy( + address staker, + IStrategy strategy, + IERC20 token, + uint256 amount + ) external returns (bytes memory); + + function queueWithdrawal( + address staker, + uint256[] calldata strategyIndexes, + IStrategy[] calldata strategies, + uint256[] calldata shares, + address withdrawer, + bool undelegateIfPossible + ) external returns (bytes memory); + + function completeQueuedWithdrawal( + address staker, + IStrategyManager.QueuedWithdrawal calldata queuedWithdrawal, + IERC20[] calldata tokens, + uint256 middlewareTimesIndex, + bool receiveAsTokens + ) external returns (bytes memory); + + function transfer( + address staker, + address token, + address to, + uint256 amount + ) external returns (bytes memory) ; + + function callAddress( + address to, + bytes memory data + ) external payable returns (bytes memory); +} diff --git a/src/contracts/libraries/BeaconChainProofs.sol b/src/contracts/libraries/BeaconChainProofs.sol index 849141858..98e2e973a 100644 --- a/src/contracts/libraries/BeaconChainProofs.sol +++ b/src/contracts/libraries/BeaconChainProofs.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity ^0.8.0; import "./Merkle.sol"; import "../libraries/Endian.sol"; diff --git a/src/contracts/libraries/Endian.sol b/src/contracts/libraries/Endian.sol index 42db62096..03da404ed 100644 --- a/src/contracts/libraries/Endian.sol +++ b/src/contracts/libraries/Endian.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BUSL-1.1 -pragma solidity =0.8.12; +pragma solidity ^0.8.0; library Endian { /** diff --git a/src/contracts/libraries/Merkle.sol b/src/contracts/libraries/Merkle.sol index 0fe9ee239..8954c8dc8 100644 --- a/src/contracts/libraries/Merkle.sol +++ b/src/contracts/libraries/Merkle.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: BUSL-1.1 // Adapted from OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/MerkleProof.sol) -pragma solidity =0.8.12; +pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Tree proofs. diff --git a/src/contracts/middleware/BLSOperatorStateRetriever.sol b/src/contracts/middleware/BLSOperatorStateRetriever.sol index 36b3001a8..3cc8d87a8 100644 --- a/src/contracts/middleware/BLSOperatorStateRetriever.sol +++ b/src/contracts/middleware/BLSOperatorStateRetriever.sol @@ -100,16 +100,19 @@ contract BLSOperatorStateRetriever { IStakeRegistry stakeRegistry = registryCoordinator.stakeRegistry(); CheckSignaturesIndices memory checkSignaturesIndices; + // get the indices of the quorumBitmap updates for each of the operators in the nonSignerOperatorIds array checkSignaturesIndices.nonSignerQuorumBitmapIndices = registryCoordinator.getQuorumBitmapIndicesByOperatorIdsAtBlockNumber(referenceBlockNumber, nonSignerOperatorIds); + // get the indices of the totalStake updates for each of the quorums in the quorumNumbers array checkSignaturesIndices.totalStakeIndices = stakeRegistry.getTotalStakeIndicesByQuorumNumbersAtBlockNumber(referenceBlockNumber, quorumNumbers); checkSignaturesIndices.nonSignerStakeIndices = new uint32[][](quorumNumbers.length); for (uint8 quorumNumberIndex = 0; quorumNumberIndex < quorumNumbers.length; quorumNumberIndex++) { uint256 numNonSignersForQuorum = 0; - // this array's length will be at most the number of nonSignerOperatorIds + // this array's length will be at most the number of nonSignerOperatorIds, this will be trimmed after it is filled checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex] = new uint32[](nonSignerOperatorIds.length); for (uint i = 0; i < nonSignerOperatorIds.length; i++) { + // get the quorumBitmap for the operator at the given blocknumber and index uint192 nonSignerQuorumBitmap = registryCoordinator.getQuorumBitmapByOperatorIdAtBlockNumberByIndex( nonSignerOperatorIds[i], @@ -118,7 +121,8 @@ contract BLSOperatorStateRetriever { ); // if the operator was a part of the quorum and the quorum is a part of the provided quorumNumbers - if (nonSignerQuorumBitmap >> uint8(quorumNumbers[quorumNumberIndex]) & 1 == 1) { + if ((nonSignerQuorumBitmap >> uint8(quorumNumbers[quorumNumberIndex])) & 1 == 1) { + // get the index of the stake update for the operator at the given blocknumber and quorum number checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex][numNonSignersForQuorum] = stakeRegistry.getStakeUpdateIndexForOperatorIdForQuorumAtBlockNumber( nonSignerOperatorIds[i], uint8(quorumNumbers[quorumNumberIndex]), @@ -137,6 +141,7 @@ contract BLSOperatorStateRetriever { } IBLSPubkeyRegistry blsPubkeyRegistry = registryCoordinator.blsPubkeyRegistry(); + // get the indices of the quorum apks for each of the provided quorums at the given blocknumber checkSignaturesIndices.quorumApkIndices = blsPubkeyRegistry.getApkIndicesForQuorumsAtBlockNumber(quorumNumbers, referenceBlockNumber); return checkSignaturesIndices; diff --git a/src/contracts/middleware/BLSPublicKeyCompendium.sol b/src/contracts/middleware/BLSPublicKeyCompendium.sol index aa3fc0883..21e4a6ab6 100644 --- a/src/contracts/middleware/BLSPublicKeyCompendium.sol +++ b/src/contracts/middleware/BLSPublicKeyCompendium.sol @@ -10,8 +10,7 @@ import "../libraries/BN254.sol"; * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service */ contract BLSPublicKeyCompendium is IBLSPublicKeyCompendium { - //Hash of the zero public key: BN254.hashG1Point(G1Point(0,0)) - bytes32 internal constant ZERO_PK_HASH = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; + using BN254 for BN254.G1Point; /// @notice mapping from operator address to pubkey hash mapping(address => bytes32) public operatorToPubkeyHash; @@ -24,41 +23,38 @@ contract BLSPublicKeyCompendium is IBLSPublicKeyCompendium { /** * @notice Called by an operator to register themselves as the owner of a BLS public key and reveal their G1 and G2 public key. - * @param s is the field element of the operator's Schnorr signature - * @param rPoint is the group element of the operator's Schnorr signature - * @param pubkeyG1 is the the G1 pubkey of the operator - * @param pubkeyG2 is the G2 with the same private key as the pubkeyG1 + * @param signedMessageHash is the registration message hash signed by the private key of the operator + * @param pubkeyG1 is the corresponding G1 public key of the operator + * @param pubkeyG2 is the corresponding G2 public key of the operator */ - function registerBLSPublicKey(uint256 s, BN254.G1Point memory rPoint, BN254.G1Point memory pubkeyG1, BN254.G2Point memory pubkeyG2) external { - // calculate -g1 - BN254.G1Point memory negGeneratorG1 = BN254.negate(BN254.G1Point({X: 1, Y: 2})); - // verify a Schnorr signature (s, R) of pubkeyG1 - // calculate s*-g1 + (R + H(msg.sender, P, R)*P) = 0 - // which is the Schnorr signature verification equation - BN254.G1Point memory shouldBeZero = - BN254.plus( - BN254.scalar_mul(negGeneratorG1, s), - BN254.plus( - rPoint, - BN254.scalar_mul( - pubkeyG1, - uint256(keccak256(abi.encodePacked(msg.sender, pubkeyG1.X, pubkeyG1.Y, rPoint.X, rPoint.Y))) % BN254.FR_MODULUS - ) - ) - ); + function registerBLSPublicKey(BN254.G1Point memory signedMessageHash, BN254.G1Point memory pubkeyG1, BN254.G2Point memory pubkeyG2) external { + // H(m) + BN254.G1Point memory messageHash = BN254.hashToG1(keccak256(abi.encodePacked( + msg.sender, + block.chainid, + "EigenLayer_BN254_Pubkey_Registration" + ))); - require(shouldBeZero.X == 0 && shouldBeZero.Y == 0, "BLSPublicKeyCompendium.registerBLSPublicKey: incorrect schnorr singature"); - - // verify that the G2 pubkey has the same discrete log as the G1 pubkey - // e(P, [1]_2)e([-1]_1, P') = [1]_T + // gamma = h(sigma, P, P', H(m)) + uint256 gamma = uint256(keccak256(abi.encodePacked( + signedMessageHash.X, + signedMessageHash.Y, + pubkeyG1.X, + pubkeyG1.Y, + pubkeyG2.X, + pubkeyG2.Y, + messageHash.X, + messageHash.Y + ))) % BN254.FR_MODULUS; + + // e(sigma + P * gamma, [-1]_2) = e(H(m) + [1]_1 * gamma, P') require(BN254.pairing( - pubkeyG1, - BN254.generatorG2(), - negGeneratorG1, + signedMessageHash.plus(pubkeyG1.scalar_mul(gamma)), + BN254.negGeneratorG2(), + messageHash.plus(BN254.generatorG1().scalar_mul(gamma)), pubkeyG2 ), "BLSPublicKeyCompendium.registerBLSPublicKey: G1 and G2 private key do not match"); - // getting pubkey hash bytes32 pubkeyHash = BN254.hashG1Point(pubkeyG1); require( @@ -70,7 +66,6 @@ contract BLSPublicKeyCompendium is IBLSPublicKeyCompendium { "BLSPublicKeyCompendium.registerBLSPublicKey: public key already registered" ); - // store updates operatorToPubkeyHash[msg.sender] = pubkeyHash; pubkeyHashToOperator[pubkeyHash] = msg.sender; diff --git a/src/test/DepositWithdraw.t.sol b/src/test/DepositWithdraw.t.sol index 25dfff493..984907608 100644 --- a/src/test/DepositWithdraw.t.sol +++ b/src/test/DepositWithdraw.t.sol @@ -138,7 +138,7 @@ contract DepositWithdrawTests is EigenLayerTestHelper { slasher.recordFirstStakeUpdate(staker, serveUntilBlock); cheats.stopPrank(); //check middlewareTimes entry is correct - require(slasher.getMiddlewareTimesIndexBlock(staker, 0) == 1, "middleware updateBlock update incorrect"); + require(slasher.getMiddlewareTimesIndexStalestUpdateBlock(staker, 0) == 1, "middleware updateBlock update incorrect"); require(slasher.getMiddlewareTimesIndexServeUntilBlock(staker, 0) == 5, "middleware serveUntil update incorrect"); @@ -147,10 +147,10 @@ contract DepositWithdrawTests is EigenLayerTestHelper { slasher.recordFirstStakeUpdate(staker, serveUntilBlock+1); cheats.stopPrank(); //check middlewareTimes entry is correct - require(slasher.getMiddlewareTimesIndexBlock(staker, 1) == 1, "middleware updateBlock update incorrect"); + require(slasher.getMiddlewareTimesIndexStalestUpdateBlock(staker, 1) == 1, "middleware updateBlock update incorrect"); require(slasher.getMiddlewareTimesIndexServeUntilBlock(staker, 1) == 6, "middleware serveUntil update incorrect"); //check old entry has not changed - require(slasher.getMiddlewareTimesIndexBlock(staker, 0) == 1, "middleware updateBlock update incorrect"); + require(slasher.getMiddlewareTimesIndexStalestUpdateBlock(staker, 0) == 1, "middleware updateBlock update incorrect"); require(slasher.getMiddlewareTimesIndexServeUntilBlock(staker, 0) == 5, "middleware serveUntil update incorrect"); //move ahead a block before queuing the withdrawal @@ -180,7 +180,7 @@ contract DepositWithdrawTests is EigenLayerTestHelper { slasher.recordStakeUpdate(staker, updateBlock, serveUntilBlock, insertAfter); cheats.stopPrank(); //check middlewareTimes entry is correct - require(slasher.getMiddlewareTimesIndexBlock(staker, 2) == 1, "middleware updateBlock update incorrect"); + require(slasher.getMiddlewareTimesIndexStalestUpdateBlock(staker, 2) == 1, "middleware updateBlock update incorrect"); require(slasher.getMiddlewareTimesIndexServeUntilBlock(staker, 2) == 7, "middleware serveUntil update incorrect"); cheats.startPrank(middleware_2); @@ -188,7 +188,7 @@ contract DepositWithdrawTests is EigenLayerTestHelper { slasher.recordStakeUpdate(staker, updateBlock, serveUntilBlock+3, insertAfter); cheats.stopPrank(); //check middlewareTimes entry is correct - require(slasher.getMiddlewareTimesIndexBlock(staker, 3) == 3, "middleware updateBlock update incorrect"); + require(slasher.getMiddlewareTimesIndexStalestUpdateBlock(staker, 3) == 3, "middleware updateBlock update incorrect"); require(slasher.getMiddlewareTimesIndexServeUntilBlock(staker, 3) == 10, "middleware serveUntil update incorrect"); cheats.startPrank(middleware); @@ -199,7 +199,7 @@ contract DepositWithdrawTests is EigenLayerTestHelper { slasher.recordStakeUpdate(staker, updateBlock, serveUntilBlock, insertAfter); cheats.stopPrank(); //check middlewareTimes entry is correct - require(slasher.getMiddlewareTimesIndexBlock(staker, 4) == 3, "middleware updateBlock update incorrect"); + require(slasher.getMiddlewareTimesIndexStalestUpdateBlock(staker, 4) == 3, "middleware updateBlock update incorrect"); require(slasher.getMiddlewareTimesIndexServeUntilBlock(staker, 4) == 10, "middleware serveUntil update incorrect"); //move timestamp to 6, one middleware is past serveUntilBlock but the second middleware is still using the restaked funds. @@ -210,7 +210,7 @@ contract DepositWithdrawTests is EigenLayerTestHelper { cheats.startPrank(staker); //when called with the correct middlewareTimesIndex the call reverts - slasher.getMiddlewareTimesIndexBlock(staker, 3); + slasher.getMiddlewareTimesIndexStalestUpdateBlock(staker, 3); { diff --git a/src/test/mocks/BLSPublicKeyCompendiumMock.sol b/src/test/mocks/BLSPublicKeyCompendiumMock.sol index e55689741..f6c9cb2ae 100644 --- a/src/test/mocks/BLSPublicKeyCompendiumMock.sol +++ b/src/test/mocks/BLSPublicKeyCompendiumMock.sol @@ -19,15 +19,13 @@ contract BLSPublicKeyCompendiumMock is IBLSPublicKeyCompendium, DSTest { /** * @notice Called by an operator to register themselves as the owner of a BLS public key and reveal their G1 and G2 public key. - * @param s is the field element of the operator's Schnorr signature - * @param rPoint is the group element of the operator's Schnorr signature - * @param pubkeyG1 is the the G1 pubkey of the operator - * @param pubkeyG2 is the G2 with the same private key as the pubkeyG1 + * @param signedMessageHash is the registration message hash signed by the private key of the operator + * @param pubkeyG1 is the corresponding G1 public key of the operator + * @param pubkeyG2 is the corresponding G2 public key of the operator */ - function registerBLSPublicKey(uint256 s, BN254.G1Point memory rPoint, BN254.G1Point memory pubkeyG1, BN254.G2Point memory pubkeyG2) external { + function registerBLSPublicKey(BN254.G1Point memory signedMessageHash, BN254.G1Point memory pubkeyG1, BN254.G2Point memory pubkeyG2) external { } - function registerPublicKey(BN254.G1Point memory pk) external { bytes32 pubkeyHash = BN254.hashG1Point(pk); diff --git a/src/test/mocks/SlasherMock.sol b/src/test/mocks/SlasherMock.sol index b6e66e801..3a27a3686 100644 --- a/src/test/mocks/SlasherMock.sol +++ b/src/test/mocks/SlasherMock.sol @@ -63,7 +63,7 @@ contract SlasherMock is ISlasher, Test { function middlewareTimesLength(address operator) external view returns (uint256) {} /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator][index].stalestUpdateBlock`. - function getMiddlewareTimesIndexBlock(address operator, uint32 index) external view returns(uint32) {} + function getMiddlewareTimesIndexStalestUpdateBlock(address operator, uint32 index) external view returns(uint32) {} /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator][index].latestServeUntilBlock`. function getMiddlewareTimesIndexServeUntilBlock(address operator, uint32 index) external view returns(uint32) {} diff --git a/src/test/unit/BLSOperatorStateRetrieverUnit.t.sol b/src/test/unit/BLSOperatorStateRetrieverUnit.t.sol index a93ea223a..405efb142 100644 --- a/src/test/unit/BLSOperatorStateRetrieverUnit.t.sol +++ b/src/test/unit/BLSOperatorStateRetrieverUnit.t.sol @@ -104,16 +104,16 @@ contract BLSOperatorStateRetrieverUnitTests is MockAVSDeployer { nonSignerOperatorIds ); - assertEq(checkSignaturesIndices.nonSignerQuorumBitmapIndices.length, 0); - assertEq(checkSignaturesIndices.quorumApkIndices.length, allInclusiveQuorumNumbers.length); - assertEq(checkSignaturesIndices.totalStakeIndices.length, allInclusiveQuorumNumbers.length); - assertEq(checkSignaturesIndices.nonSignerStakeIndices.length, allInclusiveQuorumNumbers.length); + assertEq(checkSignaturesIndices.nonSignerQuorumBitmapIndices.length, 0, "nonSignerQuorumBitmapIndices should be empty if no nonsigners"); + assertEq(checkSignaturesIndices.quorumApkIndices.length, allInclusiveQuorumNumbers.length, "quorumApkIndices should be the number of quorums queried for"); + assertEq(checkSignaturesIndices.totalStakeIndices.length, allInclusiveQuorumNumbers.length, "totalStakeIndices should be the number of quorums queried for"); + assertEq(checkSignaturesIndices.nonSignerStakeIndices.length, allInclusiveQuorumNumbers.length, "nonSignerStakeIndices should be the number of quorums queried for"); // assert the indices are the number of registered operators for the quorum minus 1 for (uint8 i = 0; i < allInclusiveQuorumNumbers.length; i++) { uint8 quorumNumber = uint8(allInclusiveQuorumNumbers[i]); - assertEq(checkSignaturesIndices.quorumApkIndices[i], expectedOperatorOverallIndices[quorumNumber].length - 1); - assertEq(checkSignaturesIndices.totalStakeIndices[i], expectedOperatorOverallIndices[quorumNumber].length - 1); + assertEq(checkSignaturesIndices.quorumApkIndices[i], expectedOperatorOverallIndices[quorumNumber].length - 1, "quorumApkIndex should be the number of registered operators for the quorum minus 1"); + assertEq(checkSignaturesIndices.totalStakeIndices[i], expectedOperatorOverallIndices[quorumNumber].length - 1, "totalStakeIndex should be the number of registered operators for the quorum minus 1"); } } @@ -147,25 +147,25 @@ contract BLSOperatorStateRetrieverUnitTests is MockAVSDeployer { nonSignerOperatorIds ); - assertEq(checkSignaturesIndices.nonSignerQuorumBitmapIndices.length, nonSignerOperatorIds.length); - assertEq(checkSignaturesIndices.quorumApkIndices.length, allInclusiveQuorumNumbers.length); - assertEq(checkSignaturesIndices.totalStakeIndices.length, allInclusiveQuorumNumbers.length); - assertEq(checkSignaturesIndices.nonSignerStakeIndices.length, allInclusiveQuorumNumbers.length); + assertEq(checkSignaturesIndices.nonSignerQuorumBitmapIndices.length, nonSignerOperatorIds.length, "nonSignerQuorumBitmapIndices should be the number of nonsigners"); + assertEq(checkSignaturesIndices.quorumApkIndices.length, allInclusiveQuorumNumbers.length, "quorumApkIndices should be the number of quorums queried for"); + assertEq(checkSignaturesIndices.totalStakeIndices.length, allInclusiveQuorumNumbers.length, "totalStakeIndices should be the number of quorums queried for"); + assertEq(checkSignaturesIndices.nonSignerStakeIndices.length, allInclusiveQuorumNumbers.length, "nonSignerStakeIndices should be the number of quorums queried for"); // assert the indices are the number of registered operators for the quorum minus 1 for (uint8 i = 0; i < allInclusiveQuorumNumbers.length; i++) { uint8 quorumNumber = uint8(allInclusiveQuorumNumbers[i]); - assertEq(checkSignaturesIndices.quorumApkIndices[i], expectedOperatorOverallIndices[quorumNumber].length - 1); - assertEq(checkSignaturesIndices.totalStakeIndices[i], expectedOperatorOverallIndices[quorumNumber].length - 1); + assertEq(checkSignaturesIndices.quorumApkIndices[i], expectedOperatorOverallIndices[quorumNumber].length - 1, "quorumApkIndex should be the number of registered operators for the quorum minus 1"); + assertEq(checkSignaturesIndices.totalStakeIndices[i], expectedOperatorOverallIndices[quorumNumber].length - 1, "totalStakeIndex should be the number of registered operators for the quorum minus 1"); } // assert the quorum bitmap and stake indices are zero because there have been no kicks or stake updates for (uint i = 0; i < nonSignerOperatorIds.length; i++) { - assertEq(checkSignaturesIndices.nonSignerQuorumBitmapIndices[i], 0); + assertEq(checkSignaturesIndices.nonSignerQuorumBitmapIndices[i], 0, "nonSignerQuorumBitmapIndices should be zero because there have been no kicks"); } for (uint i = 0; i < checkSignaturesIndices.nonSignerStakeIndices.length; i++) { for (uint j = 0; j < checkSignaturesIndices.nonSignerStakeIndices[i].length; j++) { - assertEq(checkSignaturesIndices.nonSignerStakeIndices[i][j], 0); + assertEq(checkSignaturesIndices.nonSignerStakeIndices[i][j], 0, "nonSignerStakeIndices should be zero because there have been no stake updates past the first one"); } } } diff --git a/src/test/unit/BLSPublicKeyCompendiumUnit.t.sol b/src/test/unit/BLSPublicKeyCompendiumUnit.t.sol new file mode 100644 index 000000000..a6d4513a1 --- /dev/null +++ b/src/test/unit/BLSPublicKeyCompendiumUnit.t.sol @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: BUSL-1.1 +pragma solidity =0.8.12; + +import "forge-std/Test.sol"; +import "../../contracts/middleware/BLSPublicKeyCompendium.sol"; +import "../../contracts/middleware/BLSPublicKeyCompendium.sol"; + +contract BLSPublicKeyCompendiumUnitTests is Test { + using BN254 for BN254.G1Point; + + BLSPublicKeyCompendium compendium; + + uint256 privKey = 69; + + BN254.G1Point pubKeyG1; + BN254.G2Point pubKeyG2; + BN254.G1Point signedMessageHash; + + address alice = address(1); + address bob = address(2); + + function setUp() public { + compendium = new BLSPublicKeyCompendium(); + + pubKeyG1 = BN254.generatorG1().scalar_mul(privKey); + + //privKey*G2 + pubKeyG2.X[1] = 19101821850089705274637533855249918363070101489527618151493230256975900223847; + pubKeyG2.X[0] = 5334410886741819556325359147377682006012228123419628681352847439302316235957; + pubKeyG2.Y[1] = 354176189041917478648604979334478067325821134838555150300539079146482658331; + pubKeyG2.Y[0] = 4185483097059047421902184823581361466320657066600218863748375739772335928910; + } + + function testRegisterBLSPublicKey() public { + signedMessageHash = _signMessage(alice); + vm.prank(alice); + compendium.registerBLSPublicKey(signedMessageHash, pubKeyG1, pubKeyG2); + + assertEq(compendium.operatorToPubkeyHash(alice), BN254.hashG1Point(pubKeyG1), "pubkey hash not stored correctly"); + assertEq(compendium.pubkeyHashToOperator(BN254.hashG1Point(pubKeyG1)), alice, "operator address not stored correctly"); + } + + function testRegisterBLSPublicKey_NoMatch_Reverts() public { + signedMessageHash = _signMessage(alice); + BN254.G1Point memory badPubKeyG1 = BN254.generatorG1().scalar_mul(420); // mismatch public keys + + vm.prank(alice); + vm.expectRevert(bytes("BLSPublicKeyCompendium.registerBLSPublicKey: G1 and G2 private key do not match")); + compendium.registerBLSPublicKey(signedMessageHash, badPubKeyG1, pubKeyG2); + } + + function testRegisterBLSPublicKey_BadSig_Reverts() public { + signedMessageHash = _signMessage(bob); // sign with wrong private key + + vm.prank(alice); + vm.expectRevert(bytes("BLSPublicKeyCompendium.registerBLSPublicKey: G1 and G2 private key do not match")); + compendium.registerBLSPublicKey(signedMessageHash, pubKeyG1, pubKeyG2); + } + + function testRegisterBLSPublicKey_OpRegistered_Reverts() public { + testRegisterBLSPublicKey(); // register alice + + vm.prank(alice); + vm.expectRevert(bytes("BLSPublicKeyCompendium.registerBLSPublicKey: operator already registered pubkey")); + compendium.registerBLSPublicKey(signedMessageHash, pubKeyG1, pubKeyG2); + } + + function testRegisterBLSPublicKey_PkRegistered_Reverts() public { + testRegisterBLSPublicKey(); + signedMessageHash = _signMessage(bob); // same private key different operator + + vm.prank(bob); + vm.expectRevert(bytes("BLSPublicKeyCompendium.registerBLSPublicKey: public key already registered")); + compendium.registerBLSPublicKey(signedMessageHash, pubKeyG1, pubKeyG2); + } + + function _signMessage(address signer) internal view returns(BN254.G1Point memory) { + BN254.G1Point memory messageHash = BN254.hashToG1(keccak256(abi.encodePacked(signer, block.chainid, "EigenLayer_BN254_Pubkey_Registration"))); + return BN254.scalar_mul(messageHash, privKey); + } + +} \ No newline at end of file diff --git a/src/test/unit/BLSSignatureCheckerUnit.t.sol b/src/test/unit/BLSSignatureCheckerUnit.t.sol index 386156e4c..8585d6ab7 100644 --- a/src/test/unit/BLSSignatureCheckerUnit.t.sol +++ b/src/test/unit/BLSSignatureCheckerUnit.t.sol @@ -15,6 +15,9 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { blsSignatureChecker = new BLSSignatureChecker(registryCoordinator); } + // this test checks that a valid signature from maxOperatorsToRegister with a random number of nonsigners is checked + // correctly on the BLSSignatureChecker contract when all operators are only regsitered for a single quorum and + // the signature is only checked for stakes on that quorum function testBLSSignatureChecker_SingleQuorum_Valid(uint256 pseudoRandomNumber) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 1); @@ -25,7 +28,10 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); uint256 gasBefore = gasleft(); - blsSignatureChecker.checkSignatures( + ( + BLSSignatureChecker.QuorumStakeTotals memory quorumStakeTotals, + bytes32 signatoryRecordHash + ) = blsSignatureChecker.checkSignatures( msgHash, quorumNumbers, referenceBlockNumber, @@ -33,12 +39,16 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { ); uint256 gasAfter = gasleft(); emit log_named_uint("gasUsed", gasBefore - gasAfter); + assertTrue(quorumStakeTotals.signedStakeForQuorum[0] > 0); // 0 nonSigners: 159908 // 1 nonSigner: 178683 // 2 nonSigners: 197410 } + // this test checks that a valid signature from maxOperatorsToRegister with a random number of nonsigners is checked + // correctly on the BLSSignatureChecker contract when all operators are registered for the first 100 quorums + // and the signature is only checked for stakes on those quorums function testBLSSignatureChecker_100Quorums_Valid(uint256 pseudoRandomNumber) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 1); @@ -218,6 +228,7 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { // set the sigma to a different value nonSignerStakesAndSignature.sigma.X++; + // expect a non-specific low-level revert, since this call will ultimately fail as part of the precompile call cheats.expectRevert(); blsSignatureChecker.checkSignatures( msgHash,