-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathaddStarknetChain.ts
85 lines (74 loc) · 2.15 KB
/
addStarknetChain.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { Address } from "@argent/x-shared"
import type { AddStarknetChainParameters } from "@starknet-io/types-js"
import { AddStarknetChainParametersSchema } from "@argent/x-window"
import { ETH_TOKEN_ADDRESS } from "../../shared/network/constants"
import { sendMessage, waitForMessage } from "../messageActions"
import { WalletRPCError, WalletRPCErrorCodes } from "./errors"
export async function addStarknetChainHandler(
callParams: AddStarknetChainParameters,
): Promise<boolean> {
const {
chain_id,
chain_name,
id,
block_explorer_url,
native_currency,
rpc_urls,
} = AddStarknetChainParametersSchema.parse(callParams)
sendMessage({
type: "REQUEST_ADD_CUSTOM_NETWORK",
data: {
id,
name: chain_name,
chainId: chain_id,
rpcUrl: rpc_urls?.[0],
explorerUrl: block_explorer_url?.[0],
possibleFeeTokenAddresses: [
(native_currency?.options.address as Address) ?? ETH_TOKEN_ADDRESS,
],
},
})
const req = await Promise.race([
waitForMessage("REQUEST_ADD_CUSTOM_NETWORK_RES", 1000),
waitForMessage("REQUEST_ADD_CUSTOM_NETWORK_REJ", 1000),
])
if ("error" in req) {
throw Error(req.error)
}
const { exists, actionHash } = req
if (exists) {
// network already exists
return true
}
if (!actionHash) {
throw Error("Unexpected error: actionHash is undefined")
}
sendMessage({ type: "OPEN_UI" })
const result = await Promise.race([
waitForMessage(
"APPROVE_REQUEST_ADD_CUSTOM_NETWORK",
11 * 60 * 1000,
(x) => x.data.actionHash === actionHash,
),
waitForMessage(
"REJECT_REQUEST_ADD_CUSTOM_NETWORK",
10 * 60 * 1000,
(x) => x.data.actionHash === actionHash,
)
.then(() => "error" as const)
.catch(() => {
sendMessage({
type: "REJECT_REQUEST_ADD_CUSTOM_NETWORK",
data: { actionHash },
})
return "timeout" as const
}),
])
if (result === "error") {
throw new WalletRPCError({ code: WalletRPCErrorCodes.UserAborted })
}
if (result === "timeout") {
throw new WalletRPCError({ code: WalletRPCErrorCodes.Unknown })
}
return true
}