/
bityProvider.ts
608 lines (558 loc) · 19.2 KB
/
bityProvider.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
import { lt, toFixed } from 'biggystring'
import { asArray, asEither, asMaybe, asNumber, asObject, asString, asValue } from 'cleaners'
import { EdgeCurrencyWallet, EdgeSpendInfo } from 'edge-core-js'
import { sprintf } from 'sprintf-js'
import { lstrings } from '../../../locales/strings'
import { HomeAddress, SepaInfo } from '../../../types/FormTypes'
import { StringMap } from '../../../types/types'
import { FiatPaymentType, FiatPluginUi } from '../fiatPluginTypes'
import {
FiatProvider,
FiatProviderApproveQuoteParams,
FiatProviderAssetMap,
FiatProviderError,
FiatProviderFactory,
FiatProviderFactoryParams,
FiatProviderGetQuoteParams,
FiatProviderQuote
} from '../fiatProviderTypes'
const providerId = 'bity'
const storeId = 'com.bity'
const partnerIcon = 'logoBity.png'
const pluginDisplayName = 'Bity'
const supportedPaymentType: FiatPaymentType = 'sepa'
const partnerFee = 0.005
const allowedCurrencyCodes: FiatProviderAssetMap = { crypto: {}, fiat: {} }
const allowedCountryCodes: { readonly [code: string]: boolean } = {
AT: true,
BE: true,
BG: true,
CH: true,
CZ: true,
DK: true,
EE: true,
FI: true,
FR: true,
DE: true,
GR: true,
HU: true,
IT: true,
LV: true,
LT: true,
LU: true,
NL: true,
PL: true,
PT: true,
RO: true,
SK: true,
SI: true,
ES: true,
SE: true,
HR: true,
LI: true,
NO: true,
SM: true,
GB: true
}
const CURRENCY_PLUGINID_MAP: StringMap = {
BTC: 'bitcoin',
ETH: 'ethereum',
LTC: 'litecoin'
}
const EDGE_CLIENT_ID = '4949bf59-c23c-4d71-949e-f5fd56ff815b'
const asBityApiKeys = asObject({
clientId: asMaybe(asString, EDGE_CLIENT_ID)
})
const asBityCurrencyTag = asValue('crypto', 'erc20', 'ethereum', 'fiat')
const asBityCurrency = asObject({
tags: asArray(asBityCurrencyTag),
code: asString,
max_digits_in_decimal_part: asNumber
})
const asBityCurrencyResponse = asObject({ currencies: asArray(asBityCurrency) })
export type BityCurrency = ReturnType<typeof asBityCurrency>
export type BityCurrencyTag = ReturnType<typeof asBityCurrencyTag>
interface BityQuoteRequest {
input: {
amount?: string
currency: string
}
output: {
amount?: string
currency: string
}
}
interface BityBuyOrderRequest {
client_value: number
input: {
amount: string
currency: string
type: 'bank_account'
iban: string
bic_swift: string
}
output: {
currency: string
type: 'crypto_address'
crypto_address: string
}
partner_fee: { factor: number }
}
interface BitySellOrderRequest {
client_value: number
input: {
amount: string
currency: string
type: 'crypto_address'
crypto_address: string
}
output: {
currency: string
type: 'bank_account'
iban: string
bic_swift: string
owner: {
name: string
address: string
address_complement?: string
city: string
country: string
state: string
zip: string
}
}
partner_fee: { factor: number }
}
const asBitySellApproveQuoteResponse = asObject({
id: asString,
input: asObject({
amount: asString,
currency: asString,
crypto_address: asString
}),
output: asObject({
amount: asString,
currency: asString
}),
payment_details: asObject({
crypto_address: asString,
type: asValue('crypto_address')
})
})
const asBityBuyApproveQuoteResponse = asObject({
id: asString,
input: asObject({
amount: asString,
currency: asString
}),
output: asObject({
amount: asString,
currency: asString,
crypto_address: asString
}),
payment_details: asObject({
iban: asString,
swift_bic: asString,
reference: asString,
recipient_name: asString,
recipient: asString
})
})
const asBityApproveQuoteResponse = asEither(asBityBuyApproveQuoteResponse, asBitySellApproveQuoteResponse)
type BityApproveQuoteResponse = ReturnType<typeof asBityApproveQuoteResponse>
const fetchBityQuote = async (bodyData: BityQuoteRequest) => {
const request = {
method: 'POST',
headers: {
Host: 'exchange.api.bity.com',
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyData)
}
const result = await fetch('https://exchange.api.bity.com/v2/orders/estimate', request)
if (result.ok) {
const newData = await result.json()
return newData
} else {
throw new Error('Bity: Unable to fetch quote: ' + (await result.text()))
}
}
const approveBityQuote = async (
wallet: EdgeCurrencyWallet,
data: BityBuyOrderRequest | BitySellOrderRequest,
clientId: string
): Promise<BityApproveQuoteResponse> => {
const baseUrl = 'https://exchange.api.bity.com'
const orderUrl = 'https://exchange.api.bity.com/v2/orders'
const orderReq: RequestInit = {
method: 'POST',
headers: {
Host: 'exchange.api.bity.com',
Accept: 'application/json',
'Content-Type': 'application/json',
'Client-Id': clientId
},
credentials: 'include',
body: JSON.stringify(data)
}
const orderRes = await fetch(orderUrl, orderReq)
if (orderRes.status !== 201) {
const errorData = await orderRes.json()
throw new Error(errorData.errors[0].code + ' ' + errorData.errors[0].message)
}
// "location": "https://...bity.com/v2/orders/[orderid]"
const locationHeader = orderRes.headers.get('Location')
const locationUrl = baseUrl + locationHeader
const locationReq: RequestInit = {
method: 'GET',
credentials: 'include'
}
const locationRes = await fetch(locationUrl, locationReq)
if (locationRes.status !== 200) {
console.error(JSON.stringify({ locationRes }, null, 2))
throw new Error('Problem confirming order: Code n200')
}
const orderData = await locationRes.json()
if (orderData.message_to_sign != null) {
const { body } = orderData.message_to_sign
const { publicAddress } = await wallet.getReceiveAddress()
const signedMessage = await wallet.signMessage(body, { otherParams: { publicAddress } })
const signUrl = baseUrl + orderData.message_to_sign.signature_submission_url
const request = {
method: 'POST',
headers: {
Host: 'exchange.api.bity.com',
'Content-Type': '*/*'
},
body: signedMessage
}
const signedTransactionResponse = await fetch(signUrl, request)
if (signedTransactionResponse.status === 400) {
throw new Error('Could not complete transaction. Code: 400')
}
if (signedTransactionResponse.status === 204) {
const bankDetailsReq = {
method: 'GET',
credentials: 'include'
}
const detailUrl = orderUrl + '/' + orderData.id
// @ts-expect-error
const bankDetailRes = await fetch(detailUrl, bankDetailsReq)
if (bankDetailRes.status === 200) {
const bankDetailResJson = await bankDetailRes.json()
return asBityApproveQuoteResponse(bankDetailResJson)
}
}
}
return asBityApproveQuoteResponse(orderData)
}
export const bityProvider: FiatProviderFactory = {
providerId,
storeId,
makeProvider: async (params: FiatProviderFactoryParams): Promise<FiatProvider> => {
const { apiKeys } = params
const clientId = asBityApiKeys(apiKeys).clientId
const out = {
providerId,
partnerIcon,
pluginDisplayName,
getSupportedAssets: async (paymentTypes: FiatPaymentType[]): Promise<FiatProviderAssetMap> => {
// Return nothing if 'sepa' is not included in the props
if (!paymentTypes.includes(supportedPaymentType)) return { crypto: {}, fiat: {} }
const response = await fetch(`https://exchange.api.bity.com/v2/currencies`).catch(e => undefined)
if (response == null || !response.ok) {
console.error(`Bity getSupportedAssets response error: ${await response?.text()}`)
return allowedCurrencyCodes
}
const result = await response.json()
let bityCurrencies: BityCurrency[] = []
try {
bityCurrencies = asBityCurrencyResponse(result).currencies
} catch (error: any) {
console.error(error)
return allowedCurrencyCodes
}
for (const currency of bityCurrencies) {
let isAddCurrencySuccess = false
if (currency.tags.length === 1 && currency.tags[0] === 'fiat') {
allowedCurrencyCodes.fiat['iso:' + currency.code.toUpperCase()] = currency
isAddCurrencySuccess = true
} else if (currency.tags.includes('crypto')) {
// Bity reports cryptos with a set of multiple tags such that there is
// overlap, such as USDC being 'crypto', 'ethereum', 'erc20'.
if (currency.tags.includes('erc20') && currency.tags.includes('ethereum')) {
// ETH tokens
addToAllowedCurrencies('ethereum', currency, currency.code)
isAddCurrencySuccess = true
} else if (Object.keys(CURRENCY_PLUGINID_MAP).includes(currency.code)) {
// Mainnet currencies
addToAllowedCurrencies(CURRENCY_PLUGINID_MAP[currency.code], currency, currency.code)
isAddCurrencySuccess = true
}
}
// Unhandled combination not caught by cleaner. Skip to be safe.
if (!isAddCurrencySuccess) console.log('Unhandled Bity supported currency: ', currency)
}
return allowedCurrencyCodes
},
getQuote: async (params: FiatProviderGetQuoteParams): Promise<FiatProviderQuote> => {
const {
amountType, // input amount type - fiat | crypto
direction,
exchangeAmount,
fiatCurrencyCode,
paymentTypes,
regionCode,
pluginId,
displayCurrencyCode
} = params
const isBuy = direction === 'buy'
if (!allowedCountryCodes[regionCode.countryCode]) throw new FiatProviderError({ errorType: 'regionRestricted', displayCurrencyCode })
if (!paymentTypes.includes(supportedPaymentType)) throw new FiatProviderError({ errorType: 'paymentUnsupported' })
const cryptoCurrencyObj = asBityCurrency(allowedCurrencyCodes.crypto[pluginId][displayCurrencyCode])
const fiatCurrencyObj = asBityCurrency(allowedCurrencyCodes.fiat[fiatCurrencyCode])
if (cryptoCurrencyObj == null || fiatCurrencyObj == null) throw new Error('Bity: Could not query supported currencies')
const cryptoCode = cryptoCurrencyObj.code
const fiatCode = fiatCurrencyObj.code
const inputCurrencyCode = isBuy ? fiatCode : cryptoCode
const outputCurrencyCode = isBuy ? cryptoCode : fiatCode
const amountPrecision = amountType === 'fiat' ? fiatCurrencyObj.max_digits_in_decimal_part : cryptoCurrencyObj.max_digits_in_decimal_part
const amount = toFixed(exchangeAmount, amountPrecision)
const isReverseQuote = (isBuy && amountType === 'crypto') || (!isBuy && amountType === 'fiat')
const quoteRequest: BityQuoteRequest = {
input: {
amount: isReverseQuote ? undefined : amount,
currency: inputCurrencyCode
},
output: {
amount: isReverseQuote ? amount : undefined,
currency: outputCurrencyCode
}
}
const bityQuote = await fetchBityQuote(quoteRequest)
console.log('Got Bity quote:\n', JSON.stringify(bityQuote, null, 2))
const minimumAmount = isReverseQuote ? bityQuote.output.minimum_amount : bityQuote.input.minimum_amount
if (lt(amount, minimumAmount)) {
throw new FiatProviderError({
// TODO: direction,
errorType: 'underLimit',
errorAmount: parseFloat(minimumAmount)
})
}
const paymentQuote: FiatProviderQuote = {
providerId,
partnerIcon,
regionCode,
paymentTypes,
pluginDisplayName,
displayCurrencyCode: params.displayCurrencyCode,
isEstimate: false,
fiatCurrencyCode: params.fiatCurrencyCode,
fiatAmount: isBuy ? bityQuote.input.amount : bityQuote.output.amount,
cryptoAmount: isBuy ? bityQuote.output.amount : bityQuote.input.amount,
direction: params.direction,
expirationDate: new Date(Date.now() + 50000),
approveQuote: async (approveParams: FiatProviderApproveQuoteParams): Promise<void> => {
const { coreWallet, showUi } = approveParams
// Either input or output always require SEPA info, depending on if
// input or output are of type 'bank_account'.
// Bity only checks SEPA info format validity.
// Home address and KYC is only required for sell.
const cryptoAddress = (await coreWallet.getReceiveAddress()).publicAddress
await showUi.sepaForm({
headerTitle: lstrings.sepa_form_title,
onSubmit: async (sepaInfo: SepaInfo) => {
let approveQuoteRes: BityApproveQuoteResponse | null = null
try {
if (isBuy) {
approveQuoteRes = await executeBuyOrderFetch(coreWallet, bityQuote, fiatCode, sepaInfo, outputCurrencyCode, cryptoAddress, clientId)
} else {
// Sell approval - Needs extra address input step
await showUi.addressForm({
countryCode: regionCode.countryCode,
headerTitle: lstrings.home_address_title,
onSubmit: async (homeAddress: HomeAddress) => {
approveQuoteRes = await executeSellOrderFetch(
coreWallet,
bityQuote,
inputCurrencyCode,
cryptoAddress,
outputCurrencyCode,
sepaInfo,
homeAddress,
clientId
)
}
})
}
} catch (e) {
// TODO: Post-fiat-plugin-router implementation:
// Route to the appropriate scene where the user needs to fix
// their personal info depending on what was wrong with the
// order, i.e. invalid bank or address info.
console.error('Bity order error: ', e)
}
if (approveQuoteRes == null) {
return
}
if (isBuy) {
await completeBuyOrder(approveQuoteRes, showUi)
} else {
await completeSellOrder(approveQuoteRes, coreWallet, showUi)
}
showUi.exitScene()
}
})
},
closeQuote: async (): Promise<void> => {}
}
return paymentQuote
}
}
return out
}
}
const addToAllowedCurrencies = (pluginId: string, currency: BityCurrency, currencyCode: string) => {
if (allowedCurrencyCodes.crypto[pluginId] == null) allowedCurrencyCodes.crypto[pluginId] = {}
allowedCurrencyCodes.crypto[pluginId][currencyCode] = currency
}
/**
* Transition to the send scene pre-populted with the payment address from the
* previously opened/approved sell order
*/
const completeSellOrder = async (approveQuoteRes: BityApproveQuoteResponse, coreWallet: EdgeCurrencyWallet, showUi: FiatPluginUi) => {
const { input, id, payment_details: paymentDetails } = asBitySellApproveQuoteResponse(approveQuoteRes)
const { amount: inputAmount, currency: inputCurrencyCode } = input
const nativeAmount = await coreWallet.denominationToNative(inputAmount, inputCurrencyCode)
if (nativeAmount == null) {
// Should not happen - input currencies should be valid before
// getting here.
throw new Error('Bity: Could not find input denomination: ' + inputCurrencyCode)
}
const spendInfo: EdgeSpendInfo = {
currencyCode: inputCurrencyCode,
spendTargets: [
{
nativeAmount,
publicAddress: paymentDetails.crypto_address
}
],
metadata: {
category: `Exchange: ${inputCurrencyCode} to EUR`,
notes: `${pluginDisplayName} ${lstrings.transaction_details_exchange_order_id}: ${id}`
}
}
await showUi.send({ walletId: coreWallet.id, spendInfo })
}
/**
* Transition to the transfer scene to display the bank transfer information
* from the previously opened/approved buy order
*/
const completeBuyOrder = async (approveQuoteRes: BityApproveQuoteResponse, showUi: FiatPluginUi) => {
const { input, output, id, payment_details: paymentDetails } = asBityBuyApproveQuoteResponse(approveQuoteRes)
const { iban, swift_bic: swiftBic, recipient, reference } = paymentDetails
await showUi.sepaTransferInfo({
headerTitle: lstrings.payment_details,
promptMessage: sprintf(lstrings.sepa_transfer_prompt_s, id),
transferInfo: {
input: {
amount: input.amount,
currency: input.currency
},
output: {
amount: output.amount,
currency: output.currency,
walletAddress: output.crypto_address
},
paymentDetails: {
id: id,
iban: iban,
swiftBic: swiftBic,
recipient: recipient,
reference: reference
}
},
onDone: async () => {
showUi.exitScene()
}
})
}
/**
* Physically opens the sell order, resulting in payment information detailing
* where to send crypto (payment address) in order to complete the order.
*/
const executeSellOrderFetch = async (
coreWallet: EdgeCurrencyWallet,
bityQuote: any,
inputCurrencyCode: string,
cryptoAddress: string,
outputCurrencyCode: string,
sepaInfo: { name: string; iban: string; swift: string },
homeAddress: { address: string; address2: string | undefined; city: string; country: string; state: string; postalCode: string },
clientId: string
): Promise<BityApproveQuoteResponse | null> => {
return await approveBityQuote(
coreWallet,
{
client_value: 0,
input: {
amount: bityQuote.input.amount,
currency: inputCurrencyCode,
type: 'crypto_address',
crypto_address: cryptoAddress
},
output: {
currency: outputCurrencyCode,
type: 'bank_account',
iban: sepaInfo.iban,
bic_swift: sepaInfo.swift,
owner: {
name: sepaInfo.name,
address: homeAddress.address,
address_complement: homeAddress.address2,
city: homeAddress.city,
state: homeAddress.state,
zip: homeAddress.postalCode,
country: homeAddress.country
}
},
partner_fee: { factor: partnerFee }
},
clientId
)
}
/**
* Physically opens the buy order, resulting in payment information detailing
* where to send fiat (bank details) in order to complete the order.
*/
const executeBuyOrderFetch = async (
coreWallet: EdgeCurrencyWallet,
bityQuote: any,
fiatCode: string,
sepaInfo: { name: string; iban: string; swift: string },
outputCurrencyCode: string,
cryptoAddress: string,
clientId: string
): Promise<BityApproveQuoteResponse | null> => {
return await approveBityQuote(
coreWallet,
{
client_value: 0,
input: {
amount: bityQuote.input.amount,
currency: fiatCode,
type: 'bank_account',
iban: sepaInfo.iban,
bic_swift: sepaInfo.swift
},
output: {
currency: outputCurrencyCode,
type: 'crypto_address',
crypto_address: cryptoAddress
},
partner_fee: { factor: partnerFee }
},
clientId
)
}