Skip to content

Commit

Permalink
(1CT) Add events when creating 1CT session in swap review (#3971)
Browse files Browse the repository at this point in the history
* feat: add events when creating 1CT session

* (1CT) Split txs for Ledger in swap review modal (#3972)

* feat: split txs for Ledger

* fix: wrong override

* feat: default to non ledger behavior

* improvement: naming

* improvement: typos
  • Loading branch information
JoseRFelix authored Nov 26, 2024
1 parent 1df4386 commit 794ca5c
Show file tree
Hide file tree
Showing 6 changed files with 398 additions and 164 deletions.
4 changes: 2 additions & 2 deletions packages/stores/src/account/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,7 @@ export class AccountStore<Injects extends Record<string, any>[] = []> {
fee?: StdFee,
signOptions?: SignOptions,
onTxEvents?:
| ((tx: DeliverTxResponse) => void)
| ((tx: DeliverTxResponse) => void | Promise<void>)
| {
onBroadcastFailed?: (e?: Error) => void;
onBroadcasted?: (txHash: Uint8Array) => void;
Expand Down Expand Up @@ -709,7 +709,7 @@ export class AccountStore<Injects extends Record<string, any>[] = []> {
}

if (onFulfill) {
onFulfill(tx);
await onFulfill(tx);
}
} catch (e) {
const error = e as Error | AccountStoreNoBroadcastErrorEvent;
Expand Down
164 changes: 130 additions & 34 deletions packages/web/hooks/limit-orders/use-place-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { useTranslation } from "~/hooks/language";
import { useOrderbook } from "~/hooks/limit-orders/use-orderbook";
import { onAdd1CTSession } from "~/hooks/mutations/one-click-trading";
import { onEnd1CTSession } from "~/hooks/mutations/one-click-trading/use-remove-one-click-trading-session";
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";
Expand Down Expand Up @@ -287,11 +288,28 @@ export const usePlaceLimit = ({
const { oneClickMessages, isLoadingOneClickMessages, shouldSend1CTTx } =
use1CTSwapReviewMessages();

/**
* Default isLedger to true, just in case the wallet does
* not return the correct value
*/
const { value: isLedger } = useAsync(async () => {
const result = await account?.client?.getAccount?.(
accountStore.osmosisChainId
);
return result?.isNanoLedger ?? true;
// Disable deps to include account address in order to recompute the value as the others are memoized mobx values
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [account, account?.address, accountStore.osmosisChainId]);

const limitMessages = useMemo(() => {
if (isLedger) {
return encodedMsg && !isMarket ? [encodedMsg] : [];
}

return encodedMsg && !isMarket
? [encodedMsg, ...(oneClickMessages?.msgs ?? [])]
: [];
}, [encodedMsg, isMarket, oneClickMessages?.msgs]);
}, [encodedMsg, isLedger, isMarket, oneClickMessages?.msgs]);

const placeLimit = useCallback(async () => {
const quantity = paymentTokenValue?.toCoin().amount ?? "0";
Expand Down Expand Up @@ -374,39 +392,116 @@ export const usePlaceLimit = ({

try {
logEvent([EventName.LimitOrder.placeOrderStarted, baseEvent]);
await accountStore.signAndBroadcast(
accountStore.osmosisChainId,
"executeWasm",
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,
});
/**
* If it's ledger and we have one-click messages, we need to add a 1CT session
* before broadcasting the transaction as there is a payload limit on ledger
*/
if (
isLedger &&
oneClickMessages &&
oneClickMessages.msgs &&
shouldSend1CTTx
) {
await accountStore.signAndBroadcast(
accountStore.osmosisChainId,
"Add 1CT session",
oneClickMessages.msgs,
undefined,
undefined,
undefined,
async (tx) => {
const { code } = tx;
if (code) {
throw new Error("Failed to send swap exact amount in message");
} else {
if (
oneClickMessages &&
oneClickMessages.type === "create-1ct-session"
) {
await 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,
});
} else if (
shouldSend1CTTx &&
oneClickMessages &&
oneClickMessages.type === "remove-1ct-session"
) {
await onEnd1CTSession({
accountStore,
authenticatorId: oneClickMessages.authenticatorId,
logEvent,
});
}
}
}
}
);
);

await accountStore.signAndBroadcast(
accountStore.osmosisChainId,
"executeWasm",
limitMessages
);
} else {
await accountStore.signAndBroadcast(
accountStore.osmosisChainId,
"executeWasm",
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,
});
} else if (
shouldSend1CTTx &&
oneClickMessages &&
oneClickMessages.type === "remove-1ct-session"
) {
onEnd1CTSession({
accountStore,
authenticatorId: oneClickMessages.authenticatorId,
logEvent,
});
}
}
}
);
}
logEvent([EventName.LimitOrder.placeOrderCompleted, baseEvent]);
} catch (error) {
console.error("Error attempting to broadcast place limit tx", error);
Expand All @@ -432,9 +527,10 @@ export const usePlaceLimit = ({
feeUsdValue,
marketState,
logEvent,
accountStore,
shouldSend1CTTx,
isLedger,
oneClickMessages,
shouldSend1CTTx,
accountStore,
account?.address,
apiUtils.local.oneClickTrading.getSessionAuthenticator.fetch,
t,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ export async function onAdd1CTSession({
transaction1CTParams,
allowedAmount,
t,
logEvent,
}: {
privateKey: PrivKeySecp256k1;
tx: DeliverTxResponse;
Expand All @@ -197,6 +198,7 @@ export async function onAdd1CTSession({
transaction1CTParams: OneClickTradingTransactionParams;
allowedAmount: string;
t: ReturnType<typeof useTranslation>["t"];
logEvent: ReturnType<typeof useAmplitudeAnalytics>["logEvent"];
}) {
const publicKey = toBase64(privateKey.getPubKey().toBytes());

Expand Down Expand Up @@ -243,6 +245,13 @@ export async function onAdd1CTSession({
},
ToastType.ONE_CLICK_TRADING
);
logEvent([
EventName.OneClickTrading.startSession,
{
spendLimit: Number(transaction1CTParams.spendLimit.toDec().toString()),
sessionPeriod: transaction1CTParams.sessionPeriod.end,
},
]);
}

export async function makeCreate1CTSessionMessage({
Expand Down Expand Up @@ -471,23 +480,9 @@ export const useCreateOneClickTradingSession = ({
transaction1CTParams,
allowedAmount,
t,
logEvent,
});
},
{
...queryOptions,
onSuccess: (...params) => {
const [, { transaction1CTParams }] = params;
queryOptions?.onSuccess?.(...params);
logEvent([
EventName.OneClickTrading.startSession,
{
spendLimit: Number(
transaction1CTParams?.spendLimit.toDec().toString()
),
sessionPeriod: transaction1CTParams?.sessionPeriod.end,
},
]);
},
}
queryOptions
);
};
Loading

0 comments on commit 794ca5c

Please sign in to comment.