Skip to content

Commit

Permalink
feat(rebalance-wallet): rebalance wallet if usdcBalance is low (dydxp…
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredvu authored Jun 13, 2024
1 parent 3b51ec6 commit 26a70e9
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 24 deletions.
1 change: 1 addition & 0 deletions src/constants/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export type Hdkey = {
};

export const AMOUNT_RESERVED_FOR_GAS_USDC = 0.5;
export const AMOUNT_USDC_BEFORE_REBALANCE = 0.05;

/**
* @description The number of parentSubaccounts: 0 - 127, 128 is the first childSubaccount
Expand Down
48 changes: 28 additions & 20 deletions src/hooks/useSubaccount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import type {
HumanReadableTriggerOrdersPayload,
ParsingError,
} from '@/constants/abacus';
import { AMOUNT_RESERVED_FOR_GAS_USDC } from '@/constants/account';
import { AMOUNT_RESERVED_FOR_GAS_USDC, AMOUNT_USDC_BEFORE_REBALANCE } from '@/constants/account';
import { STRING_KEYS } from '@/constants/localization';
import { QUANTUM_MULTIPLIER } from '@/constants/numbers';
import { TradeTypes } from '@/constants/trade';
Expand Down Expand Up @@ -240,7 +240,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall
}
},
}),
[compositeClient]
[compositeClient, usdcDecimals]
);

const [subaccountNumber] = useState(0);
Expand All @@ -259,31 +259,39 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall
useEffect(() => {
dispatch(setSubaccount(undefined));
dispatch(setHistoricalPnl([]));
}, [dydxAddress]);
}, [dispatch, dydxAddress]);

// ------ Deposit/Withdraw Methods ------ //
const depositFunds = useCallback(
const rebalanceWalletFunds = useCallback(
async (balance: AccountBalance) => {
if (!localDydxWallet) return;

const amount = parseFloat(balance.amount) - AMOUNT_RESERVED_FOR_GAS_USDC;

if (amount > 0) {
const newSubaccountClient = new SubaccountClient(localDydxWallet, 0);
await depositToSubaccount({ amount, subaccountClient: newSubaccountClient });
if (!subaccountClient) return;
const balanceAmount = parseFloat(balance.amount);
const shouldDeposit = balanceAmount - AMOUNT_RESERVED_FOR_GAS_USDC > 0;
const shouldWithdraw = balanceAmount - AMOUNT_USDC_BEFORE_REBALANCE <= 0;

if (shouldDeposit) {
await depositToSubaccount({
amount: balanceAmount - AMOUNT_RESERVED_FOR_GAS_USDC,
subaccountClient,
});
} else if (shouldWithdraw) {
await withdrawFromSubaccount({
amount: AMOUNT_RESERVED_FOR_GAS_USDC - balanceAmount,
subaccountClient,
});
}
},
[localDydxWallet, depositToSubaccount]
[subaccountClient, depositToSubaccount, withdrawFromSubaccount]
);

const balances = useAppSelector(getBalances, shallowEqual);
const usdcCoinBalance = balances?.[usdcDenom];

useEffect(() => {
if (usdcCoinBalance) {
depositFunds(usdcCoinBalance);
rebalanceWalletFunds(usdcCoinBalance);
}
}, [usdcCoinBalance]);
}, [usdcCoinBalance, rebalanceWalletFunds]);

const deposit = useCallback(
async (amount: number) => {
Expand Down Expand Up @@ -318,7 +326,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall
? transferFromSubaccountToAddress({ subaccountClient, amount, recipient })
: transferNativeToken({ subaccountClient, amount, recipient, memo }))) as IndexedTx;
},
[subaccountClient, transferFromSubaccountToAddress, transferNativeToken]
[subaccountClient, transferFromSubaccountToAddress, transferNativeToken, usdcDenom]
);

const sendSquidWithdraw = useCallback(
Expand Down Expand Up @@ -374,7 +382,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall
const subaccountTransferPayload = abacusStateManager.adjustIsolatedMarginOfPosition(callback);
return subaccountTransferPayload;
},
[subaccountClient]
[]
);

// ------ Faucet Methods ------ //
Expand Down Expand Up @@ -444,7 +452,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall

return placeOrderParams;
},
[subaccountClient]
[dispatch]
);

const closePosition = useCallback(
Expand Down Expand Up @@ -486,7 +494,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall
dispatch(cancelOrderSubmitted(orderId));
abacusStateManager.cancelOrder(orderId, callback);
},
[subaccountClient]
[dispatch]
);

// ------ Trigger Orders Methods ------ //
Expand Down Expand Up @@ -557,7 +565,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall

return triggerOrderParams;
},
[subaccountClient]
[dispatch]
);

const { newMarketProposal } = useGovernanceVariables();
Expand All @@ -583,7 +591,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall

return response;
},
[compositeClient, localDydxWallet]
[compositeClient, localDydxWallet, newMarketProposal]
);

// ------ Staking Methods ------ //
Expand Down
29 changes: 25 additions & 4 deletions src/views/menus/AccountMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
type StringGetterFunction,
} from '@/constants/localization';
import { isDev } from '@/constants/networks';
import { SMALL_USD_DECIMALS, USD_DECIMALS } from '@/constants/numbers';
import { DydxChainAsset, WalletType, wallets } from '@/constants/wallets';

import { useAccountBalance } from '@/hooks/useAccountBalance';
Expand Down Expand Up @@ -60,7 +61,7 @@ export const AccountMenu = () => {
const onboardingState = useAppSelector(getOnboardingState);
const { freeCollateral } = useAppSelector(getSubaccount, shallowEqual) ?? {};

const { nativeTokenBalance } = useAccountBalance();
const { nativeTokenBalance, usdcBalance } = useAccountBalance();
const { usdcLabel, chainTokenLabel } = useTokenConfigs();
const theme = useAppSelector(getAppTheme);

Expand All @@ -71,8 +72,6 @@ export const AccountMenu = () => {

const { showMfaEnrollmentModal } = useMfaEnrollment();

const usdcBalance = freeCollateral?.current ?? 0;

const onRecoverKeys = () => {
dispatch(openDialog({ type: DialogTypes.Onboarding }));
};
Expand Down Expand Up @@ -169,6 +168,24 @@ export const AccountMenu = () => {
stringGetter={stringGetter}
/>
</div>
{isDev && (
<div>
<div>
<$label>
{stringGetter({
key: STRING_KEYS.WALLET_BALANCE,
params: { ASSET: usdcLabel },
})}
<AssetIcon symbol="USDC" />
</$label>
<$BalanceOutput
type={OutputType.Asset}
value={usdcBalance}
fractionDigits={SMALL_USD_DECIMALS}
/>
</div>
</div>
)}
<div>
<div>
<$label>
Expand All @@ -178,7 +195,11 @@ export const AccountMenu = () => {
})}
<AssetIcon symbol="USDC" />
</$label>
<$BalanceOutput type={OutputType.Asset} value={usdcBalance} fractionDigits={2} />
<$BalanceOutput
type={OutputType.Asset}
value={freeCollateral?.current ?? 0}
fractionDigits={USD_DECIMALS}
/>
</div>
<AssetActions
asset={DydxChainAsset.USDC}
Expand Down

0 comments on commit 26a70e9

Please sign in to comment.