Skip to content

Commit baff738

Browse files
feat: WalletConnect: error handling
1 parent be751dc commit baff738

File tree

7 files changed

+232
-67
lines changed

7 files changed

+232
-67
lines changed

apps/web/src/components/Menu/ErrorLogsMenu/ErrorLogsMenu.tsx

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { Box, Button, Divider, Flex, Heading, Link, Text, VStack } from "@chakra-ui/react";
22
import { errorsActions, useAppDispatch, useAppSelector } from "@umami/state";
3-
import { handleTezError } from "@umami/utils";
43

54
import { useColor } from "../../../styles/useColor";
65
import { EmptyMessage } from "../../EmptyMessage";
@@ -61,8 +60,7 @@ export const ErrorLogsMenu = () => {
6160
</Text>
6261
{errorLog.technicalDetails && (
6362
<Text marginTop="12px" color={color("700")} size="sm">
64-
{handleTezError({ name: "unknown", message: errorLog.technicalDetails }) ??
65-
""}
63+
{JSON.stringify(errorLog.technicalDetails)}
6664
</Text>
6765
)}
6866
</Flex>

apps/web/src/components/WalletConnect/WalletConnectProvider.tsx

+15-13
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type EventEmitter from "events";
33
import { type NetworkType } from "@airgap/beacon-wallet";
44
import { useToast } from "@chakra-ui/react";
55
import { type WalletKitTypes } from "@reown/walletkit";
6+
import { TezosOperationError } from "@taquito/taquito";
67
import { useDynamicModalContext } from "@umami/components";
78
import {
89
createWalletKit,
@@ -12,10 +13,10 @@ import {
1213
walletKit,
1314
} from "@umami/state";
1415
import { type Network } from "@umami/tezos";
15-
import { CustomError, WalletConnectError } from "@umami/utils";
16+
import { CustomError, WalletConnectError, type WcErrorKey, getWcErrorResponse } from "@umami/utils";
1617
import { formatJsonRpcError } from "@walletconnect/jsonrpc-utils";
1718
import { type SessionTypes } from "@walletconnect/types";
18-
import { type SdkErrorKey, getSdkError } from "@walletconnect/utils";
19+
import { getSdkError } from "@walletconnect/utils";
1920
import { type PropsWithChildren, useCallback, useEffect, useRef } from "react";
2021

2122
import { SessionProposalModal } from "./SessionProposalModal";
@@ -94,7 +95,7 @@ export const WalletConnectProvider = ({ children }: PropsWithChildren) => {
9495
handleAsyncActionUnsafe(async () => {
9596
const activeSessions: Record<string, SessionTypes.Struct> = walletKit.getActiveSessions();
9697
if (!(event.topic in activeSessions)) {
97-
throw new WalletConnectError("Session not found", "INVALID_EVENT", null);
98+
throw new WalletConnectError("Session not found", "SESSION_NOT_FOUND", null);
9899
}
99100

100101
const session = activeSessions[event.topic];
@@ -105,19 +106,20 @@ export const WalletConnectProvider = ({ children }: PropsWithChildren) => {
105106
await handleWcRequest(event, session);
106107
}).catch(async error => {
107108
const { id, topic } = event;
108-
let sdkErrorKey: SdkErrorKey =
109-
error instanceof WalletConnectError ? error.sdkError : "SESSION_SETTLEMENT_FAILED";
110-
if (sdkErrorKey === "USER_REJECTED") {
111-
console.info("WC request rejected", sdkErrorKey, event, error);
109+
let wcErrorKey: WcErrorKey = "UNKNOWN_ERROR";
110+
111+
if (error instanceof WalletConnectError) {
112+
wcErrorKey = error.wcError;
113+
} else if (error instanceof TezosOperationError) {
114+
wcErrorKey = "REJECTED_BY_CHAIN";
115+
}
116+
const response = formatJsonRpcError(id, getWcErrorResponse(error));
117+
if (wcErrorKey === "USER_REJECTED") {
118+
console.info("WC request rejected", wcErrorKey, event, error);
112119
} else {
113-
if (error.message.includes("delegate.unchanged")) {
114-
sdkErrorKey = "INVALID_EVENT";
115-
}
116-
console.warn("WC request failed", sdkErrorKey, event, error);
120+
console.warn("WC request failed", wcErrorKey, event, error, response);
117121
}
118122
// dApp is waiting so we need to notify it
119-
const sdkErrorMessage = getSdkError(sdkErrorKey).message;
120-
const response = formatJsonRpcError(id, sdkErrorMessage);
121123
await walletKit.respondSessionRequest({ topic, response });
122124
}),
123125
[handleAsyncActionUnsafe, handleWcRequest, toast]

apps/web/src/components/WalletConnect/useHandleWcRequest.tsx

+27-15
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,9 @@ import {
1414
useGetOwnedAccountSafe,
1515
walletKit,
1616
} from "@umami/state";
17-
import { WalletConnectError } from "@umami/utils";
17+
import { WC_ERRORS, WalletConnectError } from "@umami/utils";
1818
import { formatJsonRpcError, formatJsonRpcResult } from "@walletconnect/jsonrpc-utils";
1919
import { type SessionTypes, type SignClientTypes, type Verify } from "@walletconnect/types";
20-
import { type SdkErrorKey, getSdkError } from "@walletconnect/utils";
2120

2221
import { SignPayloadRequestModal } from "../common/SignPayloadRequestModal";
2322
import { BatchSignPage } from "../SendFlow/common/BatchSignPage";
@@ -61,11 +60,18 @@ export const useHandleWcRequest = () => {
6160
let modal;
6261
let onClose;
6362

63+
const handleUserRejected = () => {
64+
// dApp is waiting so we need to notify it
65+
const response = formatJsonRpcError(id, WC_ERRORS.USER_REJECTED);
66+
console.info("WC request rejected by user", event, response);
67+
void walletKit.respondSessionRequest({ topic, response });
68+
};
69+
6470
switch (request.method) {
6571
case "tezos_getAccounts": {
6672
const wcPeers = walletKit.getActiveSessions();
6773
if (!(topic in wcPeers)) {
68-
throw new WalletConnectError(`Unknown session ${topic}`, "UNAUTHORIZED_EVENT", null);
74+
throw new WalletConnectError(`Unknown session ${topic}`, "SESSION_NOT_FOUND", null);
6975
}
7076
const session = wcPeers[topic];
7177
const accountPkh = session.namespaces.tezos.accounts[0].split(":")[2];
@@ -89,15 +95,20 @@ export const useHandleWcRequest = () => {
8995

9096
case "tezos_sign": {
9197
if (!request.params.account) {
92-
throw new WalletConnectError("Missing account in request", "INVALID_EVENT", session);
98+
throw new WalletConnectError(
99+
"Missing account in request",
100+
"MISSING_ACCOUNT_IN_REQUEST",
101+
session
102+
);
93103
}
94104
const signer = getImplicitAccount(request.params.account);
95105
const network = findNetwork(chainId.split(":")[1]);
96106
if (!network) {
97107
throw new WalletConnectError(
98108
`Unsupported network ${chainId}`,
99109
"UNSUPPORTED_CHAINS",
100-
session
110+
session,
111+
chainId
101112
);
102113
}
103114

@@ -115,24 +126,24 @@ export const useHandleWcRequest = () => {
115126

116127
modal = <SignPayloadRequestModal opts={signPayloadProps} />;
117128
onClose = () => {
118-
const sdkErrorKey: SdkErrorKey = "USER_REJECTED";
119-
console.info("WC request rejected by user", sdkErrorKey, event);
120-
// dApp is waiting so we need to notify it
121-
const response = formatJsonRpcError(id, getSdkError(sdkErrorKey).message);
122-
void walletKit.respondSessionRequest({ topic, response });
129+
handleUserRejected();
123130
};
124131
return openWith(modal, { onClose });
125132
}
126133

127134
case "tezos_send": {
128135
if (!request.params.account) {
129-
throw new WalletConnectError("Missing account in request", "INVALID_EVENT", session);
136+
throw new WalletConnectError(
137+
"Missing account in request",
138+
"MISSING_ACCOUNT_IN_REQUEST",
139+
session
140+
);
130141
}
131142
const signer = getAccount(request.params.account);
132143
if (!signer) {
133144
throw new WalletConnectError(
134145
`Unknown account, no signer: ${request.params.account}`,
135-
"UNAUTHORIZED_EVENT",
146+
"INTERNAL_SIGNER_IS_MISSING",
136147
session
137148
);
138149
}
@@ -168,16 +179,17 @@ export const useHandleWcRequest = () => {
168179
modal = <BatchSignPage {...signProps} {...event.params.request.params} />;
169180
}
170181
onClose = () => {
171-
throw new WalletConnectError("Rejected by user", "USER_REJECTED", session);
182+
handleUserRejected();
172183
};
173184

174185
return openWith(modal, { onClose });
175186
}
176187
default:
177188
throw new WalletConnectError(
178189
`Unsupported method ${request.method}`,
179-
"WC_METHOD_UNSUPPORTED",
180-
session
190+
"METHOD_UNSUPPORTED",
191+
session,
192+
request.method
181193
);
182194
}
183195
});

packages/state/src/slices/errors.test.ts

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ describe("Errors reducer", () => {
2929
description: `error ${i}`,
3030
stacktrace: "stacktrace",
3131
technicalDetails: "technicalDetails",
32+
code: i,
3233
})
3334
);
3435
}

packages/test-utils/src/errorContext.ts

+2
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@ export const errorContext1 = {
22
timestamp: "2023-08-03T19:27:43.735Z",
33
description: "error1",
44
stacktrace: "stacktrace",
5+
code: 100,
56
technicalDetails: "technicalDetails",
67
};
78

89
export const errorContext2 = {
910
timestamp: "2023-08-03T20:21:58.395Z",
1011
description: "error1",
1112
stacktrace: "stacktrace",
13+
code: 200,
1214
technicalDetails: "technicalDetails",
1315
};

packages/utils/src/ErrorContext.test.ts

+83-14
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
import { CustomError, WalletConnectError, getErrorContext, handleTezError } from "./ErrorContext";
1+
import { TezosOperationError, type TezosOperationErrorWithMessage } from "@taquito/taquito";
2+
3+
import {
4+
CustomError,
5+
WalletConnectError,
6+
getTezErrorMessage,
7+
getErrorContext,
8+
getWcErrorResponse,
9+
} from "./ErrorContext";
210

311
describe("getErrorContext", () => {
412
it("should handle error object with message and stack", () => {
@@ -12,7 +20,7 @@ describe("getErrorContext", () => {
1220
expect(context.technicalDetails).toBe("some error message");
1321
expect(context.stacktrace).toBe("some stacktrace");
1422
expect(context.description).toBe(
15-
"Something went wrong. Please try again or contact support if the issue persists."
23+
"Something went wrong. Please try again. Contact support if the issue persists. Details: some error message"
1624
);
1725
expect(context.timestamp).toBeDefined();
1826
});
@@ -25,7 +33,7 @@ describe("getErrorContext", () => {
2533
expect(context.technicalDetails).toBe("string error message");
2634
expect(context.stacktrace).toBe("");
2735
expect(context.description).toBe(
28-
"Something went wrong. Please try again or contact support if the issue persists."
36+
"Something went wrong. Please try again. Contact support if the issue persists."
2937
);
3038
expect(context.timestamp).toBeDefined();
3139
});
@@ -48,53 +56,114 @@ describe("getErrorContext", () => {
4856

4957
const context = getErrorContext(error);
5058

51-
expect(context.technicalDetails).toBe("");
59+
expect(context.technicalDetails).toBeUndefined();
5260
expect(context.description).toBe("Custom error message");
5361
expect(context.stacktrace).toBeDefined();
5462
expect(context.timestamp).toBeDefined();
5563
});
5664
it("should handle WalletConnectError instances", () => {
57-
const error = new WalletConnectError("Custom WC error message", "UNSUPPORTED_EVENTS", null);
65+
const error = new WalletConnectError("Custom WC error message", "INTERNAL_ERROR", null);
5866

5967
const context = getErrorContext(error);
6068

61-
expect(context.technicalDetails).toBe("");
69+
expect(context.technicalDetails).toBeUndefined();
6270
expect(context.description).toBe("Custom WC error message");
6371
expect(context.stacktrace).toBeDefined();
6472
expect(context.timestamp).toBeDefined();
6573
});
6674
});
6775

68-
describe("handleTezError", () => {
76+
describe("getTezErrorMessage", () => {
6977
it("catches subtraction_underflow", () => {
70-
const res = handleTezError(new Error("subtraction_underflow"));
78+
const res = getTezErrorMessage("subtraction_underflow");
7179
expect(res).toBe("Insufficient balance, please make sure you have enough funds.");
7280
});
7381

7482
it("catches non_existing_contract", () => {
75-
const res = handleTezError(new Error("contract.non_existing_contract"));
83+
const res = getTezErrorMessage("contract.non_existing_contract");
7684
expect(res).toBe("Contract does not exist, please check if the correct network is selected.");
7785
});
7886

7987
it("catches staking_to_delegate_that_refuses_external_staking", () => {
80-
const res = handleTezError(new Error("staking_to_delegate_that_refuses_external_staking"));
88+
const res = getTezErrorMessage("staking_to_delegate_that_refuses_external_staking");
8189
expect(res).toBe("The baker you are trying to stake to does not accept external staking.");
8290
});
8391

8492
it("catches empty_implicit_delegated_contract", () => {
85-
const res = handleTezError(new Error("empty_implicit_delegated_contract"));
93+
const res = getTezErrorMessage("empty_implicit_delegated_contract");
8694
expect(res).toBe(
8795
"Emptying an implicit delegated account is not allowed. End delegation before trying again."
8896
);
8997
});
9098

9199
it("catches delegate.unchanged", () => {
92-
const res = handleTezError(new Error("delegate.unchanged"));
100+
const res = getTezErrorMessage("delegate.unchanged");
93101
expect(res).toBe("The delegate is unchanged. Delegation to this address is already done.");
94102
});
95103

104+
it("catches contract.manager.unregistered_delegate", () => {
105+
const res = getTezErrorMessage("contract.manager.unregistered_delegate");
106+
expect(res).toBe(
107+
"The provided delegate address is not registered as a delegate. Verify the delegate address and ensure it is active."
108+
);
109+
});
110+
96111
it("returns undefined for unknown errors", () => {
97-
const err = new Error("unknown error");
98-
expect(handleTezError(err)).toBeUndefined();
112+
const err = "unknown error";
113+
expect(getTezErrorMessage(err)).toBeUndefined();
114+
});
115+
116+
it("should return default error message for unknown error", () => {
117+
const error = new Error("Unknown error");
118+
const context = getErrorContext(error);
119+
expect(context.description).toBe(
120+
"Something went wrong. Please try again. Contact support if the issue persists. Details: Unknown error"
121+
);
122+
});
123+
124+
it("should return custom error message for CustomError", () => {
125+
const error = new CustomError("Custom error message");
126+
const context = getErrorContext(error);
127+
expect(context.description).toBe("Custom error message");
128+
});
129+
130+
it("should return WalletConnectError message", () => {
131+
const error = new WalletConnectError("WC error custom text", "INTERNAL_ERROR", null);
132+
const context = getErrorContext(error);
133+
expect(context.description).toBe("WC error custom text");
134+
expect(context.code).toBe(4011);
135+
expect(context.technicalDetails).toBeUndefined();
136+
});
137+
138+
it("should return TezosOperationError message", () => {
139+
// const error = new TezosOperationError(errors:[], lastError: { id: 'michelson_v1.script_rejected', with: { prim: 'Unit' } });
140+
const mockError: TezosOperationErrorWithMessage = {
141+
kind: "temporary",
142+
id: "proto.020-PsParisC.michelson_v1.script_rejected",
143+
with: { string: "Fail entrypoint" }, // Include the `with` field for testing
144+
};
145+
const error = new TezosOperationError(
146+
[mockError],
147+
"Operation failed due to a rejected script.",
148+
[]
149+
);
150+
const context = getErrorContext(error);
151+
expect(context.description).toContain(
152+
"Rejected by chain. The contract code failed to run. Please check the contract. Details: Fail entrypoint"
153+
);
154+
expect(context.technicalDetails).toEqual([
155+
"proto.020-PsParisC.michelson_v1.script_rejected",
156+
{ with: { string: "Fail entrypoint" } },
157+
]);
158+
});
159+
160+
it("should return error response for getWcErrorResponse", () => {
161+
const error = new Error("Unknown error");
162+
const response = getWcErrorResponse(error);
163+
expect(response.message).toBe(
164+
"Something went wrong. Please try again. Contact support if the issue persists. Details: Unknown error"
165+
);
166+
expect(response.code).toBe(4011);
167+
expect(response.data).toBe("Unknown error");
99168
});
100169
});

0 commit comments

Comments
 (0)