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

feat(bonsai-core): modifyUsdcAssetPosition #1423

Open
wants to merge 2 commits into
base: jv/withdraw-rewrite-2
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
136 changes: 136 additions & 0 deletions src/abacus-ts/calculators/subaccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { mapValues, orderBy } from 'lodash';

import { NUM_PARENT_SUBACCOUNTS } from '@/constants/account';
import {
IndexerAssetPositionResponseObject,
IndexerPerpetualMarketResponseObject,
IndexerPerpetualPositionResponseObject,
IndexerPerpetualPositionStatus,
Expand All @@ -14,6 +15,7 @@ import { calc } from '@/lib/do';
import { BIG_NUMBERS, MaybeBigNumber, MustBigNumber, ToBigNumber } from '@/lib/numbers';
import { isPresent } from '@/lib/typeUtils';

import { SubaccountBatchedOperations, SubaccountOperations } from '../types/operationTypes';
import { ChildSubaccountData, MarketsData, ParentSubaccountData } from '../types/rawTypes';
import {
GroupedSubaccountSummary,
Expand Down Expand Up @@ -288,3 +290,137 @@ function calculatePositionDerivedExtra(
updatedUnrealizedPnlPercent,
};
}

export function createUsdcDepositOperations({
subaccountNumber,
depositAmount,
}: {
subaccountNumber: number;
depositAmount: string;
}): SubaccountBatchedOperations {
return {
operations: [
SubaccountOperations.ModifyUsdcAssetPosition({
subaccountNumber,
changes: {
size: depositAmount,
},
}),
],
};
}

export function createUsdcWithdrawalOperations({
subaccountNumber,
withdrawAmount,
}: {
subaccountNumber: number;
withdrawAmount: string;
}): SubaccountBatchedOperations {
return {
operations: [
SubaccountOperations.ModifyUsdcAssetPosition({
subaccountNumber,
changes: {
size: MustBigNumber(withdrawAmount).negated().toString(),
},
}),
],
};
}

function modifyUsdcAssetPosition(
parentSubaccountData: ParentSubaccountData,
payload: {
subaccountNumber: number;
changes: Partial<Pick<IndexerAssetPositionResponseObject, 'size'>>;
}
): void {
const { subaccountNumber, changes } = payload;

if (!changes.size) return;
const sizeBN = MustBigNumber(changes.size);

let childSubaccount: ChildSubaccountData | undefined =
parentSubaccountData.childSubaccounts[subaccountNumber];

if (childSubaccount != null) {
// Modify childSubaccount
if (childSubaccount.assetPositions.USDC != null) {
const size = MustBigNumber(childSubaccount.assetPositions.USDC.size).plus(sizeBN).toString();
const assetPositions = {
...childSubaccount.assetPositions,
USDC: {
...childSubaccount.assetPositions.USDC,
size,
},
};

childSubaccount = {
...childSubaccount,
assetPositions,
};
} else {
if (sizeBN.gt(0)) {
childSubaccount.assetPositions.USDC = {
assetId: '0',
symbol: 'USDC',
size: sizeBN.toString(),
side: IndexerPositionSide.LONG,
subaccountNumber,
};
}
}
} else {
// Upsert ChildSubaccountData into parentSubaccountData.childSubaccounts
childSubaccount = {
address: parentSubaccountData.address,
subaccountNumber,
openPerpetualPositions: {},
assetPositions: {
USDC: {
assetId: '0',
symbol: 'USDC',
size: sizeBN.toString(),
side: IndexerPositionSide.LONG,
subaccountNumber,
},
},
};
}

parentSubaccountData.childSubaccounts = {
...parentSubaccountData.childSubaccounts,
[subaccountNumber]: childSubaccount,
};
}

export function applyOperationsToSubaccount(
parentSubaccount: ParentSubaccountData,
batchedOperations: SubaccountBatchedOperations
): ParentSubaccountData {
const parentSubaccountData: ParentSubaccountData = { ...parentSubaccount };

batchedOperations.operations.forEach((op) => {
const { payload, operation } = op;

switch (operation) {
case 'AddPerpetualPosition': {
// TODO: Implement addPerpetualPosition
break;
}
case 'ModifyPerpetualPosition': {
// TODO: Implement modifyPerpetualPosition
break;
}
case 'ModifyUsdcAssetPosition': {
modifyUsdcAssetPosition(parentSubaccountData, payload);
break;
}
default:
throw new Error(`Error processing invalid operation type`);
}
});

return parentSubaccountData;
}
16 changes: 16 additions & 0 deletions src/abacus-ts/ontology.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ import {
selectParentSubaccountSummary,
selectParentSubaccountSummaryLoading,
} from './selectors/account';
import {
createSelectParentSubaccountPositionsDeposit,
createSelectParentSubaccountPositionsWithdrawal,
createSelectParentSubaccountSummaryDeposit,
createSelectParentSubaccountSummaryWithdrawal,
} from './selectors/accountActions';
import {
selectAllAssetsInfo,
selectAllAssetsInfoLoading,
Expand Down Expand Up @@ -97,6 +103,16 @@ export const BonsaiHelpers = {
fills: getCurrentMarketAccountFills,
},
},
account: {
deposit: {
parentSubaccountSummary: createSelectParentSubaccountSummaryDeposit,
parentSubaccountPositions: createSelectParentSubaccountPositionsDeposit,
},
withdraw: {
parentSubaccountSummary: createSelectParentSubaccountSummaryWithdrawal,
parentSubaccountPositions: createSelectParentSubaccountPositionsWithdrawal,
},
},
} as const satisfies NestedSelectors;

export const BonsaiHooks = {
Expand Down
2 changes: 1 addition & 1 deletion src/abacus-ts/selectors/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const selectRelevantMarketsList = createAppSelector(
}
);

const selectRelevantMarketsData = createAppSelector(
export const selectRelevantMarketsData = createAppSelector(
[selectRelevantMarketsList, selectRawMarketsData],
(marketIds, markets) => {
if (markets == null || marketIds == null) {
Expand Down
129 changes: 129 additions & 0 deletions src/abacus-ts/selectors/accountActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { shallowEqual } from 'react-redux';

import { createAppSelector } from '@/state/appTypes';

import {
applyOperationsToSubaccount,
calculateParentSubaccountPositions,
calculateParentSubaccountSummary,
createUsdcDepositOperations,
createUsdcWithdrawalOperations,
} from '../calculators/subaccount';
import { selectRelevantMarketsData } from './account';
import { selectRawParentSubaccountData } from './base';

export const createSelectParentSubaccountSummaryDeposit = () =>
createAppSelector(
[
selectRawParentSubaccountData,
selectRelevantMarketsData,
(
_s,
input: {
subaccountNumber: number;
depositAmount: string;
}
) => input,
],
(parentSubaccount, markets, depositInputs) => {
if (parentSubaccount == null || markets == null) {
return undefined;
}

const operations = createUsdcDepositOperations(depositInputs);
const modifiedParentSubaccount = applyOperationsToSubaccount(parentSubaccount, operations);
const result = calculateParentSubaccountSummary(modifiedParentSubaccount, markets);
return result;
},
{
// use shallow equal for result so that we only update when these specific keys differ
memoizeOptions: { resultEqualityCheck: shallowEqual },
}
);

export const createSelectParentSubaccountPositionsDeposit = () =>
createAppSelector(
[
selectRawParentSubaccountData,
selectRelevantMarketsData,
(
_s,
input: {
subaccountNumber: number;
depositAmount: string;
}
) => input,
],
(parentSubaccount, markets, depositInputs) => {
if (parentSubaccount == null || markets == null) {
return undefined;
}

const operations = createUsdcDepositOperations(depositInputs);
const modifiedParentSubaccount = applyOperationsToSubaccount(parentSubaccount, operations);
const result = calculateParentSubaccountPositions(modifiedParentSubaccount, markets);
return result;
},
{
// use shallow equal for result so that we only update when these specific keys differ
memoizeOptions: { resultEqualityCheck: shallowEqual },
}
);

export const createSelectParentSubaccountSummaryWithdrawal = () =>
createAppSelector(
[
selectRawParentSubaccountData,
selectRelevantMarketsData,
(
_s,
input: {
subaccountNumber: number;
withdrawAmount: string;
}
) => input,
],
(parentSubaccount, markets, withdrawalInputs) => {
if (parentSubaccount == null || markets == null) {
return undefined;
}

const operations = createUsdcWithdrawalOperations(withdrawalInputs);
const modifiedParentSubaccount = applyOperationsToSubaccount(parentSubaccount, operations);
const result = calculateParentSubaccountSummary(modifiedParentSubaccount, markets);
return result;
},
{
// use shallow equal for result so that we only update when these specific keys differ
memoizeOptions: { resultEqualityCheck: shallowEqual },
}
);

export const createSelectParentSubaccountPositionsWithdrawal = () =>
createAppSelector(
[
selectRawParentSubaccountData,
selectRelevantMarketsData,
(
_s,
input: {
subaccountNumber: number;
withdrawAmount: string;
}
) => input,
],
(parentSubaccount, markets, withdrawalInputs) => {
if (parentSubaccount == null || markets == null) {
return undefined;
}

const operations = createUsdcWithdrawalOperations(withdrawalInputs);
const modifiedParentSubaccount = applyOperationsToSubaccount(parentSubaccount, operations);
const result = calculateParentSubaccountPositions(modifiedParentSubaccount, markets);
return result;
},
{
// use shallow equal for result so that we only update when these specific keys differ
memoizeOptions: { resultEqualityCheck: shallowEqual },
}
);
8 changes: 4 additions & 4 deletions src/abacus-ts/types/operationTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@ import {
export const SubaccountOperations = unionize(
{
AddPerpetualPosition: ofType<{
subaccountNumber: string;
subaccountNumber: number;
market: string;
position: Omit<IndexerPerpetualPositionResponseObject, 'market' | 'subaccountNumber'>;
}>(),
ModifyPerpetualPosition: ofType<{
subaccountNumber: string;
subaccountNumber: number;
market: string;
changes: Partial<Omit<IndexerPerpetualPositionResponseObject, 'market' | 'subaccountNumber'>>;
}>(),
ModifyUsdcAssetPosition: ofType<{
subaccountNumber: string;
changes: Partial<Pick<IndexerAssetPositionResponseObject, 'size' | 'side'>>;
subaccountNumber: number;
changes: Partial<Pick<IndexerAssetPositionResponseObject, 'size'>>;
}>(),
},
{ tag: 'operation' as const, value: 'payload' as const }
Expand Down
14 changes: 14 additions & 0 deletions src/views/dialogs/DepositDialog2/queries.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useMemo } from 'react';

import { BonsaiHelpers } from '@/abacus-ts/ontology';
import { BalanceRequest, RouteRequest, SkipClient } from '@skip-go/client';
import { useQuery } from '@tanstack/react-query';
import { Chain, parseUnits } from 'viem';
Expand All @@ -14,6 +15,7 @@ import { WalletNetworkType } from '@/constants/wallets';

import { useSkipClient } from '@/hooks/transfers/skipClient';
import { useAccounts } from '@/hooks/useAccounts';
import { useParameterizedSelector } from '@/hooks/useParameterizedSelector';

import { SourceAccount } from '@/state/wallet';

Expand Down Expand Up @@ -147,3 +149,15 @@ export function useDepositRoutes(token: TokenForTransfer, amount: string) {
placeholderData: (prev) => prev,
});
}

export function useDepositDeltas({ depositAmount }: { depositAmount: string }) {
const modifiedParentSubaccount = useParameterizedSelector(
BonsaiHelpers.account.deposit.parentSubaccountSummary,
{
subaccountNumber: 0,
depositAmount,
}
);

return modifiedParentSubaccount;
}
Loading
Loading