Verified contractExactGPL-3.0
SocialRecoveryModule
Address0x088f6cfd8bb1ddb1bb069ccb3fc1a98927d233f2
- Balance
0 ETH
- Transactions
30
- Compiler
solc 0.8.20
- Same code
5 more contracts
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- paris
- Via IR
- yes
- License
- GPL-3.0
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 20,619,229
- Creation transaction
- 0x2037a5d354…653d9c70f4
15 files
- candide-contracts/contracts/modules/social_recovery/SocialRecoveryModule.solmain16.04 KB
- @openzeppelin/contracts/interfaces/IERC1271.sol666 B
- @openzeppelin/contracts/utils/Strings.sol2.78 KB
- @openzeppelin/contracts/utils/cryptography/ECDSA.sol9.13 KB
- @openzeppelin/contracts/utils/cryptography/SignatureChecker.sol2.26 KB
- @openzeppelin/contracts/utils/math/Math.sol12.79 KB
- @openzeppelin/contracts/utils/math/SignedMath.sol1.26 KB
- @safe-global/safe-contracts/contracts/common/Enum.sol274 B
- candide-contracts/contracts/interfaces/IFallbackManager.sol686 B
- candide-contracts/contracts/interfaces/IGuardManager.sol1 KB
- candide-contracts/contracts/interfaces/IModuleManager.sol3.7 KB
- candide-contracts/contracts/interfaces/IOwnerManager.sol2.41 KB
- candide-contracts/contracts/interfaces/ISafe.sol8.12 KB
- candide-contracts/contracts/modules/social_recovery/storage/GuardianStorage.sol6.17 KB
- candide-contracts/contracts/modules/social_recovery/storage/IGuardianStorage.sol1.9 KB
candide-contracts/contracts/modules/social_recovery/SocialRecoveryModule.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.12 <0.9.0;
import {GuardianStorage} from "./storage/GuardianStorage.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {ISafe, IOwnerManager, Enum} from "./../../interfaces/ISafe.sol";
/// @title Social Recovery Module
/// @author CANDIDE Labs
contract SocialRecoveryModule is GuardianStorage {
string public constant NAME = "Social Recovery Module";
string public constant VERSION = "0.0.1";
// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
// keccak256("ExecuteRecovery(address wallet,address[] newOwners,uint256 newThreshold,uint256 nonce)");
bytes32 private constant EXECUTE_RECOVERY_TYPEHASH = 0x124b64921a7c7e677c6cc3b132eaaa57130bc6fc05ab157f35fe5264a7c198d5;
address internal constant SENTINEL_OWNERS = address(0x1);
struct SignatureData {
address signer;
bytes signature;
}
struct RecoveryRequest {
uint256 guardiansApprovalCount;
uint256 newThreshold;
uint64 executeAfter;
address[] newOwners;
}
mapping(address => RecoveryRequest) internal recoveryRequests;
mapping(bytes32 => mapping(address => bool)) internal confirmedHashes;
mapping(address => uint256) internal walletsNonces;
// Recovery period
uint256 internal immutable recoveryPeriod;
event RecoveryExecuted(
address indexed wallet,
address[] indexed newOwners,
uint256 newThreshold,
uint256 nonce,
uint64 executeAfter,
uint256 guardiansApprovalCount
);
event RecoveryFinalized(address indexed wallet, address[] indexed newOwners, uint256 newThreshold, uint256 nonce);
event RecoveryCanceled(address indexed wallet, uint256 nonce);
event NonceInvalidated(address indexed wallet, uint256 nonce);
/**
* @notice Throws if there is no ongoing recovery request.
*/
modifier whenRecovery(address _wallet) {
require(recoveryRequests[_wallet].executeAfter > 0, "SM: no ongoing recovery");
_;
}
constructor(uint256 _recoveryPeriod) {
recoveryPeriod = _recoveryPeriod;
}
////////////////
/// @dev Returns the chain id used by this contract.
function getChainId() public view returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
function domainSeparator() public view returns (bytes32) {
return
keccak256(
abi.encode(
DOMAIN_SEPARATOR_TYPEHASH,
keccak256(abi.encodePacked(NAME)),
keccak256(abi.encodePacked(VERSION)),
getChainId(),
this
)
);
}
/// @dev Returns the bytes that are hashed to be signed by guardians.
function encodeRecoveryData(
address _wallet,
address[] calldata _newOwners,
uint256 _newThreshold,
uint256 _nonce
) public view returns (bytes memory) {
bytes32 recoveryHash = keccak256(
abi.encode(EXECUTE_RECOVERY_TYPEHASH, _wallet, keccak256(abi.encodePacked(_newOwners)), _newThreshold, _nonce)
);
return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), recoveryHash);
}
/// @dev Generates the recovery hash that should be signed by the guardian to authorize a recovery
function getRecoveryHash(
address _wallet,
address[] calldata _newOwners,
uint256 _newThreshold,
uint256 _nonce
) public view returns (bytes32) {
return keccak256(encodeRecoveryData(_wallet, _newOwners, _newThreshold, _nonce));
}
/// @dev checks if valid signature to the provided signer, and if this signer is indeed a guardian, revert otherwise
function validateGuardianSignature(address _wallet, bytes32 _signHash, address _signer, bytes memory _signature) public view {
require(isGuardian(_wallet, _signer), "SM: Signer not a guardian");
require(SignatureChecker.isValidSignatureNow(_signer, _signHash, _signature), "SM: Invalid guardian signature");
}
/**
* @notice Lets single guardian confirm the execution of the recovery request.
* Can also trigger the start of the execution by passing true to '_execute' parameter.
* Once triggered the recovery is pending for the recovery period before it can be finalised.
* @param _wallet The target wallet.
* @param _newOwners The new owners' addressess.
* @param _newThreshold The new threshold for the safe.
* @param _execute Whether to auto-start execution of recovery.
*/
function confirmRecovery(address _wallet, address[] calldata _newOwners, uint256 _newThreshold, bool _execute) external {
require(isGuardian(_wallet, msg.sender), "SM: sender not a guardian");
require(_newOwners.length > 0, "SM: owners cannot be empty");
require(_newThreshold > 0 && _newOwners.length >= _newThreshold, "SM: invalid new threshold");
//
uint256 _nonce = nonce(_wallet);
bytes32 recoveryHash = getRecoveryHash(_wallet, _newOwners, _newThreshold, _nonce);
confirmedHashes[recoveryHash][msg.sender] = true;
//
if (!_execute) return;
uint256 guardiansThreshold = threshold(_wallet);
uint256 _approvalCount = getRecoveryApprovals(_wallet, _newOwners, _newThreshold);
require(_approvalCount >= guardiansThreshold, "SM: confirmed signatures less than threshold");
_executeRecovery(_wallet, _newOwners, _newThreshold, _approvalCount);
}
/**
* @notice Lets multiple guardians confirm the execution of the recovery request.
* Can also trigger the start of the execution by passing true to '_execute' parameter.
* Once triggered the recovery is pending for the recovery period before it can be finalised.
* @param _wallet The target wallet.
* @param _newOwners The new owners' addressess.
* @param _newThreshold The new threshold for the safe.
* @param _signatures The guardians signatures.
* @param _execute Whether to auto-start execution of recovery.
*/
function multiConfirmRecovery(
address _wallet,
address[] calldata _newOwners,
uint256 _newThreshold,
SignatureData[] memory _signatures,
bool _execute
) external {
require(_newOwners.length > 0, "SM: owners cannot be empty");
require(_newThreshold > 0 && _newOwners.length >= _newThreshold, "SM: invalid new threshold");
require(_signatures.length > 0, "SM: empty signatures");
uint256 guardiansThreshold = threshold(_wallet);
require(guardiansThreshold > 0, "SM: empty guardians");
//
uint256 _nonce = nonce(_wallet);
bytes32 recoveryHash = getRecoveryHash(_wallet, _newOwners, _newThreshold, _nonce);
address lastSigner = address(0);
for (uint256 i = 0; i < _signatures.length; i++) {
SignatureData memory value = _signatures[i];
if (value.signature.length == 0) {
require(isGuardian(_wallet, msg.sender), "SM: sender not a guardian");
require(msg.sender == value.signer, "SM: null signature should have the signer as the sender");
} else {
validateGuardianSignature(_wallet, recoveryHash, value.signer, value.signature);
}
require(value.signer > lastSigner, "SM: duplicate signers/invalid ordering");
confirmedHashes[recoveryHash][value.signer] = true;
lastSigner = value.signer;
}
//
if (!_execute) return;
uint256 _approvalCount = getRecoveryApprovals(_wallet, _newOwners, _newThreshold);
require(_approvalCount >= guardiansThreshold, "SM: confirmed signatures less than threshold");
_executeRecovery(_wallet, _newOwners, _newThreshold, _approvalCount);
}
/**
* @notice Lets the guardians start the execution of the recovery request.
* Once triggered the recovery is pending for the recovery period before it can be finalised.
* @param _wallet The target wallet.
* @param _newOwners The new owners' addressess.
* @param _newThreshold The new threshold for the safe.
*/
function executeRecovery(address _wallet, address[] calldata _newOwners, uint256 _newThreshold) external {
uint256 guardiansThreshold = threshold(_wallet);
require(guardiansThreshold > 0, "SM: empty guardians");
//
uint256 _approvalCount = getRecoveryApprovals(_wallet, _newOwners, _newThreshold);
require(_approvalCount >= guardiansThreshold, "SM: confirmed signatures less than threshold");
_executeRecovery(_wallet, _newOwners, _newThreshold, _approvalCount);
}
function _executeRecovery(address _wallet, address[] calldata _newOwners, uint256 _newThreshold, uint256 _approvalCount) internal {
uint256 _nonce = nonce(_wallet);
// If an ongoing recovery exists, replace only if more guardians than the previous guardians have approved this replacement
RecoveryRequest storage request = recoveryRequests[_wallet];
if (request.executeAfter > 0) {
require(_approvalCount > request.guardiansApprovalCount, "SM: not enough approvals for replacement");
delete recoveryRequests[_wallet];
emit RecoveryCanceled(_wallet, _nonce - 1);
}
// Start recovery execution
uint64 executeAfter = uint64(block.timestamp + recoveryPeriod);
recoveryRequests[_wallet] = RecoveryRequest(_approvalCount, _newThreshold, executeAfter, _newOwners);
walletsNonces[_wallet]++;
emit RecoveryExecuted(_wallet, _newOwners, _newThreshold, _nonce, executeAfter, _approvalCount);
}
/**
* @notice Finalizes an ongoing recovery request if the recovery period is over.
* The method is public and callable by anyone to enable orchestration.
* @param _wallet The target wallet.
*/
function finalizeRecovery(address _wallet) external whenRecovery(_wallet) {
RecoveryRequest storage request = recoveryRequests[_wallet];
require(uint64(block.timestamp) >= request.executeAfter, "SM: recovery period still pending");
address[] memory newOwners = request.newOwners;
uint256 newThreshold = request.newThreshold;
delete recoveryRequests[_wallet];
ISafe safe = ISafe(payable(_wallet));
address[] memory owners = safe.getOwners();
for (uint256 i = (owners.length - 1); i > 0; --i) {
bool success = safe.execTransactionFromModule({
to: _wallet,
value: 0,
data: abi.encodeCall(IOwnerManager.removeOwner, (owners[i - 1], owners[i], 1)),
operation: Enum.Operation.Call
});
if (!success) {
revert("SM: owner removal failed");
}
}
for (uint256 i = 0; i < newOwners.length; i++) {
require(!isGuardian(_wallet, newOwners[i]), "SM: new owner cannot be guardian");
bool success;
if (i == 0) {
if (newOwners[i] == owners[i]) continue;
success = safe.execTransactionFromModule({
to: _wallet,
value: 0,
data: abi.encodeCall(IOwnerManager.swapOwner, (SENTINEL_OWNERS, owners[i], newOwners[i])),
operation: Enum.Operation.Call
});
if (!success) {
revert("SM: owner replacement failed");
}
continue;
}
success = safe.execTransactionFromModule({
to: _wallet,
value: 0,
data: abi.encodeCall(IOwnerManager.addOwnerWithThreshold, (newOwners[i], 1)),
operation: Enum.Operation.Call
});
if (!success) {
revert("SM: owner addition failed");
}
}
if (newThreshold > 1) {
bool success = safe.execTransactionFromModule({
to: _wallet,
value: 0,
data: abi.encodeCall(IOwnerManager.changeThreshold, (newThreshold)),
operation: Enum.Operation.Call
});
if (!success) {
revert("SM: change threshold failed");
}
}
emit RecoveryFinalized(_wallet, newOwners, newThreshold, walletsNonces[_wallet] - 1);
}
/**
* @notice Lets the owner cancel an ongoing recovery request.
*/
function cancelRecovery() external whenRecovery(msg.sender) {
delete recoveryRequests[msg.sender];
emit RecoveryCanceled(msg.sender, walletsNonces[msg.sender] - 1);
}
/**
* @notice Invalidates the wallet's nonce. This will invalidate existing
* recovery confirmations from guardians and can be used either to cancel
* the process of collecting confirmations from guardians or when rotating
* the guardian configuration to prevent "shadow" confirmations.
* @dev This function should only be used between initiation and execution of a recovery.
*/
function invalidateNonce() external {
walletsNonces[msg.sender]++;
emit NonceInvalidated(msg.sender, walletsNonces[msg.sender] - 1);
}
/**
* @notice Retrieves the wallet's current ongoing recovery request.
* @param _wallet The target wallet.
* @return request The wallet's current recovery request
*/
function getRecoveryRequest(address _wallet) public view returns (RecoveryRequest memory request) {
return recoveryRequests[_wallet];
}
/**
* @notice Retrieves the guardian approval count for this particular recovery request at current nonce.
* @param _wallet The target wallet.
* @param _newOwners The new owners' addressess.
* @param _newThreshold The new threshold for the safe.
* @return approvalCount The wallet's current recovery request
*/
function getRecoveryApprovals(
address _wallet,
address[] calldata _newOwners,
uint256 _newThreshold
) public view returns (uint256 approvalCount) {
uint256 _nonce = nonce(_wallet);
bytes32 recoveryHash = getRecoveryHash(_wallet, _newOwners, _newThreshold, _nonce);
address[] memory guardians = getGuardians(_wallet);
approvalCount = 0;
for (uint256 i = 0; i < guardians.length; i++) {
if (confirmedHashes[recoveryHash][guardians[i]]) {
approvalCount++;
}
}
}
/**
* @notice Retrieves specific guardian approval status a particular recovery request at current nonce.
* @param _wallet The target wallet.
* @param _guardian The guardian.
* @param _newOwners The new owners' addressess.
* @param _newThreshold The new threshold for the safe.
* @return approvalCount The wallet's current recovery request
*/
function hasGuardianApproved(
address _wallet,
address _guardian,
address[] calldata _newOwners,
uint256 _newThreshold
) public view returns (bool) {
uint256 _nonce = nonce(_wallet);
bytes32 recoveryHash = getRecoveryHash(_wallet, _newOwners, _newThreshold, _nonce);
return confirmedHashes[recoveryHash][_guardian];
}
/**
* @notice Get the module nonce for a wallet.
* @param _wallet The target wallet.
* @return _nonce the nonce for this wallet.
*/
function nonce(address _wallet) public view returns (uint256 _nonce) {
return walletsNonces[_wallet];
}
}
@openzeppelin/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
* Argent and Gnosis Safe.
*
* _Available since v4.1._
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
return
(error == ECDSA.RecoverError.NoError && recovered == signer) ||
isValidERC1271SignatureNow(signer, hash, signature);
}
/**
* @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
* against the signer smart contract using ERC1271.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidERC1271SignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success &&
result.length >= 32 &&
abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
}
}
@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
@openzeppelin/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
@safe-global/safe-contracts/contracts/common/Enum.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/**
* @title Enum - Collection of enums used in Safe contracts.
* @author Richard Meissner - @rmeissner
*/
abstract contract Enum {
enum Operation {
Call,
DelegateCall
}
}
candide-contracts/contracts/interfaces/IFallbackManager.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/**
* @title IFallbackManager - A contract interface managing fallback calls made to this contract.
* @author @safe-global/safe-protocol
*/
interface IFallbackManager {
event ChangedFallbackHandler(address indexed handler);
/**
* @notice Set Fallback Handler to `handler` for the Safe.
* @dev Only fallback calls without value and with data will be forwarded.
* This can only be done via a Safe transaction.
* Cannot be set to the Safe itself.
* @param handler contract to handle fallback calls.
*/
function setFallbackHandler(address handler) external;
}candide-contracts/contracts/interfaces/IGuardManager.sol
// SPDX-License-Identifier: LGPL-3.0-only
/* solhint-disable one-contract-per-file */
pragma solidity >=0.7.0 <0.9.0;
/**
* @title IGuardManager - A contract interface managing transaction guards which perform pre and post-checks on Safe transactions.
* @author @safe-global/safe-protocol
*/
interface IGuardManager {
event ChangedGuard(address indexed guard);
/**
* @dev Set a guard that checks transactions before execution
* This can only be done via a Safe transaction.
* ⚠️ IMPORTANT: Since a guard has full power to block Safe transaction execution,
* a broken guard can cause a denial of service for the Safe. Make sure to carefully
* audit the guard code and design recovery mechanisms.
* @notice Set Transaction Guard `guard` for the Safe. Make sure you trust the guard.
* @param guard The address of the guard to be used or the 0 address to disable the guard
*/
function setGuard(address guard) external;
}candide-contracts/contracts/interfaces/IModuleManager.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import {Enum} from "@safe-global/safe-contracts/contracts/common/Enum.sol";
import {IGuardManager} from "./IGuardManager.sol";
/**
* @title IModuleManager - An interface of contract managing Safe modules
* @notice Modules are extensions with unlimited access to a Safe that can be added to a Safe by its owners.
⚠️ WARNING: Modules are a security risk since they can execute arbitrary transactions,
so only trusted and audited modules should be added to a Safe. A malicious module can
completely takeover a Safe.
* @author @safe-global/safe-protocol
*/
interface IModuleManager is IGuardManager {
event EnabledModule(address indexed module);
event DisabledModule(address indexed module);
event ExecutionFromModuleSuccess(address indexed module);
event ExecutionFromModuleFailure(address indexed module);
/**
* @notice Enables the module `module` for the Safe.
* @dev This can only be done via a Safe transaction.
* @param module Module to be whitelisted.
*/
function enableModule(address module) external;
/**
* @notice Disables the module `module` for the Safe.
* @dev This can only be done via a Safe transaction.
* @param prevModule Previous module in the modules linked list.
* @param module Module to be removed.
*/
function disableModule(address prevModule, address module) external;
/**
* @notice Execute `operation` (0: Call, 1: DelegateCall) to `to` with `value` (Native Token)
* @dev Function is virtual to allow overriding for L2 singleton to emit an event for indexing.
* @param to Destination address of module transaction.
* @param value Ether value of module transaction.
* @param data Data payload of module transaction.
* @param operation Operation type of module transaction.
* @return success Boolean flag indicating if the call succeeded.
*/
function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) external returns (bool success);
/**
* @notice Execute `operation` (0: Call, 1: DelegateCall) to `to` with `value` (Native Token) and return data
* @param to Destination address of module transaction.
* @param value Ether value of module transaction.
* @param data Data payload of module transaction.
* @param operation Operation type of module transaction.
* @return success Boolean flag indicating if the call succeeded.
* @return returnData Data returned by the call.
*/
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) external returns (bool success, bytes memory returnData);
/**
* @notice Returns if an module is enabled
* @return True if the module is enabled
*/
function isModuleEnabled(address module) external view returns (bool);
/**
* @notice Returns an array of modules.
* If all entries fit into a single page, the next pointer will be 0x1.
* If another page is present, next will be the last element of the returned array.
* @param start Start of the page. Has to be a module or start pointer (0x1 address)
* @param pageSize Maximum number of modules that should be returned. Has to be > 0
* @return array Array of modules.
* @return next Start of the next page.
*/
function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next);
}candide-contracts/contracts/interfaces/IOwnerManager.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/**
* @title IOwnerManager - Interface for contract which manages Safe owners and a threshold to authorize transactions.
* @author @safe-global/safe-protocol
*/
interface IOwnerManager {
event AddedOwner(address indexed owner);
event RemovedOwner(address indexed owner);
event ChangedThreshold(uint256 threshold);
/**
* @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
* @dev This can only be done via a Safe transaction.
* @param owner New owner address.
* @param _threshold New threshold.
*/
function addOwnerWithThreshold(address owner, uint256 _threshold) external;
/**
* @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
* @dev This can only be done via a Safe transaction.
* @param prevOwner Owner that pointed to the owner to be removed in the linked list
* @param owner Owner address to be removed.
* @param _threshold New threshold.
*/
function removeOwner(address prevOwner, address owner, uint256 _threshold) external;
/**
* @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
* @dev This can only be done via a Safe transaction.
* @param prevOwner Owner that pointed to the owner to be replaced in the linked list
* @param oldOwner Owner address to be replaced.
* @param newOwner New owner address.
*/
function swapOwner(address prevOwner, address oldOwner, address newOwner) external;
/**
* @notice Changes the threshold of the Safe to `_threshold`.
* @dev This can only be done via a Safe transaction.
* @param _threshold New threshold.
*/
function changeThreshold(uint256 _threshold) external;
/**
* @notice Returns the number of required confirmations for a Safe transaction aka the threshold.
* @return Threshold number.
*/
function getThreshold() external view returns (uint256);
/**
* @notice Returns if `owner` is an owner of the Safe.
* @return Boolean if owner is an owner of the Safe.
*/
function isOwner(address owner) external view returns (bool);
/**
* @notice Returns a list of Safe owners.
* @return Array of Safe owners.
*/
function getOwners() external view returns (address[] memory);
}candide-contracts/contracts/interfaces/ISafe.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import {Enum} from "@safe-global/safe-contracts/contracts/common/Enum.sol";
import "./IModuleManager.sol";
import "./IOwnerManager.sol";
import "./IFallbackManager.sol";
/**
* @title ISafe - A multisignature wallet interface with support for confirmations using signed messages based on EIP-712.
* @author @safe-global/safe-protocol
*/
interface ISafe is IModuleManager, IOwnerManager, IFallbackManager {
event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
event SignMsg(bytes32 indexed msgHash);
event ExecutionFailure(bytes32 indexed txHash, uint256 payment);
event ExecutionSuccess(bytes32 indexed txHash, uint256 payment);
/**
* @notice Sets an initial storage of the Safe contract.
* @dev This method can only be called once.
* If a proxy was created without setting up, anyone can call setup and claim the proxy.
* @param _owners List of Safe owners.
* @param _threshold Number of required confirmations for a Safe transaction.
* @param to Contract address for optional delegate call.
* @param data Data payload for optional delegate call.
* @param fallbackHandler Handler for fallback calls to this contract
* @param paymentToken Token that should be used for the payment (0 is ETH)
* @param payment Value that should be paid
* @param paymentReceiver Address that should receive the payment (or 0 if tx.origin)
*/
function setup(
address[] calldata _owners,
uint256 _threshold,
address to,
bytes calldata data,
address fallbackHandler,
address paymentToken,
uint256 payment,
address payable paymentReceiver
) external;
/** @notice Executes a `operation` {0: Call, 1: DelegateCall}} transaction to `to` with `value` (Native Currency)
* and pays `gasPrice` * `gasLimit` in `gasToken` token to `refundReceiver`.
* @dev The fees are always transferred, even if the user transaction fails.
* This method doesn't perform any sanity check of the transaction, such as:
* - if the contract at `to` address has code or not
* - if the `gasToken` is a contract or not
* It is the responsibility of the caller to perform such checks.
* @param to Destination address of Safe transaction.
* @param value Ether value of Safe transaction.
* @param data Data payload of Safe transaction.
* @param operation Operation type of Safe transaction.
* @param safeTxGas Gas that should be used for the Safe transaction.
* @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
* @param gasPrice Gas price that should be used for the payment calculation.
* @param gasToken Token address (or 0 if ETH) that is used for the payment.
* @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
* @param signatures Signature data that should be verified.
* Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.
* @return success Boolean indicating transaction's success.
*/
function execTransaction(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures
) external payable returns (bool success);
/**
* @notice Checks whether the signature provided is valid for the provided data and hash. Reverts otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param signatures Signature data that should be verified.
* Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.
*/
function checkSignatures(bytes32 dataHash, bytes memory signatures) external view;
/**
* @notice Checks whether the signature provided is valid for the provided data and hash. Reverts otherwise.
* @dev Since the EIP-1271 does an external call, be mindful of reentrancy attacks.
* @param executor Address that executing the transaction.
* ⚠️⚠️⚠️ Make sure that the executor address is a legitmate executor.
* Incorrectly passed the executor might reduce the threshold by 1 signature. ⚠️⚠️⚠️
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param signatures Signature data that should be verified.
* Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.
* @param requiredSignatures Amount of required valid signatures.
*/
function checkNSignatures(address executor, bytes32 dataHash, bytes memory signatures, uint256 requiredSignatures) external view;
/**
* @notice Marks hash `hashToApprove` as approved.
* @dev This can be used with a pre-approved hash transaction signature.
* IMPORTANT: The approved hash stays approved forever. There's no revocation mechanism, so it behaves similarly to ECDSA signatures
* @param hashToApprove The hash to mark as approved for signatures that are verified by this contract.
*/
function approveHash(bytes32 hashToApprove) external;
/**
* @dev Returns the domain separator for this contract, as defined in the EIP-712 standard.
* @return bytes32 The domain separator hash.
*/
function domainSeparator() external view returns (bytes32);
/**
* @notice Returns transaction hash to be signed by owners.
* @param to Destination address.
* @param value Ether value.
* @param data Data payload.
* @param operation Operation type.
* @param safeTxGas Gas that should be used for the safe transaction.
* @param baseGas Gas costs for data used to trigger the safe transaction.
* @param gasPrice Maximum gas price that should be used for this transaction.
* @param gasToken Token address (or 0 if ETH) that is used for the payment.
* @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
* @param _nonce Transaction nonce.
* @return Transaction hash.
*/
function getTransactionHash(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) external view returns (bytes32);
/**
* External getter function for state variables.
*/
/**
* @notice Returns the version of the Safe contract.
* @return Version string.
*/
// solhint-disable-next-line
function VERSION() external view returns (string memory);
/**
* @notice Returns the nonce of the Safe contract.
* @return Nonce.
*/
function nonce() external view returns (uint256);
/**
* @notice Returns a uint if the messageHash is signed by the owner.
* @param messageHash Hash of message that should be checked.
* @return Number denoting if an owner signed the hash.
*/
function signedMessages(bytes32 messageHash) external view returns (uint256);
/**
* @notice Returns a uint if the messageHash is approved by the owner.
* @param owner Owner address that should be checked.
* @param messageHash Hash of message that should be checked.
* @return Number denoting if an owner approved the hash.
*/
function approvedHashes(address owner, bytes32 messageHash) external view returns (uint256);
}candide-contracts/contracts/modules/social_recovery/storage/GuardianStorage.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.12 <0.9.0;
import {IGuardianStorage} from "./IGuardianStorage.sol";
import {ISafe} from "./../../../interfaces/ISafe.sol";
/**
* @title GuardianStorage
* @notice Contract storing the state of wallets related to guardians.
* This contract contains all guardian management rules, only enabled modules for a wallet can modify its state.
* @author CANDIDE Labs team
*/
contract GuardianStorage is IGuardianStorage {
address internal constant SENTINEL_GUARDIANS = address(0x1);
struct GuardianStorageEntry {
// the list of guardians
mapping(address => address) guardians;
// guardians count
uint256 count;
// recovery threshold
uint256 threshold;
}
mapping (address => GuardianStorageEntry) internal entries;
event GuardianAdded(address indexed wallet, address indexed guardian);
event GuardianRevoked(address indexed wallet, address indexed guardian);
event ChangedThreshold(address indexed wallet, uint256 threshold);
/**
* @dev Throws if the caller is not an enabled module.
*/
modifier onlyWhenModuleIsEnabled() {
// solhint-disable-next-line reason-string
require(ISafe(payable(msg.sender)).isModuleEnabled(address(this)), "GS: method only callable when module is enabled");
_;
}
/**
* @dev Lets an authorised module add a guardian to a wallet and change the threshold.
* @param _guardian The guardian to add.
*/
function addGuardianWithThreshold(address _guardian, uint256 _threshold) external onlyWhenModuleIsEnabled() {
require(_threshold > 0, "GS: threshold cannot be 0");
require(_guardian != address(0) && _guardian != SENTINEL_GUARDIANS && _guardian != msg.sender, "GS: invalid guardian");
require(!ISafe(payable(msg.sender)).isOwner(_guardian), "GS: guardian cannot be an owner");
GuardianStorageEntry storage entry = entries[msg.sender];
require(entry.guardians[_guardian] == address(0), "GS: duplicate guardian");
if (entry.count == 0){
entry.guardians[SENTINEL_GUARDIANS] = _guardian;
entry.guardians[_guardian] = SENTINEL_GUARDIANS;
} else {
entry.guardians[_guardian] = entry.guardians[SENTINEL_GUARDIANS];
entry.guardians[SENTINEL_GUARDIANS] = _guardian;
}
entry.count++;
emit GuardianAdded(msg.sender, _guardian);
if (entry.threshold != _threshold){
_changeThreshold(msg.sender, _threshold);
}
}
/**
* @dev Lets an authorised module revoke a guardian from a wallet and change the threshold.
* @param _prevGuardian Guardian that pointed to the guardian to be removed in the linked list
* @param _guardian The guardian to revoke.
*/
function revokeGuardianWithThreshold(address _prevGuardian, address _guardian, uint256 _threshold) external onlyWhenModuleIsEnabled() {
GuardianStorageEntry storage entry = entries[msg.sender];
require(_guardian != address(0) && _guardian != SENTINEL_GUARDIANS, "GS: invalid guardian");
require(entry.guardians[_prevGuardian] == _guardian, "GS: invalid previous guardian");
require(entry.count - 1 >= _threshold, "GS: invalid threshold");
entry.guardians[_prevGuardian] = entry.guardians[_guardian];
entry.guardians[_guardian] = address(0);
entry.count--;
emit GuardianRevoked(msg.sender, _guardian);
if (entry.threshold != _threshold){
_changeThreshold(msg.sender, _threshold);
}
}
/**
* @dev Allows to update the number of required confirmations by guardians.
* @param _threshold New threshold.
*/
function changeThreshold(uint256 _threshold) external onlyWhenModuleIsEnabled() {
_changeThreshold(msg.sender, _threshold);
}
function _changeThreshold(address _wallet, uint256 _threshold) internal {
GuardianStorageEntry storage entry = entries[_wallet];
// Validate that threshold is smaller than or equal to number of guardians.
require(_threshold <= entry.count, "GS: threshold must be lower or equal to guardians count");
if (entry.count > 0){
require(_threshold > 0, "GS: threshold cannot be 0");
}
entry.threshold = _threshold;
emit ChangedThreshold(_wallet, _threshold);
}
/**
* @dev Checks if an account is a guardian for a wallet.
* @param _wallet The target wallet.
* @param _guardian The account.
* @return true if the account is a guardian for a wallet.
*/
function isGuardian(address _wallet, address _guardian) public view returns (bool) {
return _guardian != SENTINEL_GUARDIANS && entries[_wallet].guardians[_guardian] != address(0);
}
/**
* @dev Returns the number of guardians for a wallet.
* @param _wallet The target wallet.
* @return the number of guardians.
*/
function guardiansCount(address _wallet) public view returns (uint256) {
return entries[_wallet].count;
}
/**
* @dev Retrieves the wallet threshold count.
* @param _wallet The target wallet.
* @return uint256 Threshold count.
*/
function threshold(address _wallet) public view returns (uint256) {
return entries[_wallet].threshold;
}
/**
* @dev Gets the list of guaridans for a wallet.
* @param _wallet The target wallet.
* @return address[] list of guardians.
*/
function getGuardians(address _wallet) public view returns (address[] memory) {
GuardianStorageEntry storage entry = entries[_wallet];
if (entry.count == 0){
return new address[](0);
}
address[] memory array = new address[](entry.count);
uint256 index = 0;
address currentGuardian = entry.guardians[SENTINEL_GUARDIANS];
while (currentGuardian != SENTINEL_GUARDIANS) {
array[index] = currentGuardian;
currentGuardian = entry.guardians[currentGuardian];
index++;
}
return array;
}
}candide-contracts/contracts/modules/social_recovery/storage/IGuardianStorage.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.12 <0.9.0;
interface IGuardianStorage {
/**
* @dev Lets an authorised module add a guardian to a wallet and change the threshold.
* @param _guardian The guardian to add.
*/
function addGuardianWithThreshold(address _guardian, uint256 _threshold) external;
/**
* @dev Lets an authorised module revoke a guardian from a wallet and change the threshold.
* @param _prevGuardian Guardian that pointed to the guardian to be removed in the linked list
* @param _guardian The guardian to revoke.
*/
function revokeGuardianWithThreshold(address _prevGuardian, address _guardian, uint256 _threshold) external;
/**
* @dev Allows to update the number of required confirmations by guardians.
* @param _threshold New threshold.
*/
function changeThreshold(uint256 _threshold) external;
/**
* @dev Checks if an account is a guardian for a wallet.
* @param _wallet The target wallet.
* @param _guardian The account.
* @return true if the account is a guardian for a wallet.
*/
function isGuardian(address _wallet, address _guardian) external view returns (bool);
/**
* @dev Retrieves the wallet guardians count.
* @param _wallet The target wallet.
* @return uint256 Guardians count.
*/
function guardiansCount(address _wallet) external view returns (uint256);
/**
* @dev Retrieves the wallet threshold count.
* @param _wallet The target wallet.
* @return uint256 Threshold count.
*/
function threshold(address _wallet) external view returns (uint256);
/**
* @dev Retrieves all guardians for a wallet.
* @param _wallet The target wallet.
* @return address[] Array of guardians.
*/
function getGuardians(address _wallet) external view returns (address[] memory);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"libraries": {},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"evmVersion": "paris",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.