Verified contractPartialAGPL-3.0-only
CVStreamingFacet
Address0x82eb6af646175a203b8b78c1a2d2b59dac73c84b
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.23
- Same code
Only this contract
Details
- Compiler
- solc 0.8.23+commit.f704f362
- Language
- solidity
- Optimization
- Yes, 0 runs
- EVM version
- shanghai
- License
- AGPL-3.0-only
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,383,282
- Creation transaction
- 0xa797a52407…8a6473f015
- Libraries
- pkg/contracts/src/CVStrategy/facets/CVStreamingFacet.sol:ConvictionsUtils0xf7ce…abfb12
129 files
The source code is large: one file is shown at a time. Choose a file in the list.
- pkg/contracts/src/CVStrategy/facets/CVStreamingFacet.solmain19.08 KB
- lib/allo-v2/contracts/core/interfaces/IAllo.sol17.73 KB
- lib/allo-v2/contracts/core/interfaces/IRegistry.sol12.44 KB
- lib/allo-v2/contracts/core/interfaces/IStrategy.sol10.67 KB
- lib/allo-v2/contracts/core/libraries/Clone.sol5.03 KB
- lib/allo-v2/contracts/core/libraries/Errors.sol7.31 KB
- lib/allo-v2/contracts/core/libraries/Metadata.sol4.58 KB
- lib/allo-v2/contracts/core/libraries/Native.sol4.49 KB
- lib/allo-v2/contracts/core/libraries/Transfer.sol7.51 KB
- lib/allo-v2/contracts/strategies/BaseStrategy.sol19.47 KB
- lib/allo-v2/lib/solady/src/utils/SafeTransferLib.sol19.02 KB
- lib/forge-std/src/Vm.sol85.41 KB
- lib/forge-std/src/console.sol66.69 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.87 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/IAccessControlUpgradeable.sol2.93 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol3.17 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/ClonesUpgradeable.sol4.04 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol6.64 KB
- lib/openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol3.68 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol9.38 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.48 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/StringsUpgradeable.sol2.85 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.54 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/IERC165Upgradeable.sol864 B
- lib/openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol12.8 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/math/SignedMathUpgradeable.sol1.27 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol2.92 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol2.62 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol667 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol738 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol879 B
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol1.29 KB
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol6.04 KB
- lib/openzeppelin-contracts/contracts/proxy/Proxy.sol3.25 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/BeaconProxy.sol2.1 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol450 B
- lib/openzeppelin-contracts/contracts/proxy/beacon/UpgradeableBeacon.sol2.04 KB
- lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol6.62 KB
- lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol4.36 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol12.85 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.74 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol2.26 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol6.91 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.88 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol761 B
- lib/openzeppelin-contracts/contracts/token/ERC777/IERC777.sol6.73 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol9.36 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol844 B
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.11 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol2.78 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol987 B
- lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Checker.sol5.07 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol853 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol12.79 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol35.08 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol1.26 KB
- lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/src/strings.sol25.7 KB
- lib/openzeppelin-foundry-upgrades/src/Defender.sol8.47 KB
- lib/openzeppelin-foundry-upgrades/src/LegacyUpgrades.sol16.2 KB
- lib/openzeppelin-foundry-upgrades/src/Options.sol4.43 KB
- lib/openzeppelin-foundry-upgrades/src/internal/Core.sol18.84 KB
- lib/openzeppelin-foundry-upgrades/src/internal/DefenderDeploy.sol13.43 KB
- lib/openzeppelin-foundry-upgrades/src/internal/Utils.sol10.08 KB
- lib/openzeppelin-foundry-upgrades/src/internal/Versions.sol269 B
- lib/openzeppelin-foundry-upgrades/src/internal/interfaces/IProxyAdmin.sol567 B
- lib/openzeppelin-foundry-upgrades/src/internal/interfaces/IUpgradeableBeacon.sol200 B
- lib/openzeppelin-foundry-upgrades/src/internal/interfaces/IUpgradeableProxy.sol563 B
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/agreements/AgreementBase.sol902 B
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/agreements/AgreementLibrary.sol8.67 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/agreements/gdav1/GDAv1StorageLayout.sol14.88 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/agreements/gdav1/GeneralDistributionAgreementV1.sol36.39 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/agreements/gdav1/SuperfluidPool.sol21.09 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/agreements/gdav1/SuperfluidPoolDeployerLibrary.sol1.25 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/apps/SuperAppBase.sol2.8 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/apps/SuperTokenV1Library.sol77.9 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/agreements/IConstantFlowAgreementV1.sol19.59 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/agreements/IInstantDistributionAgreementV1.sol18.21 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/agreements/gdav1/IGeneralDistributionAgreementV1.sol12.85 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/agreements/gdav1/IPoolAdminNFT.sol600 B
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/agreements/gdav1/IPoolNFTBase.sol1.49 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/agreements/gdav1/ISuperfluidPool.sol5.88 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/superfluid/Definitions.sol12.11 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/superfluid/ISuperAgreement.sol1.05 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/superfluid/ISuperApp.sol5.54 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/superfluid/ISuperToken.sol22.69 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/superfluid/ISuperTokenFactory.sol6.74 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol28.08 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluidGovernance.sol3.03 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluidToken.sol15.22 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/interfaces/tokens/ISETH.sol572 B
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/libs/CallUtils.sol4.33 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/libs/SlotsBitmapLibrary.sol3.84 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/libs/SolvencyHelperLibrary.sol1.36 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/upgradability/BeaconProxiable.sol568 B
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/upgradability/SuperfluidUpgradeableBeacon.sol1.04 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/upgradability/UUPSProxiable.sol1.89 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/upgradability/UUPSUtils.sol1.07 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/utils/ForwarderBase.sol1.8 KB
- lib/protocol-monorepo/packages/ethereum-contracts/contracts/utils/GDAv1Forwarder.sol9.54 KB
- lib/protocol-monorepo/packages/solidity-semantic-money/src/SemanticMoney.sol21.28 KB
- lib/protocol-monorepo/packages/solidity-semantic-money/src/TokenMonad.sol5.81 KB
- pkg/contracts/src/BaseStrategyUpgradeable.sol16.64 KB
- pkg/contracts/src/CVStrategy/CVStrategy.sol47.39 KB
- pkg/contracts/src/CVStrategy/CVStrategyBaseFacet.sol28.59 KB
- pkg/contracts/src/CVStrategy/CVStreamingStorage.sol2.39 KB
- pkg/contracts/src/CVStrategy/CVThresholdStorage.sol648 B
- pkg/contracts/src/CVStrategy/ConvictionsUtils.sol6.19 KB
- pkg/contracts/src/CVStrategy/DecimalScalingUtils.sol2.02 KB
- pkg/contracts/src/CVStrategy/ICVStrategy.sol4.92 KB
- pkg/contracts/src/CVStrategy/PowerManagementUtils.sol5.39 KB
- pkg/contracts/src/CVStrategy/StreamingEscrow.sol13.56 KB
- pkg/contracts/src/IRegistryFactory.sol1.01 KB
- pkg/contracts/src/ISybilScorer.sol748 B
- pkg/contracts/src/PassportScorer.sol9.06 KB
- pkg/contracts/src/ProxyOwnableUpgrader.sol1.42 KB
- pkg/contracts/src/RegistryCommunity/RegistryCommunity.sol25.33 KB
- pkg/contracts/src/diamonds/interfaces/IDiamond.sol418 B
- pkg/contracts/src/diamonds/interfaces/IDiamondCut.sol841 B
- pkg/contracts/src/diamonds/interfaces/IDiamondLoupe.sol1.32 KB
- pkg/contracts/src/diamonds/libraries/LibDiamond.sol11.32 KB
- pkg/contracts/src/interfaces/FAllo.sol678 B
- pkg/contracts/src/interfaces/IArbitrable.sol2.09 KB
- pkg/contracts/src/interfaces/IArbitrator.sol5.71 KB
- pkg/contracts/src/interfaces/ICollateralVault.sol435 B
- pkg/contracts/src/interfaces/IPauseController.sol696 B
- pkg/contracts/src/interfaces/ISafe.sol1.53 KB
- pkg/contracts/src/interfaces/IVotingPowerRegistry.sol756 B
- pkg/contracts/src/pausing/LibPauseStorage.sol410 B
pkg/contracts/src/CVStrategy/facets/CVStreamingFacet.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;
import {CVStrategyBaseFacet} from "../CVStrategyBaseFacet.sol";
import {IArbitrator} from "../../interfaces/IArbitrator.sol";
import {Proposal, ProposalStatus, ArbitrableConfig} from "../ICVStrategy.sol";
import {CVStreamingStorage, CVStreamingBase} from "../CVStreamingStorage.sol";
import {StreamingEscrow} from "../StreamingEscrow.sol";
import {ConvictionsUtils} from "../ConvictionsUtils.sol";
import {IRegistryFactory} from "../../IRegistryFactory.sol";
import {ISafe} from "../../interfaces/ISafe.sol";
import "@superfluid-finance/ethereum-contracts/contracts/apps/SuperTokenV1Library.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
interface IStreamingEscrowSync {
function syncOutflow() external;
function depositAmount() external view returns (uint256);
function drainToStrategy() external;
}
/**
* @title CVStreamingFacet
* @notice Facet containing streaming-related functions for CVStrategy
* @dev This facet is called via delegatecall from CVStrategy
* CRITICAL: Inherits storage layout from CVStrategyBaseFacet
*/
contract CVStreamingFacet is CVStrategyBaseFacet, CVStreamingBase {
using SuperTokenV1Library for ISuperToken;
/*|--------------------------------------------|*/
/*| ERRORS |*/
/*|--------------------------------------------|*/
error StreamingRateOverflow(uint256 streamingRatePerSecond);
error SuperTokenTransferFailed(address to, uint256 amount);
error UpdateMemberUnitsFailed(address member, uint128 units);
error ApproveFailed(address token, address spender, uint256 amount);
error StreamingEscrowNotFound(address escrow);
error UnauthorizedRebalanceCaller(address caller);
event EscrowStreamStopped(address indexed escrow, address indexed stoppedBy);
event EscrowSyncFailed(address indexed escrow, bytes reason);
/*|--------------------------------------------|*/
/*| FUNCTIONS |*/
/*|--------------------------------------------|*/
/**
* @notice Rebalance the outgoing streams based on current active proposals and their conviction levels
* @dev This function should be called periodically to ensure that the outgoing streams reflect the current
* state of active proposals and their conviction levels. (rate limiting to be implemented in future)
* Sig: 0x7d7c2a1c
*/
function rebalance() external {
if (!_isAuthorizedRebalanceCaller(msg.sender)) {
revert UnauthorizedRebalanceCaller(msg.sender);
}
// Rate limiting
if (rebalanceCooldown() != 0 && block.timestamp < lastRebalanceAt() + rebalanceCooldown()) {
revert RebalanceCooldownActive(lastRebalanceAt() + rebalanceCooldown() - block.timestamp);
}
bool strategyEnabled = _isStrategyEnabled();
if (!strategyEnabled) {
bool didWorkWhenDisabled = _rebalanceWhenDisabled();
if (didWorkWhenDisabled) {
setLastRebalanceAt(block.timestamp);
}
return;
}
wrapIfNeeded();
uint256 poolAmount = getPoolAmount();
bool didMeaningfulWork = false;
bool hadEscrowSyncError = false;
bool syncedAnyEscrow = false;
uint256 totalEligibleConviction = _totalEligibleConviction(poolAmount);
// Start/update/stop stream based on pool conviction share.
uint256 maxConviction = ConvictionsUtils.getMaxConviction(_getPoolThresholdPoints(), cvParams.decay);
bool shouldStartStream = _shouldStartStream(totalEligibleConviction, maxConviction);
uint256 requestedFlowRate = 0;
if (shouldStartStream) {
uint256 clampedConviction =
totalEligibleConviction > maxConviction ? maxConviction : totalEligibleConviction;
requestedFlowRate = (_streamingRatePerSecondInSuperTokenUnits() * clampedConviction) / maxConviction;
}
uint128 streamingUnitBudget = _streamingUnitBudget(requestedFlowRate);
_updateProposalUnits(poolAmount, shouldStartStream, totalEligibleConviction, streamingUnitBudget);
int96 currentFlowRate = superfluidToken.getGDAFlowRate(address(this), superfluidGDA);
int96 actualFlowRate = superfluidToken.distributeFlow(superfluidGDA, _toInt96StreamingRate(requestedFlowRate));
if (currentFlowRate != actualFlowRate) {
didMeaningfulWork = true;
emit StreamRateUpdated(address(superfluidGDA), actualFlowRate > 0 ? uint256(uint96(actualFlowRate)) : 0);
}
uint256[] storage openProposalIds = openStreamingProposalIds;
// Keep escrow deposits and outflows in sync with the latest GDA member flow rates.
for (uint256 i = 0; i < openProposalIds.length; i++) {
address escrow = streamingEscrow(openProposalIds[i]);
if (escrow == address(0) || CVStreamingStorage.layout().stoppedEscrows[escrow]) {
continue;
}
if (_topUpEscrowDepositIfNeeded(escrow)) {
didMeaningfulWork = true;
}
try IStreamingEscrowSync(escrow).syncOutflow() {
syncedAnyEscrow = true;
} catch (bytes memory reason) {
hadEscrowSyncError = true;
emit EscrowSyncFailed(escrow, reason);
}
}
if (syncedAnyEscrow) {
didMeaningfulWork = true;
}
if (didMeaningfulWork && !hadEscrowSyncError) {
setLastRebalanceAt(block.timestamp);
}
}
function _totalEligibleConviction(uint256 poolAmount) internal returns (uint256 totalEligibleConviction) {
uint256[] storage openProposalIds = openStreamingProposalIds;
// First pass: identify eligible conviction and clear non-active proposal units.
for (uint256 i = 0; i < openProposalIds.length; i++) {
uint256 proposalId = openProposalIds[i];
Proposal storage proposal = proposals[proposalId];
address escrow = streamingEscrow(proposalId);
if (escrow == address(0)) {
continue; // Skip if no escrow (shouldn't happen for streaming proposals)
}
if (CVStreamingStorage.layout().stoppedEscrows[escrow]) {
continue;
}
// Ensure non-active proposals never keep receiving pool share.
if (proposal.proposalStatus != ProposalStatus.Active && proposal.proposalStatus != ProposalStatus.Disputed)
{
if (!superfluidGDA.updateMemberUnits(escrow, 0)) {
revert UpdateMemberUnitsFailed(escrow, 0);
}
emit StreamMemberUnitUpdated(escrow, 0);
continue;
}
uint256 convictionValue = calculateProposalConviction(proposalId);
if (_isProposalAboveThreshold(proposal, convictionValue, poolAmount)) {
totalEligibleConviction += convictionValue;
}
}
}
function _updateProposalUnits(
uint256 poolAmount,
bool shouldStartStream,
uint256 totalEligibleConviction,
uint128 streamingUnitBudget
) internal {
uint256[] storage openProposalIds = openStreamingProposalIds;
// Second pass: update units after the requested flow is known. When a stream is requested,
// cap total units to the requested flow rate so GDA integer division cannot round it to zero.
for (uint256 i = 0; i < openProposalIds.length; i++) {
uint256 proposalId = openProposalIds[i];
Proposal storage proposal = proposals[proposalId];
address escrow = streamingEscrow(proposalId);
if (escrow == address(0) || CVStreamingStorage.layout().stoppedEscrows[escrow]) {
continue;
}
if (proposal.proposalStatus != ProposalStatus.Active && proposal.proposalStatus != ProposalStatus.Disputed)
{
continue;
}
uint256 convictionValue = calculateProposalConviction(proposalId);
uint128 units = 0;
if (_isProposalAboveThreshold(proposal, convictionValue, poolAmount)) {
units = shouldStartStream
? _scaledUnitsForStreaming(convictionValue, totalEligibleConviction, streamingUnitBudget)
: _legacyScaledUnits(convictionValue);
}
if (!superfluidGDA.updateMemberUnits(escrow, units)) {
revert UpdateMemberUnitsFailed(escrow, units);
}
// Once an active proposal becomes ineligible, return the pool-funded
// escrow reserve before the subsequent sync can classify it as
// beneficiary-payable excess at a zero GDA flow rate.
// slither-disable-next-line incorrect-equality
if (units == 0 && proposal.proposalStatus == ProposalStatus.Active) {
IStreamingEscrowSync(escrow).drainToStrategy();
}
emit StreamMemberUnitUpdated(escrow, int96(int128(units)));
}
}
/// @notice Emergency stop stream for a specific escrow
/// @dev This sets GDA member units to zero, stops the escrow outflow, and returns residual funds to the strategy.
function stopEscrowStream(address escrow) external onlyOwner {
if (escrow == address(0)) {
revert StreamingEscrowNotFound(escrow);
}
if (!superfluidGDA.updateMemberUnits(escrow, 0)) {
revert UpdateMemberUnitsFailed(escrow, 0);
}
CVStreamingStorage.layout().stoppedEscrows[escrow] = true;
emit StreamMemberUnitUpdated(escrow, 0);
StreamingEscrow(escrow).drainToStrategy();
emit EscrowStreamStopped(escrow, msg.sender);
}
function setAuthorizedRebalanceCaller(address _caller, bool _authorized) external {
onlyCouncilSafe();
CVStreamingStorage.layout().authorizedRebalanceCallers[_caller] = _authorized;
emit RebalanceCallerAuthorizationUpdated(_caller, _authorized);
}
function isAuthorizedRebalanceCaller(address _caller) external view returns (bool) {
return _isAuthorizedRebalanceCaller(_caller);
}
/// @notice Returns the active-points denominator protected by the pool-level decay checkpoint.
function getPoolThresholdPoints() external view returns (uint256) {
return _getPoolThresholdPoints();
}
/**
* @notice Wrap unwrapped pool tokens into supertokens if needed
* @dev Checks the balance of the underlying pool token and wraps it to supertoken
*/
function wrapIfNeeded() public virtual {
if (address(superfluidToken) == address(0)) {
return;
}
// Get the underlying pool token address
address poolToken = allo.getPool(poolId).token;
if (poolToken == NATIVE_TOKEN) {
return; // Cannot wrap native token directly
}
if (poolToken == address(superfluidToken)) {
return; // Pure SuperToken pool: balance already lives in the streaming asset
}
// Get underlying token from supertoken
address underlyingToken = superfluidToken.getUnderlyingToken();
if (underlyingToken != poolToken) {
return; // Mismatch between pool token and supertoken underlying
}
// Check balance of unwrapped tokens
uint256 unwrappedBalance = IERC20(poolToken).balanceOf(address(this));
if (unwrappedBalance == 0) {
return;
}
uint256 upgradeAmount = _toSuperTokenAmount(unwrappedBalance, poolToken, superfluidToken);
if (upgradeAmount == 0) {
return;
}
// Approve supertoken to spend the underlying tokens
if (!IERC20(poolToken).approve(address(superfluidToken), unwrappedBalance)) {
revert ApproveFailed(poolToken, address(superfluidToken), unwrappedBalance);
}
// Wrap tokens to supertokens. SuperToken upgrade amounts are denominated in the SuperToken's decimals.
superfluidToken.upgrade(upgradeAmount);
}
/**
* @notice Check if streaming should start based on supertoken balance
* @dev Returns true if there are supertokens available to stream
* @return bool True if streaming should start
*/
function _shouldStartStream(uint256 totalEligibleConviction, uint256 maxConviction)
internal
view
virtual
returns (bool)
{
if (address(superfluidToken) == address(0)) {
return false;
}
// Check if there's a supertoken balance available for streaming
uint256 superTokenBalance = superfluidToken.balanceOf(address(this));
if (superTokenBalance == 0) {
return false;
}
if (streamingRatePerSecond == 0 || maxConviction == 0 || totalEligibleConviction == 0) {
return false;
}
return true;
}
function _isProposalAboveThreshold(Proposal storage proposal, uint256 convictionValue, uint256 poolAmount)
internal
view
returns (bool)
{
if (totalPointsActivated == 0) {
return false;
}
uint256 threshold = ConvictionsUtils.calculateThreshold(
0, // Streaming proposals use zero requestedAmount; calculateThreshold should still run its normal math for that input.
poolAmount,
_getThresholdPoints(proposal),
cvParams.decay,
cvParams.weight,
cvParams.maxRatio,
cvParams.minThresholdPoints
);
return convictionValue > threshold;
}
function _toInt96StreamingRate(uint256 flowRate) internal pure returns (int96) {
if (flowRate > uint256(uint96(type(int96).max))) {
revert StreamingRateOverflow(flowRate);
}
return int96(uint96(flowRate));
}
function _streamingUnitBudget(uint256 requestedFlowRate) internal pure returns (uint128) {
if (requestedFlowRate > type(uint128).max) {
return type(uint128).max;
}
return uint128(requestedFlowRate);
}
function _scaledUnitsForStreaming(uint256 convictionValue, uint256 totalEligibleConviction, uint128 unitBudget)
internal
pure
returns (uint128)
{
if (unitBudget == 0 || convictionValue == 0 || totalEligibleConviction == 0) {
return 0;
}
uint256 units = Math.mulDiv(convictionValue, unitBudget, totalEligibleConviction);
if (units == 0) {
units = 1;
}
return units > type(uint128).max ? type(uint128).max : uint128(units);
}
function _legacyScaledUnits(uint256 convictionValue) internal pure returns (uint128) {
uint256 scaledConviction = convictionValue / ConvictionsUtils.D;
return scaledConviction > type(uint128).max ? type(uint128).max : uint128(scaledConviction);
}
function _topUpEscrowDepositIfNeeded(address escrow) internal returns (bool) {
uint256 requiredDeposit;
try IStreamingEscrowSync(escrow).depositAmount() returns (uint256 amount) {
requiredDeposit = amount;
} catch {
return false;
}
if (requiredDeposit == 0) {
return false;
}
// Keep a 50 bps buffer above Superfluid's required deposit; 10_000 bps is 100%.
uint256 targetDeposit = requiredDeposit + Math.ceilDiv(requiredDeposit * 50, 10_000);
uint256 escrowBalance = superfluidToken.balanceOf(escrow);
if (escrowBalance >= targetDeposit) {
return false;
}
uint256 missingDeposit = targetDeposit - escrowBalance;
uint256 strategyBalance = superfluidToken.balanceOf(address(this));
if (strategyBalance == 0) {
return false;
}
uint256 topUp = missingDeposit > strategyBalance ? strategyBalance : missingDeposit;
if (topUp != 0) {
if (!superfluidToken.transfer(escrow, topUp)) {
revert SuperTokenTransferFailed(escrow, topUp);
}
return true;
}
return false;
}
function _rebalanceWhenDisabled() internal returns (bool) {
if (address(superfluidToken) == address(0) || address(superfluidGDA) == address(0)) {
return false;
}
int96 currentFlowRate = superfluidToken.getGDAFlowRate(address(this), superfluidGDA);
int96 actualFlowRate = superfluidToken.distributeFlow(superfluidGDA, 0);
if (currentFlowRate != actualFlowRate) {
emit StreamRateUpdated(address(superfluidGDA), 0);
return true;
}
return false;
}
function _isAuthorizedRebalanceCaller(address caller) internal view returns (bool) {
if (address(registryCommunity) == address(0)) {
// Defensive default: never allow open rebalance access before full initialization.
return false;
}
address ownerAddress = effectiveOwner();
address councilSafeAddress = _tryCouncilSafe();
if (
caller == address(this) || (ownerAddress != address(0) && caller == ownerAddress)
|| (councilSafeAddress != address(0) && caller == councilSafeAddress)
) {
return true;
}
if (councilSafeAddress != address(0) && _isCouncilSafeOwner(councilSafeAddress, caller)) {
return true;
}
if (_isFactoryRebalanceCaller(caller)) {
return true;
}
return CVStreamingStorage.layout().authorizedRebalanceCallers[caller];
}
function _isFactoryRebalanceCaller(address caller) internal view returns (bool) {
address registryFactoryAddress = registryCommunity.registryFactory();
if (registryFactoryAddress == address(0)) {
return false;
}
return IRegistryFactory(registryFactoryAddress).isAuthorizedWallet(caller);
}
function _isCouncilSafeOwner(address councilSafeAddress, address caller) internal view returns (bool) {
if (councilSafeAddress.code.length == 0) {
return false;
}
try ISafe(councilSafeAddress).getOwners() returns (address[] memory owners) {
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] == caller) return true;
}
} catch {}
return false;
}
function _tryCouncilSafe() internal view returns (address councilSafeAddress) {
(bool ok, bytes memory data) = address(registryCommunity).staticcall(abi.encodeWithSignature("councilSafe()"));
if (!ok || data.length < 32) {
return councilSafeAddress;
}
councilSafeAddress = abi.decode(data, (address));
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {
"pkg/contracts/src/CVStrategy/facets/CVStreamingFacet.sol": {
"ConvictionsUtils": "0xf7cea4be970dde4041d54a092ecd7f4d7aabfb12"
}
},
"optimizer": {
"runs": 0,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"allo-v2/=lib/allo-v2/",
"allo-v2-contracts/=lib/allo-v2/contracts/",
"allo-v2-test/=lib/allo-v2/test/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/foundry/=lib/openzeppelin-foundry-upgrades/src/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@superfluid-finance/=lib/protocol-monorepo/packages/",
"@src/=pkg/contracts/src/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/allo-v2/lib/solady/src/",
"@prb/math/=lib/allo-v2/lib/v2-core/lib/prb-math/",
"@prb/test/=lib/allo-v2/lib/v2-core/lib/prb-test/src/",
"@sablier/v2-core/=lib/allo-v2/lib/v2-core/",
"ERC1155/=lib/allo-v2/lib/hats-protocol/lib/ERC1155/",
"__safe-smart-account/=lib/__safe-smart-account/",
"ds-test/=lib/allo-v2/lib/forge-std/lib/ds-test/src/",
"eas-contracts/=lib/allo-v2/lib/eas-contracts/contracts/",
"eas-proxy/=lib/allo-v2/lib/eas-proxy/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/allo-v2/lib/permit2/lib/forge-gas-snapshot/src/",
"hats-protocol/=lib/allo-v2/lib/hats-protocol/",
"hedgey-vesting/=lib/allo-v2/lib/hedgey-vesting/contracts/",
"lib/ERC1155/=lib/allo-v2/lib/hats-protocol/lib/ERC1155/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/",
"permit2/=lib/allo-v2/lib/permit2/",
"prb-math/=lib/allo-v2/lib/v2-core/lib/prb-math/src/",
"prb-test/=lib/allo-v2/lib/v2-core/lib/prb-test/src/",
"protocol-monorepo/=lib/protocol-monorepo/packages/solidity-semantic-money/src/",
"safe-smart-account/=lib/safe-smart-account/",
"solarray/=lib/allo-v2/lib/v2-core/lib/solarray/src/",
"solbase/=lib/allo-v2/lib/hats-protocol/lib/solbase/src/",
"solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
"solmate/=lib/allo-v2/lib/permit2/lib/solmate/",
"superfluid-protocol-monorepo/=lib/allo-v2/lib/superfluid-protocol-monorepo/packages/solidity-semantic-money/src/",
"utils/=lib/allo-v2/lib/hats-protocol/lib/utils/",
"v2-core/=lib/allo-v2/lib/v2-core/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.