// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
if (success) {
if (returndata.length==0) {
// only check isContract if the call was successful and the return data is empty// otherwise we already know that it was a contractrequire(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 2 of 36: AddressRegistry.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.19;// Utilsimport {Ownable} from"../utils/Ownable.sol";
// Interfacesimport {IOracle} from"../interfaces/IOracle.sol";
import {IGovernanceModule} from"../interfaces/IGovernanceModule.sol";
///@title AddressRegistry contract///@notice Handle state and logic for external authorized call (mainly keeper) and the oracle moduleabstractcontractAddressRegistryisOwnable{
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*////@notice Address of the oracle module
IOracle public oracleModule;
///@notice Governance Registry contract address interface
IGovernanceModule publicimmutable GOVERNANCE_MODULE;
addresspublic RELAYER;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/eventOracleModuleUpdated(addressindexed oracleModule);
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/constructor(address _govModule, address _relayer) {
GOVERNANCE_MODULE = IGovernanceModule(_govModule);
RELAYER = _relayer;
}
/*//////////////////////////////////////////////////////////////
ACCESS
//////////////////////////////////////////////////////////////*/functionsetRelayer(address _relayer) externalonlyOwner{
RELAYER = _relayer;
}
///@notice Set the oracle addressfunctionsetOracleModule(address _oracle) publiconlyOwner{
oracleModule = IOracle(_oracle);
emit OracleModuleUpdated(_oracle);
}
}
Contract Source Code
File 3 of 36: AssetRegistry.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.19;import {AssetInfo} from"./Structs.sol";
import {AddressRegistry} from"./AddressRegistry.sol";
import {ProtocolState} from"./ProtocolState.sol";
import {Ownable} from"../utils/Ownable.sol";
import {BaseChecker} from"../utils/BaseChecker.sol";
import {IERC20Metadata} from"openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IUniswapV3PoolImmutables} from"lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol";
import {IRelayer} from"src/interfaces/IRelayer.sol";
///@title AssetRegistry contract///@notice Handle logic and state for logging informations regarding the assetsabstractcontractAssetRegistryisOwnable, BaseChecker, AddressRegistry, ProtocolState{
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*////@notice Asset list;address[] public assetsList;
///@notice last block incentiveFactor was updated, safety measureuint128public lastIncentiveUpdateBlock;
int128public incentiveCap;
///@notice Map asset address to struct containing infomapping(address=> AssetInfo) public assetInfo;
/*//////////////////////////////////////////////////////////////
ERROR
//////////////////////////////////////////////////////////////*/errorPoolNotValid();
errorAssetSupported(address asset);
errorNotNormalized();
errorNotZero();
errorCoolDownPeriodActive();
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/eventAssetAdded(address _asset);
eventIncentiveFactorUpdated(addressindexed asset, int72 incentiveFactor);
eventTargetConcentrationsUpdated();
eventUniswapPoolUpdated(addressindexed asset, address uniswapPool);
eventAssetRemoved(addressindexed asset);
/*//////////////////////////////////////////////////////////////
ADD ASSETS
//////////////////////////////////////////////////////////////*////@notice Add assets in batch///@param _assets Array of assets to add///@param _uniswapPools Array of address of uniswap Pool///@dev only uniswap pool and incentive factor are relevant in assetsInfo, the rest is retrieved/// on-chainfunctionaddAssets(address[] calldata _assets, address[] calldata _uniswapPools)
externalonlyOwner{
if (_assets.length!= _uniswapPools.length) revert InconsistentLengths();
for (uint256 i; i < _assets.length; ++i) {
_addAsset(_assets[i], _uniswapPools[i]);
}
}
function_addAsset(address _asset, address _uniswapPool) private{
if (assetInfo[_asset].isSupported) revert AssetSupported(_asset);
assetInfo[_asset].isSupported =true;
assetInfo[_asset].assetDecimals = IERC20Metadata(_asset).decimals();
setUniswapPool(_asset, _uniswapPool);
assetsList.push(_asset);
emit AssetAdded(_asset);
}
///@notice Removes asset from the protocol whitelist///@param _assetIdx index of the asset in the assets array///@dev only possible if there are no tokens of the asset held by the protocol anymorefunctionremoveAsset(uint256 _assetIdx) externalonlyOwner{
address asset = assetsList[_assetIdx];
if (totalAssetAccounting[asset] !=0) revert NotZero();
if (assetInfo[asset].targetConcentration !=0) revert NotZero();
delete assetInfo[asset];
assetsList[_assetIdx] = assetsList[assetsList.length-1];
assetsList.pop();
emit AssetRemoved(asset);
}
/*//////////////////////////////////////////////////////////////
SETTER
//////////////////////////////////////////////////////////////*////@notice Set target concentration for all asset///@param _targetConcentrations Target concentration (1e18 -> 1%)///@dev 1e18 = 1%///@dev targetConcentrations must have same length as assetsList -> can only update all conc at// once to enforce normalizationfunctionsetTargetConcentrations(uint72[] calldata _targetConcentrations) externalonlyOwner{
if (_targetConcentrations.length!= assetsList.length) revert InconsistentLengths();
uint72 sum;
for (uint256 i; i < _targetConcentrations.length; i++) {
sum += _targetConcentrations[i];
}
if (sum > (1e20+1e10) || sum < (1e20-1e10)) revert NotNormalized();
for (uint256 i; i < _targetConcentrations.length; i++) {
assetInfo[assetsList[i]].targetConcentration = _targetConcentrations[i];
}
emit TargetConcentrationsUpdated();
}
///@notice Set target concentration for an asset///@param _asset Asset address///@param _incentiveFactor IncentiveFactor (1e18 -> 1%)///@dev 1e18 = 1%, max incentiveCap///@dev Can only be called every 5 blocks, safety measure in case of compromised IncentiveManagerfunctionsetIncentiveFactor(address _asset, int72 _incentiveFactor) externalonlyIncentiveManager{
if (int128(_incentiveFactor) > incentiveCap) revert ValueOutOfBounds();
if (block.number<uint256(lastIncentiveUpdateBlock) +5) revert CoolDownPeriodActive();
lastIncentiveUpdateBlock =uint128(block.number);
assetInfo[_asset].incentiveFactor = _incentiveFactor;
emit IncentiveFactorUpdated(_asset, _incentiveFactor);
}
///@notice Set maximum incentive factor///@param _incentiveCap maximum incentive factor///@dev Capped at 1e20 == 100%functionsetIncentiveCap(int128 _incentiveCap) externalonlyOwner{
if (_incentiveCap >1e20) revert ValueOutOfBounds();
incentiveCap = _incentiveCap;
}
///@notice Set uniswap pool for an asset///@param _asset Asset address///@param _uniswapPool Uniswap pool addressfunctionsetUniswapPool(address _asset, address _uniswapPool) publiconlyOwner{
if (_uniswapPool ==address(0x0)) {
assetInfo[_asset].uniswapPool = _uniswapPool;
} else {
address token0 = IUniswapV3PoolImmutables(_uniswapPool).token0();
address token1 = IUniswapV3PoolImmutables(_uniswapPool).token1();
address quoteToken;
if (token0 == _asset) quoteToken = token1;
elseif (token1 == _asset) quoteToken = token0;
elserevert PoolNotValid();
assetInfo[_asset].uniswapPool = _uniswapPool;
assetInfo[_asset].uniswapQuoteToken = quoteToken;
assetInfo[_asset].quoteTokenDecimals = IERC20Metadata(quoteToken).decimals();
}
emit UniswapPoolUpdated(_asset, _uniswapPool);
}
/*//////////////////////////////////////////////////////////////
GETTER
//////////////////////////////////////////////////////////////*////@notice Get isSupported for an asset///@param _assets asset addresses///@return address of first not supported asset or address(0x0) if all supportedfunctionisAnyNotSupported(address[] memory _assets) publicviewreturns (address) {
for (uint256 i; i < _assets.length; i++) {
if (!assetInfo[_assets[i]].isSupported) return _assets[i];
}
returnaddress(0x0);
}
///@notice Get isSwapAllowed for an asset array///@param _assets asset addresses///@return address of first not supported asset or address(0x0) if all supportedfunctionisSwapAllowed(address[] memory _assets) publicviewreturns (address) {
for (uint256 i; i < _assets.length; i++) {
if (assetInfo[_assets[i]].incentiveFactor ==-100e18) return _assets[i];
}
returnaddress(0x0);
}
///@notice Get number of asset decimals///@param _asset Asset address///@return number of decimalsfunctiongetAssetDecimals(address _asset) externalviewreturns (uint8) {
return assetInfo[_asset].assetDecimals;
}
///@notice Get number of assets in protocolfunctiongetAssetsListLength() publicviewreturns (uint256) {
return assetsList.length;
}
///@dev caller has to be whitelisted manager on relayermodifieronlyIncentiveManager() {
if (!IRelayer(RELAYER).isIncentiveManager(msg.sender)) revert Unauthorized();
_;
}
}
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity >=0.8.0;/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation./// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.abstractcontractERC20{
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/eventTransfer(addressindexedfrom, addressindexed to, uint256 amount);
eventApproval(addressindexed owner, addressindexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/stringpublic name;
stringpublic symbol;
uint8publicimmutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/uint256public totalSupply;
mapping(address=>uint256) public balanceOf;
mapping(address=>mapping(address=>uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/uint256internalimmutable INITIAL_CHAIN_ID;
bytes32internalimmutable INITIAL_DOMAIN_SEPARATOR;
mapping(address=>uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/constructor(stringmemory _name,
stringmemory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID =block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/functionapprove(address spender, uint256 amount) publicvirtualreturns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
returntrue;
}
functiontransfer(address to, uint256 amount) publicvirtualreturns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user// balances can't exceed the max uint256 value.unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
returntrue;
}
functiontransferFrom(addressfrom,
address to,
uint256 amount
) publicvirtualreturns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.if (allowed !=type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user// balances can't exceed the max uint256 value.unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
returntrue;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) publicvirtual{
require(deadline >=block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing// the owner's nonce which cannot realistically overflow.unchecked {
address recoveredAddress =ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress !=address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
functionDOMAIN_SEPARATOR() publicviewvirtualreturns (bytes32) {
returnblock.chainid== INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
functioncomputeDomainSeparator() internalviewvirtualreturns (bytes32) {
returnkeccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/function_mint(address to, uint256 amount) internalvirtual{
totalSupply += amount;
// Cannot overflow because the sum of all user// balances can't exceed the max uint256 value.unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function_burn(addressfrom, uint256 amount) internalvirtual{
balanceOf[from] -= amount;
// Cannot underflow because a user's balance// will never be larger than the total supply.unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
Contract Source Code
File 6 of 36: Fyde.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.19;/// Import from Core /////import {TRSY} from"./core/TRSY.sol";
import {AssetRegistry} from"./core/AssetRegistry.sol";
import {AddressRegistry} from"./core/AddressRegistry.sol";
import {ProtocolState} from"./core/ProtocolState.sol";
import {Tax} from"./core/Tax.sol";
import {GovernanceAccess} from"./core/GovernanceAccess.sol";
/// Structs /////import {RequestData, ProcessParam, AssetInfo} from"./core/Structs.sol";
/// Utils /////import {Ownable} from"./utils/Ownable.sol";
import {PercentageMath} from"./utils/PercentageMath.sol";
import {SafeERC20} from"openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
//Interfacesimport {IERC20} from"openzeppelin-contracts/token/ERC20/IERC20.sol";
import {IOracle} from"src/interfaces/IOracle.sol";
import {IRelayer} from"src/interfaces/IRelayer.sol";
///@title Fyde contract///@notice Fyde is the main contract of the protocol, it handles logic of deposit and withdraw in/// the protocol/// Deposit and withdraw occurs a mint or a burn of TRSY (ERC20 that represent shares of the/// procotol in USD value)/// Users can both deposit/withdraw in standard or governance poolcontractFydeisTRSY, AddressRegistry, ProtocolState, AssetRegistry, GovernanceAccess, Tax{
usingSafeERC20forIERC20;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/eventFeesCollected(addressindexed recipient, uint256 trsyFeesCollected);
eventDeposit(uint32 requestId, uint256 trsyPrice, uint256 usdDepositValue, uint256 trsyMinted);
eventWithdraw(uint32 requestId, uint256 trsyPrice, uint256 usdWithdrawValue, uint256 trsyBurned);
eventSwap(uint32 requestId, address assetOut, uint256 amountOut);
eventManagementFeeCollected(uint256 feeToMint);
/*//////////////////////////////////////////////////////////////
ERROR
//////////////////////////////////////////////////////////////*/errorAumNotInRange();
errorOnlyOneUpdatePerBlock();
errorSlippageExceed();
errorFydeBalanceInsufficient();
errorInsufficientTRSYBalance();
errorAssetPriceNotAvailable();
errorSwapAmountNotAvailable();
errorAssetNotSupported(address asset);
errorSwapDisabled(address asset);
errorAssetIsQuarantined(address asset);
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/constructor(address _relayer,
address _oracleModule,
address _governanceModule,
uint16 _maxAumDeviationAllowed,
uint72 _taxFactor,
uint72 _managementFee
) Ownable(msg.sender) AddressRegistry(_governanceModule, _relayer) {
oracleModule = IOracle(_oracleModule);
updateMaxAumDeviationAllowed(_maxAumDeviationAllowed);
updateTaxFactor(_taxFactor);
updateManagementFee(_managementFee);
_updateLastFeeCollectionTime();
}
/*//////////////////////////////////////////////////////////////
AUTH
//////////////////////////////////////////////////////////////*////@notice Collect and send TRSY fees (from tax fees) to an external address///@param _recipient Address to send TRSY fees to///@param _amount Amount of TRSY to sendfunctioncollectFees(address _recipient, uint256 _amount) externalonlyOwner{
_checkZeroAddress(_recipient);
_checkZeroValue(_amount);
balanceOf[address(this)] -= _amount;
balanceOf[_recipient] += _amount;
emit FeesCollected(_recipient, _amount);
}
///@notice Collect management fee by inflating TRSY and minting to Fyde/// is called by the relayer when processingRequestsfunctioncollectManagementFee() external{
uint256 feePerSecond =uint256(protocolData.managementFee /31_557_600);
uint256 timePeriod =block.timestamp- protocolData.lastFeeCollectionTime;
if (timePeriod ==0) return;
uint256 feeToMint = feePerSecond * timePeriod * totalSupply /1e18;
_updateLastFeeCollectionTime();
_mint(address(this), feeToMint);
emit ManagementFeeCollected(feeToMint);
}
/*//////////////////////////////////////////////////////////////
RELAYER & KEEPER FUNCTIONS
//////////////////////////////////////////////////////////////*////@notice Update protocol AUM, called by keeper///@param _aum New AUM///@dev Can at most be updated by maxDeviationThreshold and only once per blockfunctionupdateProtocolAUM(uint256 _aum) external{
if (msg.sender!= RELAYER &&msg.sender!= owner) revert Unauthorized();
if (block.number== protocolData.lastAUMUpdateBlock) revert CoolDownPeriodActive();
protocolData.lastAUMUpdateBlock =uint48(block.number);
(, uint256 limitedAum) = _AumIsInRange(_aum);
_updateProtocolAUM(limitedAum);
}
/*//////////////////////////////////////////////////////////////
PROCESSING DEPOSIT ACTIONS
//////////////////////////////////////////////////////////////*////@notice Process deposit action, called by relayer///@param _protocolAUM AUM given by keeper///@param _req RequestData struct///@return totalUsdDeposit USD value of the depositfunctionprocessDeposit(uint256 _protocolAUM, RequestData calldata _req)
externalonlyRelayerreturns (uint256)
{
// Check if asset is supported
_checkIsSupported(_req.assetIn);
_checkIsNotQuarantined(_req.assetIn);
// is keeper AUM in range
(bool isInRange,) = _AumIsInRange(_protocolAUM);
if (!isInRange) revert AumNotInRange();
(
ProcessParam[] memory processParam,
uint256 sharesToMint,
uint256 taxInTRSY,
uint256 totalUsdDeposit
) = getProcessParamDeposit(_req, _protocolAUM);
// Slippage checkerif (_req.slippageChecker > sharesToMint) revert SlippageExceed();
// Transfer assets to Fydefor (uint256 i; i < _req.assetIn.length; i++) {
IERC20(_req.assetIn[i]).safeTransferFrom(_req.requestor, address(this), _req.amountIn[i]);
}
if (_req.keepGovRights) _govDeposit(_req, processParam);
else _standardDeposit(_req, sharesToMint);
// Mint tax and keep in contractif (taxInTRSY >0) _mint(address(this), taxInTRSY);
_updateProtocolAUM(_protocolAUM + totalUsdDeposit);
uint256 trsyPrice = (1e18* (_protocolAUM + totalUsdDeposit)) / totalSupply;
emit Deposit(_req.id, trsyPrice, totalUsdDeposit, sharesToMint);
return totalUsdDeposit;
}
function_standardDeposit(RequestData calldata _req, uint256 _sharesToMint) internal{
// Accounting
_increaseAssetTotalAmount(_req.assetIn, _req.amountIn);
// Minting shares
_mint(_req.requestor, _sharesToMint);
}
function_govDeposit(RequestData calldata _req, ProcessParam[] memory _processParam) internal{
uint256[] memory sharesAfterTax =newuint256[](_req.assetIn.length);
uint256[] memory amountInAfterTax =newuint256[](_req.assetIn.length);
// Same average tax rate is applied to each assetuint256 taxMultiplicator;
uint256 totalTrsy;
for (uint256 i; i < _req.assetIn.length; i++) {
taxMultiplicator =1e18* _processParam[i].sharesAfterTax / (_processParam[i].sharesBeforeTax);
amountInAfterTax[i] = _req.amountIn[i] * taxMultiplicator /1e18;
sharesAfterTax[i] = _processParam[i].sharesAfterTax;
totalTrsy += sharesAfterTax[i];
}
// Mint stTRSY and transfer token into proxyaddress proxy = GOVERNANCE_MODULE.govDeposit(
_req.requestor, _req.assetIn, amountInAfterTax, sharesAfterTax, totalTrsy
);
for (uint256 i; i < _req.assetIn.length; i++) {
IERC20(_req.assetIn[i]).safeTransfer(proxy, amountInAfterTax[i]);
}
// Accounting
_increaseAssetTotalAmount(_req.assetIn, _req.amountIn);
_increaseAssetProxyAmount(_req.assetIn, amountInAfterTax);
// Mint
_mint(address(GOVERNANCE_MODULE), totalTrsy);
}
/*//////////////////////////////////////////////////////////////
PROCESSING WITHDRAW ACTIONS
//////////////////////////////////////////////////////////////*////@notice Process withdraw action, called by relayer///@param _protocolAUM AUM given by keeper///@param _req RequestData struct///@return totalUsdWithdraw USD value of the withdrawfunctionprocessWithdraw(uint256 _protocolAUM, RequestData calldata _req)
externalonlyRelayerreturns (uint256)
{
// Check if asset is supported
_checkIsSupported(_req.assetOut);
_checkIsNotQuarantined(_req.assetOut);
// is keeper AUM in range
(bool isInRange,) = _AumIsInRange(_protocolAUM);
if (!isInRange) revert AumNotInRange();
uint256 totalUsdWithdraw;
uint256 totalSharesToBurn;
(totalUsdWithdraw, totalSharesToBurn) =
_req.keepGovRights ? _govWithdraw(_protocolAUM, _req) : _standardWithdraw(_protocolAUM, _req);
// Accounting
_decreaseAssetTotalAmount(_req.assetOut, _req.amountOut);
_updateProtocolAUM(_protocolAUM - totalUsdWithdraw);
// Calculate for offchain purposeuint256 trsyPrice =
totalSupply !=0 ? (1e18* (_protocolAUM - totalUsdWithdraw)) / totalSupply : 0;
emit Withdraw(_req.id, trsyPrice, totalUsdWithdraw, totalSharesToBurn);
return totalUsdWithdraw;
}
function_govWithdraw(uint256 _protocolAUM, RequestData calldata _req)
internalreturns (uint256, uint256)
{
uint256 usdVal = getQuote(_req.assetOut[0], _req.amountOut[0]);
if (usdVal ==0) revert AssetPriceNotAvailable();
uint256 trsyToBurn = _convertToShares(usdVal, _protocolAUM);
if (_req.slippageChecker < trsyToBurn) revert SlippageExceed();
_burn(address(GOVERNANCE_MODULE), trsyToBurn);
_decreaseAssetProxyAmount(_req.assetOut, _req.amountOut);
GOVERNANCE_MODULE.govWithdraw(_req.requestor, _req.assetOut[0], _req.amountOut[0], trsyToBurn);
IERC20(_req.assetOut[0]).safeTransfer(_req.requestor, _req.amountOut[0]);
return (usdVal, trsyToBurn);
}
function_standardWithdraw(uint256 _protocolAUM, RequestData calldata _req)
internalreturns (uint256, uint256)
{
// check if requested token are availablefor (uint256 i =0; i < _req.assetOut.length; i++) {
if (standardAssetAccounting(_req.assetOut[i]) < _req.amountOut[i]) {
revert FydeBalanceInsufficient();
}
}
(, uint256 totalSharesToBurn,, uint256 taxInTRSY, uint256 totalUsdWithdraw) =
getProcessParamWithdraw(_req, _protocolAUM);
if (totalSharesToBurn > _req.slippageChecker) revert SlippageExceed();
if (balanceOf[_req.requestor] < totalSharesToBurn) revert InsufficientTRSYBalance();
_burn(_req.requestor, totalSharesToBurn);
// Give tax to this contractif (taxInTRSY >0) _mint(address(this), taxInTRSY);
for (uint256 i =0; i < _req.assetOut.length; i++) {
// Send asset to recipient
IERC20(_req.assetOut[i]).safeTransfer(_req.requestor, _req.amountOut[i]);
}
return (totalUsdWithdraw, totalSharesToBurn);
}
/*//////////////////////////////////////////////////////////////
SWAP
//////////////////////////////////////////////////////////////*/functionprocessSwap(uint256 _protocolAUM, RequestData calldata _req)
externalonlyRelayerreturns (int256)
{
// Check if asset is supported
_checkIsSupported(_req.assetIn);
_checkIsSupported(_req.assetOut);
_checkIsNotQuarantined(_req.assetIn);
_checkIsNotQuarantined(_req.assetOut);
_checkIfSwapAllowed(_req.assetIn);
_checkIfSwapAllowed(_req.assetOut);
// is keeper AUM in range
(bool isInRange,) = _AumIsInRange(_protocolAUM);
if (!isInRange) revert AumNotInRange();
(uint256 amountOut, int256 deltaAUM) =
getSwapAmountOut(_req.assetIn[0], _req.amountIn[0], _req.assetOut[0], _protocolAUM);
if (amountOut ==0) revert SwapAmountNotAvailable();
if (amountOut < _req.slippageChecker) revert SlippageExceed();
// Check enough asset in protocolif (standardAssetAccounting(_req.assetOut[0]) < amountOut) revert FydeBalanceInsufficient();
// Update AUMuint256 aum;
// If the swapper pays net tax, we mint the corresponding TRSY to fyde. This way TRSY price// stays constantif (deltaAUM >0) {
aum = _protocolAUM +uint256(deltaAUM);
_mint(address(this), _convertToShares(uint256(deltaAUM), _protocolAUM));
// If incentives are higher tan taxes, we burn TRSY from fyde, to keep TRSY price constant// as backup if not enough TRSY in Fyde, we don't burn, i.e. TRSY price goes down and// incentives are// paid by pool// this way by frequently cashing out TRSY from fyde we can manually decide how much tax to// keep for ourselves// or leave in Fyde for incentives
} elseif (deltaAUM <0) {
aum = _protocolAUM -uint256(-deltaAUM);
uint256 trsyToBurn = _convertToShares(uint256(-deltaAUM), _protocolAUM);
trsyToBurn = balanceOf[address(this)] >= trsyToBurn ? trsyToBurn : balanceOf[address(this)];
if (trsyToBurn !=0) _burn(address(this), trsyToBurn);
} else {
aum = _protocolAUM;
}
_updateProtocolAUM(aum);
// Log accounting
_increaseAssetTotalAmount(_req.assetIn[0], _req.amountIn[0]);
_decreaseAssetTotalAmount(_req.assetOut[0], amountOut);
// Transfer asset
IERC20(_req.assetIn[0]).safeTransferFrom(_req.requestor, address(this), _req.amountIn[0]);
IERC20(_req.assetOut[0]).safeTransfer(_req.requestor, amountOut);
emit Swap(_req.id, _req.assetOut[0], amountOut);
return deltaAUM;
}
/*///////////////////////////////////////////////////////////////
GETTERS
//////////////////////////////////////////////////////////////*////@notice Give a quote for a speficic asset deposit///@param _asset asset address to quote///@param _amount amount of asset to deposit///@return USD value of the specified deposit (return 18 decimals, 1USD = 1e18)///@dev If price is inconsistent or not available, returns 0 from oracle module -> needs proper/// handlingfunctiongetQuote(address _asset, uint256 _amount) publicviewoverridereturns (uint256) {
AssetInfo memory _assetInfo = assetInfo[_asset];
uint256 price = oracleModule.getPriceInUSD(_asset, _assetInfo);
return (_amount * price) / (10** _assetInfo.assetDecimals);
}
///@notice Get the USD value of an asset in the protocol///@param _asset asset address///@return USD value of the asset///@dev If price is inconsistent or not available, returns 0 -> needs proper handlingfunctiongetAssetAUM(address _asset) publicviewreturns (uint256) {
return getQuote(_asset, totalAssetAccounting[_asset]);
}
///@notice Compute the USD AUM for the protocol///@dev Should NOT be call within a contract (GAS EXPENSIVE), called off-chain by keeperfunctioncomputeProtocolAUM() publicviewreturns (uint256) {
address asset;
uint256 aum;
uint256 assetAUM;
address[] memory nAsset = assetsList;
uint256 length = nAsset.length;
for (uint256 i =0; i < length; ++i) {
asset = nAsset[i];
if (totalAssetAccounting[asset] ==0) continue;
assetAUM = getAssetAUM(asset);
if (assetAUM ==0) return protocolData.aum;
aum += assetAUM;
}
return aum;
}
/*//////////////////////////////////////////////////////////////
PROCESS PARAM
//////////////////////////////////////////////////////////////*////@notice Return the process param for a deposit///@param _req RequestData struct///@param _protocolAUM AUM given by keeper///@return processParam array of ProcessParam struct///@return sharesToMint amount of shares to mint///@return taxInTRSY amount of tax in TRSY///@return totalUsdDeposit USD value of the depositnfunctiongetProcessParamDeposit(RequestData memory _req, uint256 _protocolAUM)
publicviewreturns (
ProcessParam[] memory processParam,
uint256 sharesToMint,
uint256 taxInTRSY,
uint256 totalUsdDeposit
)
{
processParam =new ProcessParam[](_req.assetIn.length);
// Build data struct and compute value of depositfor (uint256 i; i < _req.assetIn.length; i++) {
uint256 usdVal = getQuote(_req.assetIn[i], _req.amountIn[i]);
if (usdVal ==0) revert AssetPriceNotAvailable();
processParam[i] = ProcessParam({
targetConc: assetInfo[_req.assetIn[i]].targetConcentration,
currentConc: _getAssetConcentration(_req.assetIn[i], _protocolAUM),
usdValue: usdVal,
sharesBeforeTax: _convertToShares(usdVal, _protocolAUM),
taxableAmount: 0,
taxInUSD: 0,
sharesAfterTax: 0
});
totalUsdDeposit += usdVal;
}
for (uint256 i; i < processParam.length; i++) {
// Get the TaxInUSD
processParam[i] =
_getDepositTax(processParam[i], _protocolAUM, totalUsdDeposit, protocolData.taxFactor);
// Apply tax to the deposit
processParam[i].sharesAfterTax =
_convertToShares(processParam[i].usdValue - processParam[i].taxInUSD, _protocolAUM);
sharesToMint += processParam[i].sharesAfterTax;
taxInTRSY += processParam[i].sharesBeforeTax - processParam[i].sharesAfterTax;
}
return (processParam, sharesToMint, taxInTRSY, totalUsdDeposit);
}
///@notice Return the process param for a withdraw///@param _req RequestData struct///@param _protocolAUM AUM given by keeper///@return processParam array of ProcessParam struct///@return totalSharesToBurn amount of shares to burn///@return sharesToBurnBeforeTax amount of shares to burn before tax///@return taxInTRSY amount of tax in TRSY///@return totalUsdWithdraw USD value of the withdrawfunctiongetProcessParamWithdraw(RequestData calldata _req, uint256 _protocolAUM)
publicviewreturns (
ProcessParam[] memory processParam,
uint256 totalSharesToBurn,
uint256 sharesToBurnBeforeTax,
uint256 taxInTRSY,
uint256 totalUsdWithdraw
)
{
processParam =new ProcessParam[](_req.assetOut.length);
// Build data struct and compute value of depositfor (uint256 i; i < _req.assetOut.length; i++) {
uint256 usdVal = getQuote(_req.assetOut[i], _req.amountOut[i]);
if (usdVal ==0) revert AssetPriceNotAvailable();
processParam[i] = ProcessParam({
targetConc: assetInfo[_req.assetOut[i]].targetConcentration,
currentConc: _getAssetConcentration(_req.assetOut[i], _protocolAUM),
usdValue: usdVal,
sharesBeforeTax: 0,
taxableAmount: 0,
taxInUSD: 0,
sharesAfterTax: 0
});
totalUsdWithdraw += usdVal;
}
for (uint256 i; i < processParam.length; i++) {
// Get the TaxInUSD
processParam[i] =
_getWithdrawTax(processParam[i], _protocolAUM, totalUsdWithdraw, protocolData.taxFactor);
taxInTRSY += _convertToShares(processParam[i].taxInUSD, _protocolAUM);
}
sharesToBurnBeforeTax = _convertToShares(totalUsdWithdraw, _protocolAUM);
totalSharesToBurn = sharesToBurnBeforeTax + taxInTRSY;
}
///@notice Return the amountOut for a swap accounting for tax and incentive///@param _assetIn asset address to swap///@param _amountIn amount of asset to swap///@param _assetOut asset address to receive///@param _protocolAUM AUM given by keeperfunctiongetSwapAmountOut(address _assetIn,
uint256 _amountIn,
address _assetOut,
uint256 _protocolAUM
) publicviewreturns (uint256, int256) {
// Scope to avoid stack too deep
{
uint256 usdValIn = getQuote(_assetIn, _amountIn);
uint256 assetOutPrice = getQuote(_assetOut, 10** assetInfo[_assetOut].assetDecimals);
if (usdValIn ==0|| assetOutPrice ==0) return (0, int256(0));
}
ProcessParam memory processParamIn = ProcessParam({
targetConc: assetInfo[_assetIn].targetConcentration,
currentConc: _getAssetConcentration(_assetIn, _protocolAUM),
usdValue: getQuote(_assetIn, _amountIn),
sharesBeforeTax: 0,
taxableAmount: 0,
taxInUSD: 0,
sharesAfterTax: 0
});
ProcessParam memory processParamOut = ProcessParam({
targetConc: assetInfo[_assetOut].targetConcentration,
currentConc: _getAssetConcentration(_assetOut, _protocolAUM),
usdValue: 0,
sharesBeforeTax: 0,
taxableAmount: 0,
taxInUSD: 0,
sharesAfterTax: 0
});
uint256 usdAmountOut = _getSwapRate(
processParamIn,
processParamOut,
_protocolAUM,
protocolData.taxFactor,
assetInfo[_assetIn].incentiveFactor,
assetInfo[_assetOut].incentiveFactor
);
return (
1e18* usdAmountOut / getQuote(_assetOut, 1e18),
int256(processParamIn.usdValue) -int256(usdAmountOut)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*////@notice Return asset concentration with keeper AUM///@param _asset asset address///@param _protocolAUM AUM given by keeper///@return current concentration for an asset///@dev If price is inconsistent or not available, returns 0 -> needs proper handlingfunction_getAssetConcentration(address _asset, uint256 _protocolAUM)
internalviewreturns (uint256)
{
// To avoid division by 0if (_protocolAUM ==0&& protocolData.aum ==0) return0;
return (1e20* getAssetAUM(_asset)) / _protocolAUM;
}
///@notice Perform the comparison between AUM registry and one given by Keeper, return limited AUM/// if out of boundsfunction_AumIsInRange(uint256 _keeperAUM) internalviewreturns (bool, uint256) {
uint16 maxAumDeviationAllowed = protocolData.maxAumDeviationAllowed;
uint256 currAum = protocolData.aum;
uint256 lowerBound = PercentageMath.percentSub(currAum, maxAumDeviationAllowed);
uint256 upperBound = PercentageMath.percentAdd(currAum, maxAumDeviationAllowed);
if (_keeperAUM < lowerBound) return (false, lowerBound);
if (_keeperAUM > upperBound) return (false, upperBound);
return (true, _keeperAUM);
}
function_checkIsSupported(address[] memory _assets) internalview{
address notSupportedAsset = isAnyNotSupported(_assets);
if (notSupportedAsset !=address(0x0)) revert AssetNotSupported(notSupportedAsset);
}
function_checkIsNotQuarantined(address[] memory _assets) internalview{
address quarantinedAsset = IRelayer(RELAYER).isAnyQuarantined(_assets);
if (quarantinedAsset !=address(0x0)) revert AssetIsQuarantined(quarantinedAsset);
}
function_checkIfSwapAllowed(address[] memory _assets) internalview{
address notAllowedAsset = isSwapAllowed(_assets);
if (notAllowedAsset !=address(0x0)) revert SwapDisabled(notAllowedAsset);
}
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/modifieronlyRelayer() {
if (msg.sender!= RELAYER) revert Unauthorized();
_;
}
}
Contract Source Code
File 7 of 36: GovernanceAccess.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.19;/// Import from Core /////import {AddressRegistry} from"./AddressRegistry.sol";
import {AssetRegistry} from"./AssetRegistry.sol";
import {ProtocolState} from"./ProtocolState.sol";
import {TRSY} from"./TRSY.sol";
/// Structs /////import {RebalanceParam} from"./Structs.sol";
// Interfaceimport {IERC20} from"openzeppelin-contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from"openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
///@title GovernanceAccess contract///@notice Exposes functions for the governance moduleabstractcontractGovernanceAccessisTRSY, AddressRegistry, ProtocolState, AssetRegistry{
usingSafeERC20forIERC20;
///@notice Called by the governance module in order to transfer asset when proxy is funded///@param _asset asset address///@param _recipient user address///@param _amount number of tokenfunctiontransferAsset(address _asset, address _recipient, uint256 _amount)
externalonlyGovernance{
IERC20(_asset).safeTransfer(_recipient, _amount);
}
///@notice Called by the governance module in order to update proxy Accounting after rebalancing///@param _asset asset address///@param _amount number of tokenfunctionupdateAssetProxyAmount(address _asset, uint256 _amount) externalonlyGovernance{
proxyAssetAccounting[_asset] = _amount;
}
///@notice Called by the governance module in order get all variables for rebalancing in one call/// (save gas)///@param _asset asset address///@return RebalanceParam struct with rebalance parametersfunctiongetRebalanceParams(address _asset) externalviewreturns (RebalanceParam memory) {
return RebalanceParam(
_asset,
totalAssetAccounting[_asset],
proxyAssetAccounting[_asset],
getQuote(_asset, 1e18),
0,
1e18* protocolData.aum / totalSupply
);
}
functiongetQuote(address _asset, uint256 _amount) publicviewvirtualreturns (uint256);
modifieronlyGovernance() {
if (msg.sender!=address(GOVERNANCE_MODULE)) revert Unauthorized();
_;
}
}
Contract Source Code
File 8 of 36: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom, address to, uint256 amount) externalreturns (bool);
}
Contract Source Code
File 9 of 36: IERC20Metadata.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
Contract Source Code
File 10 of 36: IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/interfaceIERC20Permit{
/**
* @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].
*/functionpermit(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.
*/functionnonces(address owner) externalviewreturns (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-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title Pool state that never changes/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same valuesinterfaceIUniswapV3PoolImmutables{
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface/// @return The contract addressfunctionfactory() externalviewreturns (address);
/// @notice The first of the two tokens of the pool, sorted by address/// @return The token contract addressfunctiontoken0() externalviewreturns (address);
/// @notice The second of the two tokens of the pool, sorted by address/// @return The token contract addressfunctiontoken1() externalviewreturns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6/// @return The feefunctionfee() externalviewreturns (uint24);
/// @notice The pool tick spacing/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, .../// This value is an int24 to avoid casting even though it is always positive./// @return The tick spacingfunctiontickSpacing() externalviewreturns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool/// @return The max amount of liquidity per tickfunctionmaxLiquidityPerTick() externalviewreturns (uint128);
}
Contract Source Code
File 15 of 36: MathUtil.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)pragmasolidity 0.8.19;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMathUtil{
/**
* @dev Returns the largest of two numbers.
*/functionmax(int256 a, int256 b) internalpurereturns (int256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/functionmin(int256 a, int256 b) internalpurereturns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
}
Contract Source Code
File 16 of 36: Ownable.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.19;///@title Ownable contract/// @notice Simple 2step owner authorization combining solmate and OZ implementationabstractcontractOwnable{
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*////@notice Address of the owneraddresspublic owner;
///@notice Address of the pending owneraddresspublic pendingOwner;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/eventOwnershipTransferred(addressindexed user, addressindexed newOner);
eventOwnershipTransferStarted(addressindexed user, addressindexed newOwner);
eventOwnershipTransferCanceled(addressindexed pendingOwner);
/*//////////////////////////////////////////////////////////////
ERROR
//////////////////////////////////////////////////////////////*/errorUnauthorized();
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/constructor(address _owner) {
owner = _owner;
emit OwnershipTransferred(address(0), _owner);
}
/*//////////////////////////////////////////////////////////////
OWNERSHIP LOGIC
//////////////////////////////////////////////////////////////*////@notice Transfer ownership to a new address///@param newOwner address of the new owner///@dev newOwner have to acceptOwnershipfunctiontransferOwnership(address newOwner) externalonlyOwner{
pendingOwner = newOwner;
emit OwnershipTransferStarted(msg.sender, pendingOwner);
}
///@notice NewOwner accept the ownership, it transfer the ownership to newOwnerfunctionacceptOwnership() external{
if (msg.sender!= pendingOwner) revert Unauthorized();
address oldOwner = owner;
owner = pendingOwner;
delete pendingOwner;
emit OwnershipTransferred(oldOwner, owner);
}
///@notice Cancel the ownership transferfunctioncancelTransferOwnership() externalonlyOwner{
emit OwnershipTransferCanceled(pendingOwner);
delete pendingOwner;
}
modifieronlyOwner() {
if (msg.sender!= owner) revert Unauthorized();
_;
}
}
Contract Source Code
File 17 of 36: PercentageMath.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.19;libraryPercentageMath{
/// CONSTANTS ///uint256internalconstant PERCENTAGE_FACTOR =1e4; // 100.00%uint256internalconstant HALF_PERCENTAGE_FACTOR =0.5e4; // 50.00%uint256internalconstant MAX_UINT256 =2**256-1;
uint256internalconstant MAX_UINT256_MINUS_HALF_PERCENTAGE =2**256-1-0.5e4;
/// INTERNAL //////@notice Check if value are within the rangefunction_isInRange(uint256 valA, uint256 valB, uint256 deviationThreshold)
internalpurereturns (bool)
{
uint256 lowerBound = percentSub(valA, deviationThreshold);
uint256 upperBound = percentAdd(valA, deviationThreshold);
if (valB < lowerBound || valB > upperBound) returnfalse;
elsereturntrue;
}
/// @notice Executes a percentage addition (x * (1 + p)), rounded up./// @param x The value to which to add the percentage./// @param percentage The percentage of the value to add./// @return y The result of the addition.functionpercentAdd(uint256 x, uint256 percentage) internalpurereturns (uint256 y) {
// Must revert if// PERCENTAGE_FACTOR + percentage > type(uint256).max// or x * (PERCENTAGE_FACTOR + percentage) + HALF_PERCENTAGE_FACTOR > type(uint256).max// <=> percentage > type(uint256).max - PERCENTAGE_FACTOR// or x > (type(uint256).max - HALF_PERCENTAGE_FACTOR) / (PERCENTAGE_FACTOR + percentage)// Note: PERCENTAGE_FACTOR + percentage >= PERCENTAGE_FACTOR > 0assembly {
y :=add(PERCENTAGE_FACTOR, percentage) // Temporary assignment to save gas.ifor(
gt(percentage, sub(MAX_UINT256, PERCENTAGE_FACTOR)),
gt(x, div(MAX_UINT256_MINUS_HALF_PERCENTAGE, y))
) { revert(0, 0) }
y :=div(add(mul(x, y), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)
}
}
/// @notice Executes a percentage subtraction (x * (1 - p)), rounded up./// @param x The value to which to subtract the percentage./// @param percentage The percentage of the value to subtract./// @return y The result of the subtraction.functionpercentSub(uint256 x, uint256 percentage) internalpurereturns (uint256 y) {
// Must revert if// percentage > PERCENTAGE_FACTOR// or x * (PERCENTAGE_FACTOR - percentage) + HALF_PERCENTAGE_FACTOR > type(uint256).max// <=> percentage > PERCENTAGE_FACTOR// or ((PERCENTAGE_FACTOR - percentage) > 0 and x > (type(uint256).max -// HALF_PERCENTAGE_FACTOR) / (PERCENTAGE_FACTOR - percentage))assembly {
y :=sub(PERCENTAGE_FACTOR, percentage) // Temporary assignment to save gas.ifor(
gt(percentage, PERCENTAGE_FACTOR), mul(y, gt(x, div(MAX_UINT256_MINUS_HALF_PERCENTAGE, y)))
) { revert(0, 0) }
y :=div(add(mul(x, y), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)
}
}
}
Contract Source Code
File 18 of 36: ProtocolState.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.19;import {ProtocolData} from"./Structs.sol";
import {Ownable} from"../utils/Ownable.sol";
///@title ProtocolState contract///@notice Protocol data storageabstractcontractProtocolStateisOwnable{
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*////@notice Protocol data
ProtocolData public protocolData;
///@notice Number of token in the protocolmapping(address=>uint256) public totalAssetAccounting;
///@notice Number of token in the proxymapping(address=>uint256) public proxyAssetAccounting;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/errorValueOutOfBounds();
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/eventProtocolAumUpdated(uint256);
eventMaxAumDeviationAllowedUpdated(uint16);
eventTaxFactorUpdated(uint72);
eventManagementFeeUpdated(uint72);
/*//////////////////////////////////////////////////////////////
GETTER
//////////////////////////////////////////////////////////////*////@notice Get number of token in the standard pool///@param _asset asset address///@return number of token in standard poolfunctionstandardAssetAccounting(address _asset) publicviewreturns (uint256) {
return totalAssetAccounting[_asset] - proxyAssetAccounting[_asset];
}
///@notice Get protocolAUM in USD///@return protocol AUMfunctiongetProtocolAUM() externalviewreturns (uint256) {
return protocolData.aum;
}
/*//////////////////////////////////////////////////////////////
SETTER
//////////////////////////////////////////////////////////////*////@notice Change the AUM's comparison deviation threshold///@param threshold new threshold///@dev 200 = 2 % of deviationfunctionupdateMaxAumDeviationAllowed(uint16 threshold) publiconlyOwner{
// We bound the threshold to 0.1 % to 5%if (threshold <10|| threshold >500) revert ValueOutOfBounds();
protocolData.maxAumDeviationAllowed = threshold;
emit MaxAumDeviationAllowedUpdated(threshold);
}
///@notice set the tax factor///@param _taxFactor new tax factor///@dev 100% = 100e18functionupdateTaxFactor(uint72 _taxFactor) publiconlyOwner{
if (_taxFactor >100e18) revert ValueOutOfBounds();
protocolData.taxFactor = _taxFactor;
emit TaxFactorUpdated(_taxFactor);
}
///@notice change annual management fee///@param _annualFee new annual fee///@dev 100% = 1e18functionupdateManagementFee(uint72 _annualFee) publiconlyOwner{
// We bound the fee to 0 % to 5%if (_annualFee >5e16) revert ValueOutOfBounds();
protocolData.managementFee = _annualFee;
emit ManagementFeeUpdated(_annualFee);
}
///@notice Update last fee collection time to current timestampfunction_updateLastFeeCollectionTime() internal{
protocolData.lastFeeCollectionTime =uint48(block.timestamp);
}
///@notice Update the protocol AUMfunction_updateProtocolAUM(uint256 _aum) internal{
protocolData.aum = _aum;
emit ProtocolAumUpdated(_aum);
}
function_increaseAssetTotalAmount(address[] memory _assets, uint256[] memory _amounts) internal{
for (uint256 i; i < _assets.length; i++) {
_increaseAssetTotalAmount(_assets[i], _amounts[i]);
}
}
function_increaseAssetTotalAmount(address _asset, uint256 _amount) internal{
totalAssetAccounting[_asset] += _amount;
}
function_increaseAssetProxyAmount(address[] memory _assets, uint256[] memory _amounts) internal{
for (uint256 i; i < _assets.length; i++) {
proxyAssetAccounting[_assets[i]] += _amounts[i];
}
}
function_decreaseAssetTotalAmount(address[] memory _assets, uint256[] memory _amounts) internal{
for (uint256 i; i < _assets.length; i++) {
_decreaseAssetTotalAmount(_assets[i], _amounts[i]);
}
}
function_decreaseAssetTotalAmount(address _asset, uint256 _amount) internal{
totalAssetAccounting[_asset] -= _amount;
}
function_decreaseAssetProxyAmount(address[] memory _assets, uint256[] memory _amounts) internal{
for (uint256 i; i < _assets.length; i++) {
proxyAssetAccounting[_assets[i]] -= _amounts[i];
}
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
import"../extensions/IERC20Permit.sol";
import"../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/librarySafeERC20{
usingAddressforaddress;
/**
* @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.
*/functionsafeTransfer(IERC20 token, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, 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.
*/functionsafeTransferFrom(IERC20 token, addressfrom, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/functionsafeApprove(IERC20 token, address spender, uint256 value) internal{
// safeApprove should only be called when setting an initial allowance,// or when resetting it to zero. To increase and decrease it, use// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'require(
(value ==0) || (token.allowance(address(this), spender) ==0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal{
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal{
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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.
*/functionforceApprove(IERC20 token, address spender, uint256 value) internal{
bytesmemory approvalCall =abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/functionsafePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal{
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore +1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/function_callOptionalReturn(IERC20 token, bytesmemory data) private{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that// the target address contains contract code and also asserts for success in the low-level call.bytesmemory returndata =address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length==0||abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/function_callOptionalReturnBool(IERC20 token, bytesmemory data) privatereturns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false// and not revert is the subcall reverts.
(bool success, bytesmemory returndata) =address(token).call(data);
return
success && (returndata.length==0||abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
Contract Source Code
File 34 of 36: Structs.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.19;structAssetInfo {
uint72 targetConcentration;
address uniswapPool;
int72 incentiveFactor;
uint8 assetDecimals;
uint8 quoteTokenDecimals;
address uniswapQuoteToken;
bool isSupported;
}
structProtocolData {
///@notice Protocol AUM in USDuint256 aum;
///@notice multiplicator for the tax equation, 100% = 100e18uint72 taxFactor;
///@notice Max deviation allowed between AUM from keeper and registryuint16 maxAumDeviationAllowed; // Default val 200 == 2 %///@notice block number where AUM was last updateduint48 lastAUMUpdateBlock;
///@notice annual fee on AUM, in % per year 100% = 100e18uint72 managementFee;
///@notice last block.timestamp when fee was collecteduint48 lastFeeCollectionTime;
}
structUserRequest {
address asset;
uint256 amount;
}
structRequestData {
uint32 id;
address requestor;
address[] assetIn;
uint256[] amountIn;
address[] assetOut;
uint256[] amountOut;
bool keepGovRights;
uint256 slippageChecker;
}
structRequestQ {
uint64 start;
uint64 end;
mapping(uint64=> RequestData) requestData;
}
structProcessParam {
uint256 targetConc;
uint256 currentConc;
uint256 usdValue;
uint256 taxableAmount;
uint256 taxInUSD;
uint256 sharesBeforeTax;
uint256 sharesAfterTax;
}
structRebalanceParam {
address asset;
uint256 assetTotalAmount;
uint256 assetProxyAmount;
uint256 assetPrice;
uint256 sTrsyTotalSupply;
uint256 trsyPrice;
}
Contract Source Code
File 35 of 36: TRSY.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.19;import {ERC20} from"solmate/tokens/ERC20.sol";
///@title TRSY contract///@notice Handle the logic for minting and burning TRSY sharesabstractcontractTRSYisERC20{
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/constructor() ERC20("TRSY", "TRSY", 18) {}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*////@notice Convert the value of deposit into share of the protocol///@param _usdValue usd value of the deposit///@param _usdAUM AUM of the protocol in USD (given by keeper)///@return TSRY share for an USD depositfunction_convertToShares(uint256 _usdValue, uint256 _usdAUM) internalviewreturns (uint256) {
uint256 supply = totalSupply;
return supply ==0 ? _usdValue : (_usdValue * supply) / _usdAUM;
}
}
Contract Source Code
File 36 of 36: Tax.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.19;import {ProcessParam} from"./Structs.sol";
import {MathUtil} from"../utils/MathUtil.sol";
import"synthetix-v3/utils/core-contracts/contracts/utils/SafeCast.sol";
///@title Tax contract///@notice Handle tax logic, for either a deposit or withdraw compute if the action is unabalacing/// the protocol/// if this is the case, the protocol will compute a tax applied on deposit or withdraw by/// reducing the number of shares to mint/// or by increasing the number of shares to burn. This tax is then minted to fyde contract./// The main logic is that for each action, we compute a taxable amount which is the amount that/// unbalance the protocol for a given deposit or withdraw,/// then we apply the tax on this taxable amount./// For the swap the logic is the same, we compute the tax and incentive for assetIn and that give/// the value of assetOut,/// for this value we compute the tax and incentive for assetOut./// SwapRate can be greater for assetOut in case there is no tax and some incentives, the same if no/// tax no incentive, or lower if there is tax and no incentive.abstractcontractTax{
usingSafeCastU256foruint256;
usingSafeCastI256forint256;
/*//////////////////////////////////////////////////////////////
MAIN
//////////////////////////////////////////////////////////////*/function_getDepositTax(
ProcessParam memory processParam,
uint256 protocolAUM,
uint256 totalUsdDeposit,
uint256 taxFactor
) internalpurereturns (ProcessParam memory) {
if (processParam.targetConc ==0) {
processParam.taxInUSD = processParam.usdValue;
return processParam;
}
if (taxFactor ==0) return processParam;
processParam = _computeDepositTaxableAmount(processParam, protocolAUM, totalUsdDeposit);
if (processParam.taxableAmount ==0) return processParam;
processParam = _computeDepositTaxInUSD(processParam, protocolAUM, totalUsdDeposit, taxFactor);
return processParam;
}
function_getWithdrawTax(
ProcessParam memory processParam,
uint256 protocolAUM,
uint256 totalUsdWithdraw,
uint256 taxFactor
) internalpurereturns (ProcessParam memory) {
if (taxFactor ==0) return processParam;
processParam = _computeWithdrawTaxableAmount(processParam, protocolAUM, totalUsdWithdraw);
if (processParam.taxableAmount ==0) return processParam;
processParam = _computeWithdrawTaxInUSD(processParam, protocolAUM, totalUsdWithdraw, taxFactor);
return processParam;
}
function_getSwapRate(
ProcessParam memory processParamIn,
ProcessParam memory processParamOut,
uint256 protocolAUM,
uint256 taxFactor,
int256 incentiveFactorIn,
int256 incentiveFactorOut
) internalpurereturns (uint256) {
// Compute tax on deposit
processParamIn = _getDepositTax(processParamIn, protocolAUM, 0, taxFactor);
int256 valIn = incentiveFactorIn
*int256(processParamIn.usdValue - processParamIn.taxableAmount) /int256(1e20);
// usdValue adjusted with potential tax and incentiveuint256 withdrawValOut = valIn >=0
? processParamIn.usdValue - processParamIn.taxInUSD + valIn.toUint()
: processParamIn.usdValue - processParamIn.taxInUSD - (-1* valIn).toUint();
processParamOut.usdValue = withdrawValOut;
processParamOut = _getWithdrawTax(processParamOut, protocolAUM, 0, taxFactor);
// usdValueOut adjusted with potential tax and incentiveint256 valOut =
incentiveFactorOut *int256(withdrawValOut - processParamOut.taxableAmount) /1e20;
uint256 usdValOut = valOut >=0
? withdrawValOut - processParamOut.taxInUSD + valOut.toUint()
: withdrawValOut - processParamOut.taxInUSD - (-1* valOut).toUint();
return usdValOut;
}
/*//////////////////////////////////////////////////////////////
DEPOSIT
//////////////////////////////////////////////////////////////*/function_computeDepositTaxableAmount(
ProcessParam memory processParam,
uint256 protocolAUM,
uint256 totalUsdDeposit
) internalpurereturns (ProcessParam memory) {
int256 deltaConc = protocolAUM.toInt()
* (processParam.currentConc.toInt() - processParam.targetConc.toInt()) /1e20;
int256 targetDeposit = totalUsdDeposit !=0
? processParam.targetConc.toInt() * totalUsdDeposit.toInt() /1e20
: int256(0);
int256 tax = processParam.usdValue.toInt() + deltaConc - targetDeposit;
processParam.taxableAmount =
MathUtil.min(processParam.usdValue.toInt(), MathUtil.max(tax, int256(0))).toUint();
return processParam;
}
function_computeDepositTaxInUSD(
ProcessParam memory processParam,
uint256 protocolAUM,
uint256 totalUsdDeposit,
uint256 taxFactor
) internalpurereturns (ProcessParam memory) {
uint256 numerator = (protocolAUM * processParam.currentConc /1e20) + processParam.usdValue;
uint256 denominator = (protocolAUM + totalUsdDeposit) * processParam.targetConc /1e20;
uint256 eq = (1e18* numerator / denominator) -1e18;
uint256 tmpRes = MathUtil.min(eq, 1e18);
uint256 taxPerc = taxFactor * tmpRes /1e20; // 1e20 for applying expressing tax as a percentage
processParam.taxInUSD = processParam.taxableAmount * taxPerc /1e18;
return processParam;
}
/*//////////////////////////////////////////////////////////////
WITHDRAW
//////////////////////////////////////////////////////////////*/function_computeWithdrawTaxableAmount(
ProcessParam memory processParam,
uint256 protocolAUM,
uint256 totalUsdWithdraw
) internalpurereturns (ProcessParam memory) {
int256 deltaConc = protocolAUM.toInt()
* (processParam.currentConc.toInt() - processParam.targetConc.toInt()) /1e20;
int256 targetDeposit = processParam.targetConc.toInt() * totalUsdWithdraw.toInt() /1e20;
int256 tax = processParam.usdValue.toInt() - deltaConc - targetDeposit;
processParam.taxableAmount =
MathUtil.min(processParam.usdValue.toInt(), MathUtil.max(tax, int256(0))).toUint();
return processParam;
}
function_computeWithdrawTaxInUSD(
ProcessParam memory processParam,
uint256 protocolAUM,
uint256 totalUsdWithdraw,
uint256 taxFactor
) internalpurereturns (ProcessParam memory) {
int256 numerator =
protocolAUM.toInt() * processParam.currentConc.toInt() /1e20- processParam.usdValue.toInt();
int256 denominator =
processParam.targetConc.toInt() * (protocolAUM.toInt() - totalUsdWithdraw.toInt()) /1e20;
int256 tmpRes =1e18- (1e18* numerator / denominator);
uint256 tmpRes2 = MathUtil.min(tmpRes.toUint(), 1e18);
uint256 taxPerc = taxFactor * tmpRes2 /1e20; // 1e20 for applying expressing tax as a// percentage
processParam.taxInUSD = processParam.taxableAmount * taxPerc /1e18;
return processParam;
}
}