forked from MetaMask/metamask-ios-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwitchChainView.swift
205 lines (185 loc) · 6.54 KB
/
SwitchChainView.swift
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//
// SwitchChainView.swift
// metamask-ios-sdk_Example
//
import SwiftUI
import Combine
import metamask_ios_sdk
@MainActor
struct SwitchChainView: View {
@Environment(\.presentationMode) var presentationMode
@EnvironmentObject var metamaskSDK: MetaMaskSDK
@State private var alert: AlertInfo?
@State var networkSelection: Network = .polygon
struct AlertInfo: Identifiable {
enum Status {
case error
case success
case chainDoesNotExist
}
let id: Status
let title: String
let message: String
var primaryButton: Alert.Button?
var secondarButton: Alert.Button?
var dismissButton: Alert.Button?
}
enum Network: String, CaseIterable, Identifiable {
case avalanche = "0xa86a"
case ethereum = "0x1"
case polygon = "0x89"
var id: Self { self }
var chainId: String {
rawValue
}
var name: String {
switch self {
case .polygon: return "Polygon"
case .ethereum: return "Ethereum"
case .avalanche: return "Avalanche"
}
}
var symbol: String {
switch self {
case .polygon: return "MATIC"
case .ethereum: return "ETH"
case .avalanche: return "AVAX"
}
}
var rpcUrls: [String] {
switch self {
case .polygon: return ["https://polygon-rpc.com"]
case .avalanche: return ["https://api.avax.network/ext/bc/C/rpc"]
default: return []
}
}
static func chain(for chainId: String) -> String {
self.allCases.first(where: { $0.rawValue == chainId })?.name ?? ""
}
}
var body: some View {
Form {
Section {
HStack {
Text("Current chain:")
.modifier(TextCallout())
Spacer()
Text("\(Network.chain(for: metamaskSDK.chainId)) (\(metamaskSDK.chainId))")
.modifier(TextCalloutLight())
}
Picker("Switch to:", selection: $networkSelection) {
ForEach(Network.allCases) { network in
Text("\(network.name)")
}
}
}
Section {
Button {
Task {
await switchEthereumChain()
}
} label: {
Text("Switch Chain ID")
.modifier(TextButton())
.frame(maxWidth: .infinity, maxHeight: 32)
}
.alert(item: $alert, content: { info in
if info.dismissButton != nil {
return Alert(
title: Text(info.title),
message: Text(info.message),
dismissButton: info.dismissButton
)
} else {
return Alert(
title: Text(info.title),
message: Text(info.message),
primaryButton: info.primaryButton!,
secondaryButton: info.secondarButton!
)
}
})
.modifier(ButtonStyle())
}
}
.onAppear {
networkSelection = metamaskSDK.chainId == networkSelection.rawValue
? .ethereum
: .polygon
}
.background(Color.blue.grayscale(0.5))
}
func switchEthereumChain() async {
let switchChainResult = await metamaskSDK.switchEthereumChain(chainId: networkSelection
.chainId)
switch switchChainResult {
case .success:
alert = AlertInfo(
id: .success,
title: "Success",
message: "Successfully switched to \(networkSelection.name)",
dismissButton: SwiftUI.Alert.Button.default(Text("OK"), action: {
presentationMode.wrappedValue.dismiss()
})
)
case let .failure(error):
if error.codeType == .unrecognizedChainId || error.codeType == .serverError {
alert = AlertInfo(
id: .chainDoesNotExist,
title: "Error",
message: "\(networkSelection.name) (\(networkSelection.chainId)) has not been added to your MetaMask wallet. Add chain?",
primaryButton: SwiftUI.Alert.Button.default(Text("OK"), action: {
Task {
await addEthereumChain()
}
}),
secondarButton: SwiftUI.Alert.Button.default(Text("Cancel"))
)
} else {
alert = AlertInfo(
id: .error,
title: "Error",
message: error.localizedDescription,
dismissButton: SwiftUI.Alert.Button.default(Text("OK"))
)
}
}
}
func addEthereumChain() async {
let addChainResult = await metamaskSDK.addEthereumChain(
chainId: networkSelection.chainId,
chainName: networkSelection.name,
rpcUrls: networkSelection.rpcUrls,
iconUrls: [],
blockExplorerUrls: nil,
nativeCurrency: NativeCurrency(
name: networkSelection.name,
symbol: networkSelection.symbol,
decimals: 18)
)
switch addChainResult {
case .success:
alert = AlertInfo(
id: .success,
title: "Success",
message: metamaskSDK.chainId == networkSelection.chainId
? "Successfully switched to \(networkSelection.name)"
: "Successfully added \(networkSelection.name)",
dismissButton: SwiftUI.Alert.Button.default(Text("OK"), action: {
presentationMode.wrappedValue.dismiss()
})
)
case let .failure(error):
alert = AlertInfo(
id: .error,
title: "Error",
message: error.localizedDescription
)
}
}
}
struct SwitchChainView_Previews: PreviewProvider {
static var previews: some View {
SwitchChainView()
}
}