-
Notifications
You must be signed in to change notification settings - Fork 10
/
script-by-wallet-csv.js
172 lines (155 loc) · 6.05 KB
/
script-by-wallet-csv.js
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
(function() {
const PAGE_COUNT = 25;
const getCookie = (name) => {
const cookies = document.cookie.split('; ');
const cookieMap = cookies.map(it => it.split('='))
.reduce((prev, curr) => {
const [key, value] = curr;
return {
...prev,
[key]: value,
}
}, {})
return cookieMap[name]
}
const fetchHeaders = () => {
const headers = new Headers();
headers.append('authority', 'api.koinly.io');
headers.append('accept', 'application/json, text/plain, */*');
headers.append('accept-language', 'en-GB,en-US;q=0.9,en;q=0.8');
headers.append('access-control-allow-credentials', 'true');
headers.append('caches-requests', '1');
headers.append('cookie', document.cookie);
headers.append('origin', 'https://app.koinly.io');
headers.append('referer', 'https://app.koinly.io/');
headers.append('sec-fetch-dest', 'empty');
headers.append('sec-fetch-mode', 'cors');
headers.append('sec-fetch-site', 'same-site');
headers.append('sec-gpc', '1');
headers.append('user-agent', navigator.userAgent);
headers.append('x-auth-token', getCookie('API_KEY'));
headers.append('x-portfolio-token', getCookie('PORTFOLIO_ID'));
return headers;
}
const fetchSession = async () => {
const requestOptions = {
method: 'GET',
headers: fetchHeaders(),
redirect: 'follow'
};
try {
const response = await fetch('https://api.koinly.io/api/sessions', requestOptions);
return response.json();
} catch(err) {
console.error(err)
throw new Error('Fetch session failed')
}
}
const fetchWallets = async (pageNumber) => {
const requestOptions = {
method: 'GET',
headers: fetchHeaders(),
redirect: 'follow'
};
try {
const response = await fetch(`https://api.koinly.io/api/wallets?per_page=${PAGE_COUNT}&page=${pageNumber}`, requestOptions);
return response.json();
} catch(err) {
console.error(err)
throw new Error('Fetch session failed')
}
}
async function getAllWallets() {
const firstPage = await fetchWallets(1);
const totalPages = firstPage.meta.page.total_pages;
const promises = [];
for (let i=2; i <= totalPages; i++) {
promises.push(fetchWallets(i));
}
const remainingPages = await Promise.all(promises);
const allPages = [firstPage, ...remainingPages];
return allPages.flatMap(it => it.wallets);
}
const fetchPage = async (pageNumber, walletID) => {
const requestOptions = {
method: 'GET',
headers: fetchHeaders(),
redirect: 'follow'
};
try {
const response = await fetch(`https://api.koinly.io/api/transactions?order=date&q[m]=and&q[g][0][from_wallet_id_or_to_wallet_id_eq]=${walletID}&page=${pageNumber}&per_page=${PAGE_COUNT}`, requestOptions);
return response.json();
} catch(err) {
console.error(err)
throw new Error(`Fetch failed for page=${pageNumber}`)
}
}
const getAllTransactions = async (walletID) => {
const firstPage = await fetchPage(1, walletID);
const totalPages = firstPage.meta.page.total_pages;
const promises = [];
for (let i=2; i <= totalPages; i++) {
promises.push(fetchPage(i, walletID));
}
const remainingPages = await Promise.all(promises);
const allPages = [firstPage, ...remainingPages];
return allPages.flatMap(it => it.transactions);
}
const toCSVFile = (walletName, baseCurrency, transactions) => {
// Headings
// Representing Koinly Spreadsheet (https://docs.google.com/spreadsheets/d/1dESkilY70aLlo18P3wqXR_PX1svNyAbkYiAk2tBPJng/edit#gid=0)
const headings = [
'Date',
'Sent Amount',
'Sent Currency',
'Received Amount',
'Received Currency',
'Fee Amount',
'Fee Currency',
'Net Worth Amount',
'Net Worth Currency',
'Label',
'Description',
'TxHash',
// EXTRA_HEADERS: Add extra headers as necessary (ensure you also update "row" below)
]
transactionRows = transactions.map((t) => {
const row = [
t.date,
t.from ? t.from.amount : '',
t.from ? t.from.currency.symbol : '',
t.to ? t.to.amount : '',
t.to ? t.to.currency.symbol : '',
t.fee ? t.fee.amount : '',
t.fee ? t.fee.currency.symbol : '',
t.net_value,
baseCurrency,
t.type,
t.description,
t.txhash,
// EXTRA_FIELDS: Add extra fields as necessary (ensure you also update "headings" above)
]
return row.join(',');
});
const csv = [
headings.join(','),
...transactionRows
].join('\n');
const hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = `${walletName} - Transactions.csv`;
hiddenElement.click();
}
const run = async () => {
const session = await fetchSession()
const baseCurrency = session.portfolios[0].base_currency.symbol;
const wallets = await getAllWallets();
wallets.forEach(async (wallet) => {
const transactions = await getAllTransactions(wallet.id);
console.log(`Your Koinly Transactions for wallet ${wallet.name}\n`, transactions);
toCSVFile(wallet.name, baseCurrency, transactions);
});
}
run()
})()