-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathCoinbase.swift
More file actions
309 lines (261 loc) · 9.45 KB
/
Coinbase.swift
File metadata and controls
309 lines (261 loc) · 9.45 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//
// Created by tkhp
// Copyright © 2022 Dash Core Group. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import AuthenticationServices
import Combine
import Foundation
let kDashAccount = "DASH"
let kCoinbaseContactURL = URL(string: "https://help.coinbase.com/en/contact-us")!
let kCoinbaseAddPaymentMethodsURL = URL(string: "https://www.coinbase.com/settings/linked-accounts")!
let kCoinbaseFeeInfoURL = URL(string: "https://help.coinbase.com/en/coinbase/trading-and-funding/pricing-and-fees/fees")!
let kMaxDashAmountToTransfer: UInt64 = kOneDash
let kMinUSDAmountOrder: Decimal = 1.99
let kMinDashAmountToTransfer: UInt64 = 10_000
// MARK: - CoinbaseObjcWrapper
@objc
class CoinbaseObjcWrapper: NSObject {
private static var wrapped = Coinbase.shared
@objc
static func start() {
wrapped.initialize()
}
@objc
static func reset() {
wrapped.reset()
}
}
// MARK: - Coinbase
class Coinbase {
public var currencyExchanger: CurrencyExchanger = .init(dataProvider: CoinbaseRatesProvider())
private lazy var coinbaseService = CoinbaseService()
private var auth: CBAuth!
private var accountService: AccountService!
private var paymentMethodsService: PaymentMethods!
func initialize() {
CoinbaseAPI.initialize(with: self)
auth = CBAuth()
accountService = AccountService(authInterop: auth)
paymentMethodsService = PaymentMethods(authInterop: auth)
currencyExchanger.startExchangeRateFetching()
prefetchData()
}
func reset() {
Task {
try await signOut()
}
}
private func prefetchData() {
Task {
try await accountService.refreshAccount(kDashAccount)
_ = try await paymentMethodsService.fetchPaymentMethods()
}
}
static func initialize() {
shared.initialize()
}
public static let shared = Coinbase()
}
extension Coinbase {
var isAuthorized: Bool { auth.currentUser != nil }
var paymentMethods: [CoinbasePaymentMethod] {
get async throws {
try await paymentMethodsService.fetchPaymentMethods()
}
}
var lastKnownBalance: UInt64? {
dashAccount?.balance
}
var sendLimit: Decimal {
auth.currentUser?.sendLimit ?? Coinbase.sendLimitAmount
}
var dashAccount: CBAccount? {
accountService.dashAccount
}
public func getUsdAccount() async -> CBAccount? {
do {
return try await accountService.account(by: Coinbase.defaultFiat)
} catch {
return nil
}
}
}
extension Coinbase {
@MainActor
public func signIn(with presentationContext: ASWebAuthenticationPresentationContextProviding) async throws {
try await auth.signIn(with: presentationContext)
try await accountService.refreshAccount(kDashAccount)
}
public func createNewCoinbaseDashAddress() async throws -> String {
do {
let address = try await accountService.retrieveAddress(for: kDashAccount)
Taxes.shared.mark(address: address, with: .transferOut)
return address
} catch Coinbase.Error.userSessionRevoked {
try await auth.signOut()
throw Coinbase.Error.userSessionRevoked
} catch {
throw error
}
}
public func getDashExchangeRate() async throws -> CoinbaseExchangeRate? {
do {
return try await coinbaseService.getCoinbaseExchangeRates(currency: kDashCurrency)
} catch Coinbase.Error.userSessionRevoked {
try await auth.signOut()
throw Coinbase.Error.userSessionRevoked
} catch {
throw error
}
}
public func transferFromCoinbaseToDashWallet(amount: UInt64,
verificationCode: String?,
idem: UUID?) async throws -> CoinbaseTransaction {
do {
let tx = try await accountService.send(from: kDashAccount, amount: amount, verificationCode: verificationCode, idem: idem)
if let address = tx.to?.address {
Taxes.shared.mark(address: address, with: .transferIn)
}
return tx
} catch Coinbase.Error.userSessionRevoked {
try await auth.signOut()
throw Coinbase.Error.userSessionRevoked
} catch {
throw error
}
}
/// Place Buy Order
///
/// - Parameters:
/// - amount: Plain amount in Dash
///
/// - Returns: CoinbasePlaceBuyOrder
///
/// - Throws: Coinbase.Error
///
func placeCoinbaseBuyOrder(amount: UInt64) async throws -> CoinbasePlaceBuyOrder {
do {
return try await accountService.placeBuyOrder(for: kDashAccount, amount: amount)
} catch Coinbase.Error.userSessionRevoked {
try await auth.signOut()
throw Coinbase.Error.userSessionRevoked
}
}
/// Deposit to the fiat account
///
/// - Parameters:
/// - paymentMethodId: Id of the payment method with which to make the deposit
/// - amount: Plain amount in Dash
///
/// - Throws: Coinbase.Error
///
func depositToFiatAccount(from paymentMethodId: String, amount: UInt64) async throws {
do {
try await accountService.deposit(to: Coinbase.defaultFiat, from: paymentMethodId, amount: amount)
} catch Coinbase.Error.userSessionRevoked {
try await auth.signOut()
throw Coinbase.Error.userSessionRevoked
}
}
/// Place trade order
///
/// This method creates an on order to trade between accounts
///
/// - Parameters:
/// - origin: Account we use to covert from
/// - destination: Account we use to convert to
/// - amount: Plain amount in crypto. The amount should be in the same currency as origin's account currency
///
/// - Returns: Order `CoinbaseSwapeTrade`
///
/// - Throws: `Coinbase.Error`
///
///
func placeTradeOrder(from origin: CBAccount, to destination: CBAccount, amount: String) async throws -> CoinbaseSwapeTrade {
do {
return try await accountService.placeTradeOrder(from: origin, to: destination, amount: amount)
} catch Coinbase.Error.userSessionRevoked {
try await auth.signOut()
throw Coinbase.Error.userSessionRevoked
} catch {
throw error
}
}
/// Commit Trade Order
///
/// - Parameters:
/// - origin: Instance of `CBAccount` you used in `placeTradeOrder` method to convert from
/// - orderID: Order id from `CoinbaseSwapeTrade` you receive by calling `placeTradeOrder`
///
/// - Returns: CoinbasePlaceBuyOrder
///
/// - Throws: Coinbase.Error
///
func commitTradeOrder(origin: CBAccount, orderID: String) async throws -> CoinbaseSwapeTrade {
do {
return try await accountService.commitTradeOrder(origin: origin, orderID: orderID)
} catch Coinbase.Error.userSessionRevoked {
try await auth.signOut()
throw Coinbase.Error.userSessionRevoked
} catch {
throw error
}
}
public func signOut() async throws {
guard isAuthorized else {
return
}
try await auth.signOut()
accountService.removeStoredAccount()
}
public func accounts() async throws -> [CBAccount] {
try await accountService.allAccounts()
}
/// Returns all crypto accounts regardless of balance.
/// Used by Maya to find accounts for currencies with zero balance.
public func accountsIncludingEmpty() async throws -> [CBAccount] {
try await accountService.allAccountsIncludingEmpty()
}
/// Fetches a specific account by currency code (e.g., "BTC", "ETH").
/// Uses direct `GET /v2/accounts/{currencyCode}` lookup which is more reliable
/// than listing all accounts when you know the currency you need.
public func account(byCurrencyCode currencyCode: String) async throws -> CBAccount {
try await accountService.account(by: currencyCode)
}
public func addUserDidChangeListener(_ listener: @escaping UserDidChangeListenerBlock) -> UserDidChangeListenerHandle {
auth.addUserDidChangeListener(listener)
}
public func removeUserDidChangeListener(handle: UserDidChangeListenerHandle) {
auth.removeUserDidChangeListener(handle: handle)
}
}
extension String {
func coinbaseAmount() -> String {
let locale = Locale(identifier: "en_US")
guard locale.decimalSeparator != Locale.current.decimalSeparator else {
return self
}
return localizedAmount(locale: locale)
}
}
// MARK: - Coinbase + CoinbaseAPIAccessTokenProvider
extension Coinbase: CoinbaseAPIAccessTokenProvider {
var accessToken: String? {
auth.accessToken
}
func refreshTokenIfNeeded() async throws {
try await auth.refreshTokenIfNeeded()
}
}