Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Review #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
334 changes: 162 additions & 172 deletions Blockchain/Blockchian/contracts/Core_logic/CDS.sol

Large diffs are not rendered by default.

153 changes: 100 additions & 53 deletions Blockchain/Blockchian/contracts/Core_logic/GlobalVariables.sol

Large diffs are not rendered by default.

216 changes: 190 additions & 26 deletions Blockchain/Blockchian/contracts/Core_logic/Treasury.sol
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ contract Treasury is
uint256 public totalVolumeOfBorrowersAmountinUSD; // Total collateral deposited in USD
uint128 public noOfBorrowers; // No of borrowers in this chain
uint256 private totalInterest; // total interest gained from lending
uint256 private totalInterestFromLiquidation;
// uint256 private totalInterestFromLiquidation;
uint256 public abondUSDaPool; // usda abond pool value
uint256 private interestFromExternalProtocolDuringLiquidation; // interest from ext protocol till liquidation
uint128 private PRECISION;
Expand All @@ -60,13 +60,16 @@ contract Treasury is
uint256 private liquidatedCollateralCollectedFromCdsWithdraw;
IGlobalVariables private globalVariables; // Global variables instance
uint256 private yieldsFromLrts; // Yields from LRTs during withdraw
uint256 private yieldsFromLiquidatedLrts; // Yields from LRTs which are liquidated
mapping(IBorrowing.AssetName => uint256 yields) private yieldsFromLiquidatedLrts;// Yields from LRTs which are liquidated
mapping(IBorrowing.AssetName => uint256 collateralAmountDeposited) public depositedCollateralAmountInWei; // Collaterals deposited in this chain
mapping(IBorrowing.AssetName => uint256 collateralAmountDepositedInUsd) private depositedCollateralAmountInUsd; // Collaterals deposited in this chain in usd
uint256 public totalVolumeOfBorrowersAmountLiquidatedInWei; // Total collateral liquidated in ETH value
mapping(IBorrowing.AssetName => uint256 collateralAmountLiquidated) public liquidatedCollateralAmountInWei; // Collaterals deposited in this chain
address odosRouterV2;
IonicInterface ionic;
uint256 private abondLiqGainsStuck;
address private usdcAddressMode;
mapping(IBorrowing.AssetName => uint256 amount) public redeemableAssets;

/**
* @dev initialize function to initialize the contract
Expand All @@ -85,6 +88,7 @@ contract Treasury is
address cdsContractAddress,
address borrowLiquidationAddress,
address usdtAddress,
address usdcAddress,
address globalVariablesAddress
) public initializer {
address[7] memory addresses = [
Expand All @@ -110,6 +114,7 @@ contract Treasury is
usda = IUSDa(usdaAddress);
abond = IABONDToken(abondAddress);
usdt = IERC20(usdtAddress);
usdcAddressMode = usdcAddress;
globalVariables = IGlobalVariables(globalVariablesAddress);
borrowLiquidation = borrowLiquidationAddress;
PRECISION = 1e18;
Expand Down Expand Up @@ -156,7 +161,8 @@ contract Treasury is
uint128 ethPrice,
uint64 depositTime,
IBorrowing.AssetName assetName,
uint256 depositingAmount
uint256 depositingAmount,
uint256 depositAmount
) external payable onlyCoreContracts returns (DepositResult memory) {
uint64 borrowerIndex;
//check if borrower is depositing for the first time or not
Expand All @@ -178,7 +184,7 @@ contract Treasury is
// update deposited amount of the user
borrowing[user].depositDetails[borrowerIndex].depositedAmountInETH = uint128(depositingAmount);

depositedCollateralAmountInWei[assetName] += depositingAmount;
depositedCollateralAmountInWei[assetName] += depositAmount;

depositedCollateralAmountInUsd[assetName] += (ethPrice * depositingAmount);

Expand Down Expand Up @@ -240,7 +246,7 @@ contract Treasury is

// Update the collateral data
depositedCollateralAmountInUsd[depositDetails.assetName] -= depositDetails.depositedAmountUsdValue;
depositedCollateralAmountInWei[depositDetails.assetName] -= depositDetails.depositedAmountInETH;
depositedCollateralAmountInWei[depositDetails.assetName] -= depositDetails.depositedAmount;
// Updating total volumes
totalVolumeOfBorrowersAmountinUSD -= depositDetails.depositedAmountUsdValue;
totalVolumeOfBorrowersAmountinWei -= depositDetails.depositedAmountInETH;
Expand Down Expand Up @@ -268,6 +274,8 @@ contract Treasury is
// if user has no deposited collaterals then decrement number of borrowers
if (borrowing[borrower].depositedAmountInETH == 0) {
--noOfBorrowers;
borrowing[borrower].hasDeposited = false;
borrowing[borrower].hasBorrowed = false;
}
borrowing[borrower].depositDetails[index] = depositDetails;
// emit withdraw event
Expand All @@ -283,7 +291,7 @@ contract Treasury is
function withdrawFromExternalProtocol(
address user,
uint128 aBondAmount
) external onlyCoreContracts returns (uint256) {
) external onlyCoreContracts nonReentrant returns (uint256) {
if (user == address(0)) revert Treasury_ZeroAddress();

// Withdraw from external protocols
Expand All @@ -303,7 +311,7 @@ contract Treasury is
function withdrawFromExternalProtocolDuringLiq(
address user,
uint64 index
) external onlyCoreContracts returns (uint256) {
) external onlyCoreContracts nonReentrant returns (uint256) {
// Calculate the current cumulative rate

uint256 balanceBeforeWithdraw = address(this).balance;
Expand Down Expand Up @@ -387,15 +395,15 @@ contract Treasury is
totalInterest += amount;
}

/**
* @dev update the total interest gained from liquidation for the protocol
* @param amount interest amount
*/
function updateTotalInterestFromLiquidation(
uint256 amount
) external onlyCoreContracts {
totalInterestFromLiquidation += amount;
}
// /**
// * @dev update the total interest gained from liquidation for the protocol
// * @param amount interest amount
// */
// function updateTotalInterestFromLiquidation(
// uint256 amount
// ) external onlyCoreContracts {
// totalInterestFromLiquidation += amount;
// }

/**
* @dev update abond usda pool
Expand Down Expand Up @@ -430,6 +438,17 @@ contract Treasury is
}
}

function updateAbondLiqGainsStuck(
uint256 amount,
bool operation
) external onlyCoreContracts {
if (operation) {
abondLiqGainsStuck += amount;
} else {
abondLiqGainsStuck -= amount;
}
}

/**
* @dev updates totalVolumeOfBorrowersAmountinWei and totalVolumeOfBorrowersAmountLiquidatedInWei
* @param amount collateral amount in eth value
Expand Down Expand Up @@ -458,10 +477,15 @@ contract Treasury is
*/
function updateDepositedCollateralAmountInWei(
IBorrowing.AssetName asset,
uint256 amount
uint256 amount,
bool operation
) external onlyCoreContracts {
depositedCollateralAmountInWei[asset] -= amount;
liquidatedCollateralAmountInWei[asset] += amount;
if(operation){
depositedCollateralAmountInWei[asset] -= amount;
liquidatedCollateralAmountInWei[asset] += amount;
} else {
liquidatedCollateralAmountInWei[asset] -= amount;
}
}

/**
Expand Down Expand Up @@ -511,9 +535,19 @@ contract Treasury is
* @param yields yields accured from liquidated till cds withdraw
*/
function updateYieldsFromLiquidatedLrts(
uint256 yields
uint256 yields,
IBorrowing.AssetName asset
) external onlyCoreContracts {
yieldsFromLiquidatedLrts += yields;
if(asset != IBorrowing.AssetName.WeETH && asset != IBorrowing.AssetName.WrsETH) revert Treasury_InvalidAsset(asset);
yieldsFromLiquidatedLrts[asset] += yields;
}

function updateRedeemableAssets(uint256 amount, IBorrowing.AssetName asset, bool operation) external onlyCoreContracts {
if(operation) {
redeemableAssets[asset] += amount;
} else {
redeemableAssets[asset] -= amount;
}
}

// GETTERS FUNCTIONS
Expand Down Expand Up @@ -618,12 +652,79 @@ contract Treasury is
uint256 amount
) external onlyOwner {
require(toAddress != address(0) && amount != 0,"Input address or amount is invalid");
require(amount <= (totalInterest + totalInterestFromLiquidation),"Treasury don't have enough interest");
require(amount <= totalInterest,"Treasury don't have enough interest");
// if (amount <= totalInterest) {
totalInterest -= amount;
// } else {
// uint256 remaining = amount - totalInterest;
// totalInterest = 0;
// totalInterestFromLiquidation -= remaining;
// }
bool sent = usda.transfer(toAddress, amount);
require(sent, "Failed to send Ether");
}

/**
* @dev This function withdraw interest.
* @param toAddress The address to whom to transfer.
* @param amount The amount to withdraw.
*/

function withdrawYieldsFromLiquidatedLrts(
address toAddress,
uint256 amount,
IBorrowing.AssetName asset
) external onlyOwner {
require(toAddress != address(0) && amount != 0,"Input address or amount is invalid");
require(amount <= yieldsFromLiquidatedLrts[asset],"Treasury don't have enough yields");

if(asset != IBorrowing.AssetName.WeETH && asset != IBorrowing.AssetName.WrsETH) revert Treasury_InvalidAsset(asset);

yieldsFromLiquidatedLrts[asset] -= amount;

bool sent = IERC20(borrow.assetAddress(asset)).transfer(toAddress, amount);
require(sent, "Failed to send asset");
}

/**
* @dev This function withdraw usda from cds withdraw.
* @param toAddress The address to whom to transfer.
* @param amount The amount to withdraw.
*/

function withdrawUSDaCollected(
address toAddress,
uint256 amount
) external onlyOwner {
require(toAddress != address(0) && amount != 0,"Input address or amount is invalid");
require(amount <= (usdaCollectedFromCdsWithdraw + abondLiqGainsStuck),"Treasury don't have enough usda to withdraw");

if (amount <= usdaCollectedFromCdsWithdraw) {
usdaCollectedFromCdsWithdraw -= amount;
} else {
uint256 remaining = amount - usdaCollectedFromCdsWithdraw;
usdaCollectedFromCdsWithdraw = 0;
abondLiqGainsStuck -= remaining;
}

bool sent = usda.transfer(toAddress, amount);
require(sent, "Failed to send USDa");
}

function withdrawIntFromExtProtocolDuringLiquidation(
address toAddress,
uint256 amount
) external onlyOwner {
require(toAddress != address(0) && amount != 0,"Input address or amount is invalid");
require(amount <= interestFromExternalProtocolDuringLiquidation,"Treasury don't have enough interest from ext protocol");

interestFromExternalProtocolDuringLiquidation -= amount;

// Transfer ETH to user
(bool sent, ) = payable(toAddress).call{value: amount}("");
if (!sent) revert Treasury_TransferFailed();
}

/**
* @dev transfer eth from treasury
* @param user address of the recepient
Expand All @@ -638,8 +739,6 @@ contract Treasury is
IGlobalVariables.OmniChainData memory omniChainData = globalVariables.getOmniChainData();
// Check whether treasury has enough collateral to transfer
require(amount <= omniChainData.collateralProfitsOfLiquidators,"Treasury don't have enough ETH amount");
omniChainData.collateralProfitsOfLiquidators -= amount;
globalVariables.setOmniChainData(omniChainData);

// Transfer ETH to user
(bool sent, ) = payable(user).call{value: amount}("");
Expand Down Expand Up @@ -703,7 +802,7 @@ contract Treasury is
function withdrawFromIonicByUser(
address user,
uint128 aBondAmount
) internal nonReentrant returns (uint256) {
) internal returns (uint256) {
uint256 currentExchangeRate = ionic.exchangeRateCurrent();
uint256 currentCumulativeRate = _calculateCumulativeRate(currentExchangeRate, Protocol.Ionic);

Expand All @@ -726,7 +825,7 @@ contract Treasury is
function withdrawFromIonicDuringLiq(
address user,
uint64 index
) internal nonReentrant returns (uint256) {
) internal returns (uint256) {
uint256 currentExchangeRate = ionic.exchangeRateCurrent();
uint256 currentCumulativeRate = _calculateCumulativeRate(currentExchangeRate,Protocol.Ionic);

Expand Down Expand Up @@ -795,6 +894,71 @@ contract Treasury is
}
}

function swapRemainingAmounts(
bytes memory odosAssembledData,
uint256 amount,
IBorrowing.AssetName asset
) external onlyCoreContracts {
if(amount > 0) {
if(asset != IBorrowing.AssetName.ETH) {
bool approved = IERC20(borrow.assetAddress(asset)).approve(odosRouterV2, amount);
// check whether the approve is successfull or not
if (!approved) revert Treasury_ApproveFailed();
}

// paas the odos assembled data as msg.data to routerV2 contract of odos
// if the asset is native, pass as msg.value
(bool success, bytes memory result) = odosRouterV2.call(odosAssembledData);
// check the swap is successfull or not.
if (!success) revert Treasury_SwapFailed();
abi.decode(result, (uint256));

redeemableAssets[IBorrowing.AssetName.USDC] += abi.decode(result, (uint256));
}
}

function swapAndTransferCollateralToBorrowLiq(
bytes memory odosAssembledData,
uint256 amount,
IBorrowing.AssetName asset
) external onlyCoreContracts returns(uint256) {
if(amount <= 0) revert ("Invalid Swap amount");

if(asset == IBorrowing.AssetName.ETH && block.chainid == 10) {
// Transfer ETH to global variable contract
(bool sent, ) = payable(borrowLiquidation).call{value: amount}("");
require(sent, "Failed to send Ether");

return amount;
} else {
if(asset != IBorrowing.AssetName.ETH) {
bool approved = IERC20(borrow.assetAddress(asset)).approve(odosRouterV2, amount);
// check whether the approve is successfull or not
if (!approved) revert Treasury_ApproveFailed();
}

// paas the odos assembled data as msg.data to routerV2 contract of odos
// if the asset is native, pass as msg.value
(bool success, bytes memory result) = odosRouterV2.call(odosAssembledData);
// check the swap is successfull or not.
if (!success) revert Treasury_SwapFailed();

IERC20 receivedToken;

if(block.chainid == 34443) {
receivedToken = IERC20(usdcAddressMode);
} else if (block.chainid == 10) {
receivedToken = IERC20(address(WETH));
}

bool transfer = receivedToken.transfer(borrowLiquidation, abi.decode(result, (uint256)));

if(!transfer) revert Treasury_TransferFailed();

return abi.decode(result, (uint256));
}
}

/**
* @dev swap collateral in odos
* @param asset collateral type to return
Expand Down
Loading