Verified contractPartialUNLICENSED
BasketRouter
Address0x222588fed936dffdbf169d9a4e6c9010b40593a5
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- UNLICENSED
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,485,329
- Creation transaction
- 0x1eaaecc0df…5e17abc324
14 files
- src/composition/routers/BasketRouter.solmain11.62 KB
- dependencies/@openzeppelin-contracts-5.4.0/interfaces/IERC1363.sol4.45 KB
- dependencies/@openzeppelin-contracts-5.4.0/interfaces/IERC165.sol193 B
- dependencies/@openzeppelin-contracts-5.4.0/interfaces/IERC20.sol182 B
- dependencies/@openzeppelin-contracts-5.4.0/token/ERC20/IERC20.sol2.78 KB
- dependencies/@openzeppelin-contracts-5.4.0/token/ERC20/utils/SafeERC20.sol10.08 KB
- dependencies/@openzeppelin-contracts-5.4.0/utils/Address.sol6 KB
- dependencies/@openzeppelin-contracts-5.4.0/utils/Errors.sol896 B
- dependencies/@openzeppelin-contracts-5.4.0/utils/ReentrancyGuardTransient.sol2.09 KB
- dependencies/@openzeppelin-contracts-5.4.0/utils/TransientSlot.sol5.08 KB
- dependencies/@openzeppelin-contracts-5.4.0/utils/introspection/IERC165.sol871 B
- src/composition/interfaces/ICompositionFactory.sol2.99 KB
- src/composition/interfaces/ICompositionVault.sol8.39 KB
- src/composition/libraries/KyberSwap.sol4.54 KB
src/composition/routers/BasketRouter.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardTransient } from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import { ICompositionFactory } from "../interfaces/ICompositionFactory.sol";
import { ICompositionVault } from "../interfaces/ICompositionVault.sol";
import { KyberSwap } from "../libraries/KyberSwap.sol";
/// @notice USDG in, basket shares out, and back: buys every constituent through Kyber and deposits in one
/// transaction, or redeems to underlying tokens or sells them back to USDG.
///
/// @dev Holds nothing between calls. Each call measures its own balances on entry and returns exactly what it
/// added and did not spend, so tokens someone pushed into the router are never paid to the next caller. The payer
/// and the recipient are always `msg.sender`; nothing in a call can redirect an output.
///
/// No route is trusted: `KyberSwap` checks every leg, and each leg must move between USDG and the constituent at its
/// own position in the vault's composition. A vault its factory did not create is refused, so calldata cannot point
/// a caller's funds at a lookalike.
///
/// The minimums cap what a bad execution can cost; they do not stop a sandwich. This is bounded, not MEV-safe.
contract BasketRouter is ReentrancyGuardTransient {
using SafeERC20 for IERC20;
// immutable getter follows forge-lint naming
ICompositionFactory public immutable FACTORY;
// immutable getter follows forge-lint naming
address public immutable KYBER;
// immutable getter follows forge-lint naming
IERC20 public immutable USDG;
event DepositedWithUsdg(address indexed user, address indexed vault, uint256 usdgSpent, uint256 shares);
event RedeemedToUsdg(address indexed user, address indexed vault, uint256 shares, uint256 usdgOut);
event RedeemedToUnderlying(
address indexed user, address indexed vault, uint256 shares, address[] tokens, uint256[] amounts
);
error ZeroAddress();
/// @notice `validBefore` is exclusive: a quote is dead at that timestamp, not after it.
error Expired(uint256 validBefore);
error UnknownVault(address vault);
error LegCountMismatch(uint256 legs, uint256 assets);
/// @notice Leg `i` does not move between USDG and constituent `i` in the direction the call needs.
error LegMismatch(uint256 i);
error InsufficientUsdgOut(uint256 usdgOut, uint256 minUsdgOut);
constructor(ICompositionFactory factory_, address kyber_, IERC20 usdg_) {
if (address(factory_) == address(0) || kyber_ == address(0) || address(usdg_) == address(0)) {
revert ZeroAddress();
}
FACTORY = factory_;
KYBER = kyber_;
USDG = usdg_;
}
/// @notice Spends up to `maxUsdgIn` buying the vault's constituents and deposits them for the caller.
/// @param buys One leg per constituent in composition order, each USDG to that constituent. A leg with zero
/// `amountIn` buys nothing, for an empty zero-weight asset the deposit does not take.
/// `minAmountOut` floors that leg's actual constituent output in its base units, independently of `minShares`.
/// @dev The vault takes what it can at its live ratio. Unspent USDG and any constituent the deposit did not need
/// go back to the caller.
function depositWithUsdg(
ICompositionVault vault,
uint256 maxUsdgIn,
KyberSwap.Leg[] calldata buys,
uint256 minShares,
uint256 expectedVersion,
uint256 validBefore
)
external
nonReentrant
returns (uint256 shares, uint256 usdgSpent)
{
address[] memory tokens = _open(vault, expectedVersion, validBefore);
if (buys.length != tokens.length) revert LegCountMismatch(buys.length, tokens.length);
uint256 usdgBefore = USDG.balanceOf(address(this));
uint256[] memory before = _balances(tokens);
USDG.safeTransferFrom(msg.sender, address(this), maxUsdgIn);
uint256[] memory bought = _buy(tokens, buys);
shares = _deposit(vault, tokens, bought, minShares, expectedVersion);
uint256 unspent = USDG.balanceOf(address(this)) - usdgBefore;
usdgSpent = maxUsdgIn - unspent;
if (unspent != 0) USDG.safeTransfer(msg.sender, unspent);
_refund(tokens, before);
emit DepositedWithUsdg(msg.sender, address(vault), usdgSpent, shares);
}
/// @notice Redeems the caller's `shares` and sells every constituent back to USDG.
/// @param sells One leg per constituent in composition order, each that constituent to USDG. A leg's `amountIn`
/// may not exceed what the redeem pays; whatever a leg leaves unsold goes back to the caller as the constituent.
/// @dev The caller approves this router for `shares` first. `minAmountsOut` floors the redeem itself, before any
/// selling; `minUsdgOut` floors the whole call.
/// Each active sell also requires its own `minAmountOut` in USDG base units, independently of `minUsdgOut`.
function redeemToUsdg(
ICompositionVault vault,
uint256 shares,
uint256[] calldata minAmountsOut,
KyberSwap.Leg[] calldata sells,
uint256 minUsdgOut,
uint256 expectedVersion,
uint256 validBefore
)
external
nonReentrant
returns (uint256 usdgOut)
{
address[] memory tokens = _open(vault, expectedVersion, validBefore);
if (sells.length != tokens.length) revert LegCountMismatch(sells.length, tokens.length);
uint256 usdgBefore = USDG.balanceOf(address(this));
uint256[] memory before = _balances(tokens);
_redeemAndSell(vault, shares, minAmountsOut, tokens, sells, expectedVersion);
usdgOut = USDG.balanceOf(address(this)) - usdgBefore;
if (usdgOut < minUsdgOut) revert InsufficientUsdgOut(usdgOut, minUsdgOut);
USDG.safeTransfer(msg.sender, usdgOut);
_refund(tokens, before);
emit RedeemedToUsdg(msg.sender, address(vault), shares, usdgOut);
}
/// @notice Redeems the caller's approved shares directly to the caller as underlying tokens, without swaps.
/// @param minAmountsOut One constituent minimum per live composition asset, in that token's base units.
/// @return tokens The live composition's token addresses, aligned with `amounts`.
/// @return amounts The quantities paid directly by the vault; standing router balances are untouched.
function redeemToUnderlying(
ICompositionVault vault,
uint256 shares,
uint256[] calldata minAmountsOut,
uint256 expectedVersion,
uint256 validBefore
)
external
nonReentrant
returns (address[] memory tokens, uint256[] memory amounts)
{
tokens = _open(vault, expectedVersion, validBefore);
IERC20(address(vault)).safeTransferFrom(msg.sender, address(this), shares);
amounts = vault.redeem(shares, minAmountsOut, msg.sender, expectedVersion);
emit RedeemedToUnderlying(msg.sender, address(vault), shares, tokens, amounts);
}
/// @dev The checks every call makes before moving anything: the quote is live, the vault is one its factory
/// created, and its composition is the one the quote was built for.
function _open(
ICompositionVault vault,
uint256 expectedVersion,
uint256 validBefore
)
private
view
returns (address[] memory tokens)
{
// quote expiry is a deadline by design
if (block.timestamp >= validBefore) revert Expired(validBefore);
// A lookalike can report any id, but only the real vault is what the factory has recorded under it.
if (FACTORY.vaultOf(vault.compositionId()) != address(vault)) revert UnknownVault(address(vault));
uint256 version;
// Weights are the vault's business; the router needs only the asset order and the version.
(tokens,, version) = vault.composition();
if (version != expectedVersion) revert ICompositionVault.StaleComposition(expectedVersion, version);
}
function _buy(address[] memory tokens, KyberSwap.Leg[] calldata buys) private returns (uint256[] memory bought) {
bought = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
KyberSwap.Leg calldata leg = buys[i];
if (leg.amountIn == 0) continue;
if (leg.tokenIn != address(USDG) || leg.tokenOut != tokens[i]) revert LegMismatch(i);
// USDG spent is accounted once, as the whole call's balance change, not leg by leg.
(, bought[i]) = KyberSwap.execute(KYBER, leg);
}
}
/// @dev Takes the caller's shares, redeems them to this router, and sells each constituent to USDG.
function _redeemAndSell(
ICompositionVault vault,
uint256 shares,
uint256[] calldata minAmountsOut,
address[] memory tokens,
KyberSwap.Leg[] calldata sells,
uint256 expectedVersion
)
private
{
IERC20(address(vault)).safeTransferFrom(msg.sender, address(this), shares);
// What the redeem paid is measured as balance changes by the caller, so its returned amounts are not needed.
vault.redeem(shares, minAmountsOut, address(this), expectedVersion);
_sell(tokens, sells);
}
function _sell(address[] memory tokens, KyberSwap.Leg[] calldata sells) private {
for (uint256 i = 0; i < tokens.length; ++i) {
KyberSwap.Leg calldata leg = sells[i];
if (leg.amountIn == 0) continue;
if (leg.tokenIn != tokens[i] || leg.tokenOut != address(USDG)) revert LegMismatch(i);
// Proceeds are measured once, as the whole call's USDG balance change, so per-leg amounts are unused.
KyberSwap.execute(KYBER, leg);
}
}
/// @dev Approves the vault for exactly what was bought, deposits for the caller, then clears the approvals.
function _deposit(
ICompositionVault vault,
address[] memory tokens,
uint256[] memory amounts,
uint256 minShares,
uint256 expectedVersion
)
private
returns (uint256 shares)
{
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20(tokens[i]).forceApprove(address(vault), amounts[i]);
}
shares = vault.deposit(amounts, minShares, msg.sender, expectedVersion);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20(tokens[i]).forceApprove(address(vault), 0);
}
}
function _balances(address[] memory tokens) private view returns (uint256[] memory balances) {
balances = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
// loop length is capped by the protocol maximum
balances[i] = IERC20(tokens[i]).balanceOf(address(this));
}
}
/// @dev Pays the caller whatever this call added and did not spend, and nothing that was here before it.
function _refund(address[] memory tokens, uint256[] memory before) private {
for (uint256 i = 0; i < tokens.length; ++i) {
// loop length is capped by the protocol maximum
uint256 leftover = IERC20(tokens[i]).balanceOf(address(this)) - before[i];
if (leftover != 0) IERC20(tokens[i]).safeTransfer(msg.sender, leftover);
}
}
}
dependencies/@openzeppelin-contracts-5.4.0/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
dependencies/@openzeppelin-contracts-5.4.0/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
dependencies/@openzeppelin-contracts-5.4.0/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
dependencies/@openzeppelin-contracts-5.4.0/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the 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);
}
dependencies/@openzeppelin-contracts-5.4.0/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
dependencies/@openzeppelin-contracts-5.4.0/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}
dependencies/@openzeppelin-contracts-5.4.0/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
dependencies/@openzeppelin-contracts-5.4.0/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
dependencies/@openzeppelin-contracts-5.4.0/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
dependencies/@openzeppelin-contracts-5.4.0/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC 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);
}
src/composition/interfaces/ICompositionFactory.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
interface ICompositionFactory {
struct CreateParams {
uint256 expectedVaultVersion;
bytes32 expectedVaultImplementationCodeHash;
string name;
string symbol;
bool compositionMutable;
bool rebalancerMutable;
address rebalancer;
bool feeMutable;
/// @notice Annual creator fee in basis points.
uint256 feeBps;
address[] tokens;
/// @notice Target value weights in basis points, aligned with `tokens`.
uint256[] weights;
/// @notice Native token amounts aligned with `tokens`.
uint256[] seedAmounts;
address seedReceiver;
}
struct VaultCreatedData {
string name;
string symbol;
bool compositionMutable;
address rebalancer;
bool rebalancerMutable;
bool feeMutable;
uint256 feeBps;
address[] tokens;
uint256[] weights;
uint256[] seedAmounts;
uint256 seedShares;
uint256 vaultVersion;
}
event VaultCreated(
bytes32 indexed compositionId, address indexed vault, address indexed creator, VaultCreatedData data
);
event AllowedSet(address indexed asset, bool allowed);
event VaultCohortCreated(uint256 indexed version, address indexed beacon, address indexed implementation);
event VaultImplementationUpgraded(uint256 indexed version, address indexed implementation);
error ZeroAsset();
error VaultExists(bytes32 compositionId, address vault);
error SeedLengthMismatch();
/// @notice The asset is not on the allowlist. The same list governs what a vault may be created with and
/// what a rebalance may add, so there is one rule for what a composition may hold.
error IneligibleAsset(address token);
error UnknownVaultVersion(uint256 version);
error VaultVersionMismatch(uint256 expectedVersion, uint256 actualVersion);
error VaultImplementationMismatch(bytes32 expectedCodeHash, bytes32 actualCodeHash);
function initialize(address initialOwner, address initialVaultImplementation) external;
function createVault(CreateParams calldata p) external returns (address vault, uint256 seedShares);
function createVaultCohort(address implementation) external returns (uint256 version, address beacon);
function upgradeVaultImplementation(uint256 version, address implementation) external;
function setAllowed(address asset, bool allowed) external;
function isAllowed(address asset) external view returns (bool);
function vaultOf(bytes32 compositionId) external view returns (address vault);
function activeVaultVersion() external view returns (uint256);
function vaultBeacon(uint256 version) external view returns (address);
function vaultImplementation(uint256 version) external view returns (address);
function vaultVersionOf(address vault) external view returns (uint256);
}
src/composition/interfaces/ICompositionVault.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
/// @notice A composition vault's external surface.
///
/// @dev Names follow ERC-4626 wherever the shape survives the jump to a multi-asset composition, so a reader who knows
/// the standard can read this one. It cannot implement ERC-4626: `asset()` and `totalAssets()` want a single
/// underlying and a single scalar, and this vault holds two to eight assets and owns no oracle to price them into
/// one number. Pricing its own composition is exactly what it refuses to do — every entry and exit is pro-rata
/// against accounted token balances, excluding unsolicited transfers.
///
/// So the scalars become arrays in token-composition order, and the members that cannot mean anything without a
/// numéraire are absent rather than faked: no `asset`, no `totalAssets`, no `convertToShares` / `convertToAssets`.
/// `withdraw` and `mint` are absent too — both name an exact-assets side of a trade that a basket cannot honour
/// without pricing it. What remains is `deposit` / `previewDeposit` and `redeem` / `previewRedeem`.
interface ICompositionVault {
struct InitializeParams {
address creator;
address factory;
string name;
string symbol;
bool compositionMutable;
bool rebalancerMutable;
address rebalancer;
bool feeMutable;
uint256 feeBps;
address[] tokens;
uint256[] weights;
}
/// @notice Mirrors ERC-4626's `Deposit` ordering — amounts before shares — with the amounts as an array.
event Deposit(address indexed caller, address indexed receiver, uint256[] amountsIn, uint256 shares);
/// @notice Mirrors ERC-4626's `Withdraw`. The standard emits it for both `withdraw` and `redeem`; this vault
/// only has the redeem shape, so every exit lands here.
event Withdraw(address indexed caller, address indexed receiver, uint256[] amountsOut, uint256 shares);
event RebalancerSet(address indexed oldRebalancer, address indexed newRebalancer);
event Accrued(address indexed creator, uint256 feeShares, uint256 newSupply);
event FeeChanged(uint256 oldBps, uint256 newBps);
/// @notice Emitted once by every rebalance, whatever it changed. `tokens` / `weights` are the composition now in
/// force and `version` its version; `targetBalances` is each asset's accounted backing; `removedTokens` /
/// `removedAmounts` are the assets the rebalance dropped and what went back of each, empty unless the asset set
/// changed.
event Rebalanced(
address indexed rebalancer,
uint256 indexed version,
address[] tokens,
uint256[] weights,
uint256[] targetBalances,
address[] removedTokens,
uint256[] removedAmounts
);
error RebalancerImmutable();
error NotCreator();
error FeeImmutable();
error ZeroReceiver();
error LengthMismatch();
error NotInitialized();
error SeedAssetZero(uint256 i);
error ZeroShares();
error InsufficientShares(uint256 shares, uint256 minShares);
error EmptyDeposit();
error AssetTransferMismatch(address token);
error InsufficientAmountOut(uint256 i, uint256 amountOut, uint256 minAmountOut);
error FeeTooHigh(uint256 feeBps);
error NotRebalancer();
error CompositionImmutable();
error IneligibleAsset(address token);
error StaleComposition(uint256 expectedVersion, uint256 actualVersion);
error AlreadySeeded();
error NotFactory();
function initialize(InitializeParams calldata params) external;
/// @notice Opens an empty vault. Factory-only, and one-shot. `amountsIn` use composition order and are taken in
/// full — unlike `deposit`, nothing is scaled down, because there is no live ratio to bind against yet.
/// @dev ERC-4626 has no analogue: a single-asset vault has nothing to bootstrap a ratio from.
function seed(uint256[] calldata amountsIn, address receiver) external returns (uint256 shares);
/// @notice Deposits into a seeded vault at its live ratio. ERC-4626 `deposit` in shape, but `maxAmountsIn` is a
/// ceiling rather than an exact amount: it is scaled down to whichever asset binds hardest, so the vault may pull
/// less than offered. `previewDeposit` says how much less; `minShares` is the floor on what you get back.
function deposit(
uint256[] calldata maxAmountsIn,
uint256 minShares,
address receiver,
uint256 expectedVersion
)
external
returns (uint256 shares);
/// @notice Quotes `deposit`, and reverts before the vault is seeded. Returns `amountsIn` as well — how much of
/// `maxAmountsIn` the vault would actually take — which a single-asset vault never needs, having no binding
/// asset.
function previewDeposit(uint256[] calldata maxAmountsIn)
external
view
returns (uint256 shares, uint256[] memory amountsIn);
/// @notice Redeems an exact share count for a pro-rata slice of every asset, with a floor on each. Burns and
/// pays whatever it is worth, bound to the named composition version.
function redeem(
uint256 shares,
uint256[] calldata minAmountsOut,
address receiver,
uint256 expectedVersion
)
external
returns (uint256[] memory amountsOut);
/// @notice `redeem` with every protection waived: no floors, no composition-version check. Named to be
/// unattractive, because it is the raw escape hatch.
function redeemUnchecked(uint256 shares, address receiver) external returns (uint256[] memory amountsOut);
/// @notice What burning `shares` pays out right now, per asset in composition order.
function previewRedeem(uint256 shares) external view returns (uint256[] memory amountsOut);
/// @notice Moves the vault to a stated composition. `targetBalances` are absolute accounted token balances,
/// not changes: shortfalls are pulled from the caller, accounted surpluses are sent back, and an omitted
/// asset's backing is returned whole. Unsolicited excess remains excluded.
/// @dev The trusted keeper must price assets, normalize decimals, and validate targets against value weights
/// before execution. The vault checks token settlement; it has no oracle and permits zero targets and no-ops.
function rebalance(
address[] calldata nextTokens,
uint256[] calldata nextWeights,
uint256[] calldata targetBalances,
uint256 expectedVersion
)
external;
function accrue() external;
/// @notice Accrues the old annual rate through execution time, then applies `newBps` immediately.
/// @dev Creator governance must enforce any announcement or execution delay outside the vault.
function setFee(uint256 newBps) external;
/// @notice Creator-only when the rebalancer address is mutable.
function setRebalancer(address newRebalancer) external;
/// @notice `weights` are target value basis points; `version` binds positional calls to token-composition order.
function composition() external view returns (address[] memory tokens, uint256[] memory weights, uint256 version);
/// @notice Token units backing shares, excluding unsolicited transfers. Excess custody remains unaccounted.
function accountedBalance(address token) external view returns (uint256);
function compositionId() external view returns (bytes32);
function creator() external view returns (address);
/// @notice Returns the factory that created this vault. A rebalancer reads it to reach the
/// registries the vault itself is vouched by, rather than trusting an address whoever deployed the rebalancer
/// chose.
function factory() external view returns (address);
function rebalancer() external view returns (address);
function compositionMutable() external view returns (bool);
function rebalancerMutable() external view returns (bool);
/// @notice Returns the live annual creator fee in basis points.
function feeBps() external view returns (uint256);
function feeMutable() external view returns (bool);
/// @notice Returns the unaccrued interval's start, initialized to creation time and advanced on settlement.
function lastAccrual() external view returns (uint256);
}
src/composition/libraries/KyberSwap.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
/// @notice Executes one swap through KyberSwap's aggregation router and proves what it did.
///
/// @dev Route calldata is built off-chain by Kyber's API, so nothing in it is trusted. Before the call, the decoded
/// swap description must name exactly the tokens, input amount and receiver the caller declared. Around the call,
/// the input allowance is exact and cleared afterwards, and both sides are measured as balance changes on this
/// contract. So a route that spends a different token, pulls more than declared, sends the output elsewhere, or
/// returns less than the floor reverts.
///
/// Written against the router verified on Robinhood Chain (`MetaRouter.sol`, Sourcify exact match for chain 4663),
/// not the older Ethereum source at the same address. That version has no partial-fill mode, so a call that
/// returns is all-or-nothing.
library KyberSwap {
using SafeERC20 for IERC20;
/// @dev `swap(SwapExecutionParams)`. Every recorded Robinhood Chain route uses it.
bytes4 internal constant SWAP_SELECTOR = 0xe21fd0e9;
/// @notice One declared swap. `data` is Kyber `swap` calldata built with this contract as sender and recipient.
struct Leg {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 minAmountOut;
bytes data;
}
/// @dev Kyber's own types, mirrored only to decode `Leg.data`. Field order and types match the verified source.
struct SwapDescriptionV2 {
address srcToken;
address dstToken;
address[] srcReceivers;
uint256[] srcAmounts;
address[] feeReceivers;
uint256[] feeAmounts;
address dstReceiver;
uint256 amount;
uint256 minReturnAmount;
uint256 flags;
bytes permit;
}
struct SwapExecutionParams {
address callTarget;
address approveTarget;
bytes targetData;
SwapDescriptionV2 desc;
bytes clientData;
}
error WrongSelector(bytes4 selector);
/// @notice The route's own description disagrees with the declared leg.
error RouteMismatch();
error ZeroMinimum();
error InsufficientOutput(address tokenOut, uint256 received, uint256 minAmountOut);
/// @return spent What left this contract in `tokenIn`, never more than `amountIn`.
/// @return received What arrived in `tokenOut`, never less than `minAmountOut`.
function execute(address router, Leg calldata leg) internal returns (uint256 spent, uint256 received) {
if (leg.minAmountOut == 0) revert ZeroMinimum();
_requireRouteMatches(leg);
IERC20 tokenIn = IERC20(leg.tokenIn);
IERC20 tokenOut = IERC20(leg.tokenOut);
uint256 inBefore = tokenIn.balanceOf(address(this));
uint256 outBefore = tokenOut.balanceOf(address(this));
tokenIn.forceApprove(router, leg.amountIn);
// Reverts with the route's own reason, and with `AddressEmptyCode` when no router is deployed. Kyber's
// reported `returnAmount` is ignored on purpose: what arrived is measured below rather than taken on trust.
Address.functionCall(router, leg.data);
tokenIn.forceApprove(router, 0);
spent = inBefore - tokenIn.balanceOf(address(this));
received = tokenOut.balanceOf(address(this)) - outBefore;
if (received < leg.minAmountOut) revert InsufficientOutput(leg.tokenOut, received, leg.minAmountOut);
}
/// @dev A zero `dstReceiver` means Kyber pays its caller, which is this contract, so both are accepted. A
/// permit is refused: this contract never signs one, so any permit in a route is someone else's.
function _requireRouteMatches(Leg calldata leg) private view {
if (leg.data.length < 4 || bytes4(leg.data[:4]) != SWAP_SELECTOR) revert WrongSelector(bytes4(leg.data));
SwapDescriptionV2 memory desc = abi.decode(leg.data[4:], (SwapExecutionParams)).desc;
if (
leg.tokenIn == leg.tokenOut || desc.srcToken != leg.tokenIn || desc.dstToken != leg.tokenOut
|| desc.amount != leg.amountIn || (desc.dstReceiver != address(0) && desc.dstReceiver != address(this))
|| desc.permit.length != 0
) revert RouteMismatch();
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.4.0/",
"@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.4.0/",
"forge-std/=dependencies/forge-std-1.9.7/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.