forked from datcsv/tez-tax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03_BS_Generation.R
387 lines (333 loc) · 14.3 KB
/
03_BS_Generation.R
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
################################################################################
# #
# Copyright 2022 datcsv #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# 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. #
# #
################################################################################
# Load income statement data
load(file="data/is.RData")
# Adjust tokenID for easier debugging
is %<>% mutate(., tokenID = str_replace(tokenID, "_", "/"))
# Fungible token list (Only necessary if 'collectible' is set to TRUE)
fungible <- c(
"KT1AFA2mwNUMNd4SsujE1YYp29vd8BZejyKW_0", # hDAO
"KT1Trhji1aVzDtGiAxiCfWNi9T74Kyi49DK1_0", # PURPLE
"KT1G1cCRNBgQ48mVDjopHjEmTN5Sbtar8nn9_0", # Hedgehoge
"KT18hYjnko76SBVv6TaCT4kU6B32mJk6JWLZ_0", # MATH
"KT193D4vozYnhGJQVtw7CoxxqphqUEEwK6Vb_0", # QUIPU
"KT1AM3PV1cwmGRw28DVTgsjjsjHvmL6z4rGh_0" # akaDAO
)
# Generate empy balance sheet dataset
bs <- tibble(
timestamp = POSIXct(),
asset = character(),
quantity = double(),
costBasis = double()
)
# Generate empty tax form 8949 dataset
tax_8949 <- tibble(
Description = character(),
Date_Acquired = Date(),
Date_Sold = Date(),
Proceeds = double(),
Cost_Basis = double(),
Codes = character(),
Adjustment = double(),
Gain_Loss = double()
)
# Initialize variables
xtzIncome <- 0
xtzIncome_data <- is[0, ]
# Loop through rows of income statement to generate tax figures
for (i in 1:nrow(is)) {
# Initialize variables
xtzBalance <- 0
xtzCost <- 0
xtzProceeds <- 0
tokenBalance <- 0
tokenCost <- 0
tokenProceeds <- 0
subtract_j <- 0
# Isolate row
is_i <- is[i, ]
##############################################################################
# Adjust Tezos sent/received: #
# (1) If Tezos is sent and received in the same transaction, net the values.#
# (2) For token transfers, base the calculation on sender/receiver. #
# (3) For all other transactions, base the calculation on highest value. #
# (*) This assumption should be used for estimates only and is not #
# an accurate or long-term solution. #
##############################################################################
# Adjust XTZ sent/received
if (is_i$xtzSent > 0 & is_i$xtzReceived > 0) {
if (is_i$xtzReceived >= is_i$xtzSent) {
is_i$xtzReceived <- is_i$xtzReceived - is_i$xtzSent
is_i$xtzSent <- 0
}
else {
is_i$xtzSent <- is_i$xtzSent - is_i$xtzReceived
is_i$xtzReceived <- 0
}
}
##############################################################################
# Do not calculate gain (loss) for purchases or income: #
# (1) If 'xtzBuy' is TRUE, mark as purchase. #
# (2) If Tezos are received but no tokens are sent, mark as income. #
##############################################################################
# Add Tezos purchases to balance sheet
if (is_i$xtzBuy) {
bs %<>%
add_row(.,
timestamp = is_i$timestamp,
asset = "xtz",
quantity = is_i$xtzReceived,
costBasis = ifelse(
is.na(is_i$costBasis), is_i$quote, is_i$costBasis / is_i$xtzReceived
)
)
next
}
# Add Tezos income to balance sheet
else if ((is_i$xtzReceived > 0) & (is_i$tokenSent == 0)) {
bs %<>%
add_row(.,
timestamp = is_i$timestamp,
asset = "xtz",
quantity = is_i$xtzReceived,
costBasis = is_i$quote
)
xtzIncome <- xtzIncome + is_i$quote * is_i$xtzReceived
xtzIncome_data %<>% bind_rows(., is_i)
next
}
##############################################################################
# Calculate gain (loss) on Tezos sent. #
##############################################################################
if (is_i$xtzSent > 0) {
# Initialize variables
xtzBalance <- is_i$xtzSent
xtzCost <- 0
xtzProceeds <- is_i$quote * is_i$xtzSent
# Subtract Tezos from balance sheet, calculate tax figures
for (j in 1:nrow(bs)) {
if (xtzBalance <= 0) break
if (bs$asset[j] == "xtz" & bs$quantity[j] > 0) {
# Find how much can be reduced from the balance sheet
subtract_j <- min(bs$quantity[j], xtzBalance)
# Reduce the balance sheet accordingly
bs$quantity[j] <- bs$quantity[j] - subtract_j
# Calculate remaining transaction balance
xtzBalance <- xtzBalance - subtract_j
# Calculate transaction cost basis
xtzCost <- xtzCost + subtract_j * bs$costBasis[j]
# Update tax form 8949 dataset (Transfers adjusted in 'classify_tx.R')
tax_8949 %<>%
add_row(.,
Description = paste(subtract_j, bs$asset[j]),
Date_Acquired = as_date(bs$timestamp[j]),
Date_Sold = as_date(is_i$timestamp),
Proceeds = round(subtract_j * is_i$quote, 2),
Cost_Basis = round(subtract_j * bs$costBasis[j], 2),
Codes = NA,
Adjustment = NA,
Gain_Loss = Proceeds - Cost_Basis
)
}
}
# If balance sheet deficit, issue warning and assume cost basis of zero
if (xtzBalance > 0) {
warning(cat("\nTezos deficit, cost basis assumed zero:", i, is_i$id))
tax_8949 %<>%
add_row(.,
Description = paste(xtzBalance, bs$asset[j]),
Date_Acquired = NA,
Date_Sold = as_date(is_i$timestamp),
Proceeds = round(xtzBalance * (xtzProceeds / is_i$xtzSent), 2),
Cost_Basis = 0,
Codes = NA,
Adjustment = NA,
Gain_Loss = Proceeds
)
# Add row to balance sheet for debugging
bs %<>%
add_row(.,
timestamp = is_i$timestamp,
asset = "xtz",
quantity = -1 * xtzBalance,
costBasis = NA
)
}
# Log proceeds and gain (loss) to income statement
is$xtzProceeds[i] <- round(xtzProceeds, 2)
is$xtzGainLoss[i] <- round(xtzProceeds, 2) - round(xtzCost, 2)
}
##############################################################################
# Calculate gain (loss) on tokens sent. #
##############################################################################
if (is_i$tokenSent > 0) {
# Initialize variables
tokenBalance <- is_i$tokenSent
tokenCost <- 0
tokenProceeds <- is_i$xtzReceived * is_i$quote
j <- 1
# Subtract tokens from balance sheet, calculate tax figures
while (j <= nrow(bs)) {
if (tokenBalance <= 0) break
if (bs$asset[j] == is_i$tokenID & bs$quantity[j] > 0) {
# Find how much can be reduced from the balance sheet
subtract_j <- min(bs$quantity[j], tokenBalance)
# Reduce the balance sheet accordingly
bs$quantity[j] <- bs$quantity[j] - subtract_j
# Calculate remaining transaction balance
tokenBalance <- tokenBalance - subtract_j
# Calculate transaction cost basis
tokenCost <- tokenCost + subtract_j * bs$costBasis[j]
# Update tax form 8949 dataset, ignore transfers
if (!(is_i$case %in% c("Token transfer", "Wallet transfer"))) {
tax_8949 %<>%
add_row(.,
Description = paste(subtract_j, bs$asset[j]),
Date_Acquired = as_date(bs$timestamp[j]),
Date_Sold = as_date(is_i$timestamp),
Proceeds = round(subtract_j * (tokenProceeds / is_i$tokenSent), 2),
Cost_Basis = round(subtract_j * bs$costBasis[j], 2),
Codes = ifelse(is_i$tokenID %in% fungible, NA, "C"),
Adjustment = NA,
Gain_Loss = Proceeds - Cost_Basis
)
}
}
# While loop is used to account for the RCS mint assumption
j <- j + 1
##########################################################################
# RCS mint assumption: #
# (1) Assume RCS tokens lacking transaction history were minted at 5tz. #
# (2) Minted RCS tokens are treated like fungible tokens. #
# (*) This assumption should be used for estimates only and is not #
# an accurate or long-term solution. #
##########################################################################
if (
(rcs_mint) &
(j == nrow(bs)) &
(tokenBalance > 0) &
(str_split(is_i$tokenID, "/")[[1]][1] == "KT1HZVd9Cjc2CMe3sQvXgbxhpJkdena21pih")
) {
is_i$tokenID <- "KT1HZVd9Cjc2CMe3sQvXgbxhpJkdena21pih/0"
j <- 1
}
}
# If balance sheet deficit, issue warning and assume cost basis of zero
if (tokenBalance > 0) {
##########################################################################
# Token deficit assumption (In progress, not working): #
# (1) If there is no record of a token entering the balance sheet, #
# the token is assumed to have a cost basis of zero. #
# (2) For tax form 8949, an acquisition date is required; in order to #
# impute this value, the timestamp value is set to the last time #
# the wallet had a positive token balance update. #
# (*) This assumption should be used for estimates only and is not #
# an accurate or long-term solution. #
##########################################################################
warning(cat("\nToken deficit assumption:", is_i$id, is_i$tokenID))
# def_ops <- tzkt_operations_hash(hash=is_i$hash, quote=currency)
# def_dif <- def_ops$diffs[[1]][1, ]
# def_key <- tzkt_bigmap_updates(id=def_dif$bigmap, key=def_dif$content$hash)
# def_acq <- as_datetime(tail(filter(def_upd, value > 0), 1)$timestamp)
def_acq <- NA
if (!(is_i$case %in% c("Token transfer", "Wallet transfer"))){
tax_8949 %<>%
add_row(.,
Description = paste(tokenBalance, is_i$tokenID),
Date_Acquired = def_acq,
Date_Sold = as_date(is_i$timestamp),
Proceeds = round(tokenBalance * (tokenProceeds / is_i$tokenSent), 2),
Cost_Basis = 0,
Codes = ifelse(is_i$tokenID %in% fungible & collectible, NA, "C"),
Adjustment = NA,
Gain_Loss = Proceeds
)
}
# Add row to balance sheet for debugging
bs %<>%
add_row(.,
timestamp = is_i$timestamp,
asset = is_i$tokenID,
quantity = -1 * tokenBalance,
costBasis = NA
)
}
# Log proceeds and gain (loss) to income statement
is$tokenProceeds[i] <- round(tokenProceeds, 2)
is$tokenGainLoss[i] <- round(tokenProceeds, 2) - round(tokenCost, 2)
# Add Tezos received in token transactions to balance sheet
if (is_i$xtzReceived > 0) {
bs %<>%
add_row(.,
timestamp = is_i$timestamp,
asset = "xtz",
quantity = is_i$xtzReceived,
costBasis = is_i$quote
)
}
}
##############################################################################
# Log any tokens received to balance sheet. #
##############################################################################
# Calculate total transaction proceeds (as cost basis)
if (is.na(is_i$costBasis)) {
is$costBasis[i] <- xtzProceeds + tokenProceeds
}
# Add tokens received to balance sheet
if (is_i$tokenReceived > 0) {
bs %<>%
add_row(.,
timestamp = is_i$timestamp,
asset = is_i$tokenID,
quantity = is_i$tokenReceived,
costBasis = is$costBasis[i] / is_i$tokenReceived
)
}
if (is.na(is_i$tokenReceived)) {
print(is_i$id)
}
# If token sent and token received in same transaction, issue warning
if ((is_i$tokenSent > 0) & (is_i$tokenReceived > 0)) {
warning(cat("\nToken sent and received in same transaction!", is_i$id))
}
# Balance reconciliation
# if (i %% 50 == 0) {
# is$balTZ[i] <- tzkt_balance(wallets[1], is_i$level)
# is$balBS[i] <- sum(select(filter(bs, asset == "xtz"), "quantity"))
# }
}
# Adjust collectibles
if (!collectible) tax_8949 %<>% mutate(., Codes = NA)
# Add token ID column to tax data
tax_8949 %<>%
mutate(.,
Token_Quantity = str_split(Description, " ", simplify=TRUE)[, 1],
Token_ID = str_split(Description, " ", simplify=TRUE)[, 2],
Token_ID_Short = ifelse(
nchar(Token_ID) > 16,
substr(Token_ID, nchar(Token_ID) - 15, nchar(Token_ID)),
Token_ID
),
Description = paste(Token_Quantity, Token_ID_Short)
)
# Save income statement, balance sheet, and tax data
save(is, file="data/is_updated.RData")
save(bs, file="data/bs.RData")
save(tax_8949, file="data/tax_8949.RData")
save(tax_8949, file="data/tax_8949_original.RData")
save(xtzIncome_data, file="data/xtzIncome_data.RData")