Token Factory
TokenFactory
Inherits: ReentrancyGuardUpgradeable, OwnableUpgradeable, UUPSUpgradeable, BaseContract
The main purposes of this contract is to act as a vault as well as it contains the shared logic used by riskON/OFF tokens.
Acts as the vault for holding the underlying assets/tokens. Also contains shared logic used by riskON/OFF
State Variables
rebalanceElements
dailyFeeFactors
userRebalanceElements
REBALANCE_INT_MULTIPLIER
smartTokenArray
lastRebalanceCount
This mapping keeps track of the last rebalance applied to a user/address
lastdailyFFcount
baseToken
This is the instance of the underlying Token
baseTokenDecimals
The number of decimals of the underlying Asset/Token
interval
The rebalance interval in seconds
lastTimeStamp
The timestamp of the last rebalance
smartTokenInitialized
This boolean keeps track if the smart tokens(RiskON/OFF) have already been initialized in the system
signers
This is the signers address of RP api's that generate encoded params for rebalance
FFinterval
This is used by the feefactors method to calculate the fees
FFLastTimeStamp
sequenceNumberApplied
This keeps track of the 'sequenceNumber' of a rebalance which helps
managementFeesRate
managementFeesRateRebalance
managementFeeEnabled
lastRebalanceFees
treasuryWallet
orchestrator
isNativeToken
premiumPercentage
premiumCharged
scheduledRebalances
A mapping to hold the scheduled rebalances. This helps in storing rebalances in the order they are scheduled till they are all executed
scheduledRebalancesLength
nextSequenceNumber
A counter to generate a unique sequence number for each rebalance. This ensures that rebalances are executed in the order they are scheduled.
period
withdrawLimit
depositLimit
hasWithdrawLimit
hasDepositLimit
currentWithdrawPeriodEnd
currentWithdrawPeriodAmount
currentDepositPeriodEnd
currentDepositPeriodAmount
Functions
onlySmartTokens
Ensures the caller is one of the SmartTokens(RiskOn/Off).
This modifier checks if the caller is either smartTokenArray[0] or smartTokenArray[1]. If not, it reverts with a custom error message.
onlyOrchestrator
onlyIntializedOnce
constructor
initialize
Initializes(replacement for the constructor) the Vault (TokenFactory) contract with specified params
This function sets up the initial state of the TokenFactory contract. Callable only once.
Parameters
baseTokenAddress
IERC20Update
The address of the underlying token/asset
rebalanceInterval
uint256
The interval (in seconds) at which natural rebalances are scheduled.
ffInterval
uint256
sanctionsContract_
address
The address of the sanctions contract(chainalysis contract) to verify blacklisted addresses
signersAddress_
address
The address of the signer ( RP Api's) which signed the rebalance data
owner_
address
withdrawLimit_
uint256
depositLimit_
uint256
limitPeriod_
uint256
isNativeToken_
bool
_authorizeUpgrade
Authorizes an upgrade to a new contract implementation.
This function can only be called by the contract owner. It overrides the _authorizeUpgrade
function from the UUPSUpgradeable
contract to include the onlyOwner
modifier, ensuring only the owner can authorize upgrades.
initializeSMART
Initializes the smart tokens associated with this TokenFactory. renaming this method to avoid conflicts with upgradable initialize
This function can only be called once, and only by the contract owner.
Parameters
token1
SmartToken
The first smart token
token2
SmartToken
The second smart token
initializeOrchestrator
_tryGetAssetDecimals
Attempts to fetch the decimals of underlying token
This function uses a static call to query the decimals from the asset. If the call fails or the returned data is invalid, it defaults to 0.
Parameters
asset_
IERC20
The address of the underlying token
Returns
<none>
bool
A return vaule containing a boolean indicating success and the decimals of the token. or false if it failed somehow
<none>
uint8
decimals
Fetches the decimal value of the underlying token
This function returns the value of decimals that was set in the 'initialize' method
Returns
<none>
uint8
The number of decimals of the underlying token
getBaseToken
Retrieves the instance of the underlying token contract
This function provides a way to access the instance of the underlying contract
Returns
<none>
IERC20Update
The instance of the underlying contract
maxAmountToWithdraw
Returns the maximum amount of assets the owner can withdraw.
This function compares the balance of both smart tokens(RiskON/OFF) for the owner and returns the balance of the smart token with the lesser amount.
Parameters
owner_
address
The address of the owner
Returns
<none>
uint256
The maximum amount of assets the specified owner can withdraw.
maxSharesOwned
Determines the maximum amount of shares owned by the owner
This function compares the balance of both smart tokens(RiskON/OFF) for the owner and returns the balance of the smart token with the greater amount.
Parameters
owner_
address
The address of the owner
Returns
<none>
uint256
The maximum amount of shares owned by the specified owner.
_deposit
Deposit/mint common workflow, deposit underlying tokens, mints new shares(RiskON/OFF) to the receiver, and also charges management fees
Deposit/mint common workflow.
This function can only be called by the smart tokens and requires the caller and receiver to not be sanctioned.
Parameters
caller
address
The address of depositor
receiver
address
The address of receiver
assets
uint256
The amount of underlying tokens being deposited.
shares
uint256
The amount of shares(RiskON/OFF) to mint to the receiver.
_withdraw
Withdraw/redeem common workflow. Handles the withdrawal of underlying token. burns shares(RiskON/OFF) from the caller, and refund any management fees
This function can only be called by the smart tokens and requires the caller and receiver to not be sanctioned.
Parameters
caller
address
The address withdrawing.
receiver
address
The address receiving the underlying token.
owner
address
The owner of the shares.
assets
uint256
The amount of underlying Token being withdrawn.
shares
uint256
The amount of shares(RiskON/OFF) to burn from the caller.
getUserRecords
transferRecords
updateRecord
updateRecord
factoryMint
Mints the specified amount of Shares(RiskON/OFF) to the receiver
It first previews the minting process to get the amount of Shares(RiskON/OFF)that will be minted, and then performs the actual minting.
Parameters
smartTokenIndex
uint256
The index of the smart token in the smartTokenArray.
receiver
address
The address of the receiver
amount
uint256
The amount of Shares(RiskON/OFF) to mint.
factoryBurn
Burns the specified amount of Shares(either of RiskON/OFF)from the owner
It calls the burn
function on the smart token contract
Parameters
smartTokenIndex
uint256
The index of the smart token in the smartTokenArray
.
owner_
address
The address of the owner
amount
uint256
The amount of Shares(either of RiskON/OFF) to burn.
factoryTreasuryTransfer
factoryBalanceAdjust
executeRebalance
Executes a rebalance based on the provided encoded data and signature.
This function validates the rebalance call, schedules it, and possibly triggers a rebalance if the sequence is in order. It first verifies the signature of the rebalance params with the signer's public key. Then we verify if the sequence number is aligned and not already used. Then we push the rebalance params into an array of scheduled rebalances. Finally, if there is no gaps between the previous rebalance'sequence number, we execute this rebalance This function can only be called when rebalance is not stopped with the stopRebalance
modifier.
Parameters
encodedData
bytes
The encoded data containing the sequence number, the boolean value for natural rebalance and the price of underlying and smartTokenX
signature
bytes
The signature of the encoded data to verify its authenticity.
executeScheduledRebalances
Executes scheduled rebalances pending in the queue
This function is called when the scheduled rebalance queue had more than 5 entries only 5 will be executed and the rest will be left in the queue
chargeFees
Charges the management fees
This function is responsible for charging the fees of the whole universe and related functionalities. We charge the fees on a daily Basis/ each FFinterval
rebalance
Handles the actual rebalancing mechanism.
This function processes up to 5 scheduled rebalances per call. Different factors that will help calculating user balances are calculated here using the rebalance params.
updateFeeFactor
dailyFeeFactorsUpdate
applyFF
should apply this to users before any interaction with the contracts
updateUserLastFFCount
FFCheck
applyRebalance
Applies rebalance to an account
This function adjusts the balance of smart tokens(RiskON/RiskOFF) according to the rollOverValue. This function can only be called when rebalance is stopped. It also calculates and applies management fees.
Parameters
owner_
address
The address of the account to which the rebalance will be applied.
underlyingTransfer
underlyingReturn
calculateRollOverValue
Calculates the rollover value(Units of RiskON/OFF) for an account
This function calculates the net balance(Units of RiskON/OFF) of a user after rebalance and management fees are applied.
Parameters
owner_
address
The address of the owner
Returns
<none>
uint256
The calculated roll over value.
<none>
uint256
updateUserLastRebalanceCount
Updates the last rebalance count of a user.
This function sets the last rebalance count for a user if their unscaled balances for both smart tokens(RiskON/RiskOFF) are zero. We may use this in cases where a receiever is new to the system
Parameters
owner_
address
The address of the user
verifyAndDecode
Verifies the provided signature and decodes the encoded data into ScheduledRebalance
struct.
It recovers the address from the Ethereum signed message hash and the provided signature
. If the recovered address doesn't match the signersAddress
, it reverts the transaction. If the signature is valid, it decodes the encodedData
into a ScheduledRebalance
struct and returns it.
Parameters
signature
bytes
The signature to be verified.
encodedData
bytes
The data to be decoded into a ScheduledRebalance
struct.
Returns
<none>
Shared.ScheduledRebalance
data A ScheduledRebalance
struct containing the decoded data.
setSignersAddress
Update the address authorized to sign rebalance transactions.
This function can only be called by the owner of the contract. It updates the signersAddress
address with the provided addr
address.
Parameters
addr
address
The new address
removeSigner
setManagementFeeRate
Updates the rate of management fees.
It updates the managementFeesRate
state variable with the provided rate
value, if the rate is within a valid range, otherwise, it reverts the transaction. The rate is in terms of percentage per day scaling factor is 10E18 Example 5% per day = 0.0510E18*
Parameters
rate
uint256
The new rate of management fees. It is DAILY RATE
rateRebalance
uint256
The new rate of management fees for rebalance.(REBALANCE RATE)
Returns
<none>
bool
A boolean value
setManagementFeeState
Toggles the state of management fee collection.
This function can only be called by the contract owner. It either enables or disables the management fee collection
Parameters
state
bool
The new state of management fee collection.
Returns
<none>
bool
A boolean value
setTreasuryWallet
calculateManagementFee
Calculates the management fee for a given amount over a particular time span.
It computes the management fee either using the default management fee rate or a provided fee rate. This function can be used both for deposit and withdrawal scenarios.
Parameters
amount
uint256
The amount of RiskON/OFF to calculate the fee against.
mgmtFee
uint256
The management fee rate to use if isDefault
is set to false.
Returns
<none>
uint256
userFees The calculated management fee
rebalanceCheck
Checks if a user is an existing user and applies user rebalance when needed.
This function is triggered to ensure a user's balances are updated with any rebalances that have occurred since their last interaction with the contract.
Parameters
user
address
The address of the user
removeRebalance
Removes a rebalance entry from the scheduledRebalances
mapping at the given sequence number.
It deletes the entry at the given sequence number and decrements the scheduledRebalancesLength
variable. It is also guarded by 'nonReentrant' modifier.
Parameters
sequenceNumber
uint256
The sequenceNumber of the scheduledRebalances
mapping to remove.
isValidSigner
Verifies if a signer is valid
Verifies if a signer is valid
Parameters
addr
address
The address of the signer
Returns
<none>
bool
true if signer is valid
withdrawLimitMod
ratelimits
depositLimitMod
updatePeriod
updateWithdrawLimit
updateDepositLimit
updateLimitPeriod
toggleWithdrawLimit
toggleDepositLimit
setPremiumPercentage
drainFlashloanPremiums
getScheduledRebalances
Retrieves the scheduledRebalance
struct at the given sequence number.
This function is a getter for a single scheduledRebalance
struct.
Parameters
sequenceNumber
uint256
The sequence number of the scheduledRebalances
mapping to retrieve.
Returns
<none>
Shared.ScheduledRebalance
The scheduledRebalance
struct at the given sequence number.
getNextSequenceNumber
Retrieves the nextSequenceNumber
This function is a getter for the nextSequenceNumber
variable.
Returns
<none>
uint256
The anextSequenceNumber
getLastTimeStamp
Retrieves the lastTimeStamp
This function is a getter for the lastTimeStamp
variable.
Returns
<none>
uint256
The lastTimeStamp
getManagementFeeRate
getManagementFeeState
Retrieves the managementFeeEnabled
This function is a getter for the managementFeeEnabled
variable.
Returns
<none>
bool
The managementFeeEnabled
getRebalanceNumber
getUserLastRebalanceCount
getSmartTokenAddress
Retrieves the interval
This function is a getter for the interval
variable.
Parameters
index
uint8
The index of the SmartToken in the smartTokenArray
.
Returns
<none>
SmartToken
The interval
getTreasuryAddress
getInterval
Retrieves the interval
This function is a getter for the interval
variable.
Returns
<none>
uint256
The interval
insufficientUnderlying
Validates if the amount of underlying locked in the token factory is
This function is used the smartoken modifer
Returns
<none>
bool
true if underlying is less
withdrawLimitStatus
depositLimitStatus
getWithdrawLimit
getDepositLimit
getLimitPeriod
getUserLimitPerPeriod
getLastFFTimeStamp
Getters for the new fees mechanisms
getDailyFeeFactorNumber
getUserLastFFCount
getIsNativeToken
getFlashloanPremium
getAccumulatedFlashLoanPremium
Events
RebalanceApplied
Rebalance
Deposit
Withdraw
PremiumDrained
WithdrawLimitToggled
DepositLimitToggled
Errors
TokenFactory__MethodNotAllowed
TokenFactory__InvalidDivision
TokenFactory__InvalidRebalanceParams
TokenFactory__InvalidSequenceNumber
TokenFactory__InvalidNaturalRebalance
TokenFactory__AlreadyInitialized
TokenFactory__InvalidSignature
TokenFactory__InvalidSignatureLength
TokenFactory__InvalidManagementFees
TokenFactory__SmartTokenArrayOutOfBounds
TokenFactory__NoPremiumsToDrain
Structs
RebalanceElements
UserRebalanceElements
Last updated