Verified contractPartialAGPL-3.0-or-later
RIVRBatchRequestManager
Address0x5617d3797174ca47fb06fb48fa540adfcfef8590
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 200 runs
- License
- AGPL-3.0-or-later
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,356,135
- Creation transaction
- 0x5216e3f8b6…6ebe62efef
28 files
- contracts/vaults/RIVRBatchRequestManager.solmain42.45 KB
- contracts/core/hub/interfaces/IHubRegistry.sol6.49 KB
- contracts/core/hub/interfaces/IHubRequestManager.sol1.22 KB
- contracts/core/hub/interfaces/IHubRequestManagerCallback.sol910 B
- contracts/core/libraries/PricingLib.sol13.87 KB
- contracts/core/messaging/interfaces/IGateway.sol9.19 KB
- contracts/core/messaging/interfaces/IMessageHandler.sol580 B
- contracts/core/types/AssetId.sol951 B
- contracts/core/types/PoolId.sol798 B
- contracts/core/types/ShareClassId.sol852 B
- contracts/core/utils/BatchedMulticall.sol2.39 KB
- contracts/core/utils/interfaces/IBatchedMulticall.sol443 B
- contracts/misc/Auth.sol867 B
- contracts/misc/Multicall.sol1.12 KB
- contracts/misc/ReentrancyProtection.sol963 B
- contracts/misc/interfaces/IAuth.sol768 B
- contracts/misc/interfaces/IERC165.sol738 B
- contracts/misc/interfaces/IERC20.sol7.69 KB
- contracts/misc/interfaces/IERC6909.sol9.04 KB
- contracts/misc/interfaces/IMulticall.sol949 B
- contracts/misc/interfaces/IRecoverable.sol1.22 KB
- contracts/misc/libraries/BytesLib.sol6.7 KB
- contracts/misc/libraries/CastLib.sol1.77 KB
- contracts/misc/libraries/MathLib.sol8.64 KB
- contracts/misc/types/D18.sol3.93 KB
- contracts/vaults/interfaces/IBatchRequestManager.sol19.45 KB
- contracts/vaults/libraries/RequestCallbackMessageLib.sol5.56 KB
- contracts/vaults/libraries/RequestMessageLib.sol3.37 KB
contracts/vaults/RIVRBatchRequestManager.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {RequestCallbackMessageLib} from "./libraries/RequestCallbackMessageLib.sol";
import {RequestMessageLib, RequestType as RequestMessageType} from "./libraries/RequestMessageLib.sol";
import {
IBatchRequestManager,
EpochInvestAmounts,
EpochRedeemAmounts,
UserOrder,
QueuedOrder,
RequestType,
EpochId
} from "./interfaces/IBatchRequestManager.sol";
import {Auth} from "../misc/Auth.sol";
import {D18, d18} from "../misc/types/D18.sol";
import {IAuth} from "../misc/interfaces/IAuth.sol";
import {CastLib} from "../misc/libraries/CastLib.sol";
import {MathLib} from "../misc/libraries/MathLib.sol";
import {IERC165} from "../misc/interfaces/IERC165.sol";
import {BytesLib} from "../misc/libraries/BytesLib.sol";
import {PoolId} from "../core/types/PoolId.sol";
import {AssetId} from "../core/types/AssetId.sol";
import {PricingLib} from "../core/libraries/PricingLib.sol";
import {ShareClassId} from "../core/types/ShareClassId.sol";
import {IGateway} from "../core/messaging/interfaces/IGateway.sol";
import {BatchedMulticall} from "../core/utils/BatchedMulticall.sol";
import {IHubRegistry} from "../core/hub/interfaces/IHubRegistry.sol";
import {IHubRequestManagerCallback} from "../core/hub/interfaces/IHubRequestManagerCallback.sol";
import {IHubRequestManager, IHubRequestManagerNotifications} from "../core/hub/interfaces/IHubRequestManager.sol";
/// @title RIVRBatchRequestManager
/// @notice Manager for handling deposit/redeem requests, epochs, and fulfillment logic for share classes
contract RIVRBatchRequestManager is Auth, BatchedMulticall, IBatchRequestManager {
using MathLib for *;
using CastLib for *;
using BytesLib for bytes;
using RequestMessageLib for *;
using RequestCallbackMessageLib for *;
IHubRequestManagerCallback public hub;
IHubRegistry public immutable hubRegistry;
// Epochs
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => EpochId))) public epochId;
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => mapping(uint32 epochId_ => EpochInvestAmounts))))
public epochInvestAmounts;
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => mapping(uint32 epochId_ => EpochRedeemAmounts))))
public epochRedeemAmounts;
// Pending requests
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => uint128))) public pendingRedeem;
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => uint128))) public pendingDeposit;
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => mapping(bytes32 investor => UserOrder)))) public
redeemRequest;
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => mapping(bytes32 investor => UserOrder)))) public
depositRequest;
// Queued requests
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => mapping(bytes32 investor => QueuedOrder)))) public
queuedRedeemRequest;
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => mapping(bytes32 investor => QueuedOrder)))) public
queuedDepositRequest;
// Force cancel request safeguards
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => mapping(bytes32 investor => bool)))) public
allowForceDepositCancel;
mapping(PoolId => mapping(ShareClassId => mapping(AssetId => mapping(bytes32 investor => bool)))) public
allowForceRedeemCancel;
constructor(IHubRegistry poolRegistry_, IGateway gateway_, address deployer)
Auth(deployer)
BatchedMulticall(gateway_)
{
hubRegistry = poolRegistry_;
}
//----------------------------------------------------------------------------------------------
// Administration
//----------------------------------------------------------------------------------------------
/// Accepts a `bytes32` representation of 'hub'
function file(bytes32 what, address data) external auth {
if (what == "hub") hub = IHubRequestManagerCallback(data);
else revert FileUnrecognizedParam();
emit File(what, data);
}
modifier isManager(PoolId poolId) {
require(hubRegistry.manager(poolId, msgSender()), IAuth.NotAuthorized());
_;
}
/// @dev used only for migrations
function setEpochIds(PoolId poolId, ShareClassId scId, AssetId assetId, EpochId memory epochIdData) external auth {
epochId[poolId][scId][assetId] = epochIdData;
emit EpochIdModified(poolId, scId, assetId, epochIdData);
}
//----------------------------------------------------------------------------------------------
// Incoming requests
//----------------------------------------------------------------------------------------------
/// @inheritdoc IHubRequestManager
function request(PoolId poolId, ShareClassId scId, AssetId assetId, bytes calldata payload) external auth {
uint8 kind = uint8(RequestMessageLib.requestType(payload));
if (kind == uint8(RequestMessageType.DepositRequest)) {
RequestMessageLib.DepositRequest memory m = payload.deserializeDepositRequest();
requestDeposit(poolId, scId, m.amount, m.investor, assetId);
} else if (kind == uint8(RequestMessageType.RedeemRequest)) {
RequestMessageLib.RedeemRequest memory m = payload.deserializeRedeemRequest();
requestRedeem(poolId, scId, m.amount, m.investor, assetId);
} else if (kind == uint8(RequestMessageType.CancelDepositRequest)) {
RequestMessageLib.CancelDepositRequest memory m = payload.deserializeCancelDepositRequest();
uint128 cancelledAssetAmount = cancelDepositRequest(poolId, scId, m.investor, assetId);
// Cancellation might have been queued such that it will be executed in the future during claiming
if (cancelledAssetAmount > 0) {
hub.requestCallback(
poolId,
scId,
assetId,
RequestCallbackMessageLib.FulfilledDepositRequest(m.investor, 0, 0, cancelledAssetAmount)
.serialize(),
0,
true,
address(0) // Refund is not used because we're in unpaid mode with no payment
);
}
} else if (kind == uint8(RequestMessageType.CancelRedeemRequest)) {
RequestMessageLib.CancelRedeemRequest memory m = payload.deserializeCancelRedeemRequest();
uint128 cancelledShareAmount = cancelRedeemRequest(poolId, scId, m.investor, assetId);
// Cancellation might have been queued such that it will be executed in the future during claiming
if (cancelledShareAmount > 0) {
hub.requestCallback(
poolId,
scId,
assetId,
RequestCallbackMessageLib.FulfilledRedeemRequest(m.investor, 0, 0, cancelledShareAmount)
.serialize(),
0,
true,
address(0) // Refund is not used because we're in unpaid mode with no payment
);
}
} else {
revert UnknownRequestType();
}
}
/// @inheritdoc IBatchRequestManager
function requestDeposit(PoolId poolId, ShareClassId scId_, uint128 amount, bytes32 investor, AssetId depositAssetId)
public
auth
{
// NOTE: Vaults ensure amount > 0
_updatePending(poolId, scId_, amount, true, investor, depositAssetId, RequestType.Deposit);
}
/// @inheritdoc IBatchRequestManager
function cancelDepositRequest(PoolId poolId, ShareClassId scId_, bytes32 investor, AssetId depositAssetId)
public
auth
returns (uint128 cancelledAssetAmount)
{
allowForceDepositCancel[poolId][scId_][depositAssetId][investor] = true;
uint128 cancellingAmount = depositRequest[poolId][scId_][depositAssetId][investor].pending;
return _updatePending(poolId, scId_, cancellingAmount, false, investor, depositAssetId, RequestType.Deposit);
}
/// @inheritdoc IBatchRequestManager
function requestRedeem(PoolId poolId, ShareClassId scId_, uint128 amount, bytes32 investor, AssetId payoutAssetId)
public
auth
{
// NOTE: Vaults ensure amount > 0
_updatePending(poolId, scId_, amount, true, investor, payoutAssetId, RequestType.Redeem);
}
/// @inheritdoc IBatchRequestManager
function cancelRedeemRequest(PoolId poolId, ShareClassId scId_, bytes32 investor, AssetId payoutAssetId)
public
auth
returns (uint128 cancelledShareAmount)
{
allowForceRedeemCancel[poolId][scId_][payoutAssetId][investor] = true;
uint128 cancellingAmount = redeemRequest[poolId][scId_][payoutAssetId][investor].pending;
return _updatePending(poolId, scId_, cancellingAmount, false, investor, payoutAssetId, RequestType.Redeem);
}
//----------------------------------------------------------------------------------------------
// Manager actions
//----------------------------------------------------------------------------------------------
/// @inheritdoc IBatchRequestManager
function approveDeposits(
PoolId poolId,
ShareClassId scId_,
AssetId depositAssetId,
uint32 nowDepositEpochId,
uint128 approvedAssetAmount,
D18 pricePoolPerAsset,
address refund
) external payable isManager(poolId) {
require(
nowDepositEpochId == nowDepositEpoch(poolId, scId_, depositAssetId),
EpochNotInSequence(nowDepositEpochId, nowDepositEpoch(poolId, scId_, depositAssetId))
);
// Limit in case approved > pending due to race condition of FM approval and async incoming requests
uint128 pendingAssetAmount = pendingDeposit[poolId][scId_][depositAssetId];
require(approvedAssetAmount <= pendingAssetAmount, InsufficientPending());
require(approvedAssetAmount > 0, ZeroApprovalAmount());
uint128 approvedPoolAmount = PricingLib.convertWithPrice(
approvedAssetAmount, hubRegistry.decimals(depositAssetId), hubRegistry.decimals(poolId), pricePoolPerAsset
);
// Update epoch data
EpochInvestAmounts storage epochAmounts = epochInvestAmounts[poolId][scId_][depositAssetId][nowDepositEpochId];
epochAmounts.approvedAssetAmount = approvedAssetAmount;
epochAmounts.approvedPoolAmount = approvedPoolAmount;
epochAmounts.pendingAssetAmount = pendingAssetAmount;
epochAmounts.pricePoolPerAsset = pricePoolPerAsset;
// Reduce pending
pendingDeposit[poolId][scId_][depositAssetId] -= approvedAssetAmount;
pendingAssetAmount -= approvedAssetAmount;
epochId[poolId][scId_][depositAssetId].deposit = nowDepositEpochId;
emit ApproveDeposits(
poolId,
scId_,
depositAssetId,
nowDepositEpochId,
approvedPoolAmount,
approvedAssetAmount,
pendingAssetAmount
);
bytes memory callback =
RequestCallbackMessageLib.ApprovedDeposits(approvedAssetAmount, pricePoolPerAsset.raw()).serialize();
hub.requestCallback{value: msgValue()}(poolId, scId_, depositAssetId, callback, 0, false, refund);
}
/// @inheritdoc IBatchRequestManager
function approveRedeems(
PoolId poolId,
ShareClassId scId_,
AssetId payoutAssetId,
uint32 nowRedeemEpochId,
uint128 approvedShareAmount,
D18 pricePoolPerAsset
) external payable isManager(poolId) {
require(
nowRedeemEpochId == nowRedeemEpoch(poolId, scId_, payoutAssetId),
EpochNotInSequence(nowRedeemEpochId, nowRedeemEpoch(poolId, scId_, payoutAssetId))
);
// Limit in case approved > pending due to race condition of FM approval and async incoming requests
uint128 pendingShareAmount = pendingRedeem[poolId][scId_][payoutAssetId];
require(approvedShareAmount <= pendingShareAmount, InsufficientPending());
require(approvedShareAmount > 0, ZeroApprovalAmount());
// Update epoch data
EpochRedeemAmounts storage epochAmounts = epochRedeemAmounts[poolId][scId_][payoutAssetId][nowRedeemEpochId];
epochAmounts.approvedShareAmount = approvedShareAmount;
epochAmounts.pendingShareAmount = pendingShareAmount;
epochAmounts.pricePoolPerAsset = pricePoolPerAsset;
// Reduce pending
pendingRedeem[poolId][scId_][payoutAssetId] -= approvedShareAmount;
pendingShareAmount -= approvedShareAmount;
epochId[poolId][scId_][payoutAssetId].redeem = nowRedeemEpochId;
emit ApproveRedeems(poolId, scId_, payoutAssetId, nowRedeemEpochId, approvedShareAmount, pendingShareAmount);
}
/// @inheritdoc IBatchRequestManager
function issueShares(
PoolId poolId,
ShareClassId scId_,
AssetId depositAssetId,
uint32 nowIssueEpochId,
D18 pricePoolPerShare,
uint128 extraGasLimit,
address refund
) external payable isManager(poolId) {
require(nowIssueEpochId <= epochId[poolId][scId_][depositAssetId].deposit, EpochNotFound());
require(
nowIssueEpochId == nowIssueEpoch(poolId, scId_, depositAssetId),
EpochNotInSequence(nowIssueEpochId, nowIssueEpoch(poolId, scId_, depositAssetId))
);
EpochInvestAmounts storage epochAmounts = epochInvestAmounts[poolId][scId_][depositAssetId][nowIssueEpochId];
epochAmounts.pricePoolPerShare = pricePoolPerShare;
uint128 issuedShareAmount = pricePoolPerShare.isNotZero()
? PricingLib.assetToShareAmount(
epochAmounts.approvedAssetAmount,
hubRegistry.decimals(depositAssetId),
hubRegistry.decimals(poolId),
epochAmounts.pricePoolPerAsset,
pricePoolPerShare,
MathLib.Rounding.Down
)
: 0;
epochAmounts.issuedAt = block.timestamp.toUint64();
epochId[poolId][scId_][depositAssetId].issue = nowIssueEpochId;
emit IssueShares(
poolId,
scId_,
depositAssetId,
nowIssueEpochId,
pricePoolPerShare,
epochAmounts.pricePoolPerAsset.isNotZero()
? PricingLib.priceAssetPerShare(epochAmounts.pricePoolPerShare, epochAmounts.pricePoolPerAsset)
: d18(0),
issuedShareAmount
);
bytes memory callback =
RequestCallbackMessageLib.IssuedShares(issuedShareAmount, pricePoolPerShare.raw()).serialize();
hub.requestCallback{value: msgValue()}(poolId, scId_, depositAssetId, callback, extraGasLimit, false, refund);
}
/// @inheritdoc IBatchRequestManager
function revokeShares(
PoolId poolId,
ShareClassId scId_,
AssetId payoutAssetId,
uint32 nowRevokeEpochId,
D18 pricePoolPerShare,
uint128 extraGasLimit,
address refund
) external payable isManager(poolId) {
(uint128 payoutAssetAmount, uint128 revokedShareAmount) =
_revokeShares(poolId, scId_, payoutAssetId, nowRevokeEpochId, pricePoolPerShare);
bytes memory callback = RequestCallbackMessageLib.RevokedShares(
payoutAssetAmount, revokedShareAmount, pricePoolPerShare.raw()
).serialize();
hub.requestCallback{value: msgValue()}(poolId, scId_, payoutAssetId, callback, extraGasLimit, false, refund);
}
function _revokeShares(
PoolId poolId,
ShareClassId scId_,
AssetId payoutAssetId,
uint32 nowRevokeEpochId,
D18 pricePoolPerShare
) internal returns (uint128 payoutAssetAmount, uint128 revokedShareAmount) {
require(nowRevokeEpochId <= epochId[poolId][scId_][payoutAssetId].redeem, EpochNotFound());
require(
nowRevokeEpochId == nowRevokeEpoch(poolId, scId_, payoutAssetId),
EpochNotInSequence(nowRevokeEpochId, nowRevokeEpoch(poolId, scId_, payoutAssetId))
);
EpochRedeemAmounts storage epochAmounts = epochRedeemAmounts[poolId][scId_][payoutAssetId][nowRevokeEpochId];
epochAmounts.pricePoolPerShare = pricePoolPerShare;
// NOTE: shares and pool currency have the same decimals - no conversion needed!
uint128 payoutPoolAmount = pricePoolPerShare.mulUint128(epochAmounts.approvedShareAmount, MathLib.Rounding.Down);
payoutAssetAmount = epochAmounts.pricePoolPerAsset.isNotZero()
? PricingLib.shareToAssetAmount(
epochAmounts.approvedShareAmount,
hubRegistry.decimals(poolId),
hubRegistry.decimals(payoutAssetId),
epochAmounts.pricePoolPerShare,
epochAmounts.pricePoolPerAsset,
MathLib.Rounding.Down
)
: 0;
revokedShareAmount = epochAmounts.approvedShareAmount;
epochAmounts.payoutAssetAmount = payoutAssetAmount;
epochAmounts.revokedAt = block.timestamp.toUint64();
epochId[poolId][scId_][payoutAssetId].revoke = nowRevokeEpochId;
emit RevokeShares(
poolId,
scId_,
payoutAssetId,
nowRevokeEpochId,
pricePoolPerShare,
epochAmounts.pricePoolPerAsset.isNotZero()
? PricingLib.priceAssetPerShare(epochAmounts.pricePoolPerShare, epochAmounts.pricePoolPerAsset)
: d18(0),
epochAmounts.approvedShareAmount,
payoutAssetAmount,
payoutPoolAmount
);
}
/// @inheritdoc IBatchRequestManager
function forceCancelDepositRequest(
PoolId poolId,
ShareClassId scId_,
bytes32 investor,
AssetId depositAssetId,
address refund
) external payable isManager(poolId) {
require(allowForceDepositCancel[poolId][scId_][depositAssetId][investor], CancellationInitializationRequired());
uint128 cancellingAmount = depositRequest[poolId][scId_][depositAssetId][investor].pending;
uint128 cancelledAssetAmount =
_updatePending(poolId, scId_, cancellingAmount, false, investor, depositAssetId, RequestType.Deposit);
// Cancellation might have been queued such that it will be executed in the future during claiming
if (cancelledAssetAmount > 0) {
bytes memory callback =
RequestCallbackMessageLib.FulfilledDepositRequest(investor, 0, 0, cancelledAssetAmount).serialize();
hub.requestCallback{value: msgValue()}(poolId, scId_, depositAssetId, callback, 0, false, refund);
}
}
/// @inheritdoc IBatchRequestManager
function forceCancelRedeemRequest(
PoolId poolId,
ShareClassId scId_,
bytes32 investor,
AssetId payoutAssetId,
address refund
) external payable isManager(poolId) {
require(allowForceRedeemCancel[poolId][scId_][payoutAssetId][investor], CancellationInitializationRequired());
uint128 cancellingAmount = redeemRequest[poolId][scId_][payoutAssetId][investor].pending;
uint128 cancelledShareAmount =
_updatePending(poolId, scId_, cancellingAmount, false, investor, payoutAssetId, RequestType.Redeem);
// Cancellation might have been queued such that it will be executed in the future during claiming
if (cancelledShareAmount > 0) {
bytes memory callback =
RequestCallbackMessageLib.FulfilledRedeemRequest(investor, 0, 0, cancelledShareAmount).serialize();
hub.requestCallback{value: msgValue()}(poolId, scId_, payoutAssetId, callback, 0, false, refund);
}
}
//----------------------------------------------------------------------------------------------
// Claiming methods
//----------------------------------------------------------------------------------------------
/// @inheritdoc IHubRequestManagerNotifications
function notifyDeposit(
PoolId poolId,
ShareClassId scId,
AssetId assetId,
bytes32 investor,
uint32 maxClaims,
address refund
) external payable protected {
uint128 totalPayoutShareAmount;
uint128 totalPaymentAssetAmount;
uint128 cancelledAssetAmount;
for (uint32 i = 0; i < maxClaims; i++) {
(uint128 payoutShareAmount, uint128 paymentAssetAmount, uint128 cancelled, bool canClaimAgain) =
_claimDeposit(poolId, scId, investor, assetId);
totalPayoutShareAmount += payoutShareAmount;
totalPaymentAssetAmount += paymentAssetAmount;
// Should be written at most once with non-zero amount iff the last claimable epoch was processed and
// the user had a pending cancellation
// NOTE: Purposely delaying corresponding message dispatch after deposit fulfillment message
if (cancelled > 0) {
cancelledAssetAmount = cancelled;
}
if (!canClaimAgain) {
break;
}
}
if (totalPaymentAssetAmount > 0 || cancelledAssetAmount > 0) {
hub.requestCallback{value: msgValue()}(
poolId,
scId,
assetId,
RequestCallbackMessageLib.FulfilledDepositRequest(
investor, totalPaymentAssetAmount, totalPayoutShareAmount, cancelledAssetAmount
).serialize(),
0,
false,
refund
);
}
}
function _claimDeposit(PoolId poolId, ShareClassId scId_, bytes32 investor, AssetId depositAssetId)
internal
returns (
uint128 payoutShareAmount,
uint128 paymentAssetAmount,
uint128 cancelledAssetAmount,
bool canClaimAgain
)
{
UserOrder storage userOrder = depositRequest[poolId][scId_][depositAssetId][investor];
require(userOrder.pending > 0, NoOrderFound());
require(userOrder.lastUpdate <= epochId[poolId][scId_][depositAssetId].issue, IssuanceRequired());
canClaimAgain = userOrder.lastUpdate < epochId[poolId][scId_][depositAssetId].issue;
EpochInvestAmounts storage epochAmounts =
epochInvestAmounts[poolId][scId_][depositAssetId][userOrder.lastUpdate];
// Calculate ceiling for pending reduction (ensures sum(user.pending) <= pendingTotal)
paymentAssetAmount = epochAmounts.approvedAssetAmount == 0
? 0
: userOrder.pending
.mulDiv(epochAmounts.approvedAssetAmount, epochAmounts.pendingAssetAmount, MathLib.Rounding.Up)
.toUint128();
// NOTE: To ensure sum(user.pending) <= pendingTotal, we reduce pending by ceiling of the
// proportional share. Payout amounts use floor to ensure sum(claimed) <= sum(issued).
// This means users may lose up to 1 wei per claim, but prevents unbounded drift.
if (paymentAssetAmount > 0) {
// Calculate floor for share payout (ensures sum(shares claimed) <= shares issued)
uint128 paymentAssetFloor = userOrder.pending
.mulDiv(epochAmounts.approvedAssetAmount, epochAmounts.pendingAssetAmount, MathLib.Rounding.Down)
.toUint128();
if (paymentAssetFloor > 0) {
payoutShareAmount = epochAmounts.pricePoolPerShare.isNotZero()
? PricingLib.assetToShareAmount(
paymentAssetFloor,
hubRegistry.decimals(depositAssetId),
hubRegistry.decimals(poolId),
epochAmounts.pricePoolPerAsset,
epochAmounts.pricePoolPerShare,
MathLib.Rounding.Down
)
: 0;
}
userOrder.pending -= paymentAssetAmount;
}
emit ClaimDeposit(
poolId,
scId_,
userOrder.lastUpdate,
investor,
depositAssetId,
paymentAssetAmount,
userOrder.pending,
payoutShareAmount,
epochAmounts.issuedAt
);
// If there is nothing to claim anymore we can short circuit to the latest epoch
if (userOrder.pending == 0) {
// The current epoch is always one step ahead of the stored one
userOrder.lastUpdate = nowDepositEpoch(poolId, scId_, depositAssetId);
canClaimAgain = false;
} else {
userOrder.lastUpdate += 1;
}
// If user claimed up to latest approval epoch, move queued to pending
if (userOrder.lastUpdate == nowDepositEpoch(poolId, scId_, depositAssetId)) {
cancelledAssetAmount =
_postClaimUpdateQueued(poolId, scId_, investor, depositAssetId, userOrder, RequestType.Deposit);
}
}
/// @inheritdoc IHubRequestManagerNotifications
function notifyRedeem(
PoolId poolId,
ShareClassId scId,
AssetId assetId,
bytes32 investor,
uint32 maxClaims,
address refund
) external payable protected {
uint128 totalPayoutAssetAmount;
uint128 totalPaymentShareAmount;
uint128 cancelledShareAmount;
for (uint32 i = 0; i < maxClaims; i++) {
(uint128 payoutAssetAmount, uint128 paymentShareAmount, uint128 cancelled, bool canClaimAgain) =
_claimRedeem(poolId, scId, investor, assetId);
totalPayoutAssetAmount += payoutAssetAmount;
totalPaymentShareAmount += paymentShareAmount;
// Should be written at most once with non-zero amount iff the last claimable epoch was processed and
// the user had a pending cancellation
// NOTE: Purposely delaying corresponding message dispatch after redemption fulfillment message
if (cancelled > 0) {
cancelledShareAmount = cancelled;
}
if (!canClaimAgain) {
break;
}
}
if (totalPaymentShareAmount > 0 || cancelledShareAmount > 0) {
hub.requestCallback{value: msgValue()}(
poolId,
scId,
assetId,
RequestCallbackMessageLib.FulfilledRedeemRequest(
investor, totalPayoutAssetAmount, totalPaymentShareAmount, cancelledShareAmount
).serialize(),
0,
false,
refund
);
}
}
function _claimRedeem(PoolId poolId, ShareClassId scId_, bytes32 investor, AssetId payoutAssetId)
internal
returns (
uint128 payoutAssetAmount,
uint128 paymentShareAmount,
uint128 cancelledShareAmount,
bool canClaimAgain
)
{
UserOrder storage userOrder = redeemRequest[poolId][scId_][payoutAssetId][investor];
require(userOrder.pending > 0, NoOrderFound());
require(userOrder.lastUpdate <= epochId[poolId][scId_][payoutAssetId].revoke, RevocationRequired());
canClaimAgain = userOrder.lastUpdate < epochId[poolId][scId_][payoutAssetId].revoke;
EpochRedeemAmounts storage epochAmounts = epochRedeemAmounts[poolId][scId_][payoutAssetId][userOrder.lastUpdate];
// Calculate ceiling for pending reduction (ensures sum(user.pending) <= pendingTotal)
paymentShareAmount = epochAmounts.approvedShareAmount == 0
? 0
: userOrder.pending
.mulDiv(epochAmounts.approvedShareAmount, epochAmounts.pendingShareAmount, MathLib.Rounding.Up)
.toUint128();
// NOTE: To ensure sum(user.pending) <= pendingTotal, we reduce pending by ceiling of the
// proportional share. Payout amounts use floor to ensure sum(claimed) <= sum(issued).
// This means users may lose up to 1 wei per claim, but prevents unbounded drift.
if (paymentShareAmount > 0) {
// Calculate floor for asset payout (ensures sum(assets claimed) <= assets available)
uint128 paymentShareFloor = userOrder.pending
.mulDiv(epochAmounts.approvedShareAmount, epochAmounts.pendingShareAmount, MathLib.Rounding.Down)
.toUint128();
if (paymentShareFloor > 0) {
payoutAssetAmount = epochAmounts.pricePoolPerAsset.isNotZero()
? PricingLib.shareToAssetAmount(
paymentShareFloor,
hubRegistry.decimals(poolId),
hubRegistry.decimals(payoutAssetId),
epochAmounts.pricePoolPerShare,
epochAmounts.pricePoolPerAsset,
MathLib.Rounding.Down
)
: 0;
}
userOrder.pending -= paymentShareAmount;
}
emit ClaimRedeem(
poolId,
scId_,
userOrder.lastUpdate,
investor,
payoutAssetId,
paymentShareAmount,
userOrder.pending,
payoutAssetAmount,
epochAmounts.revokedAt
);
// If there is nothing to claim anymore we can short circuit the in between epochs
if (userOrder.pending == 0) {
// The current epoch is always one step ahead of the stored one
userOrder.lastUpdate = nowRedeemEpoch(poolId, scId_, payoutAssetId);
canClaimAgain = false;
} else {
userOrder.lastUpdate += 1;
}
if (userOrder.lastUpdate == nowRedeemEpoch(poolId, scId_, payoutAssetId)) {
cancelledShareAmount =
_postClaimUpdateQueued(poolId, scId_, investor, payoutAssetId, userOrder, RequestType.Redeem);
}
}
//----------------------------------------------------------------------------------------------
// ERC-165
//----------------------------------------------------------------------------------------------
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public pure returns (bool) {
return interfaceId == type(IBatchRequestManager).interfaceId
|| interfaceId == type(IHubRequestManager).interfaceId
|| interfaceId == type(IHubRequestManagerNotifications).interfaceId
|| interfaceId == type(IERC165).interfaceId;
}
//----------------------------------------------------------------------------------------------
// View methods
//----------------------------------------------------------------------------------------------
/// @inheritdoc IBatchRequestManager
function nowDepositEpoch(PoolId poolId, ShareClassId scId_, AssetId depositAssetId) public view returns (uint32) {
return epochId[poolId][scId_][depositAssetId].deposit + 1;
}
/// @inheritdoc IBatchRequestManager
function nowIssueEpoch(PoolId poolId, ShareClassId scId_, AssetId depositAssetId) public view returns (uint32) {
return epochId[poolId][scId_][depositAssetId].issue + 1;
}
/// @inheritdoc IBatchRequestManager
function nowRedeemEpoch(PoolId poolId, ShareClassId scId_, AssetId depositAssetId) public view returns (uint32) {
return epochId[poolId][scId_][depositAssetId].redeem + 1;
}
/// @inheritdoc IBatchRequestManager
function nowRevokeEpoch(PoolId poolId, ShareClassId scId_, AssetId depositAssetId) public view returns (uint32) {
return epochId[poolId][scId_][depositAssetId].revoke + 1;
}
/// @inheritdoc IBatchRequestManager
function maxDepositClaims(PoolId poolId, ShareClassId scId_, bytes32 investor, AssetId depositAssetId)
public
view
returns (uint32)
{
return _maxClaims(
depositRequest[poolId][scId_][depositAssetId][investor], epochId[poolId][scId_][depositAssetId].issue
);
}
/// @inheritdoc IBatchRequestManager
function maxRedeemClaims(PoolId poolId, ShareClassId scId_, bytes32 investor, AssetId payoutAssetId)
public
view
returns (uint32)
{
return _maxClaims(
redeemRequest[poolId][scId_][payoutAssetId][investor], epochId[poolId][scId_][payoutAssetId].revoke
);
}
function _maxClaims(UserOrder memory userOrder, uint32 lastEpoch) internal pure returns (uint32) {
// User order either not set or not processed
if (userOrder.pending == 0 || userOrder.lastUpdate > lastEpoch) {
return 0;
}
return lastEpoch - userOrder.lastUpdate + 1;
}
//----------------------------------------------------------------------------------------------
// Internal methods
//----------------------------------------------------------------------------------------------
function _postClaimUpdateQueued(
PoolId poolId,
ShareClassId scId_,
bytes32 investor,
AssetId assetId,
UserOrder storage userOrder,
RequestType requestType
) internal returns (uint128 cancelledAmount) {
QueuedOrder storage queued = requestType == RequestType.Deposit
? queuedDepositRequest[poolId][scId_][assetId][investor]
: queuedRedeemRequest[poolId][scId_][assetId][investor];
// Increment pending by queued or cancel everything
uint128 updatePendingAmount = queued.isCancelling ? userOrder.pending : queued.amount;
if (queued.isCancelling) {
cancelledAmount = userOrder.pending + queued.amount;
userOrder.pending = 0;
} else {
userOrder.pending += queued.amount;
}
if (requestType == RequestType.Deposit) {
_updatePendingDeposit(
poolId,
scId_,
updatePendingAmount,
!queued.isCancelling,
investor,
assetId,
userOrder,
QueuedOrder(false, 0)
);
} else {
_updatePendingRedeem(
poolId,
scId_,
updatePendingAmount,
!queued.isCancelling,
investor,
assetId,
userOrder,
QueuedOrder(false, 0)
);
}
// Clear queued
queued.isCancelling = false;
queued.amount = 0;
}
/// @notice Updates the amount of a deposit or redeem request.
///
/// @param poolId Identifier of the pool
/// @param scId_ Identifier of the share class
/// @param amount Amount which is updated
/// @param isIncrement Whether the amount is positive (additional request) or negative (cancellation)
/// @param investor Address of the entity which is depositing
/// @param assetId Identifier of the asset which the investor either used as deposit or wants to redeem to
/// @param requestType Flag indicating whether the request is a deposit or redeem request
/// @return cancelledAmount Pending amount which was cancelled
function _updatePending(
PoolId poolId,
ShareClassId scId_,
uint128 amount,
bool isIncrement,
bytes32 investor,
AssetId assetId,
RequestType requestType
) internal returns (uint128 cancelledAmount) {
UserOrder storage userOrder = requestType == RequestType.Deposit
? depositRequest[poolId][scId_][assetId][investor]
: redeemRequest[poolId][scId_][assetId][investor];
QueuedOrder storage queued = requestType == RequestType.Deposit
? queuedDepositRequest[poolId][scId_][assetId][investor]
: queuedRedeemRequest[poolId][scId_][assetId][investor];
// We must only update either queued or pending
if (_updateQueued(poolId, scId_, amount, isIncrement, investor, assetId, userOrder, queued, requestType)) {
return 0;
}
cancelledAmount = isIncrement ? 0 : amount;
// NOTE: If we decrease the pending, we decrease usually by the full amount
// We keep subtraction of amount over setting to zero on purpose to not limit future higher level logic
userOrder.pending = isIncrement ? userOrder.pending + amount : userOrder.pending - amount;
userOrder.lastUpdate = requestType == RequestType.Deposit
? nowDepositEpoch(poolId, scId_, assetId)
: nowRedeemEpoch(poolId, scId_, assetId);
if (requestType == RequestType.Deposit) {
_updatePendingDeposit(poolId, scId_, amount, isIncrement, investor, assetId, userOrder, queued);
} else {
_updatePendingRedeem(poolId, scId_, amount, isIncrement, investor, assetId, userOrder, queued);
}
}
/// @notice Checks whether the pending amount can be updated. If not, it updates the queued amount.
///
/// @param poolId Identifier of the pool
/// @param scId_ Identifier of the share class
/// @param amount Amount which is updated
/// @param isIncrement Whether the amount is positive (additional request) or negative (cancellation)
/// @param investor Address of the entity which is depositing
/// @param assetId Identifier of the asset which the investor either used as deposit or wants to redeem to
/// @param userOrder User order storage for the deposit or redeem request
/// @param requestType Flag indicating whether the request is a deposit or redeem request
/// @return skipPendingUpdate Flag indicating whether the pending amount can be updated which is true if the user
/// does not need to claim
function _updateQueued(
PoolId poolId,
ShareClassId scId_,
uint128 amount,
bool isIncrement,
bytes32 investor,
AssetId assetId,
UserOrder storage userOrder,
QueuedOrder storage queued,
RequestType requestType
) internal returns (bool skipPendingUpdate) {
uint32 currentEpoch = requestType == RequestType.Deposit
? nowDepositEpoch(poolId, scId_, assetId)
: nowRedeemEpoch(poolId, scId_, assetId);
// Short circuit if user can mutate pending, i.e. last update happened after latest approval or is first update
if (_canMutatePending(userOrder, currentEpoch)) {
return false;
}
// Block increasing queued amount if cancelling is already queued
// NOTE: Can only happen due to race condition as Vaults blocks requests if cancellation is in progress
require(!(queued.isCancelling && amount > 0), CancellationQueued());
if (!isIncrement) {
queued.isCancelling = true;
} else {
queued.amount += amount;
}
if (requestType == RequestType.Deposit) {
uint128 pendingTotal = pendingDeposit[poolId][scId_][assetId];
emit UpdateDepositRequest(
poolId,
scId_,
assetId,
currentEpoch,
investor,
userOrder.pending,
pendingTotal,
queued.amount,
queued.isCancelling
);
} else {
uint128 pendingTotal = pendingRedeem[poolId][scId_][assetId];
emit UpdateRedeemRequest(
poolId,
scId_,
assetId,
currentEpoch,
investor,
userOrder.pending,
pendingTotal,
queued.amount,
queued.isCancelling
);
}
return true;
}
function _updatePendingDeposit(
PoolId poolId,
ShareClassId scId_,
uint128 amount,
bool isIncrement,
bytes32 investor,
AssetId assetId,
UserOrder storage userOrder,
QueuedOrder memory queued
) internal {
uint128 pendingTotal = pendingDeposit[poolId][scId_][assetId];
pendingTotal = isIncrement ? pendingTotal + amount : amount > pendingTotal ? 0 : pendingTotal - amount;
pendingDeposit[poolId][scId_][assetId] = pendingTotal;
emit UpdateDepositRequest(
poolId,
scId_,
assetId,
nowDepositEpoch(poolId, scId_, assetId),
investor,
userOrder.pending,
pendingTotal,
queued.amount,
queued.isCancelling
);
}
function _updatePendingRedeem(
PoolId poolId,
ShareClassId scId_,
uint128 amount,
bool isIncrement,
bytes32 investor,
AssetId assetId,
UserOrder storage userOrder,
QueuedOrder memory queued
) internal {
uint128 pendingTotal = pendingRedeem[poolId][scId_][assetId];
pendingTotal = isIncrement ? pendingTotal + amount : amount > pendingTotal ? 0 : pendingTotal - amount;
pendingRedeem[poolId][scId_][assetId] = pendingTotal;
emit UpdateRedeemRequest(
poolId,
scId_,
assetId,
nowRedeemEpoch(poolId, scId_, assetId),
investor,
userOrder.pending,
pendingTotal,
queued.amount,
queued.isCancelling
);
}
/// @dev A user cannot mutate their pending amount at all times because it affects the total pending amount. It is
/// restricted to the following three conditions:
/// 1. It's the first epoch (currentEpoch <= 1), which implies userOrder.lastUpdate == 0
/// 2. User has no pending amount (userOrder.pending == 0)
/// 3. User's last update is not behind the current epoch (userOrder.lastUpdate >= currentEpoch)
function _canMutatePending(UserOrder memory userOrder, uint32 currentEpoch) internal pure returns (bool) {
return currentEpoch <= 1 || userOrder.pending == 0 || userOrder.lastUpdate >= currentEpoch;
}
}
contracts/core/hub/interfaces/IHubRegistry.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {IHubRequestManager} from "./IHubRequestManager.sol";
import {IERC6909Decimals} from "../../../misc/interfaces/IERC6909.sol";
import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
interface IHubRegistry is IERC6909Decimals {
//----------------------------------------------------------------------------------------------
// Events
//----------------------------------------------------------------------------------------------
event NewAsset(AssetId indexed assetId, uint8 decimals);
event NewPool(PoolId poolId, address indexed manager, AssetId indexed currency);
event UpdateManager(PoolId indexed poolId, address indexed manager, bool canManage);
event SetMetadata(PoolId indexed poolId, bytes metadata);
event UpdateDependency(PoolId indexed poolId, bytes32 indexed what, address dependency);
event UpdateCurrency(PoolId indexed poolId, AssetId currency);
event SetHubRequestManager(PoolId indexed poolId, uint16 indexed rivrId, IHubRequestManager manager);
//----------------------------------------------------------------------------------------------
// Errors
//----------------------------------------------------------------------------------------------
error NonExistingPool(PoolId id);
error AssetAlreadyRegistered();
error PoolAlreadyRegistered();
error EmptyAccount();
error EmptyCurrency();
error EmptyShareClassManager();
error AssetNotFound();
//----------------------------------------------------------------------------------------------
// Registration methods
//----------------------------------------------------------------------------------------------
/// @notice Register a new asset
/// @param assetId The asset identifier
/// @param decimals_ The number of decimals for the asset
function registerAsset(AssetId assetId, uint8 decimals_) external;
/// @notice Register a new pool
/// @param poolId The pool identifier
/// @param manager The initial manager address for the pool
/// @param currency The currency asset for the pool
function registerPool(PoolId poolId, address manager, AssetId currency) external;
//----------------------------------------------------------------------------------------------
// Update methods
//----------------------------------------------------------------------------------------------
/// @notice Allow/disallow an address as a manager for the pool
/// @param poolId The pool identifier
/// @param newManager The address to update manager status for
/// @param canManage Whether the address can manage the pool
function updateManager(PoolId poolId, address newManager, bool canManage) external;
/// @notice Set the hub request manager for a pool on a specific network
/// @param poolId The pool identifier
/// @param rivr The network identifier
/// @param manager The hub request manager contract
function setHubRequestManager(PoolId poolId, uint16 rivr, IHubRequestManager manager) external;
/// @notice Sets metadata for this pool
/// @param poolId The pool identifier
/// @param metadata The metadata to attach
function setMetadata(PoolId poolId, bytes calldata metadata) external;
/// @notice Updates a dependency of the system
/// @param poolId The pool identifier
/// @param what The dependency identifier
/// @param dependency The dependency contract address
function updateDependency(PoolId poolId, bytes32 what, address dependency) external;
/// @notice Updates the currency of the pool
/// @param poolId The pool identifier
/// @param currency The new currency asset
function updateCurrency(PoolId poolId, AssetId currency) external;
//----------------------------------------------------------------------------------------------
// View methods
//----------------------------------------------------------------------------------------------
/// @notice Returns the metadata attached to the pool, if any
/// @param poolId The pool identifier
/// @return The metadata bytes
function metadata(PoolId poolId) external view returns (bytes memory);
/// @notice Returns the currency of the pool
/// @param poolId The pool identifier
/// @return The currency asset identifier
function currency(PoolId poolId) external view returns (AssetId);
/// @notice Returns the dependency used in the system
/// @param poolId The pool identifier
/// @param what The dependency identifier
/// @return The dependency contract address
function dependency(PoolId poolId, bytes32 what) external view returns (address);
/// @notice Returns whether the account is a manager
/// @param poolId The pool identifier
/// @param who The address to check
/// @return Whether the address is a manager
function manager(PoolId poolId, address who) external view returns (bool);
/// @notice Returns the hub request manager for a pool and rivr ID
/// @param poolId The pool identifier
/// @param rivrId The network identifier
/// @return The hub request manager contract
function hubRequestManager(PoolId poolId, uint16 rivrId) external view returns (IHubRequestManager);
/// @notice Compute a pool ID given an ID postfix
/// @param rivrId The network identifier
/// @param postfix The pool ID postfix
/// @return poolId The computed pool identifier
function poolId(uint16 rivrId, uint48 postfix) external view returns (PoolId poolId);
/// @notice Returns the decimals for an asset
/// @param assetId The asset identifier
/// @return The number of decimals
function decimals(AssetId assetId) external view returns (uint8);
/// @notice Returns the decimals for a pool
/// @param poolId The pool identifier
/// @return The number of decimals
function decimals(PoolId poolId) external view returns (uint8);
/// @notice Checks the existence of a pool
/// @param poolId The pool identifier
/// @return Whether the pool exists
function exists(PoolId poolId) external view returns (bool);
/// @notice Checks the existence of an asset
/// @param assetId The asset identifier
/// @return Whether the asset is registered
function isRegistered(AssetId assetId) external view returns (bool);
}
contracts/core/hub/interfaces/IHubRequestManager.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {IERC165} from "../../../misc/interfaces/IERC165.sol";
import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";
interface IHubRequestManager is IERC165 {
/// @notice Handles a request originating from the Hub side, similar to HubHelpers.request
function request(PoolId poolId, ShareClassId scId, AssetId assetId, bytes calldata payload) external;
}
interface IHubRequestManagerNotifications is IERC165 {
/// @notice Notify a deposit for an investor address located in the chain where the asset belongs
function notifyDeposit(
PoolId poolId,
ShareClassId scId,
AssetId depositAssetId,
bytes32 investor,
uint32 maxClaims,
address refund
) external payable;
/// @notice Notify a redemption for an investor address located in the chain where the asset belongs
function notifyRedeem(
PoolId poolId,
ShareClassId scId,
AssetId payoutAssetId,
bytes32 investor,
uint32 maxClaims,
address refund
) external payable;
}
contracts/core/hub/interfaces/IHubRequestManagerCallback.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";
interface IHubRequestManagerCallback {
/// @notice Handles a request callback originating from a hub request manager.
/// @param poolId The pool id
/// @param scId The share class id
/// @param assetId The asset id
/// @param payload The payload to be processed by the request callback
/// @param extraGasLimit Extra gas limit for the callback
/// @param refund address to refund the excedent of the payment
function requestCallback(
PoolId poolId,
ShareClassId scId,
AssetId assetId,
bytes calldata payload,
uint128 extraGasLimit,
bool unpaidMode,
address refund
) external payable;
}
contracts/core/libraries/PricingLib.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {D18, d18} from "../../misc/types/D18.sol";
import {MathLib} from "../../misc/libraries/MathLib.sol";
import {IERC20Metadata} from "../../misc/interfaces/IERC20.sol";
import {IERC6909MetadataExt} from "../../misc/interfaces/IERC6909.sol";
library PricingLib {
using MathLib for *;
error DivisionByZero();
/// @dev Prices are fixed-point integers with 18 decimals
uint8 internal constant PRICE_DECIMALS = 18;
//----------------------------------------------------------------------------------------------
// View methods
//----------------------------------------------------------------------------------------------
/// @dev Converts the given asset amount to share amount. Returned value is in share decimals.
/// @dev Assumes handling of zero denominator price (priceAssetPerShare_) by consumer.
///
/// NOTE: MUST ONLY be used in AsyncRequestManager which rely on priceAssetPerShare that is derived from
/// Fulfilled* message amounts. Any other codepath must use the variant with pricePoolPerAsset
/// and pricePoolPerShare
function assetToShareAmount(
address shareToken,
address asset,
uint256 tokenId,
uint128 assetAmount,
D18 priceAssetPerShare_,
MathLib.Rounding rounding
) internal view returns (uint128 shares) {
if (assetAmount == 0) {
return 0;
}
uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
uint8 shareDecimals = IERC20Metadata(shareToken).decimals();
return PricingLib.convertWithReciprocalPrice(
assetAmount, assetDecimals, shareDecimals, priceAssetPerShare_, rounding
).toUint128();
}
/// @dev Converts the given asset amount to share amount. Returned value is in share decimals.
/// @dev Assumes handling of zero denominator price (pricePoolPerShare) by consumer.
function assetToShareAmount(
address shareToken,
address asset,
uint256 tokenId,
uint128 assetAmount,
D18 pricePoolPerAsset,
D18 pricePoolPerShare,
MathLib.Rounding rounding
) internal view returns (uint128 shares) {
if (assetAmount == 0 || pricePoolPerAsset.isZero()) {
return 0;
}
uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
uint8 shareDecimals = IERC20Metadata(shareToken).decimals();
return PricingLib.assetToShareAmount(
assetAmount, assetDecimals, shareDecimals, pricePoolPerAsset, pricePoolPerShare, rounding
).toUint128();
}
/// @dev Converts the given share amount to asset amount. Returned value is in share decimals.
///
/// NOTE: MUST ONLY be used in AsyncRequestManager which rely on priceAssetPerShare that is derived from
/// Fulfilled* message amounts. Any other codepath must use the variant with pricePoolPerAsset and
/// pricePoolPerShare
function shareToAssetAmount(
address shareToken,
uint128 shareAmount,
address asset,
uint256 tokenId,
D18 priceAssetPerShare_,
MathLib.Rounding rounding
) internal view returns (uint128 assets) {
if (shareAmount == 0 || priceAssetPerShare_.isZero()) {
return 0;
}
uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
uint8 shareDecimals = IERC20Metadata(shareToken).decimals();
return PricingLib.convertWithPrice(shareAmount, shareDecimals, assetDecimals, priceAssetPerShare_, rounding);
}
/// @dev Converts the given share amount to asset amount. Returned value is in share decimals.
/// @dev Assumes handling of zero denominator price (pricePoolPerAsset) by consumer.
function shareToAssetAmount(
address shareToken,
uint128 shareAmount,
address asset,
uint256 tokenId,
D18 pricePoolPerShare,
D18 pricePoolPerAsset,
MathLib.Rounding rounding
) internal view returns (uint128 shares) {
if (shareAmount == 0 || pricePoolPerShare.isZero()) {
return 0;
}
uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
uint8 shareDecimals = IERC20Metadata(shareToken).decimals();
// NOTE: Pool and share denomination are always equal by design
return PricingLib.shareToAssetAmount(
shareAmount, shareDecimals, assetDecimals, pricePoolPerShare, pricePoolPerAsset, rounding
).toUint128();
}
/// @dev Calculates the asset price per share returns the value in price decimals
/// Denominated in ASSET_UNIT/SHARE_UNIT
/// @dev Assumes handling of zero denominator (shares == 0) by consumer.
function calculatePriceAssetPerShare(
address shareToken,
uint128 shares,
address asset,
uint256 tokenId,
uint128 assets,
MathLib.Rounding rounding
) internal view returns (D18 priceAssetPerShare_) {
if (assets == 0) {
return d18(0);
}
uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
uint8 shareDecimals = IERC20Metadata(shareToken).decimals();
// NOTE: More precise than utilizing D18
return d18(
_toPriceDecimals(assets, assetDecimals)
.mulDiv(10 ** PRICE_DECIMALS, _toPriceDecimals(shares, shareDecimals), rounding).toUint128()
);
}
/// @dev Calculates the maximum amount of assets that can be converted to shares without uint128 overflow.
/// Returns the maximum asset amount such that assetToShareAmount(result) <= maxShares.
/// @dev Assumes handling of zero denominator price (pricePoolPerAsset) by consumer.
/// @param shareToken Address of the share token
/// @param asset Address of the asset
/// @param tokenId Token ID for ERC6909 (0 for ERC20)
/// @param maxShares Maximum allowed shares (typically type(uint128).max)
/// @param pricePoolPerShare Price of share in pool units (numerator)
/// @param pricePoolPerAsset Price of asset in pool units (denominator)
/// @return Maximum asset amount that won't cause overflow, or type(uint256).max if no overflow possible
function maxConvertibleAssetAmount(
address shareToken,
address asset,
uint256 tokenId,
uint256 maxShares,
D18 pricePoolPerShare,
D18 pricePoolPerAsset
) internal view returns (uint256) {
require(pricePoolPerAsset.isNotZero(), DivisionByZero());
uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
uint8 shareDecimals = IERC20Metadata(shareToken).decimals();
return MathLib.mulDiv(
maxShares,
uint256(10 ** assetDecimals) * pricePoolPerShare.raw(),
uint256(10 ** shareDecimals) * pricePoolPerAsset.raw(),
MathLib.Rounding.Down
);
}
//----------------------------------------------------------------------------------------------
// Pure methods
//----------------------------------------------------------------------------------------------
/// @dev Converts an amount using decimals and price with implicit rounding down
function convertWithPrice(uint256 baseAmount, uint8 baseDecimals, uint8 quoteDecimals, D18 priceQuotePerBase)
internal
pure
returns (uint128 quoteAmount)
{
return convertWithPrice(baseAmount, baseDecimals, quoteDecimals, priceQuotePerBase, MathLib.Rounding.Down);
}
/// @dev Converts an amount using decimals and price with explicit rounding.
function convertWithPrice(
uint256 baseAmount,
uint8 baseDecimals,
uint8 quoteDecimals,
D18 priceQuotePerBase,
MathLib.Rounding rounding
) internal pure returns (uint128 quoteAmount) {
if (baseDecimals == quoteDecimals) {
return priceQuotePerBase.mulUint256(baseAmount, rounding).toUint128();
}
return MathLib.mulDiv(
priceQuotePerBase.raw(),
baseAmount * 10 ** quoteDecimals,
10 ** (baseDecimals + PRICE_DECIMALS),
rounding
) // cancel out exponentiation from D18 multiplication
.toUint128();
}
/// @dev Converts an amount using decimals and reciprocal price.
/// @dev Assumes handling of zero denominator price (priceBasePerQuote) by consumer.
///
/// NOTE: More precise than convertWithPrice(,,,price.reciprocal,)
function convertWithReciprocalPrice(
uint256 baseAmount,
uint8 baseDecimals,
uint8 quoteDecimals,
D18 priceBasePerQuote,
MathLib.Rounding rounding
) internal pure returns (uint128 quoteAmount) {
require(priceBasePerQuote.isNotZero(), DivisionByZero());
if (baseDecimals == quoteDecimals) {
return priceBasePerQuote.reciprocalMulUint256(baseAmount, rounding).toUint128();
}
return MathLib.mulDiv(
10 ** quoteDecimals * baseAmount,
10 ** PRICE_DECIMALS,
10 ** baseDecimals * priceBasePerQuote.raw(),
rounding
).toUint128();
}
/// @dev Converts an amount using decimals and two prices.
/// @dev Assumes handling of zero denominator price (priceDenominator) by consumer.
///
/// NOTE: More precise than custom math with one price and convertWith{Reciprocal}Price for the other
function convertWithPrices(
uint256 baseAmount,
uint8 baseDecimals,
uint8 quoteDecimals,
D18 priceNumerator,
D18 priceDenominator,
MathLib.Rounding rounding
) internal pure returns (uint128 quoteAmount) {
require(priceDenominator.isNotZero(), DivisionByZero());
return MathLib.mulDiv(
priceNumerator.raw(),
10 ** quoteDecimals * baseAmount,
10 ** baseDecimals * priceDenominator.raw(),
rounding
).toUint128();
}
/// @dev Converts asset amount to share amount.
/// @dev Assumes handling of zero denominator price (pricePoolPerShare) by consumer.
///
/// NOTE: Pool and share denomination are always equal by design
function assetToShareAmount(
uint256 assetAmount,
uint8 assetDecimals,
uint8 shareDecimals,
D18 pricePoolPerAsset,
D18 pricePoolPerShare,
MathLib.Rounding rounding
) internal pure returns (uint128 shareAmount) {
return convertWithPrices(
assetAmount, assetDecimals, shareDecimals, pricePoolPerAsset, pricePoolPerShare, rounding
);
}
/// @dev Converts share amount to asset asset amount.
/// @dev Assumes handling of zero denominator price (pricePoolPerAsset) by consumer.
///
/// NOTE: Pool and share denomination are always equal by design
function shareToAssetAmount(
uint256 shareAmount,
uint8 shareDecimals,
uint8 assetDecimals,
D18 pricePoolPerShare,
D18 pricePoolPerAsset,
MathLib.Rounding rounding
) internal pure returns (uint128 assetAmount) {
return convertWithPrices(
shareAmount, shareDecimals, assetDecimals, pricePoolPerShare, pricePoolPerAsset, rounding
);
}
/// @dev Converts pool amount to asset amount.
/// @dev Assumes handling of zero denominator price (pricePoolPerAsset) by consumer.
function poolToAssetAmount(
uint256 poolAmount,
uint8 poolDecimals,
uint8 assetDecimals,
D18 pricePoolPerAsset,
MathLib.Rounding rounding
) internal pure returns (uint128 assetAmount) {
return convertWithReciprocalPrice(poolAmount, poolDecimals, assetDecimals, pricePoolPerAsset, rounding);
}
/// @dev Converts asset amount to pool amount.
function assetToPoolAmount(
uint128 assetAmount,
uint8 assetDecimals,
uint8 poolDecimals,
D18 pricePoolPerAsset,
MathLib.Rounding rounding
) internal pure returns (uint128 poolAmount) {
return convertWithPrice(assetAmount, assetDecimals, poolDecimals, pricePoolPerAsset, rounding);
}
/// @dev Returns the asset price per share denominated in ASSET_UNIT/SHARE_UNIT
/// @dev Assumes handling of zero denominator price (pricePoolPerAsset) by consumer.
///
/// NOTE: Should never be used for calculating amounts due to precision loss. Instead, please refer to
/// conversion relying on pricePoolPerShare and pricePoolPerAsset.
function priceAssetPerShare(D18 pricePoolPerShare, D18 pricePoolPerAsset)
internal
pure
returns (D18 priceAssetPerShare_)
{
return pricePoolPerShare / pricePoolPerAsset;
}
//----------------------------------------------------------------------------------------------
// Private methods
//----------------------------------------------------------------------------------------------
/// @dev Returns the asset decimals
function _getAssetDecimals(address asset, uint256 tokenId) private view returns (uint8 assetDecimals) {
return tokenId == 0 ? IERC20Metadata(asset).decimals() : IERC6909MetadataExt(asset).decimals(tokenId);
}
/// @dev When converting assets to shares using the price, all values are normalized to PRICE_DECIMALS
/// NOTE: We require all assets to have 2 <= decimals <= 18, see `Spoke.registerAsset`
function _toPriceDecimals(uint128 _value, uint8 decimals) private pure returns (uint256) {
if (PRICE_DECIMALS == decimals) return uint256(_value);
return uint256(_value) * 10 ** (PRICE_DECIMALS - decimals);
}
}
contracts/core/messaging/interfaces/IGateway.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {IMessageHandler} from "./IMessageHandler.sol";
import {IRecoverable} from "../../../misc/interfaces/IRecoverable.sol";
import {PoolId} from "../../types/PoolId.sol";
// Reserved gas amount for processing a message failure (assuming the worst case)
uint256 constant PROCESS_FAIL_MESSAGE_GAS = 35_000;
// Max length for a supported message. Note that a batch can use several messages with this length.
uint256 constant MESSAGE_MAX_LENGTH = 1_000;
// Max length of an error that happens when processing a message.
uint16 constant ERR_MAX_LENGTH = 32 * 4; // enough for most errors
/// @notice Interface for dispatch-only gateway
interface IGateway is IMessageHandler, IRecoverable {
//----------------------------------------------------------------------------------------------
// Structs
//----------------------------------------------------------------------------------------------
struct Underpaid {
uint128 gasLimit;
uint64 counter;
}
//----------------------------------------------------------------------------------------------
// Events
//----------------------------------------------------------------------------------------------
event File(bytes32 indexed what, address addr);
event UpdateManager(PoolId poolId, address who, bool canManage);
event BlockOutgoing(uint16 rivrId, PoolId poolId, bool isBlocked);
event PrepareMessage(uint16 indexed rivrId, PoolId poolId, bytes message);
event UnderpaidBatch(uint16 indexed rivrId, bytes batch, bytes32 batchHash);
event RepayBatch(uint16 indexed rivrId, bytes batch);
event ExecuteMessage(uint16 indexed rivrId, bytes32 messageHash);
event FailMessage(uint16 indexed rivrId, bytes32 messageHash, bytes error);
event SetRefundAddress(PoolId poolId, IRecoverable refund);
event DepositSubsidy(PoolId indexed poolId, address indexed sender, uint256 amount);
event WithdrawSubsidy(PoolId indexed poolId, address indexed sender, uint256 amount);
//----------------------------------------------------------------------------------------------
// Errors
//----------------------------------------------------------------------------------------------
/// @notice Dispatched when the `what` parameter of `file()` is not supported by the implementation.
error FileUnrecognizedParam();
/// @notice Dispatched when the batch is ended without starting it.
error NoBatched();
/// @notice Dispatched when the gateway is paused.
error Paused();
/// @notice Dispatched when the gateway tries to send an empty message.
error EmptyMessage();
/// @notice Dispatched when the message exceeds MESSAGE_MAX_LENGTH.
error TooLongMessage();
/// @notice Dispatched when a message that has not failed is retried.
error NotFailedMessage();
/// @notice Dispatched when a batch that has not been underpaid is repaid.
error NotUnderpaidBatch();
/// @notice Dispatched when the content of a batch doesn't belong to the same pool
error MalformedBatch();
/// @notice Dispatched when a message is sent but the gateway is blocked for sending messages
error OutgoingBlocked();
/// @notice Dispatched when an account is not valid to withdraw subsidized pool funds
error CannotRefund();
/// @notice Dispatched when there is not enough gas to send the message
error NotEnoughGas();
/// @notice Dispatched when the batch requires more gas than the destination chain can execute in a single transaction
error BatchTooExpensive();
/// @notice Dispatched when a message was batched but there was a payment for it
error NotPayable();
/// @notice Dispatched when the callback fails with no error
error CallFailedWithEmptyRevert();
/// @notice Dispatched when the callback is called inside the callback
error CallbackIsLocked();
/// @notice Dispatched when the user doesn't call lockCallback()
error CallbackWasNotLocked();
/// @notice Dispatched when the callback was not from the sender
error CallbackWasNotFromSender();
/// @notice Dispatched when there is not enough msg.value to send to the callback
error NotEnoughValueForCallback();
/// @notice Dispatched when trying to create a batch during the send loop
error ReentrantBatchCreation();
//----------------------------------------------------------------------------------------------
// Administration
//----------------------------------------------------------------------------------------------
/// @notice Used to update an address (state variable) on very rare occasions
/// @param what The name of the variable to be updated
/// @param data New address
function file(bytes32 what, address data) external;
/// @notice Configures a manager address for a pool
/// @param poolId PoolId associated to the adapters
/// @param who Manager address
/// @param canManage If enabled as manager
function updateManager(PoolId poolId, address who, bool canManage) external;
/// @notice Indicates if the gateway for a determined pool can send messages or not
/// @param rivrId RIVR ID associated to this block
/// @param poolId PoolId associated to this block
/// @param canSend If can send messages or not
function blockOutgoing(uint16 rivrId, PoolId poolId, bool canSend) external;
//----------------------------------------------------------------------------------------------
// Message handling
//----------------------------------------------------------------------------------------------
/// @notice Repay an underpaid batch
/// @param rivrId The destination chain
/// @param batch The batch to repay
/// @param refund Address to refund excess payment
function repay(uint16 rivrId, bytes memory batch, address refund) external payable;
/// @notice Retry a failed message
/// @param rivrId The destination chain
/// @param message The message to retry
function retry(uint16 rivrId, bytes memory message) external;
/// @notice Handling outgoing messages
/// @param rivrId Destination chain
/// @param message The message to send
/// @param unpaidMode Tells if storing the message as unpaid if not enough funds
/// @param refund Address to refund excess payment
function send(uint16 rivrId, bytes calldata message, bool unpaidMode, address refund) external payable;
//----------------------------------------------------------------------------------------------
// Batching
//----------------------------------------------------------------------------------------------
/// @notice Automatic batching of cross-chain transactions through a callback.
/// Any cross-chain transactions triggered in this callback will automatically be batched.
/// @dev Should be used like:
/// ```
/// contract Integration {
/// IGateway gateway;
///
/// function doSomething(PoolId poolId) external {
/// gateway.withBatch(abi.encodeWithSelector(Integration.callback.selector, poolId));
/// }
///
/// function callback(PoolId poolId) external {
/// // Avoid reentrancy to the callback and ensure it's called from withBatch in the same contract:
/// gateway.lockCallback();
///
/// // Call several hub, balance sheet, or spoke methods that trigger cross-chain transactions
/// }
/// }
/// ```
///
/// NOTE: inside callback, `msgSender` should be used instead of msg.sender
/// @param callbackData encoding data for the callback method
/// @param callbackValue msg.value to send to the callback
/// @param refund Address to refund excess payment
function withBatch(bytes memory callbackData, uint256 callbackValue, address refund) external payable;
/// @notice Same as withBatch(..), but without sending any msg.value to the callback
function withBatch(bytes memory callbackData, address refund) external payable;
/// @notice Ensures the callback is called by withBatch in the same contract.
/// @dev calling this at the very beginning inside the multicall means:
/// - The callback is called from the gateway under `withBatch`.
/// - The callback is called from the same contract, because withBatch uses `msg.sender` as target for the callback
/// - The callback that uses this can only be called once inside withBatch scope. No reentrancy.
function lockCallback() external;
//----------------------------------------------------------------------------------------------
// View methods
//----------------------------------------------------------------------------------------------
/// @notice Returns the current gateway batching level
/// @return Whether the gateway is currently batching
function isBatching() external view returns (bool);
}
contracts/core/messaging/interfaces/IMessageHandler.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
/// @notice Generic interface for entities that handle incoming messages
interface IMessageHandler {
//----------------------------------------------------------------------------------------------
// Incoming
//----------------------------------------------------------------------------------------------
/// @notice Handling incoming messages
/// @param rivrId Source chain
/// @param message Incoming message
function handle(uint16 rivrId, bytes calldata message) external;
}
contracts/core/types/AssetId.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
/// @dev Composite Id of the rivrId (uint16) where the asset resides
/// and a local counter (uint64) that is part of the contract that registers the asset.
type AssetId is uint128;
function isNull(AssetId assetId) pure returns (bool) {
return AssetId.unwrap(assetId) == 0;
}
function raw(AssetId assetId) pure returns (uint128) {
return AssetId.unwrap(assetId);
}
function rivrId(AssetId assetId) pure returns (uint16) {
return uint16(AssetId.unwrap(assetId) >> 112);
}
function newAssetId(uint16 rivrId_, uint64 counter) pure returns (AssetId) {
return AssetId.wrap((uint128(rivrId_) << 112) + counter);
}
function newAssetId(uint32 isoCode) pure returns (AssetId) {
return AssetId.wrap(isoCode);
}
function eq(AssetId a, AssetId b) pure returns (bool) {
return a.raw() == b.raw();
}
using {isNull, raw, rivrId, eq as ==} for AssetId global;
contracts/core/types/PoolId.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {MathLib} from "../../misc/libraries/MathLib.sol";
using MathLib for uint256;
type PoolId is uint64;
function rivrId(PoolId poolId) pure returns (uint16) {
return uint16(PoolId.unwrap(poolId) >> 48);
}
function newPoolId(uint16 rivrId_, uint48 localPoolId) pure returns (PoolId) {
return PoolId.wrap((uint64(rivrId_) << 48) | uint64(localPoolId));
}
function isNull(PoolId poolId) pure returns (bool) {
return PoolId.unwrap(poolId) == 0;
}
function isEqual(PoolId a, PoolId b) pure returns (bool) {
return PoolId.unwrap(a) == PoolId.unwrap(b);
}
function raw(PoolId poolId) pure returns (uint64) {
return PoolId.unwrap(poolId);
}
using {rivrId, isNull, raw, isEqual as ==} for PoolId global;
contracts/core/types/ShareClassId.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {PoolId} from "./PoolId.sol";
type ShareClassId is bytes16;
function isNull(ShareClassId scId) pure returns (bool) {
return ShareClassId.unwrap(scId) == 0;
}
function index(ShareClassId scId) pure returns (uint32) {
return uint32(uint128(ShareClassId.unwrap(scId)));
}
function equals(ShareClassId left, ShareClassId right) pure returns (bool) {
return ShareClassId.unwrap(left) == ShareClassId.unwrap(right);
}
function raw(ShareClassId scId) pure returns (bytes16) {
return ShareClassId.unwrap(scId);
}
function newShareClassId(PoolId poolId, uint32 index_) pure returns (ShareClassId scId) {
return ShareClassId.wrap(bytes16((uint128(PoolId.unwrap(poolId)) << 64) + index_));
}
using {isNull, index, raw, equals as ==} for ShareClassId global;
contracts/core/utils/BatchedMulticall.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {IBatchedMulticall} from "./interfaces/IBatchedMulticall.sol";
import {Multicall, IMulticall} from "../../misc/Multicall.sol";
import {IGateway} from "../messaging/interfaces/IGateway.sol";
/// @title BatchedMulticall
/// @notice Abstract contract that extends Multicall with gateway batching support, enabling efficient
/// aggregation of multiple cross-chain messages into a single batch to reduce transaction costs
/// while coordinating payment handling across batched operations.
/// @dev IMPORTANT: Integrators MUST replace msg.sender with msgSender() and msg.value with msgValue()
/// for the methods called by the multicall.
/// @dev IMPORTANT: The contract which extends BatchedMulticall must not treat the gateway
/// as a permissioned/authenticated msg.sender to avoid the multicall execution to call auth methods,
/// opening security issues.
abstract contract BatchedMulticall is Multicall, IBatchedMulticall {
IGateway public gateway;
address private transient _sender;
constructor(IGateway gateway_) {
gateway = gateway_;
}
/// @inheritdoc IMulticall
/// @notice With extra support for batching
function multicall(bytes[] calldata data) public payable override {
require(_sender == address(0), AlreadyBatching());
_sender = msg.sender;
gateway.withBatch{value: msg.value}(
abi.encodeWithSelector(BatchedMulticall.executeMulticall.selector, data), msg.sender
);
_sender = address(0);
}
function executeMulticall(bytes[] calldata data) external payable protected {
gateway.lockCallback();
super.multicall(data);
}
/// @dev Integrators MUST use msgSender() instead of msg.sender, since this is replaced
/// by the gateway address inside the multicall.
function msgSender() internal view virtual returns (address) {
return _sender != address(0) && msg.sender == address(gateway) ? _sender : msg.sender;
}
/// @dev Only the call to multicall should pass the msg.value, which is then passed
/// in `gateway.withBatch`. No inner calls should pass any msg.value.
function msgValue() internal view returns (uint256 value) {
return _sender != address(0) ? 0 : msg.value;
}
}
contracts/core/utils/interfaces/IBatchedMulticall.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {IGateway} from "../../messaging/interfaces/IGateway.sol";
/// @notice A multicall that batches the messages using the gateway
interface IBatchedMulticall {
error AlreadyBatching();
/// @notice Returns the gateway contract used for batching messages
/// @return The gateway contract instance
function gateway() external view returns (IGateway);
}
contracts/misc/Auth.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {IAuth} from "./interfaces/IAuth.sol";
/// @title Auth
/// @notice Simple authentication pattern
/// @author Based on code from https://github.com/makerdao/dss
abstract contract Auth is IAuth {
/// @inheritdoc IAuth
mapping(address => uint256) public wards;
constructor(address initialWard) {
wards[initialWard] = 1;
emit Rely(initialWard);
}
/// @dev Check if the msg.sender has permissions
modifier auth() {
require(wards[msg.sender] == 1, NotAuthorized());
_;
}
/// @inheritdoc IAuth
function rely(address user) public auth {
wards[user] = 1;
emit Rely(user);
}
/// @inheritdoc IAuth
function deny(address user) public auth {
wards[user] = 0;
emit Deny(user);
}
}
contracts/misc/Multicall.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
// NOTE: This file has warning disabled due https://github.com/ethereum/solidity/issues/14359
// If perform any change on it, please ensure no other warnings appears
import {IMulticall} from "./interfaces/IMulticall.sol";
import {ReentrancyProtection} from "./ReentrancyProtection.sol";
/// @title Multicall
/// @notice Abstract contract that enables batch execution of multiple function calls in a single transaction.
abstract contract Multicall is ReentrancyProtection, IMulticall {
function multicall(bytes[] calldata data) public payable virtual protected {
uint256 totalBytes = data.length;
for (uint256 i; i < totalBytes; ++i) {
(bool success, bytes memory returnData) = address(this).delegatecall(data[i]);
if (!success) {
uint256 length = returnData.length;
require(length != 0, CallFailedWithEmptyRevert());
assembly ("memory-safe") {
revert(add(32, returnData), length)
}
}
}
}
}
contracts/misc/ReentrancyProtection.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
// NOTE: This file has warning disabled due https://github.com/ethereum/solidity/issues/14359
// If perform any change on it, please ensure no other warnings appears
/// @title ReentrancyProtection
/// @notice Abstract contract that implements reentrancy protection using transient storage.
abstract contract ReentrancyProtection {
/// @notice Dispatched when there is a re-entrancy issue
error UnauthorizedSender();
address private transient _initiator;
/// @dev The method is protected for reentrancy issues.
modifier protected() {
if (_initiator == address(0)) {
// Single call re-entrancy lock
_initiator = msg.sender;
_;
_initiator = address(0);
} else {
// Multicall re-entrancy lock
require(msg.sender == _initiator, UnauthorizedSender());
_;
}
}
}
contracts/misc/interfaces/IAuth.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
interface IAuth {
event Rely(address indexed user);
event Deny(address indexed user);
error NotAuthorized();
/// @notice Returns whether the target is a ward (has admin access)
/// @param target The address to check for ward status
/// @return The ward status (1 if ward, 0 if not)
function wards(address target) external view returns (uint256);
/// @notice Make user a ward (give them admin access)
/// @param user The address to grant ward status to
function rely(address user) external;
/// @notice Remove user as a ward (remove admin access)
/// @param user The address to remove ward status from
function deny(address user) external;
}
contracts/misc/interfaces/IERC165.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
/**
* @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.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contracts/misc/interfaces/IERC20.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
/// @title IERC20
/// @dev Interface of the ERC20 standard as defined in the EIP.
/// @author Modified from OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
interface IERC20 {
error InvalidAddress();
error InsufficientBalance();
error InsufficientAllowance();
/**
* @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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
error PermitExpired();
error InvalidPermit();
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
interface IERC20Wrapper {
/**
* @dev Returns the address of the underlying ERC-20 token that is being wrapped.
*/
function underlying() external view returns (address);
/**
* @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
*/
function depositFor(address account, uint256 value) external returns (bool);
/**
* @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
*/
function withdrawTo(address account, uint256 value) external returns (bool);
}
contracts/misc/interfaces/IERC6909.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {IERC165} from "./IERC165.sol";
interface IERC6909 is IERC165 {
error EmptyOwner();
error EmptyAmount();
error InvalidTokenId();
error InsufficientBalance(address owner, uint256 tokenId);
error InsufficientAllowance(address sender, uint256 tokenId);
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed tokenId, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed tokenId, uint256 amount);
/// @notice Owner balance of a tokenId.
/// @param owner The address of the owner.
/// @param tokenId The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 tokenId) external view returns (uint256 amount);
/// @notice Spender allowance of a tokenId.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param tokenId The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 tokenId) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of a tokenId from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param tokenId The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts.
function transfer(address receiver, uint256 tokenId, uint256 amount) external returns (bool);
/// @notice Transfers an amount of a tokenId from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param tokenId The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts.
function transferFrom(address sender, address receiver, uint256 tokenId, uint256 amount) external returns (bool);
/// @notice Approves an amount of a tokenId to a spender.
/// @param spender The address of the spender.
/// @param tokenId The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always.
function approve(address spender, uint256 tokenId, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always.
function setOperator(address operator, bool approved) external returns (bool);
}
interface IERC6909URIExt {
event TokenURISet(uint256 indexed tokenId, string uri);
event ContractURISet(address indexed target, string uri);
error EmptyURI();
/// @return uri Returns the common token URI.
function contractURI() external view returns (string memory);
/// @dev Returns empty string if tokenId does not exist.
/// MAY implemented to throw MissingURI(tokenId) error.
/// @param tokenId The token to query URI for.
/// @return uri A string representing the uri for the specific tokenId.
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IERC6909NFT is IERC6909, IERC6909URIExt {
error UnknownTokenId(address owner, uint256 tokenId);
error LessThanMinimalDecimal(uint8 minimal, uint8 actual);
/// @notice Provide URI for a specific tokenId.
/// @param tokenId Token Id.
/// @param URI URI to a document defining the collection as a whole.
function setTokenURI(uint256 tokenId, string memory URI) external;
/// @dev Optional method to set up the contract URI if needed.
/// @param URI URI to a document defining the collection as a whole.
function setContractURI(string memory URI) external;
/// @notice Mint new tokens for a given owner and sets tokenURI.
/// @dev For non-fungible tokens, call with amount = 1, for fungible it could be any amount.
/// TokenId is auto incremented by one.
///
/// @param owner Creates supply of a given tokenId by amount for owner.
/// @param tokenURI URI fortestBurningToken the newly minted token.
/// @return tokenId Id of the newly minted token.
function mint(address owner, string memory tokenURI) external returns (uint256 tokenId);
/// @notice Destroy supply of a given tokenId by amount.
/// @dev The msg.sender MUST be the owner.
///
/// @param tokenId Item which have reduced supply.
function burn(uint256 tokenId) external;
}
/// @notice Extension of ERC6909 Standard for tracking total supply
interface IERC6909TotalSupplyExt {
/// @notice The totalSupply for a token id.
///
/// @param tokenId Id of the token
/// @return supply Total supply for a given `tokenId`
function totalSupply(uint256 tokenId) external returns (uint256 supply);
}
interface IERC6909Decimals {
/// @notice Used to retrieve the decimals of an asset
/// @dev address is used but the value corresponds to a AssetId
function decimals(uint256 assetId) external view returns (uint8);
}
interface IERC6909MetadataExt is IERC6909Decimals {
/// @notice Used to retrieve the decimals of an asset
/// @dev address is used but the value corresponds to a AssetId
function decimals(uint256 assetId) external view returns (uint8);
/// @notice Used to retrieve the name of an asset
/// @dev address is used but the value corresponds to a AssetId
function name(uint256 assetId) external view returns (string memory);
/// @notice Used to retrieve the symbol of an asset
/// @dev address is used but the value corresponds to a AssetId
function symbol(uint256 assetId) external view returns (string memory);
}
interface IERC6909Fungible is IERC6909 {
/// @notice Mint new tokens for a specific tokenid and assign them to an owner
///
/// @param owner Creates supply of a given `tokenId` by `amount` for owner.
/// @param tokenId Id of the item
/// @param amount Adds `amount` to the total supply of the given `tokenId`
function mint(address owner, uint256 tokenId, uint256 amount) external;
/// @notice Destroy supply of a given tokenId by amount.
/// @dev The msg.sender MUST be the owner.
///
/// @param owner Owner of the `tokenId`
/// @param tokenId Id of the item.
/// @param amount Subtract `amount` from the total supply of the given `tokenId`
function burn(address owner, uint256 tokenId, uint256 amount) external;
/// @notice Enforces a transfer from `spender` point of view.
///
///
/// @param sender The owner of the `tokenId`
/// @param receiver Address of the receiving party
/// @param tokenId Token Id
/// @param amount Amount to be transferred
function authTransferFrom(address sender, address receiver, uint256 tokenId, uint256 amount) external returns (bool);
}
/// @dev A factory contract to deploy new collateral contracts implementing IERC6909.
interface IERC6909Factory {
/// Events
event NewTokenDeployment(address indexed owner, address instance);
/// @notice Deploys new install of a contract that implements IERC6909.
/// @dev Factory should deploy deterministically if possible.
///
/// @param owner Owner of the deployed collateral contract which has initial full rights.
/// @param salt Used to make a deterministic deployment.
/// @return An address of the newly deployed contract.
function deploy(address owner, bytes32 salt) external returns (address);
/// @notice Generates a new deterministic address based on the owner and the salt.
///
/// @param owner Owner of the deployed collateral contract which has initial full rights.
/// @param salt Used to make a deterministic deployment.
/// @return An address of the newly deployed contract.
function previewAddress(address owner, bytes32 salt) external returns (address);
}
contracts/misc/interfaces/IMulticall.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
/// @notice Allows to call several calls of the same contract in a single transaction
interface IMulticall {
/// @notice Dispatched when an empty revert is dispatched in a method in the multicall
error CallFailedWithEmptyRevert();
/// @notice Allows caller to execute multiple (batched) messages calls in one transaction.
/// @param data An array of encoded methods of the same contract.
/// @dev No reentrant execution is allowed.
/// If one call fails, it reverts the whole transaction.
/// In order to provide the correct value for functions that require top up,
/// the caller must estimate separately, in advance, how much each of the message call will cost.
/// The `msg.value` when calling this method must be the sum of all estimates.
function multicall(bytes[] calldata data) external payable;
}
contracts/misc/interfaces/IRecoverable.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
address constant ETH_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
interface IRecoverable {
/// @notice Used to recover any ERC-20 token.
/// @dev This method is called only by authorized entities
/// @param token It could be 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
/// to recover locked native ETH or token compatible with ERC20.
/// @param to Receiver of the funds
/// @param amount Amount to send to the receiver.
function recoverTokens(address token, address to, uint256 amount) external;
/// @notice Used to recover any ERC-20 or ERC-6909 token.
/// @dev This method is called only by authorized entities
/// @param token It could be 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
/// to recover locked native ETH or token compatible with ERC20 or ERC6909.
/// @param tokenId The token id, i.e. non-zero if the underlying token is ERC6909 and else zero.
/// @param to Receiver of the funds
/// @param amount Amount to send to the receiver.
function recoverTokens(address token, uint256 tokenId, address to, uint256 amount) external;
}
contracts/misc/libraries/BytesLib.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
/// @title Bytes Lib
/// @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
/// The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
/// @author Modified from Solidity Bytes Arrays Utils v0.8.0
library BytesLib {
error SliceOverflow();
error SliceOutOfBounds();
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
unchecked {
require(_length + 31 >= _length, SliceOverflow());
}
require(_bytes.length >= _start + _length, SliceOutOfBounds());
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function sliceZeroPadded(bytes memory _bytes, uint256 _start, uint256 _length)
internal
pure
returns (bytes memory)
{
bool needsPad = _bytes.length < _start + _length;
if (!needsPad) return slice(_bytes, _start, _length);
bytes memory slice_ = slice(_bytes, _start, _bytes.length - _start);
bytes memory padding = new bytes(_length + _start - _bytes.length);
return bytes.concat(slice_, padding);
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= _start + 20, SliceOutOfBounds());
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= _start + 1, SliceOutOfBounds());
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
require(_bytes.length >= _start + 2, SliceOutOfBounds());
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
require(_bytes.length >= _start + 4, SliceOutOfBounds());
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
require(_bytes.length >= _start + 8, SliceOutOfBounds());
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
require(_bytes.length >= _start + 16, SliceOutOfBounds());
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= _start + 32, SliceOutOfBounds());
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
require(_bytes.length >= _start + 32, SliceOutOfBounds());
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function toBytes16(bytes memory _bytes, uint256 _start) internal pure returns (bytes16) {
require(_bytes.length >= _start + 16, SliceOutOfBounds());
bytes16 tempBytes16;
assembly {
tempBytes16 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes16;
}
function toBool(bytes memory _bytes, uint256 _start) internal pure returns (bool) {
require(_bytes.length > _start, SliceOutOfBounds());
return _bytes[_start] != 0;
}
}
contracts/misc/libraries/CastLib.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
/// @title CastLib
library CastLib {
error PrefixNotZero();
error SizeNot128();
function toAddressLeftPadded(bytes32 addr) internal pure returns (address) {
require(bytes12(addr) == 0, PrefixNotZero());
return address(uint160(uint256(addr)));
}
function toBytes32LeftPadded(address addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(addr)));
}
function toAddress(bytes32 addr) internal pure returns (address) {
require(uint96(uint256(addr)) == 0, PrefixNotZero());
return address(bytes20(addr));
}
function toBytes32(address addr) internal pure returns (bytes32) {
return bytes32(bytes20(addr));
}
/// @dev Adds zero padding
function toBytes32(string memory source) internal pure returns (bytes32) {
return bytes32(bytes(source));
}
/// @dev Removes zero padding
function bytes128ToString(bytes memory _bytes128) internal pure returns (string memory) {
require(_bytes128.length == 128, SizeNot128());
uint8 i = 0;
while (i < 128 && _bytes128[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (uint8 j; j < i; j++) {
bytesArray[j] = _bytes128[j];
}
return string(bytesArray);
}
function toString(bytes32 _bytes32) internal pure returns (string memory) {
uint8 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
}
contracts/misc/libraries/MathLib.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
library MathLib {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
error MulDiv_Overflow();
error Uint8_Overflow();
error Uint16_Overflow();
error Uint32_Overflow();
error Uint64_Overflow();
error Uint96_Overflow();
error Uint128_Overflow();
error Int128_Overflow();
uint256 public constant One27 = 10 ** 27;
/// @notice Returns x^n with rounding precision of base
///
/// @dev Source: https://github.com/makerdao/dss/blob/fa4f6630afb0624d04a003e920b0d71a00331d98/src/jug.sol#L62
///
/// @param x The base value which should be exponentiated
/// @param n The exponent
/// @param base The scaling base, typically used for fix-point calculations
function rpow(uint256 x, uint256 n, uint256 base) public pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 { z := base }
default { z := 0 }
}
default {
switch mod(n, 2)
case 0 { z := base }
default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n, 2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0, 0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0, 0) }
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0, 0) }
z := div(zxRound, base)
}
}
}
}
}
/// @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.
// slither-disable-start divide-before-multiply
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, MulDiv_Overflow());
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
// slither-disable-end divide-before-multiply
/// @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;
}
/// @notice Safe type conversion from uint256 to uint8.
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, Uint8_Overflow());
return uint8(value);
}
/// @notice Safe type conversion from uint256 to uint16.
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, Uint16_Overflow());
return uint16(value);
}
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, Uint32_Overflow());
return uint32(value);
}
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, Uint64_Overflow());
return uint64(value);
}
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, Uint96_Overflow());
return uint96(value);
}
/// @notice Safe type conversion from uint256 to uint128.
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, Uint128_Overflow());
return uint128(value);
}
/// @notice Returns the smallest of two numbers.
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? b : a;
}
/// @notice Returns the largest of two numbers.
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
}
contracts/misc/types/D18.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
// Small library to handle fixed point number operations with 18 decimals with static typing support.
import {MathLib} from "../libraries/MathLib.sol";
type D18 is uint128;
error D18_DivisionByZero();
using MathLib for uint256;
/// @dev add two D18 types
function add(D18 d1, D18 d2) pure returns (D18) {
return D18.wrap(D18.unwrap(d1) + D18.unwrap(d2));
}
/// @dev subtract two D18 types
function sub(D18 d1, D18 d2) pure returns (D18) {
return D18.wrap(D18.unwrap(d1) - D18.unwrap(d2));
}
/// @dev Divides one D18 by another one while retaining precision:
/// - nominator (decimal): 50e18
/// - denominator (decimal): 2e19
/// - result (decimal): 25e17
function divD18(D18 d1, D18 d2) pure returns (D18) {
return D18.wrap(MathLib.mulDiv(D18.unwrap(d1), 1e18, D18.unwrap(d2)).toUint128());
}
/// @dev Multiplies one D18 with another one while retaining precision:
/// - value1 (decimal): 50e18
/// - value2 (decimal): 2e19
/// - result (decimal): 100e19
function mulD18(D18 d1, D18 d2) pure returns (D18) {
return D18.wrap(MathLib.mulDiv(D18.unwrap(d1), D18.unwrap(d2), 1e18).toUint128());
}
/// @dev Returns the reciprocal of a D18 decimal, i.e. 1 / d.
/// Example: if d = 2.0 (2e18 internally), reciprocal(d) = 0.5 (5e17 internally).
function reciprocal(D18 d) pure returns (D18) {
uint128 val = D18.unwrap(d);
require(val != 0, D18_DivisionByZero());
return d18(1e18, val);
}
/// @dev Multiplies a decimal by an integer. i.e:
/// - d (decimal): 1_500_000_000_000_000_000
/// - value (integer): 4_000_000_000_000_000_000
/// - result (integer): 6_000_000_000_000_000_000
function mulUint128(D18 d, uint128 value, MathLib.Rounding rounding) pure returns (uint128) {
return MathLib.mulDiv(D18.unwrap(d), value, 1e18, rounding).toUint128();
}
/// @dev Multiplies a decimal by an integer. i.e:
/// - d (decimal): 1_500_000_000_000_000_000
/// - value (integer): 4_000_000_000_000_000_000
/// - result (integer): 6_000_000_000_000_000_000
function mulUint256(D18 d, uint256 value, MathLib.Rounding rounding) pure returns (uint256) {
return MathLib.mulDiv(D18.unwrap(d), value, 1e18, rounding);
}
/// @dev Divides an integer by a decimal, i.e.
/// @dev Same as mulDiv for integers, i.e:
/// - d (decimal): 2_000_000_000_000_000_000
/// - value (integer): 100_000_000_000_000_000_000
/// - result (integer): 50_000_000_000_000_000_000
function reciprocalMulUint128(D18 d, uint128 value, MathLib.Rounding rounding) pure returns (uint128) {
return MathLib.mulDiv(value, 1e18, d.raw(), rounding).toUint128();
}
/// @dev Divides an integer by a decimal, i.e.
/// @dev Same as mulDiv for integers, i.e:
/// - d (decimal): 2_000_000_000_000_000_000
/// - value (integer): 100_000_000_000_000_000_000
/// - result (integer): 50_000_000_000_000_000_000
function reciprocalMulUint256(D18 d, uint256 value, MathLib.Rounding rounding) pure returns (uint256) {
return MathLib.mulDiv(value, 1e18, d.raw(), rounding);
}
/// @dev Easy way to construct a decimal number
function d18(uint128 value) pure returns (D18) {
return D18.wrap(value);
}
/// @dev Easy way to construct a decimal number
function d18(uint128 num, uint128 den) pure returns (D18) {
return D18.wrap(MathLib.mulDiv(num, 1e18, den).toUint128());
}
function eq(D18 a, D18 b) pure returns (bool) {
return D18.unwrap(a) == D18.unwrap(b);
}
function isZero(D18 a) pure returns (bool) {
return D18.unwrap(a) == 0;
}
function isNotZero(D18 a) pure returns (bool) {
return D18.unwrap(a) != 0;
}
function raw(D18 d) pure returns (uint128) {
return D18.unwrap(d);
}
using {
add as +,
sub as -,
divD18 as /,
eq,
mulD18 as *,
mulUint128,
mulUint256,
reciprocalMulUint128,
reciprocalMulUint256,
reciprocal,
raw,
isZero,
isNotZero
} for D18 global;
contracts/vaults/interfaces/IBatchRequestManager.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {D18} from "../../misc/types/D18.sol";
import {PoolId} from "../../core/types/PoolId.sol";
import {AssetId} from "../../core/types/AssetId.sol";
import {ShareClassId} from "../../core/types/ShareClassId.sol";
import {IHubRequestManager, IHubRequestManagerNotifications} from "../../core/hub/interfaces/IHubRequestManager.sol";
/// @notice Struct containing the epoch data for issuing share class tokens
/// @param approvedPoolAmount The amount of pool currency which was approved by the Fund Manager
/// @param approvedAssetAmount The amount of assets which was approved by the Fund Manager
/// @param pendingAssetAmount The amount of assets for which issuance was pending by the Fund Manager
/// @param pricePoolPerAsset The price of one asset unit in terms of pool currency at the time of approval
/// @param pricePoolPerShare The price of 1 pool currency token in terms of share class tokens at the time of issuance
/// @param issuedAt The timestamp when shares were issued
struct EpochInvestAmounts {
uint128 approvedPoolAmount;
uint128 approvedAssetAmount;
uint128 pendingAssetAmount;
D18 pricePoolPerAsset;
D18 pricePoolPerShare;
uint64 issuedAt;
}
/// @notice Struct containing the epoch data for paying out assets of a share class token
/// @param approvedShareAmount The amount of share class tokens which was approved by the Fund Manager for payout
/// @param pendingShareAmount The amount of share class tokens for which payout was pending by the Fund Manager
/// @param pricePoolPerAsset The price of one asset unit in terms of pool currency at the time of approval
/// @param pricePoolPerShare The price of 1 pool currency token in terms of share class tokens at the time of revocation
/// @param payoutAssetAmount The amount of payout assets to claim by redeeming share class tokens
/// @param revokedAt The timestamp when shares were revoked
struct EpochRedeemAmounts {
uint128 approvedShareAmount;
uint128 pendingShareAmount;
D18 pricePoolPerAsset;
D18 pricePoolPerShare;
uint128 payoutAssetAmount;
uint64 revokedAt;
}
/// @notice Struct containing the user's deposit or redeem request data
/// @param pending The amount of assets or shares which is pending for a user
/// @param lastUpdate The epoch at which the user most recently deposited or redeemed
struct UserOrder {
uint128 pending;
uint32 lastUpdate;
}
/// @notice Struct containing the user's queued deposit or redeem request data
/// @param isCancelling Whether the user is cancelling their pending requests
/// @param amount The amount of assets or shares which is queued for a user
struct QueuedOrder {
bool isCancelling;
uint128 amount;
}
/// @notice Enum indicating the type of request, either deposit or redeem
enum RequestType {
Deposit,
Redeem
}
/// @notice Struct containing the epoch IDs for each action
/// @param deposit The epoch ID for deposits
/// @param issue The epoch ID for issuing shares
/// @param redeem The epoch ID for redeems
/// @param revoke The epoch ID for revoking shares
struct EpochId {
uint32 deposit;
uint32 issue;
uint32 redeem;
uint32 revoke;
}
interface IBatchRequestManager is IHubRequestManager, IHubRequestManagerNotifications {
//----------------------------------------------------------------------------------------------
// Events
//----------------------------------------------------------------------------------------------
event ApproveDeposits(
PoolId indexed poolId,
ShareClassId indexed shareClassId,
AssetId indexed assetId,
uint32 epochId,
uint128 approvedPoolAmount,
uint128 approvedAssetAmount,
uint128 pendingAssetAmount
);
event ApproveRedeems(
PoolId indexed poolId,
ShareClassId indexed shareClassId,
AssetId indexed assetId,
uint32 epochId,
uint128 approvedShareAmount,
uint128 pendingShareAmount
);
event IssueShares(
PoolId indexed poolId,
ShareClassId indexed shareClassId,
AssetId indexed assetId,
uint32 epochId,
D18 pricePoolPerShare,
D18 priceAssetPerShare,
uint128 issuedShareAmount
);
event RevokeShares(
PoolId indexed poolId,
ShareClassId indexed shareClassId,
AssetId indexed assetId,
uint32 epochId,
D18 pricePoolPerShare,
D18 priceAssetPerShare,
uint128 approvedShareAmount,
uint128 payoutAssetAmount,
uint128 payoutPoolAmount
);
event ClaimDeposit(
PoolId indexed poolId,
ShareClassId indexed shareClassId,
uint32 indexed epochId,
bytes32 investor,
AssetId assetId,
uint128 paymentAssetAmount,
uint128 pendingAssetAmount,
uint128 payoutShareAmount,
uint64 issuedAt
);
event ClaimRedeem(
PoolId indexed poolId,
ShareClassId indexed shareClassId,
uint32 indexed epochId,
bytes32 investor,
AssetId assetId,
uint128 paymentShareAmount,
uint128 pendingShareAmount,
uint128 payoutAssetAmount,
uint64 revokedAt
);
event UpdateDepositRequest(
PoolId indexed poolId,
ShareClassId indexed shareClassId,
AssetId indexed assetId,
uint32 epochId,
bytes32 investor,
uint128 pendingAmount,
uint128 totalPendingAmount,
uint128 queuedAmount,
bool isQueuedCancellation
);
event UpdateRedeemRequest(
PoolId indexed poolId,
ShareClassId indexed shareClassId,
AssetId indexed assetId,
uint32 epochId,
bytes32 investor,
uint128 pendingAmount,
uint128 totalPendingAmount,
uint128 queuedAmount,
bool isQueuedCancellation
);
//----------------------------------------------------------------------------------------------
// Events
//----------------------------------------------------------------------------------------------
/// @notice Emitted when a call to `file()` was performed.
event File(bytes32 what, address addr);
/// @notice Emitted when epoch IDs are modified via setEpochIds during migration
event EpochIdModified(
PoolId indexed poolId, ShareClassId indexed scId, AssetId indexed assetId, EpochId epochIdData
);
//----------------------------------------------------------------------------------------------
// Errors
//----------------------------------------------------------------------------------------------
/// @notice Dispatched when the `what` parameter of `file()` is not supported by the implementation.
error FileUnrecognizedParam();
/// @notice Dispatched when unknown request type is encountered.
error UnknownRequestType();
error InsufficientPending();
error ZeroApprovalAmount();
error EpochNotFound();
error EpochNotInSequence(uint32 epochId, uint32 actualEpochId);
error NoOrderFound();
error IssuanceRequired();
error RevocationRequired();
error CancellationInitializationRequired();
error CancellationQueued();
//----------------------------------------------------------------------------------------------
// Incoming requests
//----------------------------------------------------------------------------------------------
/// @notice Submit a deposit request to invest assets into a pool's share class
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param amount The amount of assets to deposit
/// @param investor The investor's address as bytes32
/// @param depositAssetId The asset identifier for the deposit
function requestDeposit(PoolId poolId, ShareClassId scId, uint128 amount, bytes32 investor, AssetId depositAssetId)
external;
/// @notice Cancel a pending deposit request and return the deposited assets
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param investor The investor's address as bytes32
/// @param depositAssetId The asset identifier for the deposit
/// @return cancelledAssetAmount The amount of assets returned to the investor
function cancelDepositRequest(PoolId poolId, ShareClassId scId, bytes32 investor, AssetId depositAssetId)
external
returns (uint128 cancelledAssetAmount);
/// @notice Submit a redemption request to redeem shares for assets
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param amount The amount of shares to redeem
/// @param investor The investor's address as bytes32
/// @param payoutAssetId The asset identifier for the payout
function requestRedeem(PoolId poolId, ShareClassId scId, uint128 amount, bytes32 investor, AssetId payoutAssetId)
external;
/// @notice Cancel a pending redemption request and return the shares
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param investor The investor's address as bytes32
/// @param payoutAssetId The asset identifier for the payout
/// @return cancelledShareAmount The amount of shares returned to the investor
function cancelRedeemRequest(PoolId poolId, ShareClassId scId, bytes32 investor, AssetId payoutAssetId)
external
returns (uint128 cancelledShareAmount);
//----------------------------------------------------------------------------------------------
// Manager actions
//----------------------------------------------------------------------------------------------
/// @notice Approve pending deposit requests for an epoch
/// @dev This function approves a specific amount of assets from the current deposit epoch
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param depositAssetId The asset identifier for deposits
/// @param nowDepositEpochId The current deposit epoch identifier
/// @param approvedAssetAmount The amount of assets approved for this epoch
/// @param pricePoolPerAsset The price of one asset unit in terms of pool currency
/// @param refund Address to receive unused gas refund
function approveDeposits(
PoolId poolId,
ShareClassId scId,
AssetId depositAssetId,
uint32 nowDepositEpochId,
uint128 approvedAssetAmount,
D18 pricePoolPerAsset,
address refund
) external payable;
/// @notice Approve pending redemption requests for an epoch
/// @dev This function approves a specific amount of shares from the current redeem epoch
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param payoutAssetId The asset identifier for payouts
/// @param nowRedeemEpochId The current redeem epoch identifier
/// @param approvedShareAmount The amount of shares approved for redemption
/// @param pricePoolPerAsset The price of one asset unit in terms of pool currency
function approveRedeems(
PoolId poolId,
ShareClassId scId,
AssetId payoutAssetId,
uint32 nowRedeemEpochId,
uint128 approvedShareAmount,
D18 pricePoolPerAsset
) external payable;
/// @notice Issue shares to investors based on approved deposits
/// @dev This function mints shares for the approved deposit epoch using the provided share price
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param depositAssetId The asset identifier for deposits
/// @param nowIssueEpochId The current issue epoch identifier
/// @param pricePoolPerShare The price of pool currency per share unit
/// @param extraGasLimit Additional gas limit for cross-chain operations
/// @param refund Address to receive unused gas refund
function issueShares(
PoolId poolId,
ShareClassId scId,
AssetId depositAssetId,
uint32 nowIssueEpochId,
D18 pricePoolPerShare,
uint128 extraGasLimit,
address refund
) external payable;
/// @notice Revoke shares and prepare asset payouts for redemptions
/// @dev This function burns shares for the approved redeem epoch and calculates asset payouts
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param payoutAssetId The asset identifier for payouts
/// @param nowRevokeEpochId The current revoke epoch identifier
/// @param pricePoolPerShare The price of pool currency per share unit
/// @param extraGasLimit Additional gas limit for cross-chain operations
/// @param refund Address to receive unused gas refund
function revokeShares(
PoolId poolId,
ShareClassId scId,
AssetId payoutAssetId,
uint32 nowRevokeEpochId,
D18 pricePoolPerShare,
uint128 extraGasLimit,
address refund
) external payable;
/// @notice Force cancel a user's deposit request (manager action)
/// @dev This allows the manager to cancel a deposit request on behalf of a user
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param investor The investor's address as bytes32
/// @param depositAssetId The asset identifier for the deposit
/// @param refund Address to receive unused gas refund
function forceCancelDepositRequest(
PoolId poolId,
ShareClassId scId,
bytes32 investor,
AssetId depositAssetId,
address refund
) external payable;
/// @notice Force cancel a user's redemption request (manager action)
/// @dev This allows the manager to cancel a redemption request on behalf of a user
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param investor The investor's address as bytes32
/// @param payoutAssetId The asset identifier for the payout
/// @param refund Address to receive unused gas refund
function forceCancelRedeemRequest(
PoolId poolId,
ShareClassId scId,
bytes32 investor,
AssetId payoutAssetId,
address refund
) external payable;
//----------------------------------------------------------------------------------------------
// View methods
//----------------------------------------------------------------------------------------------
/// @notice Get the current deposit epoch identifier
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param depositAssetId The asset identifier for deposits
/// @return The current deposit epoch ID
function nowDepositEpoch(PoolId poolId, ShareClassId scId, AssetId depositAssetId) external view returns (uint32);
/// @notice Get the current issue epoch identifier
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param depositAssetId The asset identifier for deposits
/// @return The current issue epoch ID
function nowIssueEpoch(PoolId poolId, ShareClassId scId, AssetId depositAssetId) external view returns (uint32);
/// @notice Get the current redeem epoch identifier
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param depositAssetId The asset identifier for payouts
/// @return The current redeem epoch ID
function nowRedeemEpoch(PoolId poolId, ShareClassId scId, AssetId depositAssetId) external view returns (uint32);
/// @notice Get the current revoke epoch identifier
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param depositAssetId The asset identifier for payouts
/// @return The current revoke epoch ID
function nowRevokeEpoch(PoolId poolId, ShareClassId scId, AssetId depositAssetId) external view returns (uint32);
/// @notice Get the maximum number of deposit claims available for an investor
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param investor The investor's address as bytes32
/// @param depositAssetId The asset identifier for deposits
/// @return The maximum number of claimable deposit epochs
function maxDepositClaims(PoolId poolId, ShareClassId scId, bytes32 investor, AssetId depositAssetId)
external
view
returns (uint32);
/// @notice Get the maximum number of redeem claims available for an investor
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param investor The investor's address as bytes32
/// @param payoutAssetId The asset identifier for payouts
/// @return The maximum number of claimable redeem epochs
function maxRedeemClaims(PoolId poolId, ShareClassId scId, bytes32 investor, AssetId payoutAssetId)
external
view
returns (uint32);
//----------------------------------------------------------------------------------------------
// Epoch data access
//----------------------------------------------------------------------------------------------
/// @notice Get detailed investment amounts and pricing for a specific epoch
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param assetId The asset identifier
/// @param epochId The epoch identifier
/// @return pendingAssetAmount Assets waiting to be approved
/// @return approvedAssetAmount Assets approved for investment
/// @return approvedPoolAmount Pool currency amount after asset-to-pool conversion
/// @return pricePoolPerAsset Price of pool currency per asset unit
/// @return pricePoolPerShare Price of pool currency per share unit
/// @return issuedAt Timestamp when shares were issued
function epochInvestAmounts(PoolId poolId, ShareClassId scId, AssetId assetId, uint32 epochId)
external
view
returns (
uint128 pendingAssetAmount,
uint128 approvedAssetAmount,
uint128 approvedPoolAmount,
D18 pricePoolPerAsset,
D18 pricePoolPerShare,
uint64 issuedAt
);
/// @notice Get detailed redemption amounts and pricing for a specific epoch
/// @param poolId The pool identifier
/// @param scId The share class identifier
/// @param assetId The asset identifier
/// @param epochId The epoch identifier
/// @return approvedShareAmount Shares approved for redemption
/// @return pendingShareAmount Shares waiting to be approved
/// @return pricePoolPerAsset Price of pool currency per asset unit
/// @return pricePoolPerShare Price of pool currency per share unit
/// @return payoutAssetAmount Asset amount to be paid out
/// @return revokedAt Timestamp when shares were revoked
function epochRedeemAmounts(PoolId poolId, ShareClassId scId, AssetId assetId, uint32 epochId)
external
view
returns (
uint128 approvedShareAmount,
uint128 pendingShareAmount,
D18 pricePoolPerAsset,
D18 pricePoolPerShare,
uint128 payoutAssetAmount,
uint64 revokedAt
);
}
contracts/vaults/libraries/RequestCallbackMessageLib.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {CastLib} from "../../misc/libraries/CastLib.sol";
import {BytesLib} from "../../misc/libraries/BytesLib.sol";
enum RequestCallbackType {
/// @dev Placeholder for null request callback type
Invalid,
ApprovedDeposits,
IssuedShares,
RevokedShares,
FulfilledDepositRequest,
FulfilledRedeemRequest
}
library RequestCallbackMessageLib {
using RequestCallbackMessageLib for bytes;
using BytesLib for bytes;
using CastLib for *;
error UnknownRequestCallbackType();
function requestCallbackType(bytes memory message) internal pure returns (RequestCallbackType) {
return RequestCallbackType(message.toUint8(0));
}
//---------------------------------------
// RequestCallback.ApprovedDeposits (submsg)
//---------------------------------------
struct ApprovedDeposits {
uint128 assetAmount;
uint128 pricePoolPerAsset;
}
function deserializeApprovedDeposits(bytes memory data) internal pure returns (ApprovedDeposits memory) {
require(requestCallbackType(data) == RequestCallbackType.ApprovedDeposits, UnknownRequestCallbackType());
return ApprovedDeposits({assetAmount: data.toUint128(1), pricePoolPerAsset: data.toUint128(17)});
}
function serialize(ApprovedDeposits memory t) internal pure returns (bytes memory) {
return abi.encodePacked(RequestCallbackType.ApprovedDeposits, t.assetAmount, t.pricePoolPerAsset);
}
//---------------------------------------
// RequestCallback.IssuedShares (submsg)
//---------------------------------------
struct IssuedShares {
uint128 shareAmount;
uint128 pricePoolPerShare;
}
function deserializeIssuedShares(bytes memory data) internal pure returns (IssuedShares memory) {
require(requestCallbackType(data) == RequestCallbackType.IssuedShares, UnknownRequestCallbackType());
return IssuedShares({shareAmount: data.toUint128(1), pricePoolPerShare: data.toUint128(17)});
}
function serialize(IssuedShares memory t) internal pure returns (bytes memory) {
return abi.encodePacked(RequestCallbackType.IssuedShares, t.shareAmount, t.pricePoolPerShare);
}
//---------------------------------------
// RequestCallback.RevokedShares (submsg)
//---------------------------------------
struct RevokedShares {
uint128 assetAmount;
uint128 shareAmount;
uint128 pricePoolPerShare;
}
function deserializeRevokedShares(bytes memory data) internal pure returns (RevokedShares memory) {
require(requestCallbackType(data) == RequestCallbackType.RevokedShares, UnknownRequestCallbackType());
return RevokedShares({
assetAmount: data.toUint128(1), shareAmount: data.toUint128(17), pricePoolPerShare: data.toUint128(33)
});
}
function serialize(RevokedShares memory t) internal pure returns (bytes memory) {
return abi.encodePacked(RequestCallbackType.RevokedShares, t.assetAmount, t.shareAmount, t.pricePoolPerShare);
}
//---------------------------------------
// RequestCallback.FulfilledDepositRequest (submsg)
//---------------------------------------
struct FulfilledDepositRequest {
bytes32 investor;
uint128 fulfilledAssetAmount;
uint128 fulfilledShareAmount;
uint128 cancelledAssetAmount;
}
function deserializeFulfilledDepositRequest(bytes memory data)
internal
pure
returns (FulfilledDepositRequest memory)
{
require(requestCallbackType(data) == RequestCallbackType.FulfilledDepositRequest, UnknownRequestCallbackType());
return FulfilledDepositRequest({
investor: data.toBytes32(1),
fulfilledAssetAmount: data.toUint128(33),
fulfilledShareAmount: data.toUint128(49),
cancelledAssetAmount: data.toUint128(65)
});
}
function serialize(FulfilledDepositRequest memory t) internal pure returns (bytes memory) {
return abi.encodePacked(
RequestCallbackType.FulfilledDepositRequest,
t.investor,
t.fulfilledAssetAmount,
t.fulfilledShareAmount,
t.cancelledAssetAmount
);
}
//---------------------------------------
// RequestCallback.FulfilledRedeemRequest (submsg)
//---------------------------------------
struct FulfilledRedeemRequest {
bytes32 investor;
uint128 fulfilledAssetAmount;
uint128 fulfilledShareAmount;
uint128 cancelledShareAmount;
}
function deserializeFulfilledRedeemRequest(bytes memory data)
internal
pure
returns (FulfilledRedeemRequest memory)
{
require(requestCallbackType(data) == RequestCallbackType.FulfilledRedeemRequest, UnknownRequestCallbackType());
return FulfilledRedeemRequest({
investor: data.toBytes32(1),
fulfilledAssetAmount: data.toUint128(33),
fulfilledShareAmount: data.toUint128(49),
cancelledShareAmount: data.toUint128(65)
});
}
function serialize(FulfilledRedeemRequest memory t) internal pure returns (bytes memory) {
return abi.encodePacked(
RequestCallbackType.FulfilledRedeemRequest,
t.investor,
t.fulfilledAssetAmount,
t.fulfilledShareAmount,
t.cancelledShareAmount
);
}
}
contracts/vaults/libraries/RequestMessageLib.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;
import {CastLib} from "../../misc/libraries/CastLib.sol";
import {BytesLib} from "../../misc/libraries/BytesLib.sol";
enum RequestType {
/// @dev Placeholder for null request type
Invalid,
DepositRequest,
RedeemRequest,
CancelDepositRequest,
CancelRedeemRequest
}
library RequestMessageLib {
using RequestMessageLib for bytes;
using BytesLib for bytes;
using CastLib for *;
error UnknownRequestType();
function requestType(bytes memory message) internal pure returns (RequestType) {
return RequestType(message.toUint8(0));
}
//---------------------------------------
// Request.DepositRequest (submsg)
//---------------------------------------
struct DepositRequest {
bytes32 investor;
uint128 amount;
}
function deserializeDepositRequest(bytes memory data) internal pure returns (DepositRequest memory) {
require(requestType(data) == RequestType.DepositRequest, UnknownRequestType());
return DepositRequest({investor: data.toBytes32(1), amount: data.toUint128(33)});
}
function serialize(DepositRequest memory t) internal pure returns (bytes memory) {
return abi.encodePacked(RequestType.DepositRequest, t.investor, t.amount);
}
//---------------------------------------
// Request.RedeemRequest (submsg)
//---------------------------------------
struct RedeemRequest {
bytes32 investor;
uint128 amount;
}
function deserializeRedeemRequest(bytes memory data) internal pure returns (RedeemRequest memory) {
require(requestType(data) == RequestType.RedeemRequest, UnknownRequestType());
return RedeemRequest({investor: data.toBytes32(1), amount: data.toUint128(33)});
}
function serialize(RedeemRequest memory t) internal pure returns (bytes memory) {
return abi.encodePacked(RequestType.RedeemRequest, t.investor, t.amount);
}
//---------------------------------------
// Request.CancelDepositRequest (submsg)
//---------------------------------------
struct CancelDepositRequest {
bytes32 investor;
}
function deserializeCancelDepositRequest(bytes memory data) internal pure returns (CancelDepositRequest memory) {
require(requestType(data) == RequestType.CancelDepositRequest, UnknownRequestType());
return CancelDepositRequest({investor: data.toBytes32(1)});
}
function serialize(CancelDepositRequest memory t) internal pure returns (bytes memory) {
return abi.encodePacked(RequestType.CancelDepositRequest, t.investor);
}
//---------------------------------------
// Request.CancelRedeemRequest (submsg)
//---------------------------------------
struct CancelRedeemRequest {
bytes32 investor;
}
function deserializeCancelRedeemRequest(bytes memory data) internal pure returns (CancelRedeemRequest memory) {
require(requestType(data) == RequestType.CancelRedeemRequest, UnknownRequestType());
return CancelRedeemRequest({investor: data.toBytes32(1)});
}
function serialize(CancelRedeemRequest memory t) internal pure returns (bytes memory) {
return abi.encodePacked(RequestType.CancelRedeemRequest, t.investor);
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.