-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtransferwise.go
418 lines (352 loc) · 13.5 KB
/
transferwise.go
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/google/uuid"
"github.com/jordan-wright/email"
"github.com/mitchellh/mapstructure"
"log"
"net/http"
"net/smtp"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// transfer-wise api paths
const (
transfersAPIPath = "v1/transfers"
quotesAPIPath = "v2/quotes"
liveRateAPIPath = "v1/rates"
cancelTransferAPIPath = "v1/transfers/{transferId}/cancel"
)
// transfer-wise hosts
const (
hostProduction = "api.transferwise.com"
hostSandbox = "api.sandbox.transferwise.tech"
)
// fallback values for optional env variables
const (
fallbackInterval = "1"
fallbackMargin = "0"
)
// SMTP mail server
const (
smtpHost = "smtp.gmail.com"
smtpPort = "587"
)
// other mail related constants
const (
reminderMailSubject = "Reminder: Your transfer is about to expire"
reminderMailBody = "<h4>💸 The following transfer is going to expire on <b>%v</b></h4>" +
"<ul> <li>Transfer ID: %v </li> <li> {%v} --> {%v} </li> <li> Booked Rate: %v </li> <li> Amount: %v %v </li> </ul>"
expiryPeriodInHours = 36
)
// other constants
const PRODUCTION = "production"
const SANDBOX = "sandbox"
// error messages
const ErrNoCurrentTransferFound = "error: no current transfer found, please create a transfer before proceeding"
const ErrEnvVarMissingOrInvalid = "error: make sure env variables ENV, API_TOKEN are both provided and are valid"
// env vars
var envVar = getEnv("ENV", "")
var hostVar = getHost(envVar)
var apiTokenVar = getEnv("API_TOKEN", "")
var marginVar = getEnv("MARGIN", fallbackMargin)
var intervalVar = getEnv("INTERVAL", fallbackInterval)
var toEmailVar = getEnv("TO_MAIL", "")
var fromEmailVar = getEnv("FROM_MAIL", "")
var mailPassVar = getEnv("MAIL_PASS", "")
// HTTPClient interface
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
var (
Client HTTPClient
)
func init() {
Client = &http.Client{Timeout: 10 * time.Second}
}
func checkAndProcess() {
if hostVar == "" || apiTokenVar == "" {
log.Println(ErrEnvVarMissingOrInvalid)
return
}
result, transfer, liveRate, err := compareRates()
if err != nil {
log.Println(err)
return
}
if !result {
log.Printf("|| NO ACTION NEEDED, Live Rate: %v || Transfer ID: %v | {%v} --> {%v} | Booked Rate: %v | Amount: %v ||",
liveRate, transfer.Id, transfer.SourceCurrency, transfer.TargetCurrency, transfer.Rate, transfer.SourceAmount)
return
}
newTransfer, err := createTransfer(transfer)
if err != nil || !result {
log.Println(err)
return
}
log.Printf("|| NEW TRANSFER BOOKED || Transfer ID: %v | {%v} --> {%v} | Rate: %v | Amount: %v ||",
newTransfer.Id, newTransfer.SourceCurrency, newTransfer.TargetCurrency, newTransfer.Rate, newTransfer.SourceAmount)
}
// Send reminder mail in case the best quote is about to expire
func sendExpiryReminderMail() {
empty := Transfer{}
bookedTransfer, err := getBookedTransfer()
if err != nil || bookedTransfer == empty {
log.Printf("sendExpiryMail: %v", err)
}
quoteDetail, err := getDetailByQuoteId(bookedTransfer.QuoteUuid)
if err != nil {
log.Printf("sendExpiryMail: %v", err)
}
expiryTime, err := time.Parse(time.RFC3339, quoteDetail.RateExpirationTime)
if err != nil {
log.Printf("sendExpiryMail: %v", err)
}
if expiryTime.Sub(time.Now().UTC()).Hours() < expiryPeriodInHours {
body := fmt.Sprintf(
reminderMailBody,
expiryTime.Format("2006-01-02 15:04:05 UTC"),
bookedTransfer.Id,
bookedTransfer.SourceCurrency,
bookedTransfer.TargetCurrency,
bookedTransfer.Rate,
bookedTransfer.SourceCurrency,
bookedTransfer.SourceAmount,
)
err := sendMail(reminderMailSubject, []byte(body))
if err != nil {
log.Printf("sendExpiryMail: %v", err)
}
}
return
}
func compareRates() (result bool, bookedTransfer Transfer, currentRate float64, err error) {
empty := Transfer{}
bookedTransfer, err = getBookedTransfer()
if err != nil || bookedTransfer == empty {
return false, empty, 0, fmt.Errorf("compareRates: %v", err)
}
liveRate, err := getLiveRate(bookedTransfer.SourceCurrency, bookedTransfer.TargetCurrency)
if err != nil || liveRate == 0 {
return false, empty, 0, fmt.Errorf("compareRates: %v", err)
}
marginRate, err := strconv.ParseFloat(marginVar, 64)
if err != nil {
return false, empty, 0, fmt.Errorf("compareRates: %v", err)
}
bookedRate := bookedTransfer.Rate
if liveRate > bookedRate && (liveRate - bookedRate >= marginRate) {
return true, bookedTransfer, 0, nil
}
return false, bookedTransfer, liveRate, nil
}
func getBookedTransfer() (Transfer, error) {
params := url.Values{"limit": {"3"}, "offset": {"0"}, "status": {"incoming_payment_waiting"}}
url := &url.URL{RawQuery: params.Encode(), Host: hostVar, Scheme: "https", Path: transfersAPIPath}
response, code, err := callExternalAPI(http.MethodGet, url.String(), nil)
if err != nil || code != http.StatusOK {
return Transfer{}, fmt.Errorf("error GET transfer list API: %v : %v", code, err)
}
var transfersList []Transfer
err = mapstructure.Decode(response, &transfersList)
if err != nil {
return Transfer{}, fmt.Errorf("error decoding response: %v", err)
}
if len(transfersList) == 0 {
return Transfer{}, fmt.Errorf(ErrNoCurrentTransferFound)
}
bookedTransfer := findBestTransfer(transfersList)
quoteDetail, err := getDetailByQuoteId(bookedTransfer.QuoteUuid)
if err != nil {
return Transfer{}, fmt.Errorf("getBookedTransfer: %v", err)
}
bookedTransfer.SourceAmount = quoteDetail.SourceAmount
bookedTransfer.Profile = quoteDetail.Profile
return bookedTransfer, nil
}
func getLiveRate(source string, target string) (float64, error) {
params := url.Values{"source": {source}, "target": {target}}
url := &url.URL{RawQuery: params.Encode(), Host: hostVar, Scheme: "https", Path:liveRateAPIPath}
response, code, err := callExternalAPI(http.MethodGet, url.String(), nil)
if err != nil || code != http.StatusOK {
return 0, fmt.Errorf("error GET live rate API: %v : %v", code, err)
}
var liveRate []LiveRate
err = mapstructure.Decode(response, &liveRate)
if err != nil {
return 0, fmt.Errorf("error decoding live rate response: %v", err)
}
return liveRate[0].Rate, nil
}
func createTransfer(oldTransfer Transfer) (Transfer, error) {
quoteId, err := generateQuote(oldTransfer.SourceCurrency, oldTransfer.TargetCurrency, oldTransfer.SourceAmount, oldTransfer.Profile)
if err != nil {
return Transfer{}, fmt.Errorf("createTransfer: %v", err)
}
createRequest := CreateTransferRequest{
TargetAccount: oldTransfer.TargetAccount,
QuoteUuid: quoteId,
CustomerTransactionId: uuid.New().String(),
Details: oldTransfer.Details,
}
request, _ := json.Marshal(createRequest)
url := &url.URL{Host: hostVar, Scheme: "https", Path: transfersAPIPath}
response, code , err := callExternalAPI(http.MethodPost, url.String(), request)
if err != nil || code != http.StatusOK {
return Transfer{}, fmt.Errorf("error POST create transfer API: %v : %v", code, err)
}
var newTransfer Transfer
err = mapstructure.Decode(response, &newTransfer)
if err != nil {
return Transfer{}, fmt.Errorf("error decoding response: %v", err)
}
newTransfer.SourceAmount = oldTransfer.SourceAmount
cancelResult, err := cancelTransfer(oldTransfer.Id)
if !cancelResult || err != nil {
log.Println("Error deleting old transfer")
}
return newTransfer, nil
}
func cancelTransfer(transferId uint64) (bool, error) {
path := strings.Replace(cancelTransferAPIPath, "{transferId}", strconv.FormatUint(transferId, 10), 1)
url := &url.URL{Host: hostVar, Scheme: "https", Path: path}
_, code , err := callExternalAPI(http.MethodPut, url.String(), nil)
if err != nil || code != http.StatusOK {
return false, fmt.Errorf("error PUT cancel transfer API: %v : %v", code, err)
}
return true, nil
}
func generateQuote(source string, target string, sourceAmount float64, profile uint64) (string, error) {
quoteRequest := CreateQuoteRequest{
SourceCurrency: source,
TargetCurrency: target,
SourceAmount: sourceAmount,
Profile: profile,
}
request, _ := json.Marshal(quoteRequest)
url := &url.URL{Host: hostVar, Scheme: "https", Path: quotesAPIPath}
response, code, err := callExternalAPI(http.MethodPost, url.String(), request)
if err != nil || code != http.StatusOK {
return "", fmt.Errorf("error POST quote API: %v : %v", code, err)
}
var quote QuoteDetail
err = mapstructure.Decode(response, "e)
if err != nil {
return "", fmt.Errorf("error decoding quote response: %v", err)
}
return quote.Id, nil
}
func getDetailByQuoteId(quoteUuid string) (QuoteDetail, error) {
path := quotesAPIPath + "/" + quoteUuid
url := &url.URL{Host: hostVar, Scheme: "https", Path: path}
response, code, err := callExternalAPI(http.MethodGet, url.String(), nil)
if err != nil || code != http.StatusOK {
return QuoteDetail{}, fmt.Errorf("error GET quote detail API: %v : %v", code, err)
}
var quoteDetail QuoteDetail
err = mapstructure.Decode(response, "eDetail)
if err != nil {
return QuoteDetail{}, fmt.Errorf("error decoding to quote detail: %v : %v", code, err)
}
return quoteDetail, nil
}
func callExternalAPI(method string, url string, reqBody []byte) (response interface{}, code int, err error) {
req, err := http.NewRequest(method, url, bytes.NewReader(reqBody))
if err != nil {
return nil, http.StatusInternalServerError, fmt.Errorf("error creating external api request: %v", err)
}
req.Header.Add("Authorization", "Bearer " + apiTokenVar)
req.Header.Add("Content-Type", "application/json")
res, err := Client.Do(req)
if err != nil {
return nil, http.StatusInternalServerError, fmt.Errorf("error calling external api: %v", err)
}
err = json.NewDecoder(res.Body).Decode(&response)
if err != nil {
return nil, http.StatusInternalServerError, fmt.Errorf("error decoding json response: %v", err)
}
code = res.StatusCode
_ = res.Body.Close()
return
}
func findBestTransfer(transferList []Transfer) (bestTransfer Transfer){
for i := range transferList {
if i==0 || bestTransfer.Rate < transferList[i].Rate {
bestTransfer = transferList[i]
}
}
return
}
func sendMail(subject string, body []byte) (err error) {
if toEmailVar == "" || fromEmailVar == "" || mailPassVar == "" {
return fmt.Errorf("error: env vars TO_MAIL, FROM_MAIL, MAIL_PASS not found")
}
e := email.NewEmail()
e.From = fmt.Sprintf(" Transferwisely <%s>",fromEmailVar)
e.To = []string{toEmailVar}
e.Subject = subject
e.HTML = body
err = e.Send(smtpHost + ":" + smtpPort, smtp.PlainAuth("", fromEmailVar, mailPassVar, smtpHost))
return
}
func getHost(envVar string) string {
switch strings.ToLower(envVar) {
case SANDBOX:
return hostSandbox
case PRODUCTION:
return hostProduction
default:
return ""
}
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
type Transfer struct {
Id uint64 `json:"id"`
Profile uint64 `json:"profile"`
TargetAccount uint64 `json:"targetAccount"`
SourceAmount float64 `json:"sourceAmount"`
Rate float64 `json:"rate"`
QuoteUuid string `json:"quote"`
SourceCurrency string `json:"sourceCurrency"`
TargetCurrency string `json:"targetCurrency"`
Details TransferDetails `json:"details"`
}
type TransferDetails struct {
Reference string `json:"reference"`
TransferPurpose string `json:"transferPurpose"`
SourceOfFunds string `json:"sourceOfFunds"`
}
type QuoteDetail struct {
Id string `json:"id"`
SourceAmount float64 `json:"sourceAmount"`
Rate float64 `json:"rate"`
SourceCurrency string `json:"source"`
TargetCurrency string `json:"target"`
Profile uint64 `json:"profile"`
RateExpirationTime string `json:"rateExpirationTime"`
}
type LiveRate struct {
Rate float64 `json:"rate"`
}
type CreateTransferRequest struct {
TargetAccount uint64 `json:"targetAccount"`
QuoteUuid string `json:"quoteUuid"`
CustomerTransactionId string `json:"customerTransactionId"`
Details TransferDetails `json:"details"`
}
type CreateQuoteRequest struct {
SourceCurrency string `json:"sourceCurrency"`
TargetCurrency string `json:"targetCurrency"`
SourceAmount float64 `json:"sourceAmount"`
Profile uint64 `json:"profile"`
}