Trading
Main Flow
The Vault Manager decides to trade the assets within the vault.
To do so, they might claim additional rewards, pull tokens from the vault, or execute various swap operations to adjust the asset allocations.
Depending on the needs, the Vault Manager can swap tokens to other tokens.
Off-chain swaps can also be executed if necessary.
After all trading operations, any leftover funds are returned to the user to ensure that there's no loss of funds.
Functions
Swapping ETH (or BNB) to Token:
The _swapETHToToken function is used to swap ETH (or BNB) for a specific token.
The swapETHToToken function allows an external entity (like the vault manager) to swap ETH (or BNB) for a token.
Swapping Token to ETH (or BNB):
The _swapTokenToETH function is used internally to swap a specific token for ETH (or BNB).
Swapping Token to Token:
The _swapTokenToToken function is used to swap one token for another.
The _swapTokenToTokenInvest function swaps one token for another while investing.
The _swapTokenToTokenWithdraw function swaps one token for another while withdrawing.
Calculating Swap Amount:
The getSwapAmount function calculates the swap amount based on total supply, token amount, amount from IndexSwapLibrary, and the weight (denorm) of the token.
Swapping Token to Tokens:
The _swapTokenToTokens function allows for swapping a token into multiple tokens. This is particularly useful for distributing an investment across multiple assets in a vault.
Swaps via aggregators:
The contract also facilitates off-chain swaps using the 0x, 1inch and Paraswap protocols. The _swapTokenToTokensOffChain and _swapOffChainTokens functions are used for this purpose.
Refunds:
After any swap operation, any leftover funds are returned to the user using the returnUninvestedFunds function.
Throughout the process, there are various checks and guards in place, including reentrancy guards, access controls, and validations, to ensure that the operations are secure and only authorized entities can trigger certain functionalities.