-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathbity.ts
More file actions
201 lines (177 loc) · 5.81 KB
/
bity.ts
File metadata and controls
201 lines (177 loc) · 5.81 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
import { asArray, asObject, asString, asUnknown } from 'cleaners'
import fetch from 'node-fetch'
import { PartnerPlugin, PluginParams, PluginResult, StandardTx } from '../types'
import { datelog, safeParseFloat } from '../util'
const asBityTx = asObject({
id: asString,
customer_trading_fee: asObject,
input: asObject({ currency: asString, amount: asString }),
output: asObject({ currency: asString, amount: asString }),
partner_fee: asObject,
profit_sharing: asObject,
'non-verified_fee': asObject,
timestamp_created: asString,
timestamp_executed: asString
})
const asBityResult = asArray(asUnknown)
const BITY_TOKEN_URL = 'https://connect.bity.com/oauth2/token'
const BITY_API_URL =
'https://reporting.api.bity.com/exchange/v1/summary/monthly/'
const PAGE_SIZE = 100
export async function queryBity(
pluginParams: PluginParams
): Promise<PluginResult> {
const standardTxs: StandardTx[] = []
let tokenParams
let credentials
let authToken
let queryYear = '2020'
let queryMonth = '01'
if (typeof pluginParams.settings.lastCheckedYear === 'string') {
queryYear = pluginParams.settings.lastCheckedYear
}
if (typeof pluginParams.settings.lastCheckedMonth === 'string') {
queryMonth = pluginParams.settings.lastCheckedMonth
}
if (
typeof pluginParams.apiKeys.clientId === 'string' &&
typeof pluginParams.apiKeys.clientSecret === 'string'
) {
credentials = {
grant_type: 'client_credentials',
scope: 'https://auth.bity.com/scopes/reporting.exchange',
client_id: pluginParams.apiKeys.clientId,
client_secret: pluginParams.apiKeys.clientSecret
}
tokenParams = Object.keys(credentials)
.map(key => {
return (
encodeURIComponent(key) + '=' + encodeURIComponent(credentials[key])
)
})
.join('&')
const tokenResponse = await fetch(BITY_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: tokenParams
})
const tokenReply = await tokenResponse.json()
authToken = tokenReply.access_token
} else {
return {
settings: { lastCheckedMonth: queryMonth, lastCheckedYear: queryYear },
transactions: []
}
}
let beforeCurrentMonth = true
const currentDate = new Date(Date.now())
let currentMonth = (currentDate.getMonth() + 1).toString()
currentMonth = currentMonth.length === 1 ? `0${currentMonth}` : currentMonth
let currentYear = currentDate.getFullYear().toString()
while (beforeCurrentMonth) {
if (queryMonth === currentMonth && queryYear === currentYear) {
beforeCurrentMonth = false
}
let moreCurrentMonthsTransactions = true
let page = 1
while (moreCurrentMonthsTransactions) {
let monthlyTxs
try {
const monthlyResponse = await fetch(
`${BITY_API_URL}${queryYear}-${queryMonth}/orders?page=${page}`,
{
method: 'GET',
headers: { Authorization: `Bearer ${authToken}` }
}
)
// june 2020 has exactly 300 transactions and it gives
// status: 404
// statusText: "Not Found"
// on page 4
if (monthlyResponse.ok) {
monthlyTxs = asBityResult(await monthlyResponse.json())
} else if (
monthlyResponse.status === 404 &&
monthlyResponse.statusText === 'Not Found'
) {
break
}
} catch (e) {
datelog(e)
throw e
}
for (const rawTx of monthlyTxs) {
const standardTx = processBityTx(rawTx)
standardTxs.push(standardTx)
}
moreCurrentMonthsTransactions = monthlyTxs.length === PAGE_SIZE
page++
}
queryMonth = (parseInt(queryMonth) + 1).toString()
queryMonth = queryMonth.length === 1 ? `0${queryMonth}` : queryMonth
if (queryMonth === '13') {
queryMonth = '01'
queryYear = (parseInt(queryYear) + 1).toString()
}
}
currentMonth = (parseInt(currentMonth) - 1).toString()
currentMonth = currentMonth.length === 1 ? `0${currentMonth}` : currentMonth
if (currentMonth === '00') {
currentMonth = '12'
currentYear = (parseInt(currentYear) - 1).toString()
}
return {
settings: { lastCheckedMonth: currentMonth, lastCheckedYear: currentYear },
transactions: standardTxs
}
}
export const bity: PartnerPlugin = {
// queryFunc will take PluginSettings as arg and return PluginResult
queryFunc: queryBity,
// results in a PluginResult
pluginName: 'Bity',
pluginId: 'bity'
}
export function processBityTx(rawTx: unknown): StandardTx {
const tx = asBityTx(rawTx)
// Assume that one currency is EUR and that's the only fiat currency supported
// by Bity.
if (
tx.input.currency.toUpperCase() !== 'EUR' &&
tx.output.currency.toUpperCase() !== 'EUR'
) {
throw new Error(
`Unknown fiat currency ${tx.input.currency} or ${tx.output.currency}`
)
}
const direction = tx.input.currency.toUpperCase() === 'EUR' ? 'buy' : 'sell'
const standardTx: StandardTx = {
status: 'complete',
orderId: tx.id,
countryCode: null,
depositTxid: undefined,
depositAddress: undefined,
depositCurrency: tx.input.currency.toUpperCase(),
depositChainPluginId: undefined,
depositEvmChainId: undefined,
depositTokenId: undefined,
depositAmount: safeParseFloat(tx.input.amount),
direction,
exchangeType: 'fiat',
paymentType: 'sepa',
payoutTxid: undefined,
payoutAddress: undefined,
payoutCurrency: tx.output.currency.toUpperCase(),
payoutChainPluginId: undefined,
payoutEvmChainId: undefined,
payoutTokenId: undefined,
payoutAmount: safeParseFloat(tx.output.amount),
timestamp: Date.parse(tx.timestamp_created.concat('Z')) / 1000,
isoDate: new Date(tx.timestamp_created.concat('Z')).toISOString(),
usdValue: -1,
rawTx
}
return standardTx
}