Skip to content

Commit

Permalink
(1CT) Create single tx to activate 1-Click Trading from swap review m…
Browse files Browse the repository at this point in the history
…odal (#3970)

* feat: create single tx to activate 1ct from swap review modal

* feat: remove unused methods

* fix: tx type

* feat: remove unused params

* improvements: coderabbit feedback
  • Loading branch information
JoseRFelix authored Nov 26, 2024
1 parent 11449ab commit 12e35cc
Show file tree
Hide file tree
Showing 16 changed files with 775 additions and 852 deletions.
150 changes: 0 additions & 150 deletions packages/stores/src/account/osmosis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
import * as OsmosisMath from "@osmosis-labs/math";
import { maxTick, minTick } from "@osmosis-labs/math";
import {
makeAddAuthenticatorMsg,
makeAddToConcentratedLiquiditySuperfluidPositionMsg,
makeAddToPositionMsg,
makeBeginUnlockingMsg,
Expand All @@ -27,7 +26,6 @@ import {
makeJoinSwapExternAmountInMsg,
makeLockAndSuperfluidDelegateMsg,
makeLockTokensMsg,
makeRemoveAuthenticatorMsg,
makeSetValidatorSetPreferenceMsg,
makeSplitRoutesSwapExactAmountInMsg,
makeSplitRoutesSwapExactAmountOutMsg,
Expand Down Expand Up @@ -2203,154 +2201,6 @@ export class OsmosisAccountImpl {
);
}

async sendAddOrRemoveAuthenticatorsMsg({
addAuthenticators,
removeAuthenticators,
memo = "",
onFulfill,
onBroadcasted,
signOptions,
}: {
addAuthenticators: { authenticatorType: string; data: Uint8Array }[];
removeAuthenticators: bigint[];
memo?: string;
onFulfill?: (tx: DeliverTxResponse) => void;
onBroadcasted?: () => void;
signOptions?: SignOptions;
}) {
const addAuthenticatorMsgs = addAuthenticators.map((authenticator) =>
makeAddAuthenticatorMsg({
authenticatorType: authenticator.authenticatorType,
data: authenticator.data,
sender: this.address,
})
);
const removeAuthenticatorMsgs = removeAuthenticators.map((id) =>
makeRemoveAuthenticatorMsg({
id,
sender: this.address,
})
);
const msgs = await Promise.all([
...removeAuthenticatorMsgs,
...addAuthenticatorMsgs,
]);

await this.base.signAndBroadcast(
this.chainId,
"addOrRemoveAuthenticators",
msgs,
memo,
undefined,
signOptions,
{
onBroadcasted,
onFulfill: (tx) => {
if (!tx.code) {
// Refresh the balances
const queries = this.queriesStore.get(this.chainId);

queries.queryBalances
.getQueryBech32Address(this.address)
.balances.forEach((balance) => balance.waitFreshResponse());

queries.cosmos.queryDelegations
.getQueryBech32Address(this.address)
.waitFreshResponse();

queries.cosmos.queryRewards
.getQueryBech32Address(this.address)
.waitFreshResponse();
}
onFulfill?.(tx);
},
}
);
}

async sendAddAuthenticatorsMsg(
authenticators: { authenticatorType: string; data: any }[],
memo: string = "",
onFulfill?: (tx: DeliverTxResponse) => void
) {
const addAuthenticatorMsgs = await Promise.all(
authenticators.map((authenticator) =>
makeAddAuthenticatorMsg({
authenticatorType: authenticator.authenticatorType,
data: authenticator.data,
sender: this.address,
})
)
);

await this.base.signAndBroadcast(
this.chainId,
"addAuthenticator",
addAuthenticatorMsgs,
memo,
undefined,
undefined,
(tx) => {
if (!tx.code) {
// Refresh the balances
const queries = this.queriesStore.get(this.chainId);

queries.queryBalances
.getQueryBech32Address(this.address)
.balances.forEach((balance) => balance.waitFreshResponse());

queries.cosmos.queryDelegations
.getQueryBech32Address(this.address)
.waitFreshResponse();

queries.cosmos.queryRewards
.getQueryBech32Address(this.address)
.waitFreshResponse();
}
onFulfill?.(tx);
}
);
}

async sendRemoveAuthenticatorMsg(
id: bigint,
memo: string = "",
onFulfill?: (tx: DeliverTxResponse) => void
) {
const removeAuthenticatorMsg = await makeRemoveAuthenticatorMsg({
id: id,
sender: this.address,
});

await this.base.signAndBroadcast(
this.chainId,
"removeAuthenticator",
[removeAuthenticatorMsg],
memo,
undefined,
undefined,
(tx) => {
if (!tx.code) {
// Refresh the balances
const queries = this.queriesStore.get(this.chainId);

queries.queryBalances
.getQueryBech32Address(this.address)
.balances.forEach((balance) => balance.waitFreshResponse());

queries.cosmos.queryDelegations
.getQueryBech32Address(this.address)
.waitFreshResponse();

queries.cosmos.queryRewards
.getQueryBech32Address(this.address)
.waitFreshResponse();
}
onFulfill?.(tx);
}
);
}

protected get queries() {
return this.queriesStore.get(this.chainId).osmosis!;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import {
useOneClickTradingSession,
useTranslation,
} from "~/hooks";
import { formatSpendLimit } from "~/hooks/one-click-trading/use-one-click-trading-session-manager";
import { formatSpendLimit } from "~/hooks/one-click-trading/use-one-click-trading-swap-review";
import { useEstimateTxFees } from "~/hooks/use-estimate-tx-fees";
import { ModalBase, ModalCloseButton } from "~/modals";
import { useStore } from "~/stores";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ export const ProfileOneClickTradingSettings = ({
{
spendLimitTokenDecimals,
transaction1CTParams,
walletRepo: accountStore.getWalletRepo(chainStore.osmosis.chainId),
/**
* If the user has an existing session, remove it and add the new one.
*/
Expand Down
4 changes: 3 additions & 1 deletion packages/web/components/place-limit-tool/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,9 @@ export const PlaceLimitTool: FunctionComponent<PlaceLimitToolProps> = observer(
}}
amountWithSlippage={amountWithSlippage}
fiatAmountWithSlippage={fiatAmountWithSlippage}
isConfirmationDisabled={isSendingTx}
isConfirmationDisabled={
isSendingTx || swapState.isLoadingOneClickMessages
}
isOpen={reviewOpen}
onClose={() => setReviewOpen(false)}
expectedOutput={swapState.expectedTokenAmountOut}
Expand Down
3 changes: 2 additions & 1 deletion packages/web/components/swap-tool/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,8 @@ export const SwapTool: FunctionComponent<SwapToolProps> = observer(
const isSwapToolLoading =
isWalletLoading ||
swapState.isQuoteLoading ||
swapState.isLoadingNetworkFee;
swapState.isLoadingNetworkFee ||
swapState.isLoadingOneClickMessages;

let buttonText: string;
if (swapState.error) {
Expand Down
79 changes: 60 additions & 19 deletions packages/web/hooks/limit-orders/use-place-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ import {
isValidNumericalRawInput,
useAmountInput,
} from "~/hooks/input/use-amount-input";
import { useTranslation } from "~/hooks/language";
import { useOrderbook } from "~/hooks/limit-orders/use-orderbook";
import { onAdd1CTSession } from "~/hooks/mutations/one-click-trading";
import { use1CTSwapReviewMessages } from "~/hooks/one-click-trading";
import { mulPrice } from "~/hooks/queries/assets/use-coin-fiat-value";
import { usePrice } from "~/hooks/queries/assets/use-price";
import { useAmplitudeAnalytics } from "~/hooks/use-amplitude-analytics";
Expand Down Expand Up @@ -67,6 +70,8 @@ export const usePlaceLimit = ({
maxSlippage,
quoteType = "out-given-in",
}: UsePlaceLimitParams) => {
const apiUtils = api.useUtils();
const { t } = useTranslation();
const { logEvent } = useAmplitudeAnalytics();
const { accountStore } = useStore();
const {
Expand Down Expand Up @@ -279,6 +284,15 @@ export const usePlaceLimit = ({
placeLimitMsg,
]);

const { oneClickMessages, isLoadingOneClickMessages, shouldSend1CTTx } =
use1CTSwapReviewMessages();

const limitMessages = useMemo(() => {
return encodedMsg && !isMarket
? [encodedMsg, ...(oneClickMessages?.msgs ?? [])]
: [];
}, [encodedMsg, isMarket, oneClickMessages?.msgs]);

const placeLimit = useCallback(async () => {
const quantity = paymentTokenValue?.toCoin().amount ?? "0";
if (quantity === "0") {
Expand Down Expand Up @@ -335,7 +349,7 @@ export const usePlaceLimit = ({
}
}

if (!placeLimitMsg) return;
if (!limitMessages || limitMessages.length === 0) return;

const paymentDenom = paymentTokenValue?.toCoin().denom ?? "";

Expand All @@ -360,16 +374,38 @@ export const usePlaceLimit = ({

try {
logEvent([EventName.LimitOrder.placeOrderStarted, baseEvent]);
await account?.cosmwasm.sendExecuteContractMsg(
await accountStore.signAndBroadcast(
accountStore.osmosisChainId,
"executeWasm",
orderbookContractAddress,
placeLimitMsg!,
[
{
amount: quantity,
denom: paymentDenom,
},
]
limitMessages,
"",
undefined,
undefined,
(tx) => {
if (!tx.code) {
if (
shouldSend1CTTx &&
oneClickMessages &&
oneClickMessages.type === "create-1ct-session"
) {
onAdd1CTSession({
privateKey: oneClickMessages.key,
tx,
userOsmoAddress: account?.address ?? "",
fallbackGetAuthenticatorId:
apiUtils.local.oneClickTrading.getSessionAuthenticator.fetch,
accountStore,
allowedMessages: oneClickMessages.allowedMessages,
sessionPeriod: oneClickMessages.sessionPeriod,
spendLimitTokenDecimals:
oneClickMessages.spendLimitTokenDecimals,
transaction1CTParams: oneClickMessages.transaction1CTParams,
allowedAmount: oneClickMessages.allowedAmount,
t,
});
}
}
}
);
logEvent([EventName.LimitOrder.placeOrderCompleted, baseEvent]);
} catch (error) {
Expand All @@ -385,19 +421,23 @@ export const usePlaceLimit = ({
]);
}
}, [
orderbookContractAddress,
account,
orderDirection,
paymentTokenValue,
isMarket,
marketState,
limitMessages,
paymentFiatValue,
baseAsset,
quoteAsset,
logEvent,
orderDirection,
baseAsset?.coinDenom,
quoteAsset?.coinDenom,
page,
feeUsdValue,
placeLimitMsg,
marketState,
logEvent,
accountStore,
shouldSend1CTTx,
oneClickMessages,
account?.address,
apiUtils.local.oneClickTrading.getSessionAuthenticator.fetch,
t,
]);

const { data, isLoading: isBalancesLoading } =
Expand Down Expand Up @@ -585,7 +625,7 @@ export const usePlaceLimit = ({
error: limitGasError,
} = useEstimateTxFees({
chainId: accountStore.osmosisChainId,
messages: encodedMsg && !isMarket ? [encodedMsg] : [],
messages: limitMessages,
enabled: shouldEstimateLimitGas,
});

Expand Down Expand Up @@ -642,6 +682,7 @@ export const usePlaceLimit = ({
reset,
error,
feeUsdValue,
isLoadingOneClickMessages,
gas: {
gasAmountFiat,
isLoading: isGasLoading,
Expand Down
Loading

0 comments on commit 12e35cc

Please sign in to comment.