Address Contract Verified
Address
0xe7ab44418A0B80ed1748d4A58067EA9DF0d84dfa
Balance
0 ETH
Nonce
1
Code Size
4766 bytes
Creator
0x2Fbf774e...0DB8 at tx 0xcf723c45...0f770e
Indexed Transactions
0
Contract Bytecode
4766 bytes
0x608060405234801561001057600080fd5b50600436106100b45760003560e01c8063785e9e8611610071578063785e9e861461013b5780638129fc1c146101625780638456cb591461016a5780639035508714610172578063ce7c2ac21461017b578063e4fc6b6d1461019b57600080fd5b8063259e97d6146100b95780633a98ef39146100ce5780633cae0ecc146100ea5780633f4ba83a146100fd5780635c975abb1461010557806363037b0c1461011b575b600080fd5b6100cc6100c7366004610f7b565b6101a3565b005b6100d760655481565b6040519081526020015b60405180910390f35b6100d76100f8366004610ffc565b610254565b6100cc610326565b60335460ff1660405190151581526020016100e1565b61012e610129366004611020565b61035c565b6040516100e19190611039565b61012e7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4881565b6100cc610386565b6100cc610402565b6100d760685481565b6100d7610189366004610ffc565b60676020526000908152604090205481565b6100cc610435565b6101d57f000000000000000000000000d16bc944bf20c86c4ed47ce1a330a18538674c836001600160a01b0316610615565b604051632a6e138b60e11b81523060048201523360248201526001600160a01b0391909116906354dc27169060440160006040518083038186803b15801561021c57600080fd5b505afa158015610230573d6000803e3d6000fd5b50505050606660006102429190610e99565b61024e84848484610705565b50505050565b600060655460676000846001600160a01b03166001600160a01b03168152602001908152602001600020547f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016102cb9190611039565b602060405180830381865afa1580156102e8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061030c919061104d565b610316919061107c565b610320919061109b565b92915050565b6040805180820190915263580b2a9160e01b8152633828b3cf60e21b60208201526103518133610828565b6103596108a9565b50565b6066818154811061036c57600080fd5b6000918252602090912001546001600160a01b0316905081565b600054610100900460ff168061039f575060005460ff16155b6103c45760405162461bcd60e51b81526004016103bb906110bd565b60405180910390fd5b600054610100900460ff161580156103e6576000805461ffff19166101011790555b6103ee610936565b8015610359576000805461ff001916905550565b6040805180820190915263580b2a9160e01b8152633828b3cf60e21b602082015261042d8133610828565b6103596109ab565b60335460ff16156104585760405162461bcd60e51b81526004016103bb9061110b565b426068540361047a5760405163bdb009db60e01b815260040160405180910390fd5b426068556040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4816906370a08231906104cd903090600401611039565b602060405180830381865afa1580156104ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061050e919061104d565b905060005b6066548110156105de5760006066828154811061053257610532611135565b60009182526020808320909101546001600160a01b0316808352606790915260408220546065549193509190610568838761107c565b610572919061109b565b905080156105ae576105ae6001600160a01b037f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48168483610a03565b6001600160a01b0383163b156105c8576105c88382610a55565b50505080806105d69061114b565b915050610513565b506040518181527fddc9c30275a04c48091f24199f9c405765de34d979d6847f5b9798a57232d2e59060200160405180910390a150565b6000816001600160a01b031663f887ea406040518163ffffffff1660e01b8152600401602060405180830381865afa158015610655573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106799190611164565b6001600160a01b0316630c0450127f9a671f6643eb8ac838fd3c79576dd800fe704b35ad30189c60f0f14dab948f2a6040518263ffffffff1660e01b81526004016106c49190611181565b602060405180830381865afa1580156106e1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103209190611164565b828114610728576040516001621398b960e31b0319815260040160405180910390fd5b600060655561073960668585610eb7565b5060005b8181101561082157600085858381811061075957610759611135565b905060200201602081019061076e9190610ffc565b9050600084848481811061078457610784611135565b9050602002013590508060676000846001600160a01b03166001600160a01b031681526020019081526020016000208190555080606560008282546107c99190611196565b90915550506040518181526001600160a01b038316907f40c340f65e17194d14ddddb073d3c9f888e3cb52b5aae0c6c7706b4fbc905fac9060200160405180910390a2505080806108199061114b565b91505061073d565b5050505050565b6001600160a01b03811661084f5760405163d92e233d60e01b815260040160405180910390fd5b600061086283825b602002015183610b2c565b806108735750610873836001610857565b9050806108a45760405163889a56bb60e01b81523060048201526001600160a01b03831660248201526044016103bb565b505050565b60335460ff166108f25760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b60448201526064016103bb565b6033805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b60405161092c9190611039565b60405180910390a1565b600054610100900460ff168061094f575060005460ff16155b61096b5760405162461bcd60e51b81526004016103bb906110bd565b600054610100900460ff1615801561098d576000805461ffff19166101011790555b6033805460ff191690558015610359576000805461ff001916905550565b60335460ff16156109ce5760405162461bcd60e51b81526004016103bb9061110b565b6033805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861091f3390565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526108a4908490610c37565b604051637b35092760e11b8152600481018290526001600160a01b0383169063f66a124e906024016020604051808303816000875af1925050508015610ab8575060408051601f3d908101601f19168201909252610ab5918101906111a9565b60015b610afb573d808015610ae6576040519150601f19603f3d011682016040523d82523d6000602084013e610aeb565b606091505b508051156108a457805181602001fd5b6001600160e01b03198116637b35092760e11b146108a457604051631e4ec46b60e01b815260040160405180910390fd5b6000816001600160a01b03167f000000000000000000000000d16bc944bf20c86c4ed47ce1a330a18538674c836001600160a01b031663f887ea406040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b96573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bba9190611164565b6001600160a01b0316630c045012856040518263ffffffff1660e01b8152600401610be59190611181565b602060405180830381865afa158015610c02573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c269190611164565b6001600160a01b0316149392505050565b6000610c8c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610d099092919063ffffffff16565b8051909150156108a45780806020019051810190610caa91906111d3565b6108a45760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016103bb565b6060610d188484600085610d20565b949350505050565b606082471015610d815760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016103bb565b600080866001600160a01b03168587604051610d9d9190611219565b60006040518083038185875af1925050503d8060008114610dda576040519150601f19603f3d011682016040523d82523d6000602084013e610ddf565b606091505b5091509150610df087838387610dfb565b979650505050505050565b60608315610e6a578251600003610e63576001600160a01b0385163b610e635760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016103bb565b5081610d18565b610d188383815115610e7f5781518083602001fd5b8060405162461bcd60e51b81526004016103bb9190611235565b50805460008255906000526020600020908101906103599190610f1a565b828054828255906000526020600020908101928215610f0a579160200282015b82811115610f0a5781546001600160a01b0319166001600160a01b03843516178255602090920191600190910190610ed7565b50610f16929150610f1a565b5090565b5b80821115610f165760008155600101610f1b565b60008083601f840112610f4157600080fd5b50813567ffffffffffffffff811115610f5957600080fd5b6020830191508360208260051b8501011115610f7457600080fd5b9250929050565b60008060008060408587031215610f9157600080fd5b843567ffffffffffffffff80821115610fa957600080fd5b610fb588838901610f2f565b90965094506020870135915080821115610fce57600080fd5b50610fdb87828801610f2f565b95989497509550505050565b6001600160a01b038116811461035957600080fd5b60006020828403121561100e57600080fd5b813561101981610fe7565b9392505050565b60006020828403121561103257600080fd5b5035919050565b6001600160a01b0391909116815260200190565b60006020828403121561105f57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b600081600019048311821515161561109657611096611066565b500290565b6000826110b857634e487b7160e01b600052601260045260246000fd5b500490565b6020808252602e908201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160408201526d191e481a5b9a5d1a585b1a5e995960921b606082015260800190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b634e487b7160e01b600052603260045260246000fd5b60006001820161115d5761115d611066565b5060010190565b60006020828403121561117657600080fd5b815161101981610fe7565b6001600160e01b031991909116815260200190565b8082018082111561032057610320611066565b6000602082840312156111bb57600080fd5b81516001600160e01b03198116811461101957600080fd5b6000602082840312156111e557600080fd5b8151801515811461101957600080fd5b60005b838110156112105781810151838201526020016111f8565b50506000910152565b6000825161122b8184602087016111f5565b9190910192915050565b60208152600082518060208401526112548160408501602087016111f5565b601f01601f1916919091016040019291505056fea26469706673582212200e401bbd376b5ec13015cb96f9a192fc31e62b242172f343971345a682805cf164736f6c63430008100033
Verified Source Code Full Match
Compiler: v0.8.16+commit.07a7930e
EVM: london
Optimization: Yes (100 runs)
IERC165.sol 24 lines
pragma solidity >=0.6.0;
// This file copied from OZ, but with the version pragma updated to use >=.
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
IERC165Upgradeable.sol 24 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Context.sol 25 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import {AccessControl} from "./AccessControl.sol";
import {Router} from "./Router.sol";
import "./Routing.sol" as Routing;
using Routing.Context for Context;
/// @title Entry-point for all application-layer contracts.
/// @author landakram
/// @notice This contract provides an interface for retrieving other contract addresses and doing access
/// control.
contract Context {
/// @notice Used for retrieving other contract addresses.
/// @dev This variable is immutable. This is done to save gas, as it is expected to be referenced
/// in every end-user call with a call-chain length > 0. Note that it is written into the contract
/// bytecode at contract creation time, so if the contract is deployed as the implementation for proxies,
/// every proxy will share the same Router address.
Router public immutable router;
constructor(Router _router) {
router = _router;
}
}
ICreditLine.sol 41 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface ICreditLine {
function borrower() external view returns (address);
function limit() external view returns (uint256);
function maxLimit() external view returns (uint256);
function interestApr() external view returns (uint256);
function paymentPeriodInDays() external view returns (uint256);
function principalGracePeriodInDays() external view returns (uint256);
function termInDays() external view returns (uint256);
function lateFeeApr() external view returns (uint256);
function isLate() external view returns (bool);
function withinPrincipalGracePeriod() external view returns (bool);
// Accounting variables
function balance() external view returns (uint256);
function interestOwed() external view returns (uint256);
function principalOwed() external view returns (uint256);
function termEndTime() external view returns (uint256);
function nextDueTime() external view returns (uint256);
function interestAccruedAsOf() external view returns (uint256);
function lastFullPaymentTime() external view returns (uint256);
}
IMembershipLedger.sol 33 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IMembershipLedger {
/**
* @notice Set `addr`s allocated rewards back to 0
* @param addr address to reset rewards on
*/
function resetRewards(address addr) external;
/**
* @notice Allocate `amount` rewards for `addr` but do not send them
* @param addr address to distribute rewards to
* @param amount amount of rewards to allocate for `addr`
* @return rewards total allocated to `addr`
*/
function allocateRewardsTo(address addr, uint256 amount) external returns (uint256 rewards);
/**
* @notice Get the rewards allocated to a certain `addr`
* @param addr the address to check pending rewards for
* @return rewards pending rewards for `addr`
*/
function getPendingRewardsFor(address addr) external view returns (uint256 rewards);
/**
* @notice Get the alpha parameter for the cobb douglas function. Will always be in (0,1).
* @return numerator numerator for the alpha param
* @return denominator denominator for the alpha param
*/
function alpha() external view returns (uint128 numerator, uint128 denominator);
}
IRouter.sol 17 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
/// @title IRouter
/// @author landakram
/// @notice This contract provides service discovery for contracts using the cake framework.
/// It can be used in conjunction with the convenience methods defined in the `Routing.Context`
/// and `Routing.Keys` libraries.
interface IRouter {
event SetContract(bytes4 indexed key, address indexed addr);
/// @notice Associate a routing key to a contract address
/// @dev This function is only callable by the Router admin
/// @param key A routing key (defined in the `Routing.Keys` libary)
/// @param addr A contract address
function setContract(bytes4 key, address addr) external;
}
ISeniorPool.sol 44 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import "./ITranchedPool.sol";
abstract contract ISeniorPool {
uint256 public sharePrice;
uint256 public totalLoansOutstanding;
uint256 public totalWritedowns;
function deposit(uint256 amount) external virtual returns (uint256 depositShares);
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 depositShares);
function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount);
function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function invest(ITranchedPool pool) public virtual;
function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256);
function redeem(uint256 tokenId) public virtual;
function writedown(uint256 tokenId) public virtual;
function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount);
function assets() public view virtual returns (uint256);
function getNumShares(uint256 amount) public view virtual returns (uint256);
}
IERC721.sol 71 lines
pragma solidity >=0.6.2;
// This file copied from OZ, but with the version pragma updated to use >= & reference other >= pragma interfaces.
// NOTE: Modified to reference our updated pragma version of IERC165
import "./IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
IERC721Upgradeable.sol 142 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
Pausable.sol 18 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
// solhint-disable-next-line max-line-length
import {PausableUpgradeable as OZPausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {Base} from "./Base.sol";
import "./Routing.sol" as Routing;
abstract contract PausableUpgradeable is Base, OZPausableUpgradeable {
function pause() external onlyOperators([Routing.Keys.PauserAdmin, Routing.Keys.ProtocolAdmin]) {
_pause();
}
function unpause() external onlyOperators([Routing.Keys.PauserAdmin, Routing.Keys.ProtocolAdmin]) {
_unpause();
}
}
IMembershipVault.sol 90 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import "@openzeppelin/contracts-upgradeable/interfaces/IERC721Upgradeable.sol";
struct Position {
// address owning the position
address owner;
// how much of the position is eligible as of checkpointEpoch
uint256 eligibleAmount;
// how much of the postion is eligible the epoch after checkpointEpoch
uint256 nextEpochAmount;
// when the position was first created
uint256 createdTimestamp;
// epoch of the last checkpoint
uint256 checkpointEpoch;
}
/**
* @title IMembershipVault
* @notice Track assets held by owners in a vault, as well as the total held in the vault. Assets
* are not accounted for until the next epoch for MEV protection.
* @author Goldfinch
*/
interface IMembershipVault is IERC721Upgradeable {
/**
* @notice Emitted when an owner has adjusted their holdings in a vault
* @param owner the owner increasing their holdings
* @param eligibleAmount the new eligible amount
* @param nextEpochAmount the new next epoch amount
*/
event AdjustedHoldings(address indexed owner, uint256 eligibleAmount, uint256 nextEpochAmount);
/**
* @notice Emitted when the total within the vault has changed
* @param eligibleAmount new current amount
* @param nextEpochAmount new next epoch amount
*/
event VaultTotalUpdate(uint256 eligibleAmount, uint256 nextEpochAmount);
/**
* @notice Get the current value of `owner`. This changes depending on the current
* block.timestamp as increased holdings are not accounted for until the subsequent epoch.
* @param owner address owning the positions
* @return sum of all positions held by an address
*/
function currentValueOwnedBy(address owner) external view returns (uint256);
/**
* @notice Get the total value in the vault as of block.timestamp
* @return total value in the vault as of block.timestamp
*/
function currentTotal() external view returns (uint256);
/**
* @notice Get the total value in the vault as of epoch
* @return total value in the vault as of epoch
*/
function totalAtEpoch(uint256 epoch) external view returns (uint256);
/**
* @notice Get the position owned by `owner`
* @return position owned by `owner`
*/
function positionOwnedBy(address owner) external view returns (Position memory);
/**
* @notice Record an adjustment in holdings. Eligible assets will update this epoch and
* total assets will become eligible the subsequent epoch.
* @param owner the owner to checkpoint
* @param eligibleAmount amount of points to apply to the current epoch
* @param nextEpochAmount amount of points to apply to the next epoch
* @return id of the position
*/
function adjustHoldings(
address owner,
uint256 eligibleAmount,
uint256 nextEpochAmount
) external returns (uint256);
/**
* @notice Checkpoint a specific owner & the vault total
* @param owner the owner to checkpoint
*
* @dev to collect rewards, this must be called before `increaseHoldings` or
* `decreaseHoldings`. Those functions must call checkpoint internally
* so the historical data will be lost otherwise.
*/
function checkpoint(address owner) external;
}
ITranchedPool.sol 96 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import {IV2CreditLine} from "./IV2CreditLine.sol";
abstract contract ITranchedPool {
IV2CreditLine public creditLine;
uint256 public createdAt;
enum Tranches {
Reserved,
Senior,
Junior
}
struct TrancheInfo {
uint256 id;
uint256 principalDeposited;
uint256 principalSharePrice;
uint256 interestSharePrice;
uint256 lockedUntil;
}
struct PoolSlice {
TrancheInfo seniorTranche;
TrancheInfo juniorTranche;
uint256 totalInterestAccrued;
uint256 principalDeployed;
}
function initialize(
address _config,
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) public virtual;
function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory);
function pay(uint256 amount) external virtual;
function poolSlices(uint256 index) external view virtual returns (PoolSlice memory);
function lockJuniorCapital() external virtual;
function lockPool() external virtual;
function initializeNextSlice(uint256 _fundableAt) external virtual;
function totalJuniorDeposits() external view virtual returns (uint256);
function drawdown(uint256 amount) external virtual;
function setFundableAt(uint256 timestamp) external virtual;
function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId);
function assess() external virtual;
function depositWithPermit(
uint256 tranche,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 tokenId);
function availableToWithdraw(uint256 tokenId)
external
view
virtual
returns (uint256 interestRedeemable, uint256 principalRedeemable);
function withdraw(uint256 tokenId, uint256 amount)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMax(uint256 tokenId)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual;
function numSlices() external view virtual returns (uint256);
}
SafeERC20.sol 116 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
IERC721Upgradeable.sol 5 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC721/IERC721Upgradeable.sol";
PausableUpgradeable.sol 97 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
IGFILedger.sol 112 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IGFILedger {
struct Position {
// Owner of the position
address owner;
// Index of the position in the ownership array
uint256 ownedIndex;
// Amount of GFI held in the position
uint256 amount;
// When the position was deposited
uint256 depositTimestamp;
}
/**
* @notice Emitted when a new GFI deposit has been made
* @param owner address owning the deposit
* @param positionId id for the deposit
* @param amount how much GFI was deposited
*/
event GFIDeposit(address indexed owner, uint256 indexed positionId, uint256 amount);
/**
* @notice Emitted when a new GFI withdrawal has been made. If the remaining amount is 0, the position has bee removed
* @param owner address owning the withdrawn position
* @param positionId id for the position
* @param remainingAmount how much GFI is remaining in the position
* @param depositTimestamp block.timestamp of the original deposit
*/
event GFIWithdrawal(
address indexed owner,
uint256 indexed positionId,
uint256 withdrawnAmount,
uint256 remainingAmount,
uint256 depositTimestamp
);
/**
* @notice Account for a new deposit by the owner.
* @param owner address to account for the deposit
* @param amount how much was deposited
* @return how much was deposited
*/
function deposit(address owner, uint256 amount) external returns (uint256);
/**
* @notice Account for a new withdraw by the owner.
* @param positionId id of the position
* @return how much was withdrawn
*/
function withdraw(uint256 positionId) external returns (uint256);
/**
* @notice Account for a new withdraw by the owner.
* @param positionId id of the position
* @param amount how much to withdraw
* @return how much was withdrawn
*/
function withdraw(uint256 positionId, uint256 amount) external returns (uint256);
/**
* @notice Get the number of GFI positions held by an address
* @param addr address
* @return positions held by address
*/
function balanceOf(address addr) external view returns (uint256);
/**
* @notice Get the owner of a given position.
* @param positionId id of the position
* @return owner of the position
*/
function ownerOf(uint256 positionId) external view returns (address);
/**
* @notice Total number of positions in the ledger
* @return number of positions in the ledger
*/
function totalSupply() external view returns (uint256);
/**
* @notice Returns a position ID owned by `owner` at a given `index` of its position list
* @param owner owner of the positions
* @param index index of the owner's balance to get the position ID of
* @return position id
*
* @dev use with {balanceOf} to enumerate all of `owner`'s positions
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a position ID at a given `index` of all the positions stored by the contract.
* @param index index to get the position ID at
* @return token id
*
* @dev use with {totalSupply} to enumerate all positions
*/
function tokenByIndex(uint256 index) external view returns (uint256);
/**
* @notice Get amount of GFI of `owner`s positions, reporting what is currently
* eligible and the total amount.
* @return eligibleAmount GFI amount of positions eligible for rewards
* @return totalAmount total GFI amount of positions
*
* @dev this is used by Membership to determine how much is eligible in
* the current epoch vs the next epoch.
*/
function totalsOf(address owner) external view returns (uint256 eligibleAmount, uint256 totalAmount);
}
IMembershipCollector.sol 32 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IMembershipCollector {
/// @notice Have the collector distribute `amount` of Fidu to `addr`
/// @param addr address to distribute to
/// @param amount amount to distribute
function distributeFiduTo(address addr, uint256 amount) external;
/// @notice Get the last epoch finalized by the collector. This means the
/// collector will no longer add rewards to the epoch.
/// @return the last finalized epoch
function lastFinalizedEpoch() external view returns (uint256);
/// @notice Get the rewards associated with `epoch`. This amount may change
/// until `epoch` has been finalized (is less than or equal to getLastFinalizedEpoch)
/// @return rewards associated with `epoch`
function rewardsForEpoch(uint256 epoch) external view returns (uint256);
/// @notice Estimate rewards for a given epoch. For epochs at or before lastFinalizedEpoch
/// this will be the fixed, accurate reward for the epoch. For the current and other
/// non-finalized epochs, this will be the value as if the epoch were finalized in that
/// moment.
/// @param epoch epoch to estimate the rewards of
/// @return rewards associated with `epoch`
function estimateRewardsFor(uint256 epoch) external view returns (uint256);
/// @notice Finalize all unfinalized epochs. Causes the reserve splitter to distribute
/// if there are unfinalized epochs so all possible rewards are distributed.
function finalizeEpochs() external;
}
IERC20Splitter.sol 13 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IERC20Splitter {
function lastDistributionAt() external view returns (uint256);
function distribute() external;
function replacePayees(address[] calldata _payees, uint256[] calldata _shares) external;
function pendingDistributionFor(address payee) external view returns (uint256);
}
IMembershipOrchestrator.sol 152 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import {Context} from "../cake/Context.sol";
struct CapitalDeposit {
/// Address of the asset being deposited
/// @dev must be supported in CapitalAssets.sol
address assetAddress;
/// Id of the nft
uint256 id;
}
struct Deposit {
/// Amount of gfi to deposit
uint256 gfi;
/// List of capital deposits
CapitalDeposit[] capitalDeposits;
}
struct DepositResult {
uint256 membershipId;
uint256 gfiPositionId;
uint256[] capitalPositionIds;
}
struct ERC20Withdrawal {
uint256 id;
uint256 amount;
}
struct Withdrawal {
/// List of gfi token ids to withdraw
ERC20Withdrawal[] gfiPositions;
/// List of capital token ids to withdraw
uint256[] capitalPositions;
}
/**
* @title MembershipOrchestrator
* @notice Externally facing gateway to all Goldfinch membership functionality.
* @author Goldfinch
*/
interface IMembershipOrchestrator {
/**
* @notice Deposit multiple assets defined in `multiDeposit`. Assets can include GFI, Staked Fidu,
* and others.
* @param deposit struct describing all the assets to deposit
* @return ids all of the ids of the created depoits, in the same order as deposit. If GFI is
* present, it will be the first id.
*/
function deposit(Deposit calldata deposit) external returns (DepositResult memory);
/**
* @notice Withdraw multiple assets defined in `multiWithdraw`. Assets can be GFI or capital
* positions ids. Caller must have been permitted to act upon all of the positions.
* @param withdrawal all of the GFI and Capital ids to withdraw
*/
function withdraw(Withdrawal calldata withdrawal) external;
/**
* @notice Collect all membership rewards for the caller.
* @return how many rewards were collected and sent to caller
*/
function collectRewards() external returns (uint256);
/**
* @notice Check how many rewards are claimable at this moment in time for caller.
* @param addr the address to check claimable rewards for
* @return how many rewards could be claimed by a call to `collectRewards`
*/
function claimableRewards(address addr) external view returns (uint256);
/**
* @notice Check the voting power of a given address
* @param addr the address to check the voting power of
* @return the voting power
*/
function votingPower(address addr) external view returns (uint256);
/**
* @notice Get all GFI in Membership held by `addr`. This returns the current eligible amount and the
* total amount of GFI.
* @param addr the owner
* @return eligibleAmount how much GFI is currently eligible for rewards
* @return totalAmount how much GFI is currently eligible for rewards
*/
function totalGFIHeldBy(address addr) external view returns (uint256 eligibleAmount, uint256 totalAmount);
/**
* @notice Get all capital, denominated in USDC, in Membership held by `addr`. This returns the current
* eligible amount and the total USDC value of capital.
* @param addr the owner
* @return eligibleAmount how much USDC of capital is currently eligible for rewards
* @return totalAmount how much USDC of capital is currently eligible for rewards
*/
function totalCapitalHeldBy(address addr) external view returns (uint256 eligibleAmount, uint256 totalAmount);
/**
* @notice Get the member score of `addr`
* @param addr the owner
* @return eligibleScore the currently eligible score
* @return totalScore the total score that will be eligible next epoch
*
* @dev if eligibleScore == totalScore then there are no changes between now and the next epoch
*/
function memberScoreOf(address addr) external view returns (uint256 eligibleScore, uint256 totalScore);
/**
* @notice Estimate rewards for a given epoch. For epochs at or before lastFinalizedEpoch
* this will be the fixed, accurate reward for the epoch. For the current and other
* non-finalized epochs, this will be the value as if the epoch were finalized in that
* moment.
* @param epoch epoch to estimate the rewards of
* @return rewards associated with `epoch`
*/
function estimateRewardsFor(uint256 epoch) external view returns (uint256);
/**
* @notice Calculate what the Membership Score would be if a `gfi` amount of GFI and `capital` amount
* of Capital denominated in USDC were deposited.
* @param gfi amount of GFI to estimate with
* @param capital amount of capital to estimate with, denominated in USDC
* @return score the resulting score
*/
function calculateMemberScore(uint256 gfi, uint256 capital) external view returns (uint256 score);
/**
* @notice Get the sum of all member scores that are currently eligible and that will be eligible next epoch
* @return eligibleTotal sum of all member scores that are currently eligible
* @return nextEpochTotal sum of all member scores that will be eligible next epoch
*/
function totalMemberScores() external view returns (uint256 eligibleTotal, uint256 nextEpochTotal);
/**
* @notice Estimate the score for an existing member, given some changes in GFI and capital
* @param memberAddress the member's address
* @param gfi the change in gfi holdings, denominated in GFI
* @param capital the change in gfi holdings, denominated in USDC
* @return score resulting score for the member given the GFI and capital changes
*/
function estimateMemberScore(
address memberAddress,
int256 gfi,
int256 capital
) external view returns (uint256 score);
/// @notice Finalize all unfinalized epochs. Causes the reserve splitter to distribute
/// if there are unfinalized epochs so all possible rewards are distributed.
function finalizeEpochs() external;
}
IMembershipDirector.sol 68 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IMembershipDirector {
/**
* @notice Adjust an `owner`s membership score and position due to the change
* in their GFI and Capital holdings
* @param owner address who's holdings changed
* @return id of membership position
*/
function consumeHoldingsAdjustment(address owner) external returns (uint256);
/**
* @notice Collect all membership yield enhancements for the owner.
* @param owner address to claim rewards for
* @return amount of yield enhancements collected
*/
function collectRewards(address owner) external returns (uint256);
/**
* @notice Check how many rewards are claimable for the owner. The return
* value here is how much would be retrieved by calling `collectRewards`.
* @param owner address to calculate claimable rewards for
* @return the amount of rewards that could be claimed by the owner
*/
function claimableRewards(address owner) external view returns (uint256);
/**
* @notice Calculate the membership score
* @param gfi Amount of gfi
* @param capital Amount of capital in USDC
* @return membership score
*/
function calculateMembershipScore(uint256 gfi, uint256 capital) external view returns (uint256);
/**
* @notice Get the current score of `owner`
* @param owner address to check the score of
* @return eligibleScore score that is currently eligible for rewards
* @return totalScore score that will be elgible for rewards next epoch
*/
function currentScore(address owner) external view returns (uint256 eligibleScore, uint256 totalScore);
/**
* @notice Get the sum of all member scores that are currently eligible and that will be eligible next epoch
* @return eligibleTotal sum of all member scores that are currently eligible
* @return nextEpochTotal sum of all member scores that will be eligible next epoch
*/
function totalMemberScores() external view returns (uint256 eligibleTotal, uint256 nextEpochTotal);
/**
* @notice Estimate the score for an existing member, given some changes in GFI and capital
* @param memberAddress the member's address
* @param gfi the change in gfi holdings, denominated in GFI
* @param capital the change in gfi holdings, denominated in USDC
* @return score resulting score for the member given the GFI and capital changes
*/
function estimateMemberScore(
address memberAddress,
int256 gfi,
int256 capital
) external view returns (uint256 score);
/// @notice Finalize all unfinalized epochs. Causes the reserve splitter to distribute
/// if there are unfinalized epochs so all possible rewards are distributed.
function finalizeEpochs() external;
}
IStakingRewards.sol 111 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import {IERC721} from "./openzeppelin/IERC721.sol";
import {IERC721Metadata} from "./openzeppelin/IERC721Metadata.sol";
import {IERC721Enumerable} from "./openzeppelin/IERC721Enumerable.sol";
interface IStakingRewards is IERC721, IERC721Metadata, IERC721Enumerable {
function getPosition(uint256 tokenId) external view returns (StakedPosition memory position);
function unstake(uint256 tokenId, uint256 amount) external;
function addToStake(uint256 tokenId, uint256 amount) external;
function stakedBalanceOf(uint256 tokenId) external view returns (uint256);
function depositToCurveAndStakeFrom(
address nftRecipient,
uint256 fiduAmount,
uint256 usdcAmount
) external;
function kick(uint256 tokenId) external;
function accumulatedRewardsPerToken() external view returns (uint256);
function lastUpdateTime() external view returns (uint256);
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(
address indexed user,
uint256 indexed tokenId,
uint256 amount,
StakedPositionType positionType,
uint256 baseTokenExchangeRate
);
event DepositedAndStaked(address indexed user, uint256 depositedAmount, uint256 indexed tokenId, uint256 amount);
event DepositedToCurve(address indexed user, uint256 fiduAmount, uint256 usdcAmount, uint256 tokensReceived);
event DepositedToCurveAndStaked(
address indexed user,
uint256 fiduAmount,
uint256 usdcAmount,
uint256 indexed tokenId,
uint256 amount
);
event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount, StakedPositionType positionType);
event UnstakedMultiple(address indexed user, uint256[] tokenIds, uint256[] amounts);
event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount);
event UnstakedAndWithdrewMultiple(
address indexed user,
uint256 usdcReceivedAmount,
uint256[] tokenIds,
uint256[] amounts
);
event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);
event RewardsParametersUpdated(
address indexed who,
uint256 targetCapacity,
uint256 minRate,
uint256 maxRate,
uint256 minRateAtPercent,
uint256 maxRateAtPercent
);
event EffectiveMultiplierUpdated(address indexed who, StakedPositionType positionType, uint256 multiplier);
}
/// @notice Indicates which ERC20 is staked
enum StakedPositionType {
Fidu,
CurveLP
}
struct Rewards {
uint256 totalUnvested;
uint256 totalVested;
// @dev DEPRECATED (definition kept for storage slot)
// For legacy vesting positions, this was used in the case of slashing.
// For non-vesting positions, this is unused.
uint256 totalPreviouslyVested;
uint256 totalClaimed;
uint256 startTime;
// @dev DEPRECATED (definition kept for storage slot)
// For legacy vesting positions, this is the endTime of the vesting.
// For non-vesting positions, this is 0.
uint256 endTime;
}
struct StakedPosition {
// @notice Staked amount denominated in `stakingToken().decimals()`
uint256 amount;
// @notice Struct describing rewards owed with vesting
Rewards rewards;
// @notice Multiplier applied to staked amount when locking up position
uint256 leverageMultiplier;
// @notice Time in seconds after which position can be unstaked
uint256 lockedUntil;
// @notice Type of the staked position
StakedPositionType positionType;
// @notice Multiplier applied to staked amount to denominate in `baseStakingToken().decimals()`
// @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1.
// If you need this field, use `safeEffectiveMultiplier()`, which correctly handles old staked positions.
uint256 unsafeEffectiveMultiplier;
// @notice Exchange rate applied to staked amount to denominate in `baseStakingToken().decimals()`
// @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1.
// If you need this field, use `safeBaseTokenExchangeRate()`, which correctly handles old staked positions.
uint256 unsafeBaseTokenExchangeRate;
}
IERC20.sol 82 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
IERC20Upgradeable.sol 81 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
AccessControl.sol 42 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IAccessControl.sol";
/// @title Cake access control
/// @author landakram
/// @notice This contact centralizes contract-to-contract access control using a simple
/// access-control list. There are two types of actors: operators and admins. Operators
/// are callers involved in a regular end-user tx. This would likely be another Goldfinch
/// contract for which the current contract is a dependency. Admins are callers allowed
/// for specific admin actions (like changing parameters, topping up funds, etc.).
contract AccessControl is Initializable, IAccessControl {
/// @dev Mapping from contract address to contract admin;
mapping(address => address) public admins;
function initialize(address admin) public initializer {
admins[address(this)] = admin;
emit AdminSet(address(this), admin);
}
/// @inheritdoc IAccessControl
function setAdmin(address resource, address admin) external {
requireSuperAdmin(msg.sender);
admins[resource] = admin;
emit AdminSet(resource, admin);
}
/// @inheritdoc IAccessControl
function requireAdmin(address resource, address accessor) public view {
if (accessor == address(0)) revert ZeroAddress();
bool isAdmin = admins[resource] == accessor;
if (!isAdmin) revert RequiresAdmin(resource, accessor);
}
/// @inheritdoc IAccessControl
function requireSuperAdmin(address accessor) public view {
// The super admin is the admin of this AccessControl contract
requireAdmin({resource: address(this), accessor: accessor});
}
}
Base.sol 58 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import {Context} from "./Context.sol";
import "./Routing.sol" as Routing;
using Routing.Context for Context;
/// @title Base contract for application-layer
/// @author landakram
/// @notice This base contract is what all application-layer contracts should inherit from.
/// It provides `Context`, as well as some convenience functions for working with it and
/// using access control. All public methods on the inheriting contract should likely
/// use one of the modifiers to assert valid callers.
abstract contract Base {
error RequiresOperator(address resource, address accessor);
error ZeroAddress();
/// @dev this is safe for proxies as immutable causes the context to be written to
/// bytecode on deployment. The proxy then treats this as a constant.
Context immutable context;
constructor(Context _context) {
context = _context;
}
modifier onlyOperator(bytes4 operatorId) {
requireOperator(operatorId, msg.sender);
_;
}
modifier onlyOperators(bytes4[2] memory operatorIds) {
requireAnyOperator(operatorIds, msg.sender);
_;
}
modifier onlyAdmin() {
context.accessControl().requireAdmin(address(this), msg.sender);
_;
}
function requireAnyOperator(bytes4[2] memory operatorIds, address accessor) private view {
if (accessor == address(0)) revert ZeroAddress();
bool validOperator = isOperator(operatorIds[0], accessor) || isOperator(operatorIds[1], accessor);
if (!validOperator) revert RequiresOperator(address(this), accessor);
}
function requireOperator(bytes4 operatorId, address accessor) private view {
if (accessor == address(0)) revert ZeroAddress();
if (!isOperator(operatorId, accessor)) revert RequiresOperator(address(this), accessor);
}
function isOperator(bytes4 operatorId, address accessor) private view returns (bool) {
return context.router().contracts(operatorId) == accessor;
}
}
IV2CreditLine.sol 63 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import "./ICreditLine.sol";
abstract contract IV2CreditLine is ICreditLine {
function principal() external view virtual returns (uint256);
function totalInterestAccrued() external view virtual returns (uint256);
function termStartTime() external view virtual returns (uint256);
function setLimit(uint256 newAmount) external virtual;
function setMaxLimit(uint256 newAmount) external virtual;
function setBalance(uint256 newBalance) external virtual;
function setPrincipal(uint256 _principal) external virtual;
function setTotalInterestAccrued(uint256 _interestAccrued) external virtual;
function drawdown(uint256 amount) external virtual;
function assess()
external
virtual
returns (
uint256,
uint256,
uint256
);
function initialize(
address _config,
address owner,
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public virtual;
function setTermEndTime(uint256 newTermEndTime) external virtual;
function setNextDueTime(uint256 newNextDueTime) external virtual;
function setInterestOwed(uint256 newInterestOwed) external virtual;
function setPrincipalOwed(uint256 newPrincipalOwed) external virtual;
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual;
function setWritedownAmount(uint256 newWritedownAmount) external virtual;
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual;
function setLateFeeApr(uint256 newLateFeeApr) external virtual;
}
ERC20Splitter.sol 131 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import "openzeppelin-contracts/contracts/utils/Address.sol";
import {Context} from "../../../cake/Context.sol";
import {Base} from "../../../cake/Base.sol";
import {PausableUpgradeable} from "../../../cake/Pausable.sol";
import {IERC20Splitter} from "../../../interfaces/IERC20Splitter.sol";
using Address for address;
using SafeERC20 for IERC20;
interface IERC20SplitterReceiver {
function onReceive(uint256 amount) external returns (bytes4 retval);
}
/// @title ERC20Splitter
/// @author landakram
/// @notice Splits the ERC20 balance of this contract amongst a list of payees.
/// Unlike similar splitter contracts, all shares of the balance are distributed
/// in a single `distribute` transaction. If a payee is a smart contract implementing
/// `IERC20SplitterReceiver`, then its `onReceive` handler function will be called
/// after it receives its share.
contract ERC20Splitter is IERC20Splitter, Base, PausableUpgradeable {
error LengthMismatch();
error InvalidReceiver();
error IntraBlockDistribution();
event Distributed(uint256 total);
event PayeeAdded(address indexed payee, uint256 share);
/// @notice The total number of shares in the splitter. A payee's proportion
/// of the split can be calculated as its share / totalShares.
uint256 public totalShares;
/// @notice A list of payees
address[] public payees;
/// @notice Payee shares
mapping(address => uint256) public shares;
/// @notice The ERC20 that is distributed to payees
IERC20 public immutable erc20;
/// @notice The block.timestamp when `distribute` was last called
uint256 public lastDistributionAt;
constructor(Context _context, IERC20 _erc20) Base(_context) {
erc20 = _erc20;
}
function initialize() external initializer {
__Pausable_init_unchained();
}
function pendingDistributionFor(address payee) external view returns (uint256) {
return (erc20.balanceOf(address(this)) * shares[payee]) / totalShares;
}
/// @notice Distribute the current balance to payees. If a payee is a smart contract
/// implementing `IERC20SplitterReceiver`, then its `onReceive` handler function will
/// be called after it receives its share.
function distribute() external whenNotPaused {
if (lastDistributionAt == block.timestamp) revert IntraBlockDistribution();
lastDistributionAt = block.timestamp;
uint256 totalToDistribute = erc20.balanceOf(address(this));
for (uint256 i = 0; i < payees.length; i++) {
address payee = payees[i];
uint256 share = shares[payee];
// Due to integer division, this could result in some dust being left over in the
// contract. This is acceptable as the dust will be included in the next distribution.
uint256 owedToPayee = (totalToDistribute * share) / totalShares;
if (owedToPayee > 0) {
erc20.safeTransfer(payee, owedToPayee);
}
if (payee.isContract()) {
// Call this even if there is nothing owed to payee. Some recipients may still need
// to account for the event.
triggerOnReceive(payee, owedToPayee);
}
}
emit Distributed(totalToDistribute);
}
function triggerOnReceive(address payee, uint256 amount) internal {
try IERC20SplitterReceiver(payee).onReceive(amount) returns (bytes4 retval) {
if (retval != IERC20SplitterReceiver.onReceive.selector) revert InvalidReceiver();
} catch (bytes memory reason) {
// A zero-length reason means the payee does not implement IERC20SplitterReceiver.
// In that case, just continue.
if (reason.length > 0) {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/// @notice Replace all current payees with a new set of payees and shares
/// @param _payees An array of addresses to receive distributions
/// @param _shares An array of shares (ordered by `_payees`) to use for distributions
function replacePayees(address[] calldata _payees, uint256[] calldata _shares) external onlyAdmin {
delete payees;
_setUpPayees(_payees, _shares);
}
function _setUpPayees(address[] calldata _payees, uint256[] calldata _shares) internal {
if (_payees.length != _shares.length) revert LengthMismatch();
totalShares = 0;
payees = _payees;
for (uint256 i = 0; i < _shares.length; i++) {
address payee = _payees[i];
uint256 share = _shares[i];
shares[payee] = share;
totalShares += share;
emit PayeeAdded({payee: payee, share: share});
}
}
}
IERC20Upgradeable.sol 5 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC20/IERC20Upgradeable.sol";
Routing.sol 130 lines
// SPDX-License-Identifier: MIT
// solhint-disable const-name-snakecase
pragma solidity ^0.8.16;
import "@openzeppelin/contracts-upgradeable/interfaces/IERC20Upgradeable.sol";
import {IMembershipVault} from "../interfaces/IMembershipVault.sol";
import {IGFILedger} from "../interfaces/IGFILedger.sol";
import {ICapitalLedger} from "../interfaces/ICapitalLedger.sol";
import {IMembershipDirector} from "../interfaces/IMembershipDirector.sol";
import {IMembershipOrchestrator} from "../interfaces/IMembershipOrchestrator.sol";
import {IMembershipLedger} from "../interfaces/IMembershipLedger.sol";
import {IMembershipCollector} from "../interfaces/IMembershipCollector.sol";
import {ISeniorPool} from "../interfaces/ISeniorPool.sol";
import {IPoolTokens} from "../interfaces/IPoolTokens.sol";
import {IStakingRewards} from "../interfaces/IStakingRewards.sol";
import {IERC20Splitter} from "../interfaces/IERC20Splitter.sol";
import {Context as ContextContract} from "./Context.sol";
import {IAccessControl} from "../interfaces/IAccessControl.sol";
import {Router} from "./Router.sol";
/// @title Routing.Keys
/// @notice This library is used to define routing keys used by `Router`.
/// @dev We use uints instead of enums for several reasons. First, keys can be re-ordered
/// or removed. This is useful when routing keys are deprecated; they can be moved to a
/// different section of the file. Second, other libraries or contracts can define their
/// own routing keys independent of this global mapping. This is useful for test contracts.
library Keys {
// Membership
bytes4 internal constant MembershipOrchestrator = bytes4(keccak256("MembershipOrchestrator"));
bytes4 internal constant MembershipDirector = bytes4(keccak256("MembershipDirector"));
bytes4 internal constant GFILedger = bytes4(keccak256("GFILedger"));
bytes4 internal constant CapitalLedger = bytes4(keccak256("CapitalLedger"));
bytes4 internal constant MembershipCollector = bytes4(keccak256("MembershipCollector"));
bytes4 internal constant MembershipLedger = bytes4(keccak256("MembershipLedger"));
bytes4 internal constant MembershipVault = bytes4(keccak256("MembershipVault"));
// Tokens
bytes4 internal constant GFI = bytes4(keccak256("GFI"));
bytes4 internal constant FIDU = bytes4(keccak256("FIDU"));
bytes4 internal constant USDC = bytes4(keccak256("USDC"));
// Cake
bytes4 internal constant AccessControl = bytes4(keccak256("AccessControl"));
bytes4 internal constant Router = bytes4(keccak256("Router"));
// Core
bytes4 internal constant ReserveSplitter = bytes4(keccak256("ReserveSplitter"));
bytes4 internal constant PoolTokens = bytes4(keccak256("PoolTokens"));
bytes4 internal constant SeniorPool = bytes4(keccak256("SeniorPool"));
bytes4 internal constant StakingRewards = bytes4(keccak256("StakingRewards"));
bytes4 internal constant ProtocolAdmin = bytes4(keccak256("ProtocolAdmin"));
bytes4 internal constant PauserAdmin = bytes4(keccak256("PauserAdmin"));
}
/// @title Routing.Context
/// @notice This library provides convenience functions for getting contracts from `Router`.
library Context {
function accessControl(ContextContract context) internal view returns (IAccessControl) {
return IAccessControl(context.router().contracts(Keys.AccessControl));
}
function membershipVault(ContextContract context) internal view returns (IMembershipVault) {
return IMembershipVault(context.router().contracts(Keys.MembershipVault));
}
function capitalLedger(ContextContract context) internal view returns (ICapitalLedger) {
return ICapitalLedger(context.router().contracts(Keys.CapitalLedger));
}
function gfiLedger(ContextContract context) internal view returns (IGFILedger) {
return IGFILedger(context.router().contracts(Keys.GFILedger));
}
function gfi(ContextContract context) internal view returns (IERC20Upgradeable) {
return IERC20Upgradeable(context.router().contracts(Keys.GFI));
}
function membershipDirector(ContextContract context) internal view returns (IMembershipDirector) {
return IMembershipDirector(context.router().contracts(Keys.MembershipDirector));
}
function membershipOrchestrator(ContextContract context) internal view returns (IMembershipOrchestrator) {
return IMembershipOrchestrator(context.router().contracts(Keys.MembershipOrchestrator));
}
function stakingRewards(ContextContract context) internal view returns (IStakingRewards) {
return IStakingRewards(context.router().contracts(Keys.StakingRewards));
}
function poolTokens(ContextContract context) internal view returns (IPoolTokens) {
return IPoolTokens(context.router().contracts(Keys.PoolTokens));
}
function seniorPool(ContextContract context) internal view returns (ISeniorPool) {
return ISeniorPool(context.router().contracts(Keys.SeniorPool));
}
function fidu(ContextContract context) internal view returns (IERC20Upgradeable) {
return IERC20Upgradeable(context.router().contracts(Keys.FIDU));
}
function usdc(ContextContract context) internal view returns (IERC20Upgradeable) {
return IERC20Upgradeable(context.router().contracts(Keys.USDC));
}
function reserveSplitter(ContextContract context) internal view returns (IERC20Splitter) {
return IERC20Splitter(context.router().contracts(Keys.ReserveSplitter));
}
function membershipLedger(ContextContract context) internal view returns (IMembershipLedger) {
return IMembershipLedger(context.router().contracts(Keys.MembershipLedger));
}
function membershipCollector(ContextContract context) internal view returns (IMembershipCollector) {
return IMembershipCollector(context.router().contracts(Keys.MembershipCollector));
}
function protocolAdmin(ContextContract context) internal view returns (address) {
return context.router().contracts(Keys.ProtocolAdmin);
}
function pauserAdmin(ContextContract context) internal view returns (address) {
return context.router().contracts(Keys.PauserAdmin);
}
}
IAccessControl.sol 34 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
/// @title Cake access control
/// @author landakram
/// @notice This contact centralizes contract-to-contract access control using a simple
/// access-control list. There are two types of actors: operators and admins. Operators
/// are callers involved in a regular end-user tx. This would likely be another Goldfinch
/// contract for which the current contract is a dependency. Admins are callers allowed
/// for specific admin actions (like changing parameters, topping up funds, etc.).
interface IAccessControl {
error RequiresAdmin(address resource, address accessor);
error ZeroAddress();
event AdminSet(address indexed resource, address indexed admin);
/// @notice Set an admin for a given resource
/// @param resource An address which with `admin` should be allowed to administer
/// @param admin An address which should be allowed to administer `resource`
/// @dev This method is only callable by the super-admin (the admin of this AccessControl
/// contract)
function setAdmin(address resource, address admin) external;
/// @notice Require a valid admin for a given resource
/// @param resource An address that `accessor` is attempting to access
/// @param accessor An address on which to assert access control checks
/// @dev This method reverts when `accessor` is not a valid admin
function requireAdmin(address resource, address accessor) external view;
/// @notice Require a super-admin. A super-admin is an admin of this AccessControl contract.
/// @param accessor An address on which to assert access control checks
/// @dev This method reverts when `accessor` is not a valid super-admin
function requireSuperAdmin(address accessor) external view;
}
IERC721Enumerable.sol 17 lines
pragma solidity >=0.6.2;
// This file copied from OZ, but with the version pragma updated to use >=.
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
Initializable.sol 46 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
IPoolTokens.sol 59 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import "./openzeppelin/IERC721.sol";
interface IPoolTokens is IERC721 {
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
struct TokenInfo {
address pool;
uint256 tranche;
uint256 principalAmount;
uint256 principalRedeemed;
uint256 interestRedeemed;
}
struct MintParams {
uint256 principalAmount;
uint256 tranche;
}
function mint(MintParams calldata params, address to) external returns (uint256);
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external;
function withdrawPrincipal(uint256 tokenId, uint256 principalAmount) external;
function burn(uint256 tokenId) external;
function onPoolCreated(address newPool) external;
function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory);
function validPool(address sender) external view returns (bool);
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}
IERC721Metadata.sol 17 lines
pragma solidity >=0.6.2;
// This file copied from OZ, but with the version pragma updated to use >=.
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
ContextUpgradeable.sol 31 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
Router.sol 34 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {AccessControl} from "./AccessControl.sol";
import {IRouter} from "../interfaces/IRouter.sol";
import "./Routing.sol" as Routing;
/// @title Router
/// @author landakram
/// @notice This contract provides service discovery for contracts using the cake framework.
/// It can be used in conjunction with the convenience methods defined in the `Routing.Context`
/// and `Routing.Keys` libraries.
contract Router is Initializable, IRouter {
/// @notice Mapping of keys to contract addresses. Keys are the first 4 bytes of the keccak of
/// the contract's name. See Routing.sol for all options.
mapping(bytes4 => address) public contracts;
function initialize(AccessControl accessControl) public initializer {
contracts[Routing.Keys.AccessControl] = address(accessControl);
}
/// @notice Associate a routing key to a contract address
/// @dev This function is only callable by the Router admin
/// @param key A routing key (defined in the `Routing.Keys` libary)
/// @param addr A contract address
function setContract(bytes4 key, address addr) public {
AccessControl accessControl = AccessControl(contracts[Routing.Keys.AccessControl]);
accessControl.requireAdmin(address(this), msg.sender);
contracts[key] = addr;
emit SetContract(key, addr);
}
}
ICapitalLedger.sol 132 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
enum CapitalAssetType {
INVALID,
ERC721
}
interface ICapitalLedger {
/**
* @notice Emitted when a new capital erc721 deposit has been made
* @param owner address owning the deposit
* @param assetAddress address of the deposited ERC721
* @param positionId id for the deposit
* @param assetTokenId id of the token from the ERC721 `assetAddress`
* @param usdcEquivalent usdc equivalent value at the time of deposit
*/
event CapitalERC721Deposit(
address indexed owner,
address indexed assetAddress,
uint256 positionId,
uint256 assetTokenId,
uint256 usdcEquivalent
);
/**
* @notice Emitted when a new ERC721 capital withdrawal has been made
* @param owner address owning the deposit
* @param positionId id for the capital position
* @param assetAddress address of the underlying ERC721
* @param depositTimestamp block.timestamp of the original deposit
*/
event CapitalERC721Withdrawal(
address indexed owner,
uint256 positionId,
address assetAddress,
uint256 depositTimestamp
);
/// Thrown when called with an invalid asset type for the function. Valid
/// types are defined under CapitalAssetType
error InvalidAssetType(CapitalAssetType);
/**
* @notice Account for a deposit of `id` for the ERC721 asset at `assetAddress`.
* @dev reverts with InvalidAssetType if `assetAddress` is not an ERC721
* @param owner address that owns the position
* @param assetAddress address of the ERC20 address
* @param assetTokenId id of the ERC721 asset to add
* @return id of the newly created position
*/
function depositERC721(
address owner,
address assetAddress,
uint256 assetTokenId
) external returns (uint256);
/**
* @notice Get the id of the ERC721 asset held by position `id`. Pair this with
* `assetAddressOf` to get the address & id of the nft.
* @dev reverts with InvalidAssetType if `assetAddress` is not an ERC721
* @param positionId id of the position
* @return id of the underlying ERC721 asset
*/
function erc721IdOf(uint256 positionId) external view returns (uint256);
/**
* @notice Completely withdraw a position
* @param positionId id of the position
*/
function withdraw(uint256 positionId) external;
/**
* @notice Get the asset address of the position. Example: For an ERC721 position, this
* returns the address of that ERC721 contract.
* @param positionId id of the position
* @return asset address of the position
*/
function assetAddressOf(uint256 positionId) external view returns (address);
/**
* @notice Get the owner of a given position.
* @param positionId id of the position
* @return owner of the position
*/
function ownerOf(uint256 positionId) external view returns (address);
/**
* @notice Total number of positions in the ledger
* @return number of positions in the ledger
*/
function totalSupply() external view returns (uint256);
/**
* @notice Get the number of capital positions held by an address
* @param addr address
* @return positions held by address
*/
function balanceOf(address addr) external view returns (uint256);
/**
* @notice Returns a position ID owned by `owner` at a given `index` of its position list
* @param owner owner of the positions
* @param index index of the owner's balance to get the position ID of
* @return position id
*
* @dev use with {balanceOf} to enumerate all of `owner`'s positions
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a position ID at a given `index` of all the positions stored by the contract.
* @param index index to get the position ID at
* @return position id
*
* @dev use with {totalSupply} to enumerate all positions
*/
function tokenByIndex(uint256 index) external view returns (uint256);
/**
* @notice Get the USDC value of `owner`s positions, reporting what is currently
* eligible and the total amount.
* @param owner address owning the positions
* @return eligibleAmount USDC value of positions eligible for rewards
* @return totalAmount total USDC value of positions
*
* @dev this is used by Membership to determine how much is eligible in
* the current epoch vs the next epoch.
*/
function totalsOf(address owner) external view returns (uint256 eligibleAmount, uint256 totalAmount);
}
draft-IERC20Permit.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
Address.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Read Contract
erc20 0x785e9e86 → address
lastDistributionAt 0x90355087 → uint256
paused 0x5c975abb → bool
payees 0x63037b0c → address
pendingDistributionFor 0x3cae0ecc → uint256
shares 0xce7c2ac2 → uint256
totalShares 0x3a98ef39 → uint256
Write Contract 5 functions
These functions modify contract state and require a wallet transaction to execute.
distribute 0xe4fc6b6d
No parameters
initialize 0x8129fc1c
No parameters
pause 0x8456cb59
No parameters
replacePayees 0x259e97d6
address[] _payees
uint256[] _shares
unpause 0x3f4ba83a
No parameters
Recent Transactions
No transactions found for this address