Verified contractPartialMIT
TrancheBondUpgradeable
Address0x1cf17743cfd3e8a2ff272d3da927a7956b3f2163
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.17
- Same code
Only this contract
Details
- Compiler
- solc 0.8.17+commit.8df45f5f
- Language
- solidity
- Optimization
- Yes, 1,000 runs
- EVM version
- london
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 18,552,785
- Creation transaction
- 0x07eb2395a0…64781e98e4
37 files
- contracts/core/TrancheBondUpgradeable.solmain15.72 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/access/AccessControlEnumerableStorage.sol652 B
- @gnus.ai/contracts-upgradeable-diamond/contracts/access/AccessControlEnumerableUpgradeable.sol2.99 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/access/AccessControlStorage.sol514 B
- @gnus.ai/contracts-upgradeable-diamond/contracts/access/AccessControlUpgradeable.sol8.66 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/access/IAccessControlEnumerableUpgradeable.sol1.26 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/access/IAccessControlUpgradeable.sol2.93 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/interfaces/IERC1155Upgradeable.sol168 B
- @gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/Initializable.sol6.93 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/InitializableStorage.sol682 B
- @gnus.ai/contracts-upgradeable-diamond/contracts/security/PausableStorage.sol446 B
- @gnus.ai/contracts-upgradeable-diamond/contracts/security/PausableUpgradeable.sol2.98 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/security/ReentrancyGuardStorage.sol477 B
- @gnus.ai/contracts-upgradeable-diamond/contracts/security/ReentrancyGuardUpgradeable.sol3.32 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC1155/IERC1155Upgradeable.sol4.11 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC20/IERC20Upgradeable.sol2.78 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/utils/AddressUpgradeable.sol8.28 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/utils/ContextUpgradeable.sol1.05 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/utils/StringsUpgradeable.sol2.3 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/utils/introspection/ERC165Upgradeable.sol1.23 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/utils/introspection/IERC165Upgradeable.sol864 B
- @gnus.ai/contracts-upgradeable-diamond/contracts/utils/math/MathUpgradeable.sol12.52 KB
- @gnus.ai/contracts-upgradeable-diamond/contracts/utils/structs/EnumerableSetUpgradeable.sol12.96 KB
- contracts/beanstalk/IBeanstalkUpgradeable.sol28.08 KB
- contracts/core/TrancheBondStorage.sol2.34 KB
- contracts/core/WaterCommonStorage.sol742 B
- contracts/core/WaterTowerStorage.sol2.44 KB
- contracts/interfaces/IBeanstalkPrice.sol516 B
- contracts/interfaces/IDiamondCut.sol1.26 KB
- contracts/interfaces/IERC1155WhitelistUpgradeable.sol630 B
- contracts/interfaces/IPodsOracleUpgradeable.sol667 B
- contracts/libraries/Constants.sol2.08 KB
- contracts/libraries/FullMath.sol1.09 KB
- contracts/libraries/LibDiamond.sol12.56 KB
- contracts/libraries/PodTransferHelper.sol2.7 KB
- contracts/utils/EIP2535Initializable.sol1.48 KB
- contracts/utils/IrrigationAccessControl.sol3.02 KB
contracts/core/TrancheBondUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "@gnus.ai/contracts-upgradeable-diamond/contracts/interfaces/IERC1155Upgradeable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/security/ReentrancyGuardUpgradeable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/security/PausableUpgradeable.sol";
import "./TrancheBondStorage.sol";
import "./WaterCommonStorage.sol";
import "./WaterTowerStorage.sol";
import "../utils/EIP2535Initializable.sol";
import "../utils/IrrigationAccessControl.sol";
import "../libraries/FullMath.sol";
import "../libraries/Constants.sol";
import "../libraries/PodTransferHelper.sol";
import "../interfaces/IPodsOracleUpgradeable.sol";
import "../interfaces/IERC1155WhitelistUpgradeable.sol";
import "../interfaces/IBeanstalkPrice.sol";
/// @title TrancheBond Contract
/// @notice Allows users deposit underlying assets like pods,
/// create tranche and receive underlying assets with tranche
/// @dev users receive 3 tranche nfts(ERC1155) after deposit underlying assets.
/// tranche A and Tranche B nft holders can list owned nfts on our auction market.
/// users can set maturity date when creating tranche, and after maturity date, can receive underlying assets with tranche
contract TrancheBondUpgradeable is
EIP2535Initializable,
IrrigationAccessControl,
ReentrancyGuardUpgradeable,
PausableUpgradeable
{
using TrancheBondStorage for TrancheBondStorage.Layout;
using WaterTowerStorage for WaterTowerStorage.Layout;
uint256 internal constant FMV_DENOMINATOR = 100;
uint256 internal constant MINIMUM_FMV = 1000;
uint256 internal constant MINIMUM_WATER = 32 * 1e18;
// Offset(%) for each tranche
uint256 internal constant OFFSET_A = 0;
uint256 internal constant OFFSET_B = 20;
uint256 internal constant OFFSET_Z = 50;
// FMV(%) for each tranche
uint256 internal constant FMV_A = 20;
uint256 internal constant FMV_B = 30;
uint256 internal constant FMV_Z = 50;
// 3 tranches like A, B, and Z
uint256 internal constant TRANCHE_COUNT = 3;
/// @dev Events
event CreateTranche(
uint depositIndex,
address user,
uint periodId,
uint[] depositIndexes,
uint[] amounts,
uint[] fmvs
);
event ReceivePodsWithTranche(uint trancheId, address user, uint[] podIndexes, uint totalPods);
event SetMaturityPeriods(uint48[] periods);
/// @dev Errors
// errors for tranche pods
error InvalidPods();
error NotTranchePods();
error InsufficientPods();
// errors for general tranche
error NotOwnerOfTranche();
error NotMatureTranche();
error NotSortedPlots();
// errors for farmer's market rule
error NotEligible();
/// @notice Create tranches by depositing group of pods
/// @dev See transferPlot function in https://github.com/BeanstalkFarms/Beanstalk/blob/master/protocol/contracts/farm/facets/MarketplaceFacet/MarketplaceFacet.sol
/// @param indexes Index array of deposited pods
/// @param starts Array of start number for deposited pods
/// @param ends Array of end number for deposited pods
/// @param periodId Maturity Period id
function createTranchesWithPods(
uint256[] calldata indexes,
uint256[] calldata starts,
uint256[] calldata ends,
uint8 periodId
) external whenNotPaused onlyWaterHolder nonReentrant {
if (indexes.length != starts.length || indexes.length != ends.length) revert InvalidPods();
uint256[] memory podIndexes = new uint256[](indexes.length);
uint256[] memory amounts = new uint256[](indexes.length);
uint256[] memory fmvs = new uint256[](indexes.length);
/// @dev sum of FMVs for all deposited plots
uint256 totalFMV;
uint256 totalPods;
// calculate directly price with 6 decimals from beanstalk
uint256 beanPrice = IBeanstalkPrice(Constants.BEANSTALK_PRICE).price().price;
for (uint256 i; i < indexes.length; ) {
uint256[] memory _indexes = indexes;
uint256 _index = _indexes[i];
uint256 _start = starts[i];
uint256 _end = ends[i];
/// should input plots sorted by index
if (i >= 1 && _index <= _indexes[i - 1]) revert NotSortedPlots();
WaterCommonStorage.layout().beanstalk.transferPlot(
msg.sender,
address(this),
_index,
_start,
_end
);
/// checked inside of transferPlot function
uint256 amount;
uint256 id;
unchecked {
id = _index + _start;
podIndexes[i] = id;
amount = _end - _start;
amounts[i] = amount;
}
totalPods += amount;
/// @dev we calculate fmv in usd, decimals is 6 and it is same as bean price
uint256 _fmvInPlot = (IPodsOracleUpgradeable(address(this)).latestPriceOfPods(
id,
amount
) * beanPrice) / Constants.D18;
fmvs[i] = _fmvInPlot;
totalFMV += _fmvInPlot;
unchecked {
++i;
}
}
if (totalFMV < MINIMUM_FMV) revert InvalidPods();
uint256 curDepositCount = TrancheBondStorage.layout().curDepositCount + 1;
/// Register deposited plot
TrancheBondStorage.layout().depositedPods[curDepositCount].podIndexes = podIndexes;
TrancheBondStorage.layout().depositedPods[curDepositCount].amounts = amounts;
TrancheBondStorage.layout().depositedPods[curDepositCount].fmvs = fmvs;
/// Create underlying asset meta data
TrancheBondStorage.layout().underlyingAssets[curDepositCount] = UnderlyingAssetMetadata({
contractAddress: Constants.ZERO,
assetType: UnderlyingAssetType.PODS,
maturityDate: uint48(block.timestamp) + TrancheBondStorage.layout().periods[periodId],
totalDeposited: totalPods,
totalFMV: totalFMV
});
/// Create tranche A, B, Z
_createTranchesFromDeposit(curDepositCount, totalFMV, msg.sender);
TrancheBondStorage.layout().curDepositCount = curDepositCount;
emit CreateTranche(curDepositCount, msg.sender, periodId, podIndexes, amounts, fmvs);
}
/// @dev receive pods with tranches after maturity date is over
function receivePodsForTranche(
uint256 trancheId
) external whenNotPaused onlyWaterHolder nonReentrant {
TrancheBondStorage.Layout storage tancheBondStorage = TrancheBondStorage.layout();
(uint256 depositId, uint8 trancheLevel) = getTrancheInfo(trancheId);
DepositPods memory depositPlots = tancheBondStorage.depositedPods[depositId];
UnderlyingAssetMetadata memory underlyingAsset = TrancheBondStorage
.layout()
.underlyingAssets[depositId];
if (underlyingAsset.assetType != UnderlyingAssetType.PODS) revert NotTranchePods();
if (block.timestamp < underlyingAsset.maturityDate) revert NotMatureTranche();
uint256 claimedFMV = tancheBondStorage.tranches[trancheId].claimedFMV;
uint256 offsetFMV = _offsetFMVForTranche(
trancheLevel,
underlyingAsset.totalFMV,
claimedFMV
);
uint256 fmv = IERC1155Upgradeable(address(this)).balanceOf(msg.sender, trancheId);
if (fmv < MINIMUM_FMV) revert InsufficientPods();
uint256 startIndex;
uint256 startOffset;
uint256[] memory receivePodIndexes = new uint256[](depositPlots.podIndexes.length);
uint256 totalPods;
for (uint256 i; i < depositPlots.podIndexes.length; ) {
if (fmv == 0) break;
DepositPods memory _depositPlots = depositPlots;
uint256 plotFMV = _depositPlots.fmvs[i];
uint256 _fmv = fmv;
uint256 _level = trancheLevel;
/// if plot for the tranche is placed in this range
uint256 _offsetFMV = offsetFMV;
if (plotFMV >= _offsetFMV) {
uint256 originalPodIndex = _depositPlots.podIndexes[i];
uint128[6] memory _startIndexAndOffsets = _depositPlots.startIndexAndOffsets;
(
uint256 offset,
uint256 start,
uint256 amount,
uint256 reserveFMV
) = PodTransferHelper.getPlotWithOffset(
i,
_depositPlots.amounts[i],
plotFMV,
_offsetFMV,
_fmv,
_level,
_startIndexAndOffsets
);
unchecked {
WaterCommonStorage.layout().beanstalk.transferPlot(
address(this),
msg.sender,
originalPodIndex + offset,
start,
amount + start
);
receivePodIndexes[i] = originalPodIndex + offset + start;
// absolute offset from orignal pod index of podline
startOffset = offset + start + amount;
}
startIndex = i;
totalPods += amount;
_fmv = reserveFMV;
// offset is always 0 from next podline
_offsetFMV = 0;
} else {
_offsetFMV -= plotFMV;
}
offsetFMV = _offsetFMV;
fmv = _fmv;
unchecked {
i++;
}
}
// update startIndex and startOffset for current tranche pods
tancheBondStorage.depositedPods[depositId].startIndexAndOffsets[trancheLevel] = uint128(
startIndex
);
tancheBondStorage.depositedPods[depositId].startIndexAndOffsets[
trancheLevel + TRANCHE_COUNT
] = uint128(startOffset);
{
uint256 _trancheId = trancheId;
tancheBondStorage.tranches[_trancheId].claimedFMV = claimedFMV + fmv;
IERC1155BurnableUpgradeable(address(this)).burn(msg.sender, _trancheId, fmv);
emit ReceivePodsWithTranche(_trancheId, msg.sender, receivePodIndexes, totalPods);
}
}
function _createTranchesFromDeposit(
uint256 depositId,
uint256 totalFMVInUSD,
address owner
) internal {
uint256[TRANCHE_COUNT] memory numeratorFMV = [FMV_A, FMV_B, FMV_Z];
uint256 trancheAId = (depositId << 2) + 1;
for (uint256 i; i < TRANCHE_COUNT; ) {
uint256 trancheId = trancheAId + i;
uint256 fmv = (totalFMVInUSD * numeratorFMV[i]) / FMV_DENOMINATOR;
TrancheBondStorage.layout().tranches[trancheId].fmv = fmv;
/// mint tranche nft with trancheId and totalSupply fmv
IERC1155WhitelistUpgradeable(address(this)).mint(owner, trancheId, fmv, "");
unchecked {
++i;
}
}
}
/// @dev get functioins
function getTranchePods(
uint256 trancheId
)
public
view
returns (
TrancheMetadata memory tranche,
DepositPods memory depositPods,
UnderlyingAssetMetadata memory underlyingAsset
)
{
uint256 depositId = trancheId >> 2;
tranche = TrancheBondStorage.layout().tranches[trancheId];
underlyingAsset = TrancheBondStorage.layout().underlyingAssets[depositId];
depositPods = TrancheBondStorage.layout().depositedPods[depositId];
}
/// @notice return offset and pods to calculate how much pods users can receive
/// @param trancheId tranche nft id
/// @param user user address
/// @return starts start offset of total pods
/// @return podAmounts pods amount available for the user
function getPlotsForUser(
uint256 trancheId,
address user
) external view returns (uint256[] memory starts, uint256[] memory podAmounts) {
uint256 claimedFMV = TrancheBondStorage.layout().tranches[trancheId].claimedFMV;
uint256 userFMV = IERC1155Upgradeable(address(this)).balanceOf(user, trancheId);
(starts, podAmounts) = _plotsForTranche(trancheId, userFMV, claimedFMV);
}
function getPlotsForTranche(
uint256 trancheId
) external view returns (uint256[] memory starts, uint256[] memory podAmounts) {
uint256 trancheFMV = TrancheBondStorage.layout().tranches[trancheId].fmv;
uint256 claimedFMV = TrancheBondStorage.layout().tranches[trancheId].claimedFMV;
return _plotsForTranche(trancheId, trancheFMV, claimedFMV);
}
function _offsetFMVForTranche(
uint8 trancheLevel,
uint256 totalFMV,
uint256 claimedFMV
) internal pure returns (uint256 offsetFMV) {
uint256[TRANCHE_COUNT] memory offsetFMVs = [OFFSET_A, OFFSET_B, OFFSET_Z];
offsetFMV = (offsetFMVs[trancheLevel] * totalFMV) / FMV_DENOMINATOR + claimedFMV;
}
/// @notice return start pod indexes and pod amounts to calculate how much pods users can receive
/// @param trancheId tranche nft id
/// @return starts start ids in podlines
/// @return podAmounts pods in podlines
function _plotsForTranche(
uint256 trancheId,
uint256 userFMV,
uint256 claimedFMV
) internal view returns (uint256[] memory starts, uint256[] memory podAmounts) {
(, uint8 trancheLevel) = getTrancheInfo(trancheId);
(
,
DepositPods memory depositPlots,
UnderlyingAssetMetadata memory underlyingAsset
) = getTranchePods(trancheId);
///@dev plot for tranche is correspond to [offsetFMV, offsetFMV + userFMV]
uint256 offsetFMV = _offsetFMVForTranche(
trancheLevel,
underlyingAsset.totalFMV,
claimedFMV
);
uint256 fmv = userFMV;
uint256 podlineCount = depositPlots.podIndexes.length;
starts = new uint256[](podlineCount);
podAmounts = new uint256[](podlineCount);
for (uint256 i; i < podlineCount; ) {
if (fmv == 0) break;
uint256 plotFMV = depositPlots.fmvs[i];
/// if plot for the tranche is placed in this range
if (plotFMV >= offsetFMV) {
(uint256 start, uint256 amount, uint256 reserveFMV) = PodTransferHelper
.getPlotSplittedByFMV(depositPlots.amounts[i], plotFMV, offsetFMV, fmv);
starts[i] = start;
podAmounts[i] = amount;
fmv = reserveFMV;
offsetFMV = 0;
} else {
offsetFMV -= plotFMV;
}
unchecked {
i++;
}
}
}
/// @dev deposit Id
/// @param trancheId tranche Id
/// @return depositId deposit Id
/// @return trancheLevel tranche level number
function getTrancheInfo(
uint256 trancheId
) internal pure returns (uint256 depositId, uint8 trancheLevel) {
return (trancheId >> 2, uint8(trancheId & 3) - 1);
}
function setMaturityPeriods(uint48[] calldata periods) external onlyAdminRole {
TrancheBondStorage.layout().periods = periods;
emit SetMaturityPeriods(periods);
}
/// @dev modifiers
modifier onlyWaterHolder() {
if (WaterTowerStorage.userInfo(msg.sender).amount < MINIMUM_WATER) revert NotEligible();
_;
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/access/AccessControlEnumerableStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { AccessControlEnumerableUpgradeable } from "./AccessControlEnumerableUpgradeable.sol";
import { EnumerableSetUpgradeable } from "../utils/structs/EnumerableSetUpgradeable.sol";
library AccessControlEnumerableStorage {
struct Layout {
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) _roleMembers;
}
bytes32 internal constant STORAGE_SLOT = keccak256('openzeppelin.contracts.storage.AccessControlEnumerable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/access/AccessControlEnumerableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import { AccessControlEnumerableStorage } from "./AccessControlEnumerableStorage.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
using AccessControlEnumerableStorage for AccessControlEnumerableStorage.Layout;
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return AccessControlEnumerableStorage.layout()._roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return AccessControlEnumerableStorage.layout()._roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
AccessControlEnumerableStorage.layout()._roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
AccessControlEnumerableStorage.layout()._roleMembers[role].remove(account);
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/access/AccessControlStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { AccessControlUpgradeable } from "./AccessControlUpgradeable.sol";
library AccessControlStorage {
struct Layout {
mapping(bytes32 => AccessControlUpgradeable.RoleData) _roles;
}
bytes32 internal constant STORAGE_SLOT = keccak256('openzeppelin.contracts.storage.AccessControl');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import { AccessControlStorage } from "./AccessControlStorage.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
using AccessControlStorage for AccessControlStorage.Layout;
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return AccessControlStorage.layout()._roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(account),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return AccessControlStorage.layout()._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
AccessControlStorage.layout()._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
AccessControlStorage.layout()._roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
AccessControlStorage.layout()._roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/access/IAccessControlEnumerableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
@gnus.ai/contracts-upgradeable-diamond/contracts/access/IAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
@gnus.ai/contracts-upgradeable-diamond/contracts/interfaces/IERC1155Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155.sol)
pragma solidity ^0.8.0;
import "../token/ERC1155/IERC1155Upgradeable.sol";
@gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
import { InitializableStorage } from "./InitializableStorage.sol";
/**
* @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 proxied contracts do not make use of 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.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* 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.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !InitializableStorage.layout()._initializing;
require(
(isTopLevelCall && InitializableStorage.layout()._initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && InitializableStorage.layout()._initialized == 1),
"Initializable: contract is already initialized"
);
InitializableStorage.layout()._initialized = 1;
if (isTopLevelCall) {
InitializableStorage.layout()._initializing = true;
}
_;
if (isTopLevelCall) {
InitializableStorage.layout()._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!InitializableStorage.layout()._initializing && InitializableStorage.layout()._initialized < version, "Initializable: contract is already initialized");
InitializableStorage.layout()._initialized = version;
InitializableStorage.layout()._initializing = true;
_;
InitializableStorage.layout()._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(InitializableStorage.layout()._initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!InitializableStorage.layout()._initializing, "Initializable: contract is initializing");
if (InitializableStorage.layout()._initialized < type(uint8).max) {
InitializableStorage.layout()._initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return InitializableStorage.layout()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return InitializableStorage.layout()._initializing;
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/InitializableStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Initializable } from "./Initializable.sol";
library InitializableStorage {
struct Layout {
/*
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 _initialized;
/*
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
bytes32 internal constant STORAGE_SLOT = keccak256('openzeppelin.contracts.storage.Initializable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/security/PausableStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { PausableUpgradeable } from "./PausableUpgradeable.sol";
library PausableStorage {
struct Layout {
bool _paused;
}
bytes32 internal constant STORAGE_SLOT = keccak256('openzeppelin.contracts.storage.Pausable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/security/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import { PausableStorage } from "./PausableStorage.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 {
using PausableStorage for PausableStorage.Layout;
/**
* @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);
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage.layout()._paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return PausableStorage.layout()._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage.layout()._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage.layout()._paused = false;
emit Unpaused(_msgSender());
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/security/ReentrancyGuardStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ReentrancyGuardUpgradeable } from "./ReentrancyGuardUpgradeable.sol";
library ReentrancyGuardStorage {
struct Layout {
uint256 _status;
}
bytes32 internal constant STORAGE_SLOT = keccak256('openzeppelin.contracts.storage.ReentrancyGuard');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import { ReentrancyGuardStorage } from "./ReentrancyGuardStorage.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
using ReentrancyGuardStorage for ReentrancyGuardStorage.Layout;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage.layout()._status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(ReentrancyGuardStorage.layout()._status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
ReentrancyGuardStorage.layout()._status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
ReentrancyGuardStorage.layout()._status = _NOT_ENTERED;
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC1155/IERC1155Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC20/IERC20Upgradeable.sol
// 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 IERC20Upgradeable {
/**
* @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);
}
@gnus.ai/contracts-upgradeable-diamond/contracts/utils/AddressUpgradeable.sol
// 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 AddressUpgradeable {
/**
* @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 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);
}
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
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 onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/utils/StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/utils/introspection/IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
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);
}
@gnus.ai/contracts-upgradeable-diamond/contracts/utils/math/MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
@gnus.ai/contracts-upgradeable-diamond/contracts/utils/structs/EnumerableSetUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
contracts/beanstalk/IBeanstalkUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface IBeanstalkUpgradeable {
event SetFertilizer(uint128 id, uint128 bpf);
function addFertilizerOwner(uint128 id, uint128 amount, uint256 minLP) external payable;
function balanceOfBatchFertilizer(
address[] memory accounts,
uint256[] memory ids
) external view returns (IFertilizer.Balance[] memory);
function balanceOfFertilized(
address account,
uint256[] memory ids
) external view returns (uint256 beans);
function balanceOfFertilizer(
address account,
uint256 id
) external view returns (IFertilizer.Balance memory);
function balanceOfUnfertilized(
address account,
uint256[] memory ids
) external view returns (uint256 beans);
function beansPerFertilizer() external view returns (uint128 bpf);
function claimFertilized(uint256[] memory ids, uint8 mode) external payable;
function getActiveFertilizer() external view returns (uint256);
function getCurrentHumidity() external view returns (uint128 humidity);
function getEndBpf() external view returns (uint128 endBpf);
function getFertilizer(uint128 id) external view returns (uint256);
function getFertilizers() external view returns (FertilizerFacet.Supply[] memory fertilizers);
function getFirst() external view returns (uint128);
function getHumidity(uint128 _s) external pure returns (uint128 humidity);
function getLast() external view returns (uint128);
function getNext(uint128 id) external view returns (uint128);
function isFertilizing() external view returns (bool);
function mintFertilizer(uint128 amount, uint256 minLP, uint8 mode) external payable;
function payFertilizer(address account, uint256 amount) external payable;
function remainingRecapitalization() external view returns (uint256);
function totalFertilizedBeans() external view returns (uint256 beans);
function totalFertilizerBeans() external view returns (uint256 beans);
function totalUnfertilizedBeans() external view returns (uint256 beans);
event AddUnripeToken(
address indexed unripeToken,
address indexed underlyingToken,
bytes32 merkleRoot
);
event ChangeUnderlying(address indexed token, int256 underlying);
event Chop(address indexed account, address indexed token, uint256 amount, uint256 underlying);
event Pick(address indexed account, address indexed token, uint256 amount);
function _getPenalizedUnderlying(
address unripeToken,
uint256 amount,
uint256 supply
) external view returns (uint256 redeem);
function addUnripeToken(
address unripeToken,
address underlyingToken,
bytes32 root
) external payable;
function balanceOfPenalizedUnderlying(
address unripeToken,
address account
) external view returns (uint256 underlying);
function balanceOfUnderlying(
address unripeToken,
address account
) external view returns (uint256 underlying);
function chop(
address unripeToken,
uint256 amount,
uint8 fromMode,
uint8 toMode
) external payable returns (uint256 underlyingAmount);
function getPenalizedUnderlying(
address unripeToken,
uint256 amount
) external view returns (uint256 redeem);
function getPenalty(address unripeToken) external view returns (uint256 penalty);
function getPercentPenalty(address unripeToken) external view returns (uint256 penalty);
function getRecapFundedPercent(address unripeToken) external view returns (uint256 percent);
function getRecapPaidPercent() external view returns (uint256 penalty);
function getTotalUnderlying(address unripeToken) external view returns (uint256 underlying);
function getUnderlying(
address unripeToken,
uint256 amount
) external view returns (uint256 redeem);
function getUnderlyingPerUnripeToken(
address unripeToken
) external view returns (uint256 underlyingPerToken);
function getUnderlyingToken(
address unripeToken
) external view returns (address underlyingToken);
function isUnripe(address unripeToken) external view returns (bool unripe);
function pick(
address token,
uint256 amount,
bytes32[] memory proof,
uint8 mode
) external payable;
function picked(address account, address token) external view returns (bool);
function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
function facetAddresses() external view returns (address[] memory facetAddresses_);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function claimOwnership() external;
function owner() external view returns (address owner_);
function ownerCandidate() external view returns (address ownerCandidate_);
function transferOwnership(address _newOwner) external;
event Pause(uint256 timestamp);
event Unpause(uint256 timestamp, uint256 timePassed);
function pause() external payable;
function unpause() external payable;
function addLiquidity(
address pool,
address registry,
uint256[] memory amounts,
uint256 minAmountOut,
uint8 fromMode,
uint8 toMode
) external payable;
function exchange(
address pool,
address registry,
address fromToken,
address toToken,
uint256 amountIn,
uint256 minAmountOut,
uint8 fromMode,
uint8 toMode
) external payable;
function exchangeUnderlying(
address pool,
address fromToken,
address toToken,
uint256 amountIn,
uint256 minAmountOut,
uint8 fromMode,
uint8 toMode
) external payable;
function removeLiquidity(
address pool,
address registry,
uint256 amountIn,
uint256[] memory minAmountsOut,
uint8 fromMode,
uint8 toMode
) external payable;
function removeLiquidityImbalance(
address pool,
address registry,
uint256[] memory amountsOut,
uint256 maxAmountIn,
uint8 fromMode,
uint8 toMode
) external payable;
function removeLiquidityOneToken(
address pool,
address registry,
address toToken,
uint256 amountIn,
uint256 minAmountOut,
uint8 fromMode,
uint8 toMode
) external payable;
function advancedPipe(
AdvancedPipeCall[] memory pipes,
uint256 value
) external payable returns (bytes[] memory results);
function etherPipe(
PipeCall memory p,
uint256 value
) external payable returns (bytes memory result);
function multiPipe(PipeCall[] memory pipes) external payable returns (bytes[] memory results);
function pipe(PipeCall memory p) external payable returns (bytes memory result);
function readPipe(PipeCall memory p) external view returns (bytes memory result);
function advancedFarm(
AdvancedFarmCall[] memory data
) external payable returns (bytes[] memory results);
function farm(bytes[] memory data) external payable returns (bytes[] memory results);
event InternalBalanceChanged(address indexed user, address indexed token, int256 delta);
event TokenApproval(
address indexed owner,
address indexed spender,
address token,
uint256 amount
);
function approveToken(address spender, address token, uint256 amount) external payable;
function decreaseTokenAllowance(
address spender,
address token,
uint256 subtractedValue
) external returns (bool);
function getAllBalance(
address account,
address token
) external view returns (Storage.Rain memory b);
function getAllBalances(
address account,
address[] memory tokens
) external view returns (Storage.Rain[] memory balances);
function getBalance(address account, address token) external view returns (uint256 balance);
function getBalances(
address account,
address[] memory tokens
) external view returns (uint256[] memory balances);
function getExternalBalance(
address account,
address token
) external view returns (uint256 balance);
function getExternalBalances(
address account,
address[] memory tokens
) external view returns (uint256[] memory balances);
function getInternalBalance(
address account,
address token
) external view returns (uint256 balance);
function getInternalBalances(
address account,
address[] memory tokens
) external view returns (uint256[] memory balances);
function increaseTokenAllowance(
address spender,
address token,
uint256 addedValue
) external returns (bool);
function permitToken(
address owner,
address spender,
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
function tokenAllowance(
address account,
address spender,
address token
) external view returns (uint256);
function tokenPermitDomainSeparator() external view returns (bytes32);
function tokenPermitNonces(address owner) external view returns (uint256);
function transferInternalTokenFrom(
address token,
address sender,
address recipient,
uint256 amount,
uint8 toMode
) external payable;
function transferToken(
address token,
address recipient,
uint256 amount,
uint8 fromMode,
uint8 toMode
) external payable;
function unwrapEth(uint256 amount, uint8 mode) external payable;
function wrapEth(uint256 amount, uint8 mode) external payable;
function batchTransferERC1155(
address token,
address to,
uint256[] memory ids,
uint256[] memory values
) external payable;
function permitERC20(
address token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
function permitERC721(
address token,
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory sig
) external payable;
function transferERC1155(address token, address to, uint256 id, uint256 value) external payable;
function transferERC721(address token, address to, uint256 id) external payable;
event Harvest(address indexed account, uint256[] plots, uint256 beans);
event PodListingCancelled(address indexed account, uint256 index);
event Sow(address indexed account, uint256 index, uint256 beans, uint256 pods);
function harvest(uint256[] memory plots, uint8 mode) external payable;
function harvestableIndex() external view returns (uint256);
function maxTemperature() external view returns (uint256);
function plot(address account, uint256 index) external view returns (uint256);
function podIndex() external view returns (uint256);
function remainingPods() external view returns (uint256);
function sow(
uint256 beans,
uint256 minTemperature,
uint8 mode
) external payable returns (uint256 pods);
function sowWithMin(
uint256 beans,
uint256 minTemperature,
uint256 minSoil,
uint8 mode
) external payable returns (uint256 pods);
function temperature() external view returns (uint256);
function totalHarvestable() external view returns (uint256);
function totalHarvested() external view returns (uint256);
function totalPods() external view returns (uint256);
function totalSoil() external view returns (uint256);
function totalUnharvestable() external view returns (uint256);
function yield() external view returns (uint32);
event CompleteFundraiser(uint32 indexed id);
event CreateFundraiser(uint32 indexed id, address payee, address token, uint256 amount);
event FundFundraiser(address indexed account, uint32 indexed id, uint256 amount);
function createFundraiser(address payee, address token, uint256 amount) external payable;
function fund(uint32 id, uint256 amount, uint8 mode) external payable returns (uint256);
function fundingToken(uint32 id) external view returns (address);
function fundraiser(uint32 id) external view returns (Storage.Fundraiser memory);
function numberOfFundraisers() external view returns (uint32);
function remainingFunding(uint32 id) external view returns (uint256);
function totalFunding(uint32 id) external view returns (uint256);
event PlotTransfer(address indexed from, address indexed to, uint256 indexed id, uint256 pods);
event PodApproval(address indexed owner, address indexed spender, uint256 pods);
event PodListingCreated(
address indexed account,
uint256 index,
uint256 start,
uint256 amount,
uint24 pricePerPod,
uint256 maxHarvestableIndex,
uint256 minFillAmount,
bytes pricingFunction,
uint8 mode,
uint8 pricingType
);
event PodListingFilled(
address indexed from,
address indexed to,
uint256 index,
uint256 start,
uint256 amount,
uint256 costInBeans
);
event PodOrderCancelled(address indexed account, bytes32 id);
event PodOrderCreated(
address indexed account,
bytes32 id,
uint256 amount,
uint24 pricePerPod,
uint256 maxPlaceInLine,
uint256 minFillAmount,
bytes pricingFunction,
uint8 priceType
);
event PodOrderFilled(
address indexed from,
address indexed to,
bytes32 id,
uint256 index,
uint256 start,
uint256 amount,
uint256 costInBeans
);
function allowancePods(address owner, address spender) external view returns (uint256);
function approvePods(address spender, uint256 amount) external payable;
function cancelPodListing(uint256 index) external payable;
function cancelPodOrder(
uint24 pricePerPod,
uint256 maxPlaceInLine,
uint256 minFillAmount,
uint8 mode
) external payable;
function cancelPodOrderV2(
uint256 maxPlaceInLine,
uint256 minFillAmount,
bytes memory pricingFunction,
uint8 mode
) external payable;
function createPodListing(
uint256 index,
uint256 start,
uint256 amount,
uint24 pricePerPod,
uint256 maxHarvestableIndex,
uint256 minFillAmount,
uint8 mode
) external payable;
function createPodListingV2(
uint256 index,
uint256 start,
uint256 amount,
uint256 maxHarvestableIndex,
uint256 minFillAmount,
bytes memory pricingFunction,
uint8 mode
) external payable;
function createPodOrder(
uint256 beanAmount,
uint24 pricePerPod,
uint256 maxPlaceInLine,
uint256 minFillAmount,
uint8 mode
) external payable returns (bytes32 id);
function createPodOrderV2(
uint256 beanAmount,
uint256 maxPlaceInLine,
uint256 minFillAmount,
bytes memory pricingFunction,
uint8 mode
) external payable returns (bytes32 id);
function fillPodListing(
Listing.PodListing memory l,
uint256 beanAmount,
uint8 mode
) external payable;
function fillPodListingV2(
Listing.PodListing memory l,
uint256 beanAmount,
bytes memory pricingFunction,
uint8 mode
) external payable;
function fillPodOrder(
Order.PodOrder memory o,
uint256 index,
uint256 start,
uint256 amount,
uint8 mode
) external payable;
function fillPodOrderV2(
Order.PodOrder memory o,
uint256 index,
uint256 start,
uint256 amount,
bytes memory pricingFunction,
uint8 mode
) external payable;
function getAmountBeansToFillOrderV2(
uint256 placeInLine,
uint256 amountPodsFromOrder,
bytes memory pricingFunction
) external pure returns (uint256 beanAmount);
function getAmountPodsFromFillListingV2(
uint256 placeInLine,
uint256 podListingAmount,
uint256 fillBeanAmount,
bytes memory pricingFunction
) external pure returns (uint256 amount);
function podListing(uint256 index) external view returns (bytes32);
function podOrder(
address account,
uint24 pricePerPod,
uint256 maxPlaceInLine,
uint256 minFillAmount
) external view returns (uint256);
function podOrderById(bytes32 id) external view returns (uint256);
function podOrderV2(
address account,
uint256 maxPlaceInLine,
uint256 minFillAmount,
bytes memory pricingFunction
) external view returns (uint256);
function transferPlot(
address sender,
address recipient,
uint256 id,
uint256 start,
uint256 end
) external payable;
function bdv(address token, uint256 amount) external view returns (uint256);
function beanToBDV(uint256 amount) external pure returns (uint256);
function curveToBDV(uint256 amount) external view returns (uint256);
function unripeBeanToBDV(uint256 amount) external view returns (uint256);
function unripeLPToBDV(uint256 amount) external view returns (uint256);
event Convert(
address indexed account,
address fromToken,
address toToken,
uint256 fromAmount,
uint256 toAmount
);
event RemoveDeposits(
address indexed account,
address indexed token,
uint32[] seasons,
uint256[] amounts,
uint256 amount
);
function convert(
bytes memory convertData,
uint32[] memory crates,
uint256[] memory amounts
)
external
payable
returns (
uint32 toSeason,
uint256 fromAmount,
uint256 toAmount,
uint256 fromBdv,
uint256 toBdv
);
function getAmountOut(
address tokenIn,
address tokenOut,
uint256 amountIn
) external view returns (uint256 amountOut);
function getMaxAmountIn(
address tokenIn,
address tokenOut
) external view returns (uint256 amountIn);
event AddDeposit(
address indexed account,
address indexed token,
uint32 season,
uint256 amount,
uint256 bdv
);
event AddWithdrawal(
address indexed account,
address indexed token,
uint32 season,
uint256 amount
);
event ClaimPlenty(address indexed account, uint256 plenty);
event DepositApproval(
address indexed owner,
address indexed spender,
address token,
uint256 amount
);
event Plant(address indexed account, uint256 beans);
event RemoveDeposit(
address indexed account,
address indexed token,
uint32 season,
uint256 amount
);
event RemoveWithdrawal(
address indexed account,
address indexed token,
uint32 season,
uint256 amount
);
event RemoveWithdrawals(
address indexed account,
address indexed token,
uint32[] seasons,
uint256 amount
);
event SeedsBalanceChanged(address indexed account, int256 delta);
event StalkBalanceChanged(address indexed account, int256 delta, int256 deltaRoots);
function approveDeposit(address spender, address token, uint256 amount) external payable;
function balanceOfEarnedBeans(address account) external view returns (uint256 beans);
function balanceOfEarnedSeeds(address account) external view returns (uint256);
function balanceOfEarnedStalk(address account) external view returns (uint256);
function balanceOfGrownStalk(address account) external view returns (uint256);
function balanceOfPlenty(address account) external view returns (uint256 plenty);
function balanceOfRainRoots(address account) external view returns (uint256);
function balanceOfRoots(address account) external view returns (uint256);
function balanceOfSeeds(address account) external view returns (uint256);
function balanceOfSop(
address account
) external view returns (SiloExit.AccountSeasonOfPlenty memory sop);
function balanceOfStalk(address account) external view returns (uint256);
function claimPlenty() external payable;
function claimWithdrawal(address token, uint32 season, uint8 mode) external payable;
function claimWithdrawals(address token, uint32[] memory seasons, uint8 mode) external payable;
function decreaseDepositAllowance(
address spender,
address token,
uint256 subtractedValue
) external returns (bool);
function deposit(address token, uint256 amount, uint8 mode) external payable;
function depositAllowance(
address account,
address spender,
address token
) external view returns (uint256);
function depositPermitDomainSeparator() external view returns (bytes32);
function depositPermitNonces(address owner) external view returns (uint256);
function enrootDeposit(address token, uint32 _season, uint256 amount) external;
function enrootDeposits(
address token,
uint32[] memory seasons,
uint256[] memory amounts
) external;
function getDeposit(
address account,
address token,
uint32 season
) external view returns (uint256, uint256);
function getTotalDeposited(address token) external view returns (uint256);
function getTotalWithdrawn(address token) external view returns (uint256);
function getWithdrawal(
address account,
address token,
uint32 season
) external view returns (uint256);
function increaseDepositAllowance(
address spender,
address token,
uint256 addedValue
) external returns (bool);
function lastSeasonOfPlenty() external view returns (uint32);
function lastUpdate(address account) external view returns (uint32);
function permitDeposit(
address owner,
address spender,
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
function permitDeposits(
address owner,
address spender,
address[] memory tokens,
uint256[] memory values,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
function plant() external payable returns (uint256 beans);
function tokenSettings(address token) external view returns (Storage.SiloSettings memory);
function totalEarnedBeans() external view returns (uint256);
function totalRoots() external view returns (uint256);
function totalSeeds() external view returns (uint256);
function totalStalk() external view returns (uint256);
function transferDeposit(
address sender,
address recipient,
address token,
uint32 season,
uint256 amount
) external payable returns (uint256 bdv);
function transferDeposits(
address sender,
address recipient,
address token,
uint32[] memory seasons,
uint256[] memory amounts
) external payable returns (uint256[] memory bdvs);
function update(address account) external payable;
function withdrawDeposit(address token, uint32 season, uint256 amount) external payable;
function withdrawDeposits(
address token,
uint32[] memory seasons,
uint256[] memory amounts
) external payable;
function withdrawFreeze() external view returns (uint8);
event DewhitelistToken(address indexed token);
event WhitelistToken(address indexed token, bytes4 selector, uint256 seeds, uint256 stalk);
function dewhitelistToken(address token) external payable;
function whitelistToken(
address token,
bytes4 selector,
uint32 stalk,
uint32 seeds
) external payable;
event Incentivization(address indexed account, uint256 beans);
event Reward(uint32 indexed season, uint256 toField, uint256 toSilo, uint256 toFertilizer);
event SeasonOfPlenty(uint256 indexed season, uint256 amount, uint256 toField);
event Soil(uint32 indexed season, uint256 soil);
event Sunrise(uint256 indexed season);
event WeatherChange(uint256 indexed season, uint256 caseId, int8 change);
function abovePeg() external view returns (bool);
function gm(address account, uint8 mode) external payable returns (uint256);
function paused() external view returns (bool);
function plentyPerRoot(uint32 season) external view returns (uint256);
function poolDeltaB(address pool) external view returns (int256);
function rain() external view returns (Storage.Rain memory);
function season() external view returns (uint32);
function seasonTime() external view returns (uint32);
function sunrise() external payable returns (uint256);
function sunriseBlock() external view returns (uint32);
function time() external view returns (Storage.Season memory);
function totalDeltaB() external view returns (int256 deltaB);
function weather() external view returns (Storage.Weather memory);
}
struct AdvancedPipeCall {
address target;
bytes callData;
bytes clipboard;
}
struct PipeCall {
address target;
bytes data;
}
struct AdvancedFarmCall {
bytes callData;
bytes clipboard;
}
interface IFertilizer {
struct Balance {
uint128 amount;
uint128 lastBpf;
}
}
interface FertilizerFacet {
struct Supply {
uint128 endBpf;
uint256 supply;
}
}
interface TokenFacet {
struct Rain {
uint256 deprecated;
uint256 pods;
uint256 roots;
}
}
interface Storage {
struct Rain {
uint256 deprecated;
uint256 pods;
uint256 roots;
}
struct Fundraiser {
address payee;
address token;
uint256 total;
uint256 remaining;
uint256 start;
}
struct SiloSettings {
bytes4 selector;
uint32 seeds;
uint32 stalk;
}
struct Season {
uint32 current;
uint32 lastSop;
uint8 withdrawSeasons;
uint32 lastSopSeason;
uint32 rainStart;
bool raining;
bool fertilizing;
uint32 sunriseBlock;
bool abovePeg;
uint256 start;
uint256 period;
uint256 timestamp;
}
struct Weather {
uint256[2] deprecated;
uint128 lastDSoil;
uint32 lastSowTime;
uint32 thisSowTime;
uint32 t;
}
}
interface Listing {
struct PodListing {
address account;
uint256 index;
uint256 start;
uint256 amount;
uint24 pricePerPod;
uint256 maxHarvestableIndex;
uint256 minFillAmount;
uint8 mode;
}
}
interface Order {
struct PodOrder {
address account;
uint24 pricePerPod;
uint256 maxPlaceInLine;
uint256 minFillAmount;
}
}
interface SiloExit {
struct AccountSeasonOfPlenty {
uint32 lastRain;
uint32 lastSop;
uint256 roots;
uint256 plentyPerRoot;
uint256 plenty;
}
}
contracts/core/TrancheBondStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
enum TrancheLevel {
A,
B,
Z
}
enum UnderlyingAssetType {
PODS,
ERC20
}
struct TrancheMetadata {
// farmer's market value for tranche. it is same as totalSupply when minting
uint256 fmv;
// fmv claimed after tranche is mature
uint256 claimedFMV;
}
struct UnderlyingAssetMetadata {
// zero address if underlying asset is pods
address contractAddress;
UnderlyingAssetType assetType;
uint48 maturityDate;
// total amount of deposited underlying asset
// sum of pods for all deposited podlines if underlying asset is pods
uint256 totalDeposited;
// calculated FMV
uint256 totalFMV;
}
/// @notice stores group of podlines that user deposited
struct DepositPods {
// array of indexes for each plot
uint256[] podIndexes;
// array of pods for each plot
uint256[] amounts;
// array of fmves for each plot
uint256[] fmvs;
// FMV Farmer Market Value in USD
// uint256 totalFMV;
// represent divided podline by each tranche level after transfer some pods
// 1,3 - startIndex and Offsets for tranche A, 2,4 - for tranche B, 3,5 - for tranche Z
uint128[6] startIndexAndOffsets;
}
library TrancheBondStorage {
struct Layout {
// Stores all pods that users deposited, mapping from podline index to pods amount
// mapping(uint256 => uint256) depositedPlots;
// Pods group deposited to create tranche, mapping from deposit id to pods groups
mapping(uint256 => DepositPods) depositedPods;
// Mapping from deposit id to underlying asset metadata
mapping(uint256 => UnderlyingAssetMetadata) underlyingAssets;
// Mapping from tranch index to A,B,Z tranches. the total number of tranches is always 4 times the number of deposits
mapping(uint256 => TrancheMetadata) tranches;
// total number of deposits, also it is used as a latest id for storage to store deposited assets
uint256 curDepositCount;
uint48[] periods;
}
bytes32 internal constant STORAGE_SLOT = keccak256("irrigation.contracts.storage.TrancheBond");
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
contracts/core/WaterCommonStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {IBeanstalkUpgradeable} from "../beanstalk/IBeanstalkUpgradeable.sol";
import {IERC1155Upgradeable} from "@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC1155/IERC1155Upgradeable.sol";
library WaterCommonStorage {
struct Layout {
// Beanstalk protocol contract
IBeanstalkUpgradeable beanstalk;
// fertilizer token contract
IERC1155Upgradeable fertilizer;
}
bytes32 internal constant STORAGE_SLOT = keccak256("irrigation.contracts.storage.WaterCommon");
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
contracts/core/WaterTowerStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {IERC20Upgradeable} from "@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC20/IERC20Upgradeable.sol";
/// @notice User Setting Info
struct UserInfo {
bool isAutoIrrigate;
// last poolIndex that user interact
uint256 lastPoolIndex;
// total claimable reward of user
uint256 pending;
// reward rate in this month = sum (block time * amount)
uint256 rewardRate;
// deposited water amount
uint256 amount;
}
struct PoolInfo {
// sum of all user reward rate in this month
uint256 totalRewardRate;
uint256 monthlyRewards;
uint128 endTime;
uint128 startTime;
}
struct UserPoolHistory {
// total user reward rate = sum(staked time * staked amount)
uint256 rewardRate;
// average water amount stored by user in each pool
uint256 averageStored;
// reserve field
uint256 reserve;
}
struct LockedUserInfo {
// fee level index => total auction count for the fee level
uint32[8] lockedCounts;
uint256 lockedAmount;
}
library WaterTowerStorage {
struct Layout {
// total ether reward received from other markets
uint256 totalRewards;
// current pool index
uint256 curPoolIndex;
// total water deposit amount
uint256 totalDeposits;
// water amount sent as irrigate bonus
uint256 totalBonus;
// pool info per month
mapping(uint256 => PoolInfo) pools;
// deposit amount, pending reward, and setting for user
mapping(address => UserInfo) users;
/// @dev config variables
// bonus percent for irrigator
uint256 irrigateBonusRate;
// Middle asset for irrigating ether reward
address middleAssetForIrrigate;
// added upgrade 002
// user => locked user info
mapping(address => LockedUserInfo) lockedUsers;
}
bytes32 internal constant STORAGE_SLOT = keccak256("irrigation.contracts.storage.WaterTower");
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function curPool() internal view returns (PoolInfo storage) {
return layout().pools[layout().curPoolIndex];
}
function userInfo(address user) internal view returns (UserInfo storage) {
return layout().users[user];
}
}
contracts/interfaces/IBeanstalkPrice.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface IBeanstalkPrice {
struct Pool {
address pool;
address[2] tokens;
uint256[2] balances;
uint256 price;
uint256 liquidity;
int256 deltaB;
// uint256 lpSupply;
uint256 lpUsd;
uint256 lpBdv;
}
struct Prices {
uint256 price;
uint256 liquidity;
int deltaB;
Pool[] ps;
}
function price() external view returns (Prices memory p);
}
contracts/interfaces/IDiamondCut.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/
interface IDiamondCut {
enum FacetCutAction {Add, Replace, Remove}
// Add=0, Replace=1, Remove=2
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}
contracts/interfaces/IERC1155WhitelistUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface IERC1155WhitelistUpgradeable {
function mint(address to, uint256 id, uint256 amount, bytes memory data) external;
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) external;
/// @dev burn total amount that user hold
/// @param to user address
/// @param tokenId token id
function burnTotalAmount(address to, uint256 tokenId) external;
}
interface IERC1155BurnableUpgradeable{
function burn(address account, uint256 id, uint256 value) external;
}contracts/interfaces/IPodsOracleUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
interface IPodsOracleUpgradeable {
///@dev get virtual price of a plot with latest podIndex and harvestableIndex
function latestPriceOfPods(uint256 placeInLine, uint256 pods) external returns (uint256);
/// getter for price of a plot at any podIndex
/**
* @notice Get price for any pods to 1e18
* @param placeInLine with 1e6 decimals
* @param pods with 1e6 decimals
* @return price pods price
*/
function priceOfPods(
uint256 placeInLine,
uint256 pods,
uint256 podIndex,
uint256 harvestableIndex
) external returns (uint256);
}
contracts/libraries/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
library Constants {
/// Addresses
address internal constant CURVE_ROUTER = 0x99a58482BD75cbab83b27EC03CA68fF489b5788f;
address internal constant BEAN = 0xBEA0000029AD1c77D3d5D23Ba2D8893dB9d1Efab;
address internal constant ETHER = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address internal constant TRI_CRYPTO_POOL = 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46;
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address internal constant CURVE_BEAN_METAPOOL = 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49;
address internal constant BEANSTALK_PRICE = 0xb01CE0008CaD90104651d6A84b6B11e182a9B62A;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address internal constant ZERO = 0x0000000000000000000000000000000000000000;
address internal constant BEANSTALK = 0xC1E088fC1323b20BCBee9bd1B9fC9546db5624C5;
address internal constant FERTILIZER = 0x402c84De2Ce49aF88f5e2eF3710ff89bFED36cB6;
/// bean - weth pool
address internal constant BEAN_ETH_WELL = 0xBEA0e11282e2bB5893bEcE110cF199501e872bAd;
/// @notice time out to get price from chainlink
/// @dev should update before deploying on mainnet
uint256 internal constant GRACE_PERIOD_TIME = 6 days;
/// underlying decimals
uint256 internal constant D18 = 1e18;
// tranche nft is fractionalized with decimals 6
uint8 internal constant TRANCHE_DECIMALS = 6;
uint8 internal constant WATER_DECIMALS = 18;
bytes internal constant EMPTY = "";
/// function selectors
bytes4 internal constant ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
bytes4 internal constant ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
}
contracts/libraries/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/// @title Contains math functions
library FullMath {
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = (a * b) / denominator;
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
function mulDivRoundingUp128(
uint128 a,
uint128 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = (uint256(a) * uint256(b)) / denominator;
if (mulmod(uint256(a), uint256(b), denominator) > 0) {
// require(result < type(uint256).max); // no overflow for uint128
result++;
}
}
}
contracts/libraries/LibDiamond.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/
import { IDiamondCut } from "../interfaces/IDiamondCut.sol";
// Remember to add the loupe functions from DiamondLoupeFacet to the diamond.
// The loupe functions are required by the EIP2535 Diamonds standard
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct DiamondStorage {
// maps function selectors to the facets that execute the functions.
// and maps the selectors to their position in the selectorSlots array.
// func selector => address facet, selector position
mapping(bytes4 => bytes32) facets;
// array of slots of function selectors.
// each slot holds 8 function selectors.
mapping(uint256 => bytes32) selectorSlots;
// The number of function selectors in selectorSlots
uint16 selectorCount;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() internal view {
require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
}
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff));
bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224));
// Internal function version of diamondCut
// This code is almost the same as the external diamondCut,
// except it is using 'Facet[] memory _diamondCut' instead of
// 'Facet[] calldata _diamondCut'.
// The code is duplicated to prevent copying calldata to memory which
// causes an error for a two dimensional array.
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
DiamondStorage storage ds = diamondStorage();
uint256 originalSelectorCount = ds.selectorCount;
uint256 selectorCount = originalSelectorCount;
bytes32 selectorSlot;
// Check if last selector slot is not full
// "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8"
if (selectorCount & 7 > 0) {
// get last selectorSlot
// "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8"
selectorSlot = ds.selectorSlots[selectorCount >> 3];
}
// loop through diamond cut
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
(selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors(
selectorCount,
selectorSlot,
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].action,
_diamondCut[facetIndex].functionSelectors
);
}
if (selectorCount != originalSelectorCount) {
ds.selectorCount = uint16(selectorCount);
}
// If last selector slot is not full
// "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8"
if (selectorCount & 7 > 0) {
// "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8"
ds.selectorSlots[selectorCount >> 3] = selectorSlot;
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addReplaceRemoveFacetSelectors(
uint256 _selectorCount,
bytes32 _selectorSlot,
address _newFacetAddress,
IDiamondCut.FacetCutAction _action,
bytes4[] memory _selectors
) internal returns (uint256, bytes32) {
DiamondStorage storage ds = diamondStorage();
require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
if (_action == IDiamondCut.FacetCutAction.Add) {
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists");
// add facet for selector
ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount);
// "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8"
// " << 5 is the same as multiplying by 32 ( * 32)
uint256 selectorInSlotPosition = (_selectorCount & 7) << 5;
// clear selector position in slot and add selector
_selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition);
// if slot is full then write it to storage
if (selectorInSlotPosition == 224) {
// "_selectorSlot >> 3" is a gas efficient division by 8 "_selectorSlot / 8"
ds.selectorSlots[_selectorCount >> 3] = _selectorSlot;
_selectorSlot = 0;
}
_selectorCount++;
}
} else if (_action == IDiamondCut.FacetCutAction.Replace) {
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
address oldFacetAddress = address(bytes20(oldFacet));
// only useful if immutable functions exist
require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function");
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function");
require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist");
// replace old facet address
ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress);
}
} else if (_action == IDiamondCut.FacetCutAction.Remove) {
require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
// "_selectorCount >> 3" is a gas efficient division by 8 "_selectorCount / 8"
uint256 selectorSlotCount = _selectorCount >> 3;
// "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8"
uint256 selectorInSlotIndex = _selectorCount & 7;
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
if (_selectorSlot == 0) {
// get last selectorSlot
selectorSlotCount--;
_selectorSlot = ds.selectorSlots[selectorSlotCount];
selectorInSlotIndex = 7;
} else {
selectorInSlotIndex--;
}
bytes4 lastSelector;
uint256 oldSelectorsSlotCount;
uint256 oldSelectorInSlotPosition;
// adding a block here prevents stack too deep error
{
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
// only useful if immutable functions exist
require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function");
// replace selector with last selector in ds.facets
// gets the last selector
// " << 5 is the same as multiplying by 32 ( * 32)
lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex << 5));
if (lastSelector != selector) {
// update last selector slot position info
ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]);
}
delete ds.facets[selector];
uint256 oldSelectorCount = uint16(uint256(oldFacet));
// "oldSelectorCount >> 3" is a gas efficient division by 8 "oldSelectorCount / 8"
oldSelectorsSlotCount = oldSelectorCount >> 3;
// "oldSelectorCount & 7" is a gas efficient modulo by eight "oldSelectorCount % 8"
// " << 5 is the same as multiplying by 32 ( * 32)
oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5;
}
if (oldSelectorsSlotCount != selectorSlotCount) {
bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount];
// clears the selector we are deleting and puts the last selector in its place.
oldSelectorSlot =
(oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
(bytes32(lastSelector) >> oldSelectorInSlotPosition);
// update storage with the modified slot
ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot;
} else {
// clears the selector we are deleting and puts the last selector in its place.
_selectorSlot =
(_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
(bytes32(lastSelector) >> oldSelectorInSlotPosition);
}
if (selectorInSlotIndex == 0) {
delete ds.selectorSlots[selectorSlotCount];
_selectorSlot = 0;
}
}
_selectorCount = selectorSlotCount * 8 + selectorInSlotIndex;
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
return (_selectorCount, _selectorSlot);
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
return;
}
enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up error
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(error)
revert(add(32, error), returndata_size)
}
} else {
revert("InitializationFunctionReverted(address, bytes)");
}
}
}
function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize > 0, _errorMessage);
}
}
contracts/libraries/PodTransferHelper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
// helper methods for interacting with plots on beanstalk
library PodTransferHelper {
/// @dev get start position and pods amount for sub plot by FMV
function getPlotSplittedByFMV(
uint256 originalPods,
uint256 plotFMV,
uint256 offsetFMV,
uint256 requiredFMV
) internal pure returns (uint256 start, uint256 amount, uint256 reserveFMV) {
uint256 tranferFMV;
///@dev call when always offsetFMV <= plotFMV
uint256 availableFMV = plotFMV - offsetFMV;
if (requiredFMV >= availableFMV) {
tranferFMV = availableFMV;
reserveFMV = requiredFMV - tranferFMV;
if (offsetFMV == 0) {
/// @dev in that case, tranfer all pods in the plot and avoid unnecessary division by 1
// ignore this for gas optimization
// start = 0;
amount = originalPods;
}
} else {
tranferFMV = requiredFMV;
// ignore this for gas optimization
// reserveFMV = 0;
}
if (amount == 0) {
if (offsetFMV != 0) start = (originalPods * offsetFMV) / plotFMV;
amount = (originalPods * tranferFMV) / plotFMV;
}
}
/// @dev plots can be splitted and we get correct offset of sub plot based on historical split info by senior tranches
function getPlotWithOffset(
uint256 plotIndex, //index of plots array, not podIndex
uint256 originalPods,
uint256 plotFMV,
uint256 offsetFMV,
uint256 requiredFMV,
uint256 level,
uint128[6] memory startOffsets
) internal pure returns (uint256 offset, uint256 start, uint256 amount, uint256 reserveFMV) {
(start, amount, reserveFMV) = getPlotSplittedByFMV(originalPods, plotFMV, offsetFMV, requiredFMV);
uint256 _level = level;
// check sub plots splitted by senior tranche level
// if the sub plot is located in same plot, we start from the plot offset
while (true) {
uint256 _offset = startOffsets[_level + 3];
uint256 _lastPlotIndex = startOffsets[_level];
if (_offset != 0 && _lastPlotIndex == plotIndex) {
offset = _offset;
if (_level == level) start = 0;
else {
unchecked {
start -= _offset;
}
}
break;
}
if (_level == 0) break;
else {
unchecked {
--_level;
}
}
}
}
}
contracts/utils/EIP2535Initializable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "@gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/Initializable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/InitializableStorage.sol";
import "../libraries/LibDiamond.sol";
abstract contract EIP2535Initializable is Initializable {
// override Initializable::initializer modifier
modifier EIP2535Initializer() {
require(!InitializableStorage.layout()._initializing && InitializableStorage.layout()._initialized < 1, "Initializable: contract is already initialized");
InitializableStorage.layout()._initialized = 1;
InitializableStorage.layout()._initializing = true;
_;
// multiple facet contracts needed initialization on deployment
InitializableStorage.layout()._initialized = 0;
InitializableStorage.layout()._initializing = false;
}
modifier EIP2535Reinitializer(uint8 version) {
require(!InitializableStorage.layout()._initializing && InitializableStorage.layout()._initialized < version, "Initializable: contract is already initialized");
InitializableStorage.layout()._initialized = version;
InitializableStorage.layout()._initializing = true;
_;
// multiple facet contracts needed re-initialization on ugrades for instance
InitializableStorage.layout()._initialized = 0;
InitializableStorage.layout()._initializing = false;
}
}
contracts/utils/IrrigationAccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "@gnus.ai/contracts-upgradeable-diamond/contracts/access/AccessControlEnumerableUpgradeable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/Initializable.sol";
import "../libraries/LibDiamond.sol";
abstract contract IrrigationAccessControl is Initializable, AccessControlEnumerableUpgradeable {
bytes32 public constant AUTO_IRRIGATE_ADMIN_ROLE = keccak256("AUTO_IRRIGATE_ADMIN_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
function __IrrigationAccessControl_init() internal onlyInitializing onlySuperAdminRole {
__AccessControlEnumerable_init_unchained();
__IrrigationAccessControl_init_unchained();
}
function __IrrigationAccessControl_init_unchained() internal onlyInitializing {
address superAdmin = _msgSender();
// this sets the default admin for every ROLE created
_grantRole(DEFAULT_ADMIN_ROLE, superAdmin);
// set SuperAdmin as ADMIN_ROLE also, no need to setRoleAdmin() as it will use DEFAULT_ADMIN_ROLE
_grantRole(ADMIN_ROLE, superAdmin);
// all non-superAdmin can also grant/revoke roles of IRRIGATION_ADMIN_ROLE
_setRoleAdmin(AUTO_IRRIGATE_ADMIN_ROLE, ADMIN_ROLE);
// make superAdmin have the IRRIGATION_ADMIN_ROLE too.
_grantRole(AUTO_IRRIGATE_ADMIN_ROLE, superAdmin);
}
function grantRole(
bytes32 role,
address account
) public override(IAccessControlUpgradeable, AccessControlUpgradeable) {
// this checks the admin role that can do this.
super.grantRole(role, account);
}
// renounce role is only for yourself, so no modifier should have been added to this
function renounceRole(
bytes32 role,
address account
) public override(IAccessControlUpgradeable, AccessControlUpgradeable) {
require(
LibDiamond.diamondStorage().contractOwner != account,
"Cannot renounce superAdmin from any Roles"
);
super.renounceRole(role, account);
}
function revokeRole(
bytes32 role,
address account
) public override(IAccessControlUpgradeable, AccessControlUpgradeable) {
require(
LibDiamond.diamondStorage().contractOwner != account,
"Cannot revoke superAdmin from any Roles"
);
// this checks that only the admin(s) of the Role can revoke a Role
super.revokeRole(role, account);
}
modifier onlySuperAdminRole() {
require(LibDiamond.diamondStorage().contractOwner == msg.sender, "Only SuperAdmin allowed");
_;
}
modifier onlyAdminRole() {
require(hasRole(ADMIN_ROLE, msg.sender), "Account doesn't have admin role");
_;
}
modifier onlyAutoIrrigateAdminRole() {
require(
hasRole(AUTO_IRRIGATE_ADMIN_ROLE, msg.sender),
"Account doesn't have auto irrigate admin role"
);
_;
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "none"
},
"libraries": {},
"optimizer": {
"runs": 1000,
"enabled": true
},
"evmVersion": "london",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.