summaryrefslogtreecommitdiff
path: root/packages/taler-util/src/taler-types.ts
blob: 2b8e55e386e2bc198abe8294015de64a40fb3034 (plain)
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
/*
 This file is part of GNU Taler
 (C) 2019 GNUnet e.V.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 * Type and schema definitions and helpers for the core GNU Taler protocol.
 *
 * Even though the rest of the wallet uses camelCase for fields, use snake_case
 * here, since that's the convention for the Taler JSON+HTTP API.
 */

/**
 * Imports.
 */

import { Amounts, codecForAmountString } from "./amounts.js";
import {
  Codec,
  buildCodecForObject,
  buildCodecForUnion,
  codecForAny,
  codecForBoolean,
  codecForConstString,
  codecForList,
  codecForMap,
  codecForNumber,
  codecForString,
  codecForStringURL,
  codecOptional,
} from "./codec.js";
import { strcmp } from "./helpers.js";
import {
  CurrencySpecification,
  codecForCurrencySpecificiation,
  codecForEither,
  codecForProduct,
} from "./index.js";
import { Edx25519PublicKeyEnc } from "./taler-crypto.js";
import {
  TalerProtocolDuration,
  TalerProtocolTimestamp,
  codecForDuration,
  codecForTimestamp,
} from "./time.js";

/**
 * Denomination as found in the /keys response from the exchange.
 */
export class ExchangeDenomination {
  /**
   * Value of one coin of the denomination.
   */
  value: string;

  /**
   * Public signing key of the denomination.
   */
  denom_pub: DenominationPubKey;

  /**
   * Fee for withdrawing.
   */
  fee_withdraw: string;

  /**
   * Fee for depositing.
   */
  fee_deposit: string;

  /**
   * Fee for refreshing.
   */
  fee_refresh: string;

  /**
   * Fee for refunding.
   */
  fee_refund: string;

  /**
   * Start date from which withdraw is allowed.
   */
  stamp_start: TalerProtocolTimestamp;

  /**
   * End date for withdrawing.
   */
  stamp_expire_withdraw: TalerProtocolTimestamp;

  /**
   * Expiration date after which the exchange can forget about
   * the currency.
   */
  stamp_expire_legal: TalerProtocolTimestamp;

  /**
   * Date after which the coins of this denomination can't be
   * deposited anymore.
   */
  stamp_expire_deposit: TalerProtocolTimestamp;

  /**
   * Signature over the denomination information by the exchange's master
   * signing key.
   */
  master_sig: string;
}

/**
 * Signature by the auditor that a particular denomination key is audited.
 */
export class AuditorDenomSig {
  /**
   * Denomination public key's hash.
   */
  denom_pub_h: string;

  /**
   * The signature.
   */
  auditor_sig: string;
}

/**
 * Auditor information as given by the exchange in /keys.
 */
export class ExchangeAuditor {
  /**
   * Auditor's public key.
   */
  auditor_pub: string;

  /**
   * Base URL of the auditor.
   */
  auditor_url: string;

  /**
   * List of signatures for denominations by the auditor.
   */
  denomination_keys: AuditorDenomSig[];
}

export type ExchangeWithdrawValue =
  | ExchangeRsaWithdrawValue
  | ExchangeCsWithdrawValue;

export interface ExchangeRsaWithdrawValue {
  cipher: "RSA";
}

export interface ExchangeCsWithdrawValue {
  cipher: "CS";

  /**
   *  CSR R0 value
   */
  r_pub_0: string;

  /**
   * CSR R1 value
   */
  r_pub_1: string;
}

export interface RecoupRequest {
  /**
   * Hashed denomination public key of the coin we want to get
   * paid back.
   */
  denom_pub_hash: string;

  /**
   * Signature over the coin public key by the denomination.
   *
   * The string variant is for the legacy exchange protocol.
   */
  denom_sig: UnblindedSignature;

  /**
   * Blinding key that was used during withdraw,
   * used to prove that we were actually withdrawing the coin.
   */
  coin_blind_key_secret: string;

  /**
   * Signature of TALER_RecoupRequestPS created with the coin's private key.
   */
  coin_sig: string;

  ewv: ExchangeWithdrawValue;
}

export interface RecoupRefreshRequest {
  /**
   * Hashed enomination public key of the coin we want to get
   * paid back.
   */
  denom_pub_hash: string;

  /**
   * Signature over the coin public key by the denomination.
   *
   * The string variant is for the legacy exchange protocol.
   */
  denom_sig: UnblindedSignature;

  /**
   * Coin's blinding factor.
   */
  coin_blind_key_secret: string;

  /**
   * Signature of TALER_RecoupRefreshRequestPS created with
   * the coin's private key.
   */
  coin_sig: string;

  ewv: ExchangeWithdrawValue;
}

/**
 * Response that we get from the exchange for a payback request.
 */
export interface RecoupConfirmation {
  /**
   * Public key of the reserve that will receive the payback.
   */
  reserve_pub?: string;

  /**
   * Public key of the old coin that will receive the recoup,
   * provided if refreshed was true.
   */
  old_coin_pub?: string;
}

export type UnblindedSignature = RsaUnblindedSignature;

export interface RsaUnblindedSignature {
  cipher: DenomKeyType.Rsa;
  rsa_signature: string;
}

/**
 * Deposit permission for a single coin.
 */
export interface CoinDepositPermission {
  /**
   * Signature by the coin.
   */
  coin_sig: string;

  /**
   * Public key of the coin being spend.
   */
  coin_pub: string;

  /**
   * Signature made by the denomination public key.
   *
   * The string variant is for legacy protocol support.
   */

  ub_sig: UnblindedSignature;

  /**
   * The denomination public key associated with this coin.
   */
  h_denom: string;

  /**
   * The amount that is subtracted from this coin with this payment.
   */
  contribution: string;

  /**
   * URL of the exchange this coin was withdrawn from.
   */
  exchange_url: string;

  minimum_age_sig?: EddsaSignatureString;

  age_commitment?: Edx25519PublicKeyEnc[];

  h_age_commitment?: string;
}

/**
 * Information about an exchange as stored inside a
 * merchant's contract terms.
 */
export interface ExchangeHandle {
  // The exchange's base URL.
  url: string;

  // Master public key of the exchange.
  master_pub: EddsaPublicKeyString;
}

export interface AuditorHandle {
  /**
   * Official name of the auditor.
   */
  name: string;

  /**
   * Master public signing key of the auditor.
   */
  auditor_pub: EddsaPublicKeyString;

  /**
   * Base URL of the auditor.
   */
  url: string;
}

// Delivery location, loosely modeled as a subset of
// ISO20022's PostalAddress25.
export interface Location {
  // Nation with its own government.
  country?: string;

  // Identifies a subdivision of a country such as state, region, county.
  country_subdivision?: string;

  // Identifies a subdivision within a country sub-division.
  district?: string;

  // Name of a built-up area, with defined boundaries, and a local government.
  town?: string;

  // Specific location name within the town.
  town_location?: string;

  // Identifier consisting of a group of letters and/or numbers that
  // is added to a postal address to assist the sorting of mail.
  post_code?: string;

  // Name of a street or thoroughfare.
  street?: string;

  // Name of the building or house.
  building_name?: string;

  // Number that identifies the position of a building on a street.
  building_number?: string;

  // Free-form address lines, should not exceed 7 elements.
  address_lines?: string[];
}

export interface MerchantInfo {
  // The merchant's legal name of business.
  name: string;

  // Label for a location with the business address of the merchant.
  email?: string;

  // Label for a location with the business address of the merchant.
  website?: string;

  // An optional base64-encoded product image.
  logo?: ImageDataUrl;

  // Label for a location with the business address of the merchant.
  address?: Location;

  // Label for a location that denotes the jurisdiction for disputes.
  // Some of the typical fields for a location (such as a street address) may be absent.
  jurisdiction?: Location;
}

export interface Tax {
  // the name of the tax
  name: string;

  // amount paid in tax
  tax: AmountString;
}

export interface Product {
  // merchant-internal identifier for the product.
  product_id?: string;

  // Human-readable product description.
  description: string;

  // Map from IETF BCP 47 language tags to localized descriptions
  description_i18n?: InternationalizedString;

  // The number of units of the product to deliver to the customer.
  quantity?: Integer;

  // The unit in which the product is measured (liters, kilograms, packages, etc.)
  unit?: string;

  // The price of the product; this is the total price for quantity times unit of this product.
  price?: AmountString;

  // An optional base64-encoded product image
  image?: ImageDataUrl;

  // a list of taxes paid by the merchant for this product. Can be empty.
  taxes?: Tax[];

  // time indicating when this product should be delivered
  delivery_date?: TalerProtocolTimestamp;
}

export interface InternationalizedString {
  [lang_tag: string]: string;
}

/**
 * Contract terms from a merchant.
 * FIXME: Add type field!
 */
export interface MerchantContractTerms {
  // The hash of the merchant instance's wire details.
  h_wire: string;

  // Specifies for how long the wallet should try to get an
  // automatic refund for the purchase. If this field is
  // present, the wallet should wait for a few seconds after
  // the purchase and then automatically attempt to obtain
  // a refund.  The wallet should probe until "delay"
  // after the payment was successful (i.e. via long polling
  // or via explicit requests with exponential back-off).
  //
  // In particular, if the wallet is offline
  // at that time, it MUST repeat the request until it gets
  // one response from the merchant after the delay has expired.
  // If the refund is granted, the wallet MUST automatically
  // recover the payment.  This is used in case a merchant
  // knows that it might be unable to satisfy the contract and
  // desires for the wallet to attempt to get the refund without any
  // customer interaction.  Note that it is NOT an error if the
  // merchant does not grant a refund.
  auto_refund?: TalerProtocolDuration;

  // Wire transfer method identifier for the wire method associated with h_wire.
  // The wallet may only select exchanges via a matching auditor if the
  // exchange also supports this wire method.
  // The wire transfer fees must be added based on this wire transfer method.
  wire_method: string;

  // Human-readable description of the whole purchase.
  summary: string;

  // Map from IETF BCP 47 language tags to localized summaries.
  summary_i18n?: InternationalizedString;

  // Unique, free-form identifier for the proposal.
  // Must be unique within a merchant instance.
  // For merchants that do not store proposals in their DB
  // before the customer paid for them, the order_id can be used
  // by the frontend to restore a proposal from the information
  // encoded in it (such as a short product identifier and timestamp).
  order_id: string;

  // Total price for the transaction.
  // The exchange will subtract deposit fees from that amount
  // before transferring it to the merchant.
  amount: string;

  // Nonce generated by the wallet and echoed by the merchant
  // in this field when the proposal is generated.
  nonce: string;

  // After this deadline, the merchant won't accept payments for the contract.
  pay_deadline: TalerProtocolTimestamp;

  // More info about the merchant, see below.
  merchant: MerchantInfo;

  // Merchant's public key used to sign this proposal; this information
  // is typically added by the backend. Note that this can be an ephemeral key.
  merchant_pub: string;

  // Time indicating when the order should be delivered.
  // May be overwritten by individual products.
  delivery_date?: TalerProtocolTimestamp;

  // Delivery location for (all!) products.
  delivery_location?: Location;

  // Exchanges that the merchant accepts even if it does not accept any auditors that audit them.
  exchanges: ExchangeHandle[];

  // List of products that are part of the purchase (see Product).
  products?: Product[];

  // After this deadline has passed, no refunds will be accepted.
  refund_deadline: TalerProtocolTimestamp;

  // Transfer deadline for the exchange.  Must be in the
  // deposit permissions of coins used to pay for this order.
  wire_transfer_deadline: TalerProtocolTimestamp;

  // Time when this contract was generated.
  timestamp: TalerProtocolTimestamp;

  // Base URL of the (public!) merchant backend API.
  // Must be an absolute URL that ends with a slash.
  merchant_base_url: string;

  // URL that will show that the order was successful after
  // it has been paid for.  Optional, but either fulfillment_url
  // or fulfillment_message must be specified in every
  // contract terms.
  //
  // If a non-unique fulfillment URL is used, a customer can only
  // buy the order once and will be redirected to a previous purchase
  // when trying to buy an order with the same fulfillment URL a second
  // time. This is useful for digital goods that a customer only needs
  // to buy once but should be able to repeatedly download.
  //
  // For orders where the customer is expected to be able to make
  // repeated purchases (for equivalent goods), the fulfillment URL
  // should be made unique for every order. The easiest way to do
  // this is to include a unique order ID in the fulfillment URL.
  //
  // When POSTing to the merchant, the placeholder text "${ORDER_ID}"
  // is be replaced with the actual order ID (useful if the
  // order ID is generated server-side and needs to be
  // in the URL). Note that this placeholder can only be used once.
  // Front-ends may use other means to generate a unique fulfillment URL.
  fulfillment_url?: string;

  // URL where the same contract could be ordered again (if
  // available). Returned also at the public order endpoint
  // for people other than the actual buyer (hence public,
  // in case order IDs are guessable).
  public_reorder_url?: string;

  // Message shown to the customer after paying for the order.
  // Either fulfillment_url or fulfillment_message must be specified.
  fulfillment_message?: string;

  // Map from IETF BCP 47 language tags to localized fulfillment
  // messages.
  fulfillment_message_i18n?: InternationalizedString;

  // Maximum total deposit fee accepted by the merchant for this contract.
  // Overrides defaults of the merchant instance.
  max_fee: string;

  // Extra data that is only interpreted by the merchant frontend.
  // Useful when the merchant needs to store extra information on a
  // contract without storing it separately in their database.
  // Must really be an Object (not a string, integer, float or array).
  extra?: any;

  // Minimum age the buyer must have (in years). Default is 0.
  // This value is at least as large as the maximum over all
  // minimum age requirements of the products in this contract.
  // It might also be set independent of any product, due to
  // legal requirements.
  minimum_age?: Integer;
}

/**
 * Refund permission in the format that the merchant gives it to us.
 */
export interface MerchantAbortPayRefundDetails {
  /**
   * Amount to be refunded.
   */
  refund_amount: string;

  /**
   * Fee for the refund.
   */
  refund_fee: string;

  /**
   * Public key of the coin being refunded.
   */
  coin_pub: string;

  /**
   * Refund transaction ID between merchant and exchange.
   */
  rtransaction_id: number;

  /**
   * Exchange's key used for the signature.
   */
  exchange_pub?: string;

  /**
   * Exchange's signature to confirm the refund.
   */
  exchange_sig?: string;

  /**
   * Error replay from the exchange (if any).
   */
  exchange_reply?: any;

  /**
   * Error code from the exchange (if any).
   */
  exchange_code?: number;

  /**
   * HTTP status code of the exchange's response
   * to the merchant's refund request.
   */
  exchange_http_status: number;
}

/**
 * Planchet detail sent to the merchant.
 */
export interface TipPlanchetDetail {
  /**
   * Hashed denomination public key.
   */
  denom_pub_hash: string;

  /**
   * Coin's blinded public key.
   */
  coin_ev: CoinEnvelope;
}

/**
 * Request sent to the merchant to pick up a tip.
 */
export interface TipPickupRequest {
  /**
   * Identifier of the tip.
   */
  tip_id: string;

  /**
   * List of planchets the wallet wants to use for the tip.
   */
  planchets: TipPlanchetDetail[];
}

/**
 * Reserve signature, defined as separate class to facilitate
 * schema validation.
 */
export interface MerchantBlindSigWrapperV1 {
  /**
   * Reserve signature.
   */
  blind_sig: string;
}

/**
 * Response of the merchant
 * to the TipPickupRequest.
 */
export interface MerchantTipResponseV1 {
  /**
   * The order of the signatures matches the planchets list.
   */
  blind_sigs: MerchantBlindSigWrapperV1[];
}

export interface MerchantBlindSigWrapperV2 {
  blind_sig: BlindedDenominationSignature;
}

/**
 * Response of the merchant
 * to the TipPickupRequest.
 */
export interface MerchantTipResponseV2 {
  /**
   * The order of the signatures matches the planchets list.
   */
  blind_sigs: MerchantBlindSigWrapperV2[];
}

/**
 * Element of the payback list that the
 * exchange gives us in /keys.
 */
export class Recoup {
  /**
   * The hash of the denomination public key for which the payback is offered.
   */
  h_denom_pub: string;
}

/**
 * Structure of one exchange signing key in the /keys response.
 */
export class ExchangeSignKeyJson {
  stamp_start: TalerProtocolTimestamp;
  stamp_expire: TalerProtocolTimestamp;
  stamp_end: TalerProtocolTimestamp;
  key: EddsaPublicKeyString;
  master_sig: EddsaSignatureString;
}

/**
 * Structure that the exchange gives us in /keys.
 */
export class ExchangeKeysJson {
  /**
   * Canonical, public base URL of the exchange.
   */
  base_url: string;

  currency: string;

  /**
   * The exchange's master public key.
   */
  master_public_key: string;

  /**
   * The list of auditors (partially) auditing the exchange.
   */
  auditors: ExchangeAuditor[];

  /**
   * Timestamp when this response was issued.
   */
  list_issue_date: TalerProtocolTimestamp;

  /**
   * List of revoked denominations.
   */
  recoup?: Recoup[];

  /**
   * Short-lived signing keys used to sign online
   * responses.
   */
  signkeys: ExchangeSignKeyJson[];

  /**
   * Protocol version.
   */
  version: string;

  reserve_closing_delay: TalerProtocolDuration;

  global_fees: GlobalFees[];

  accounts: ExchangeWireAccount[];

  wire_fees: { [methodName: string]: WireFeesJson[] };

  denominations: DenomGroup[];
}

export type DenomGroup =
  | DenomGroupRsa
  | DenomGroupCs
  | DenomGroupRsaAgeRestricted
  | DenomGroupCsAgeRestricted;

export interface DenomGroupCommon {
  // How much are coins of this denomination worth?
  value: AmountString;

  // Fee charged by the exchange for withdrawing a coin of this denomination.
  fee_withdraw: AmountString;

  // Fee charged by the exchange for depositing a coin of this denomination.
  fee_deposit: AmountString;

  // Fee charged by the exchange for refreshing a coin of this denomination.
  fee_refresh: AmountString;

  // Fee charged by the exchange for refunding a coin of this denomination.
  fee_refund: AmountString;

  // XOR of all the SHA-512 hash values of the denominations' public keys
  // in this group.  Note that for hashing, the binary format of the
  // public keys is used, and not their base32 encoding.
  hash: HashCodeString;
}

export interface DenomCommon {
  // Signature of TALER_DenominationKeyValidityPS.
  master_sig: EddsaSignatureString;

  // When does the denomination key become valid?
  stamp_start: TalerProtocolTimestamp;

  // When is it no longer possible to deposit coins
  // of this denomination?
  stamp_expire_withdraw: TalerProtocolTimestamp;

  // Timestamp indicating by when legal disputes relating to these coins must
  // be settled, as the exchange will afterwards destroy its evidence relating to
  // transactions involving this coin.
  stamp_expire_legal: TalerProtocolTimestamp;

  stamp_expire_deposit: TalerProtocolTimestamp;

  // Set to 'true' if the exchange somehow "lost"
  // the private key. The denomination was not
  // necessarily revoked, but still cannot be used
  // to withdraw coins at this time (theoretically,
  // the private key could be recovered in the
  // future; coins signed with the private key
  // remain valid).
  lost?: boolean;
}

export type RsaPublicKeySring = string;
export type AgeMask = number;
export type ImageDataUrl = string;

/**
 * 32-byte value representing a point on Curve25519.
 */
export type Cs25519Point = string;

export interface DenomGroupRsa extends DenomGroupCommon {
  cipher: "RSA";

  denoms: ({
    rsa_pub: RsaPublicKeySring;
  } & DenomCommon)[];
}

export interface DenomGroupRsaAgeRestricted extends DenomGroupCommon {
  cipher: "RSA+age_restricted";
  age_mask: AgeMask;

  denoms: ({
    rsa_pub: RsaPublicKeySring;
  } & DenomCommon)[];
}

export interface DenomGroupCs extends DenomGroupCommon {
  cipher: "CS";
  age_mask: AgeMask;

  denoms: ({
    cs_pub: Cs25519Point;
  } & DenomCommon)[];
}

export interface DenomGroupCsAgeRestricted extends DenomGroupCommon {
  cipher: "CS+age_restricted";
  age_mask: AgeMask;

  denoms: ({
    cs_pub: Cs25519Point;
  } & DenomCommon)[];
}

export interface GlobalFees {
  // What date (inclusive) does these fees go into effect?
  start_date: TalerProtocolTimestamp;

  // What date (exclusive) does this fees stop going into effect?
  end_date: TalerProtocolTimestamp;

  // Account history fee, charged when a user wants to
  // obtain a reserve/account history.
  history_fee: AmountString;

  // Annual fee charged for having an open account at the
  // exchange.  Charged to the account.  If the account
  // balance is insufficient to cover this fee, the account
  // is automatically deleted/closed. (Note that the exchange
  // will keep the account history around for longer for
  // regulatory reasons.)
  account_fee: AmountString;

  // Purse fee, charged only if a purse is abandoned
  // and was not covered by the account limit.
  purse_fee: AmountString;

  // How long will the exchange preserve the account history?
  // After an account was deleted/closed, the exchange will
  // retain the account history for legal reasons until this time.
  history_expiration: TalerProtocolDuration;

  // Non-negative number of concurrent purses that any
  // account holder is allowed to create without having
  // to pay the purse_fee.
  purse_account_limit: number;

  // How long does an exchange keep a purse around after a purse
  // has expired (or been successfully merged)?  A 'GET' request
  // for a purse will succeed until the purse expiration time
  // plus this value.
  purse_timeout: TalerProtocolDuration;

  // Signature of TALER_GlobalFeesPS.
  master_sig: string;
}
/**
 * Wire fees as announced by the exchange.
 */
export class WireFeesJson {
  /**
   * Cost of a wire transfer.
   */
  wire_fee: string;

  /**
   * Cost of clising a reserve.
   */
  closing_fee: string;

  /**
   * Signature made with the exchange's master key.
   */
  sig: string;

  /**
   * Date from which the fee applies.
   */
  start_date: TalerProtocolTimestamp;

  /**
   * Data after which the fee doesn't apply anymore.
   */
  end_date: TalerProtocolTimestamp;
}

/**
 * Proposal returned from the contract URL.
 */
export class Proposal {
  /**
   * Contract terms for the propoal.
   * Raw, un-decoded JSON object.
   */
  contract_terms: any;

  /**
   * Signature over contract, made by the merchant.  The public key used for signing
   * must be contract_terms.merchant_pub.
   */
  sig: string;
}

/**
 * Response from the internal merchant API.
 */
export class CheckPaymentResponse {
  order_status: string;
  refunded: boolean | undefined;
  refunded_amount: string | undefined;
  contract_terms: any | undefined;
  taler_pay_uri: string | undefined;
  contract_url: string | undefined;
}

/**
 * Response from the bank.
 */
export class WithdrawOperationStatusResponse {
  status: "selected" | "aborted" | "confirmed" | "pending";

  selection_done: boolean;

  transfer_done: boolean;

  aborted: boolean;

  amount: string;

  sender_wire?: string;

  suggested_exchange?: string;

  confirm_transfer_url?: string;

  wire_types: string[];
}

/**
 * Response from the merchant.
 */
export class RewardPickupGetResponse {
  reward_amount: string;

  exchange_url: string;

  next_url?: string;

  expiration: TalerProtocolTimestamp;
}

export enum DenomKeyType {
  Rsa = "RSA",
  ClauseSchnorr = "CS",
}

export namespace DenomKeyType {
  export function toIntTag(t: DenomKeyType): number {
    switch (t) {
      case DenomKeyType.Rsa:
        return 1;
      case DenomKeyType.ClauseSchnorr:
        return 2;
    }
  }
}

export interface RsaBlindedDenominationSignature {
  cipher: DenomKeyType.Rsa;
  blinded_rsa_signature: string;
}

export interface CSBlindedDenominationSignature {
  cipher: DenomKeyType.ClauseSchnorr;
}

export type BlindedDenominationSignature =
  | RsaBlindedDenominationSignature
  | CSBlindedDenominationSignature;

export const codecForRsaBlindedDenominationSignature = () =>
  buildCodecForObject<RsaBlindedDenominationSignature>()
    .property("cipher", codecForConstString(DenomKeyType.Rsa))
    .property("blinded_rsa_signature", codecForString())
    .build("RsaBlindedDenominationSignature");

export const codecForBlindedDenominationSignature = () =>
  buildCodecForUnion<BlindedDenominationSignature>()
    .discriminateOn("cipher")
    .alternative(DenomKeyType.Rsa, codecForRsaBlindedDenominationSignature())
    .build("BlindedDenominationSignature");

export class ExchangeWithdrawResponse {
  ev_sig: BlindedDenominationSignature;
}

export class ExchangeWithdrawBatchResponse {
  ev_sigs: ExchangeWithdrawResponse[];
}

export interface MerchantPayResponse {
  sig: string;
  pos_confirmation?: string;
}

export interface ExchangeMeltRequest {
  coin_pub: CoinPublicKeyString;
  confirm_sig: EddsaSignatureString;
  denom_pub_hash: HashCodeString;
  denom_sig: UnblindedSignature;
  rc: string;
  value_with_fee: AmountString;
  age_commitment_hash?: HashCodeString;
}

export interface ExchangeMeltResponse {
  /**
   * Which of the kappa indices does the client not have to reveal.
   */
  noreveal_index: number;

  /**
   * Signature of TALER_RefreshMeltConfirmationPS whereby the exchange
   * affirms the successful melt and confirming the noreveal_index
   */
  exchange_sig: EddsaSignatureString;

  /*
   * public EdDSA key of the exchange that was used to generate the signature.
   * Should match one of the exchange's signing keys from /keys.  Again given
   * explicitly as the client might otherwise be confused by clock skew as to
   * which signing key was used.
   */
  exchange_pub: EddsaPublicKeyString;

  /*
   * Base URL to use for operations on the refresh context
   * (so the reveal operation).  If not given,
   * the base URL is the same as the one used for this request.
   * Can be used if the base URL for /refreshes/ differs from that
   * for /coins/, i.e. for load balancing.  Clients SHOULD
   * respect the refresh_base_url if provided.  Any HTTP server
   * belonging to an exchange MUST generate a 307 or 308 redirection
   * to the correct base URL should a client uses the wrong base
   * URL, or if the base URL has changed since the melt.
   *
   * When melting the same coin twice (technically allowed
   * as the response might have been lost on the network),
   * the exchange may return different values for the refresh_base_url.
   */
  refresh_base_url?: string;
}

export interface ExchangeRevealItem {
  ev_sig: BlindedDenominationSignature;
}

export interface ExchangeRevealResponse {
  // List of the exchange's blinded RSA signatures on the new coins.
  ev_sigs: ExchangeRevealItem[];
}

interface MerchantOrderStatusPaid {
  // Was the payment refunded (even partially, via refund or abort)?
  refunded: boolean;

  // Is any amount of the refund still waiting to be picked up (even partially)?
  refund_pending: boolean;

  // Amount that was refunded in total.
  refund_amount: AmountString;

  // Amount that already taken by the wallet.
  refund_taken: AmountString;
}

interface MerchantOrderRefundResponse {
  /**
   * Amount that was refunded in total.
   */
  refund_amount: AmountString;

  /**
   * Successful refunds for this payment, empty array for none.
   */
  refunds: MerchantCoinRefundStatus[];

  /**
   * Public key of the merchant.
   */
  merchant_pub: EddsaPublicKeyString;
}

export type MerchantCoinRefundStatus =
  | MerchantCoinRefundSuccessStatus
  | MerchantCoinRefundFailureStatus;

export interface MerchantCoinRefundSuccessStatus {
  type: "success";

  // HTTP status of the exchange request, 200 (integer) required for refund confirmations.
  exchange_status: 200;

  // the EdDSA :ref:signature (binary-only) with purpose
  // TALER_SIGNATURE_EXCHANGE_CONFIRM_REFUND using a current signing key of the
  // exchange affirming the successful refund
  exchange_sig: EddsaSignatureString;

  // public EdDSA key of the exchange that was used to generate the signature.
  // Should match one of the exchange's signing keys from /keys.  It is given
  // explicitly as the client might otherwise be confused by clock skew as to
  // which signing key was used.
  exchange_pub: EddsaPublicKeyString;

  // Refund transaction ID.
  rtransaction_id: number;

  // public key of a coin that was refunded
  coin_pub: EddsaPublicKeyString;

  // Amount that was refunded, including refund fee charged by the exchange
  // to the customer.
  refund_amount: AmountString;

  execution_time: TalerProtocolTimestamp;
}

export interface MerchantCoinRefundFailureStatus {
  type: "failure";

  // HTTP status of the exchange request, must NOT be 200.
  exchange_status: number;

  // Taler error code from the exchange reply, if available.
  exchange_code?: number;

  // If available, HTTP reply from the exchange.
  exchange_reply?: any;

  // Refund transaction ID.
  rtransaction_id: number;

  // public key of a coin that was refunded
  coin_pub: EddsaPublicKeyString;

  // Amount that was refunded, including refund fee charged by the exchange
  // to the customer.
  refund_amount: AmountString;

  execution_time: TalerProtocolTimestamp;
}

export interface MerchantOrderStatusUnpaid {
  /**
   * URI that the wallet must process to complete the payment.
   */
  taler_pay_uri: string;

  /**
   * Alternative order ID which was paid for already in the same session.
   *
   * Only given if the same product was purchased before in the same session.
   */
  already_paid_order_id?: string;
}

/**
 * Response body for the following endpoint:
 *
 * POST {talerBankIntegrationApi}/withdrawal-operation/{wopid}
 */
export interface BankWithdrawalOperationPostResponse {
  // Current status of the operation
  // pending: the operation is pending parameters selection (exchange and reserve public key)
  // selected: the operations has been selected and is pending confirmation
  // aborted: the operation has been aborted
  // confirmed: the transfer has been confirmed and registered by the bank
  status: "selected" | "aborted" | "confirmed" | "pending";

  // URL that the user needs to navigate to in order to
  // complete some final confirmation (e.g. 2FA).
  //
  // Only applicable when status is selected or pending.
  // It may contain withdrawal operation id
  confirm_transfer_url?: string;

  // Deprecated field use status instead
  // The transfer has been confirmed and registered by the bank.
  // Does not guarantee that the funds have arrived at the exchange already.
  transfer_done: boolean;
}

export const codeForBankWithdrawalOperationPostResponse =
  (): Codec<BankWithdrawalOperationPostResponse> =>
    buildCodecForObject<BankWithdrawalOperationPostResponse>()
      .property(
        "status",
        codecForEither(
          codecForConstString("selected"),
          codecForConstString("confirmed"),
          codecForConstString("aborted"),
          codecForConstString("pending"),
        ),
      )
      .property("confirm_transfer_url", codecOptional(codecForString()))
      .property("transfer_done", codecForBoolean())
      .build("BankWithdrawalOperationPostResponse");

export type DenominationPubKey = RsaDenominationPubKey | CsDenominationPubKey;

export interface RsaDenominationPubKey {
  readonly cipher: DenomKeyType.Rsa;
  readonly rsa_public_key: string;
  readonly age_mask: number;
}

export interface CsDenominationPubKey {
  readonly cipher: DenomKeyType.ClauseSchnorr;
  readonly age_mask: number;
  readonly cs_public_key: string;
}

export namespace DenominationPubKey {
  export function cmp(
    p1: DenominationPubKey,
    p2: DenominationPubKey,
  ): -1 | 0 | 1 {
    if (p1.cipher < p2.cipher) {
      return -1;
    } else if (p1.cipher > p2.cipher) {
      return +1;
    } else if (
      p1.cipher === DenomKeyType.Rsa &&
      p2.cipher === DenomKeyType.Rsa
    ) {
      if ((p1.age_mask ?? 0) < (p2.age_mask ?? 0)) {
        return -1;
      } else if ((p1.age_mask ?? 0) > (p2.age_mask ?? 0)) {
        return 1;
      }
      return strcmp(p1.rsa_public_key, p2.rsa_public_key);
    } else if (
      p1.cipher === DenomKeyType.ClauseSchnorr &&
      p2.cipher === DenomKeyType.ClauseSchnorr
    ) {
      if ((p1.age_mask ?? 0) < (p2.age_mask ?? 0)) {
        return -1;
      } else if ((p1.age_mask ?? 0) > (p2.age_mask ?? 0)) {
        return 1;
      }
      return strcmp(p1.cs_public_key, p2.cs_public_key);
    } else {
      throw Error("unsupported cipher");
    }
  }
}

export const codecForRsaDenominationPubKey = () =>
  buildCodecForObject<RsaDenominationPubKey>()
    .property("cipher", codecForConstString(DenomKeyType.Rsa))
    .property("rsa_public_key", codecForString())
    .property("age_mask", codecForNumber())
    .build("DenominationPubKey");

export const codecForCsDenominationPubKey = () =>
  buildCodecForObject<CsDenominationPubKey>()
    .property("cipher", codecForConstString(DenomKeyType.ClauseSchnorr))
    .property("cs_public_key", codecForString())
    .property("age_mask", codecForNumber())
    .build("CsDenominationPubKey");

export const codecForDenominationPubKey = () =>
  buildCodecForUnion<DenominationPubKey>()
    .discriminateOn("cipher")
    .alternative(DenomKeyType.Rsa, codecForRsaDenominationPubKey())
    .alternative(DenomKeyType.ClauseSchnorr, codecForCsDenominationPubKey())
    .build("DenominationPubKey");

declare const __amount_str: unique symbol;
export type AmountString = string & { [__amount_str]: true };
// export type AmountString = string;
export type Base32String = string;
export type EddsaSignatureString = string;
export type EddsaPublicKeyString = string;
export type CoinPublicKeyString = string;

export const codecForDenomination = (): Codec<ExchangeDenomination> =>
  buildCodecForObject<ExchangeDenomination>()
    .property("value", codecForString())
    .property("denom_pub", codecForDenominationPubKey())
    .property("fee_withdraw", codecForString())
    .property("fee_deposit", codecForString())
    .property("fee_refresh", codecForString())
    .property("fee_refund", codecForString())
    .property("stamp_start", codecForTimestamp)
    .property("stamp_expire_withdraw", codecForTimestamp)
    .property("stamp_expire_legal", codecForTimestamp)
    .property("stamp_expire_deposit", codecForTimestamp)
    .property("master_sig", codecForString())
    .build("Denomination");

export const codecForAuditorDenomSig = (): Codec<AuditorDenomSig> =>
  buildCodecForObject<AuditorDenomSig>()
    .property("denom_pub_h", codecForString())
    .property("auditor_sig", codecForString())
    .build("AuditorDenomSig");

export const codecForAuditor = (): Codec<ExchangeAuditor> =>
  buildCodecForObject<ExchangeAuditor>()
    .property("auditor_pub", codecForString())
    .property("auditor_url", codecForString())
    .property("denomination_keys", codecForList(codecForAuditorDenomSig()))
    .build("Auditor");

export const codecForExchangeHandle = (): Codec<ExchangeHandle> =>
  buildCodecForObject<ExchangeHandle>()
    .property("master_pub", codecForString())
    .property("url", codecForString())
    .build("ExchangeHandle");

export const codecForAuditorHandle = (): Codec<AuditorHandle> =>
  buildCodecForObject<AuditorHandle>()
    .property("name", codecForString())
    .property("auditor_pub", codecForString())
    .property("url", codecForString())
    .build("AuditorHandle");

export const codecForLocation = (): Codec<Location> =>
  buildCodecForObject<Location>()
    .property("country", codecOptional(codecForString()))
    .property("country_subdivision", codecOptional(codecForString()))
    .property("building_name", codecOptional(codecForString()))
    .property("building_number", codecOptional(codecForString()))
    .property("district", codecOptional(codecForString()))
    .property("street", codecOptional(codecForString()))
    .property("post_code", codecOptional(codecForString()))
    .property("town", codecOptional(codecForString()))
    .property("town_location", codecOptional(codecForString()))
    .property("address_lines", codecOptional(codecForList(codecForString())))
    .build("Location");

export const codecForMerchantInfo = (): Codec<MerchantInfo> =>
  buildCodecForObject<MerchantInfo>()
    .property("name", codecForString())
    .property("address", codecOptional(codecForLocation()))
    .property("jurisdiction", codecOptional(codecForLocation()))
    .build("MerchantInfo");

export const codecForInternationalizedString =
  (): Codec<InternationalizedString> => codecForMap(codecForString());

export const codecForMerchantContractTerms = (): Codec<MerchantContractTerms> =>
  buildCodecForObject<MerchantContractTerms>()
    .property("order_id", codecForString())
    .property("fulfillment_url", codecOptional(codecForString()))
    .property("fulfillment_message", codecOptional(codecForString()))
    .property(
      "fulfillment_message_i18n",
      codecOptional(codecForInternationalizedString()),
    )
    .property("merchant_base_url", codecForString())
    .property("h_wire", codecForString())
    .property("auto_refund", codecOptional(codecForDuration))
    .property("wire_method", codecForString())
    .property("summary", codecForString())
    .property("summary_i18n", codecOptional(codecForInternationalizedString()))
    .property("nonce", codecForString())
    .property("amount", codecForAmountString())
    .property("pay_deadline", codecForTimestamp)
    .property("refund_deadline", codecForTimestamp)
    .property("wire_transfer_deadline", codecForTimestamp)
    .property("timestamp", codecForTimestamp)
    .property("delivery_location", codecOptional(codecForLocation()))
    .property("delivery_date", codecOptional(codecForTimestamp))
    .property("max_fee", codecForAmountString())
    .property("merchant", codecForMerchantInfo())
    .property("merchant_pub", codecForString())
    .property("exchanges", codecForList(codecForExchangeHandle()))
    .property("products", codecOptional(codecForList(codecForProduct())))
    .property("extra", codecForAny())
    .property("minimum_age", codecOptional(codecForNumber()))
    .build("MerchantContractTerms");

export const codecForPeerContractTerms = (): Codec<PeerContractTerms> =>
  buildCodecForObject<PeerContractTerms>()
    .property("summary", codecForString())
    .property("amount", codecForAmountString())
    .property("purse_expiration", codecForTimestamp)
    .build("PeerContractTerms");

export const codecForMerchantRefundPermission =
  (): Codec<MerchantAbortPayRefundDetails> =>
    buildCodecForObject<MerchantAbortPayRefundDetails>()
      .property("refund_amount", codecForAmountString())
      .property("refund_fee", codecForAmountString())
      .property("coin_pub", codecForString())
      .property("rtransaction_id", codecForNumber())
      .property("exchange_http_status", codecForNumber())
      .property("exchange_code", codecOptional(codecForNumber()))
      .property("exchange_reply", codecOptional(codecForAny()))
      .property("exchange_sig", codecOptional(codecForString()))
      .property("exchange_pub", codecOptional(codecForString()))
      .build("MerchantRefundPermission");

export const codecForBlindSigWrapperV2 = (): Codec<MerchantBlindSigWrapperV2> =>
  buildCodecForObject<MerchantBlindSigWrapperV2>()
    .property("blind_sig", codecForBlindedDenominationSignature())
    .build("MerchantBlindSigWrapperV2");

export const codecForMerchantTipResponseV2 = (): Codec<MerchantTipResponseV2> =>
  buildCodecForObject<MerchantTipResponseV2>()
    .property("blind_sigs", codecForList(codecForBlindSigWrapperV2()))
    .build("MerchantTipResponseV2");

export const codecForRecoup = (): Codec<Recoup> =>
  buildCodecForObject<Recoup>()
    .property("h_denom_pub", codecForString())
    .build("Recoup");

export const codecForExchangeSigningKey = (): Codec<ExchangeSignKeyJson> =>
  buildCodecForObject<ExchangeSignKeyJson>()
    .property("key", codecForString())
    .property("master_sig", codecForString())
    .property("stamp_end", codecForTimestamp)
    .property("stamp_start", codecForTimestamp)
    .property("stamp_expire", codecForTimestamp)
    .build("ExchangeSignKeyJson");

export const codecForGlobalFees = (): Codec<GlobalFees> =>
  buildCodecForObject<GlobalFees>()
    .property("start_date", codecForTimestamp)
    .property("end_date", codecForTimestamp)
    .property("history_fee", codecForAmountString())
    .property("account_fee", codecForAmountString())
    .property("purse_fee", codecForAmountString())
    .property("history_expiration", codecForDuration)
    .property("purse_account_limit", codecForNumber())
    .property("purse_timeout", codecForDuration)
    .property("master_sig", codecForString())
    .build("GlobalFees");

// FIXME: Validate properly!
export const codecForNgDenominations: Codec<DenomGroup> = codecForAny();

export const codecForExchangeKeysJson = (): Codec<ExchangeKeysJson> =>
  buildCodecForObject<ExchangeKeysJson>()
    .property("base_url", codecForString())
    .property("currency", codecForString())
    .property("master_public_key", codecForString())
    .property("auditors", codecForList(codecForAuditor()))
    .property("list_issue_date", codecForTimestamp)
    .property("recoup", codecOptional(codecForList(codecForRecoup())))
    .property("signkeys", codecForList(codecForExchangeSigningKey()))
    .property("version", codecForString())
    .property("reserve_closing_delay", codecForDuration)
    .property("global_fees", codecForList(codecForGlobalFees()))
    .property("accounts", codecForList(codecForExchangeWireAccount()))
    .property("wire_fees", codecForMap(codecForList(codecForWireFeesJson())))
    .property("denominations", codecForList(codecForNgDenominations))
    .build("ExchangeKeysJson");

export const codecForWireFeesJson = (): Codec<WireFeesJson> =>
  buildCodecForObject<WireFeesJson>()
    .property("wire_fee", codecForString())
    .property("closing_fee", codecForString())
    .property("sig", codecForString())
    .property("start_date", codecForTimestamp)
    .property("end_date", codecForTimestamp)
    .build("WireFeesJson");

export const codecForProposal = (): Codec<Proposal> =>
  buildCodecForObject<Proposal>()
    .property("contract_terms", codecForAny())
    .property("sig", codecForString())
    .build("Proposal");

export const codecForCheckPaymentResponse = (): Codec<CheckPaymentResponse> =>
  buildCodecForObject<CheckPaymentResponse>()
    .property("order_status", codecForString())
    .property("refunded", codecOptional(codecForBoolean()))
    .property("refunded_amount", codecOptional(codecForString()))
    .property("contract_terms", codecOptional(codecForAny()))
    .property("taler_pay_uri", codecOptional(codecForString()))
    .property("contract_url", codecOptional(codecForString()))
    .build("CheckPaymentResponse");

export const codecForWithdrawOperationStatusResponse =
  (): Codec<WithdrawOperationStatusResponse> =>
    buildCodecForObject<WithdrawOperationStatusResponse>()
      .property(
        "status",
        codecForEither(
          codecForConstString("selected"),
          codecForConstString("confirmed"),
          codecForConstString("aborted"),
          codecForConstString("pending"),
        ),
      )
      .property("selection_done", codecForBoolean())
      .property("transfer_done", codecForBoolean())
      .property("aborted", codecForBoolean())
      .property("amount", codecForString())
      .property("sender_wire", codecOptional(codecForString()))
      .property("suggested_exchange", codecOptional(codecForString()))
      .property("confirm_transfer_url", codecOptional(codecForString()))
      .property("wire_types", codecForList(codecForString()))
      .build("WithdrawOperationStatusResponse");

export const codecForRewardPickupGetResponse =
  (): Codec<RewardPickupGetResponse> =>
    buildCodecForObject<RewardPickupGetResponse>()
      .property("reward_amount", codecForString())
      .property("exchange_url", codecForString())
      .property("next_url", codecOptional(codecForString()))
      .property("expiration", codecForTimestamp)
      .build("TipPickupGetResponse");

export const codecForRecoupConfirmation = (): Codec<RecoupConfirmation> =>
  buildCodecForObject<RecoupConfirmation>()
    .property("reserve_pub", codecOptional(codecForString()))
    .property("old_coin_pub", codecOptional(codecForString()))
    .build("RecoupConfirmation");

export const codecForWithdrawResponse = (): Codec<ExchangeWithdrawResponse> =>
  buildCodecForObject<ExchangeWithdrawResponse>()
    .property("ev_sig", codecForBlindedDenominationSignature())
    .build("WithdrawResponse");

export const codecForExchangeWithdrawBatchResponse =
  (): Codec<ExchangeWithdrawBatchResponse> =>
    buildCodecForObject<ExchangeWithdrawBatchResponse>()
      .property("ev_sigs", codecForList(codecForWithdrawResponse()))
      .build("WithdrawBatchResponse");

export const codecForMerchantPayResponse = (): Codec<MerchantPayResponse> =>
  buildCodecForObject<MerchantPayResponse>()
    .property("sig", codecForString())
    .property("pos_confirmation", codecOptional(codecForString()))
    .build("MerchantPayResponse");

export const codecForExchangeMeltResponse = (): Codec<ExchangeMeltResponse> =>
  buildCodecForObject<ExchangeMeltResponse>()
    .property("exchange_pub", codecForString())
    .property("exchange_sig", codecForString())
    .property("noreveal_index", codecForNumber())
    .property("refresh_base_url", codecOptional(codecForString()))
    .build("ExchangeMeltResponse");

export const codecForExchangeRevealItem = (): Codec<ExchangeRevealItem> =>
  buildCodecForObject<ExchangeRevealItem>()
    .property("ev_sig", codecForBlindedDenominationSignature())
    .build("ExchangeRevealItem");

export const codecForExchangeRevealResponse =
  (): Codec<ExchangeRevealResponse> =>
    buildCodecForObject<ExchangeRevealResponse>()
      .property("ev_sigs", codecForList(codecForExchangeRevealItem()))
      .build("ExchangeRevealResponse");

export const codecForMerchantOrderStatusPaid =
  (): Codec<MerchantOrderStatusPaid> =>
    buildCodecForObject<MerchantOrderStatusPaid>()
      .property("refund_amount", codecForAmountString())
      .property("refund_taken", codecForAmountString())
      .property("refund_pending", codecForBoolean())
      .property("refunded", codecForBoolean())
      .build("MerchantOrderStatusPaid");

export const codecForMerchantOrderStatusUnpaid =
  (): Codec<MerchantOrderStatusUnpaid> =>
    buildCodecForObject<MerchantOrderStatusUnpaid>()
      .property("taler_pay_uri", codecForString())
      .property("already_paid_order_id", codecOptional(codecForString()))
      .build("MerchantOrderStatusUnpaid");

export interface AbortRequest {
  // hash of the order's contract terms (this is used to authenticate the
  // wallet/customer in case $ORDER_ID is guessable).
  h_contract: string;

  // List of coins the wallet would like to see refunds for.
  // (Should be limited to the coins for which the original
  // payment succeeded, as far as the wallet knows.)
  coins: AbortingCoin[];
}

export interface AbortingCoin {
  // Public key of a coin for which the wallet is requesting an abort-related refund.
  coin_pub: EddsaPublicKeyString;

  // The amount to be refunded (matches the original contribution)
  contribution: AmountString;

  // URL of the exchange this coin was withdrawn from.
  exchange_url: string;
}

export interface AbortResponse {
  // List of refund responses about the coins that the wallet
  // requested an abort for.  In the same order as the 'coins'
  // from the original request.
  // The rtransaction_id is implied to be 0.
  refunds: MerchantAbortPayRefundStatus[];
}

export type MerchantAbortPayRefundStatus =
  | MerchantAbortPayRefundSuccessStatus
  | MerchantAbortPayRefundFailureStatus;

// Details about why a refund failed.
export interface MerchantAbortPayRefundFailureStatus {
  // Used as tag for the sum type RefundStatus sum type.
  type: "failure";

  // HTTP status of the exchange request, must NOT be 200.
  exchange_status: number;

  // Taler error code from the exchange reply, if available.
  exchange_code?: number;

  // If available, HTTP reply from the exchange.
  exchange_reply?: unknown;
}

// Additional details needed to verify the refund confirmation signature
// (h_contract_terms and merchant_pub) are already known
// to the wallet and thus not included.
export interface MerchantAbortPayRefundSuccessStatus {
  // Used as tag for the sum type MerchantCoinRefundStatus sum type.
  type: "success";

  // HTTP status of the exchange request, 200 (integer) required for refund confirmations.
  exchange_status: 200;

  // the EdDSA :ref:signature (binary-only) with purpose
  // TALER_SIGNATURE_EXCHANGE_CONFIRM_REFUND using a current signing key of the
  // exchange affirming the successful refund
  exchange_sig: string;

  // public EdDSA key of the exchange that was used to generate the signature.
  // Should match one of the exchange's signing keys from /keys.  It is given
  // explicitly as the client might otherwise be confused by clock skew as to
  // which signing key was used.
  exchange_pub: string;
}

export interface FutureKeysResponse {
  future_denoms: any[];

  future_signkeys: any[];

  master_pub: string;

  denom_secmod_public_key: string;

  // Public key of the signkey security module.
  signkey_secmod_public_key: string;
}

export const codecForKeysManagementResponse = (): Codec<FutureKeysResponse> =>
  buildCodecForObject<FutureKeysResponse>()
    .property("master_pub", codecForString())
    .property("future_signkeys", codecForList(codecForAny()))
    .property("future_denoms", codecForList(codecForAny()))
    .property("denom_secmod_public_key", codecForAny())
    .property("signkey_secmod_public_key", codecForAny())
    .build("FutureKeysResponse");

export interface MerchantConfigResponse {
  currency: string;
  name: string;
  version: string;
}

export const codecForMerchantConfigResponse =
  (): Codec<MerchantConfigResponse> =>
    buildCodecForObject<MerchantConfigResponse>()
      .property("currency", codecForString())
      .property("name", codecForString())
      .property("version", codecForString())
      .build("MerchantConfigResponse");

export enum ExchangeProtocolVersion {
  /**
   * Current version supported by the wallet.
   */
  V12 = 12,
}

export enum MerchantProtocolVersion {
  /**
   * Current version supported by the wallet.
   */
  V3 = 3,
}

export type CoinEnvelope = CoinEnvelopeRsa | CoinEnvelopeCs;

export interface CoinEnvelopeRsa {
  cipher: DenomKeyType.Rsa;
  rsa_blinded_planchet: string;
}

export interface CoinEnvelopeCs {
  cipher: DenomKeyType.ClauseSchnorr;
  // FIXME: add remaining fields
}

export type HashCodeString = string;

export interface ExchangeWithdrawRequest {
  denom_pub_hash: HashCodeString;
  reserve_sig: EddsaSignatureString;
  coin_ev: CoinEnvelope;
}

export interface ExchangeBatchWithdrawRequest {
  planchets: ExchangeWithdrawRequest[];
}

export interface ExchangeRefreshRevealRequest {
  new_denoms_h: HashCodeString[];
  coin_evs: CoinEnvelope[];
  /**
   * kappa - 1 transfer private keys (ephemeral ECDHE keys).
   */
  transfer_privs: string[];

  transfer_pub: EddsaPublicKeyString;

  link_sigs: EddsaSignatureString[];

  /**
   * Iff the corresponding denomination has support for age restriction,
   * the client MUST provide the original age commitment, i.e. the vector
   * of public keys.
   */
  old_age_commitment?: Edx25519PublicKeyEnc[];
}

interface DepositConfirmationSignature {
  // The EdDSA signature of `TALER_DepositConfirmationPS` using a current
  // `signing key of the exchange <sign-key-priv>` affirming the successful
  // deposit and that the exchange will transfer the funds after the refund
  // deadline, or as soon as possible if the refund deadline is zero.
  exchange_sig: EddsaSignatureString;
}

export interface BatchDepositSuccess {
  // Optional base URL of the exchange for looking up wire transfers
  // associated with this transaction.  If not given,
  // the base URL is the same as the one used for this request.
  // Can be used if the base URL for ``/transactions/`` differs from that
  // for ``/coins/``, i.e. for load balancing.  Clients SHOULD
  // respect the ``transaction_base_url`` if provided.  Any HTTP server
  // belonging to an exchange MUST generate a 307 or 308 redirection
  // to the correct base URL should a client uses the wrong base
  // URL, or if the base URL has changed since the deposit.
  transaction_base_url?: string;

  // Timestamp when the deposit was received by the exchange.
  exchange_timestamp: TalerProtocolTimestamp;

  // `Public EdDSA key of the exchange <sign-key-pub>` that was used to
  // generate the signature.
  // Should match one of the exchange's signing keys from ``/keys``.  It is given
  // explicitly as the client might otherwise be confused by clock skew as to
  // which signing key was used.
  exchange_pub: EddsaPublicKeyString;

  // Array of deposit confirmation signatures from the exchange
  // Entries must be in the same order the coins were given
  // in the batch deposit request.
  exchange_sig: EddsaSignatureString;
}

export const codecForBatchDepositSuccess = (): Codec<BatchDepositSuccess> =>
  buildCodecForObject<BatchDepositSuccess>()
    .property("exchange_pub", codecForString())
    .property("exchange_sig", codecForString())
    .property("exchange_timestamp", codecForTimestamp)
    .property("transaction_base_url", codecOptional(codecForString()))
    .build("BatchDepositSuccess");

export interface TrackTransactionWired {
  // Raw wire transfer identifier of the deposit.
  wtid: Base32String;

  // When was the wire transfer given to the bank.
  execution_time: TalerProtocolTimestamp;

  // The contribution of this coin to the total (without fees)
  coin_contribution: AmountString;

  // Binary-only Signature_ with purpose TALER_SIGNATURE_EXCHANGE_CONFIRM_WIRE
  // over a TALER_ConfirmWirePS
  // whereby the exchange affirms the successful wire transfer.
  exchange_sig: EddsaSignatureString;

  // Public EdDSA key of the exchange that was used to generate the signature.
  // Should match one of the exchange's signing keys from /keys.  Again given
  // explicitly as the client might otherwise be confused by clock skew as to
  // which signing key was used.
  exchange_pub: EddsaPublicKeyString;
}

export const codecForTackTransactionWired = (): Codec<TrackTransactionWired> =>
  buildCodecForObject<TrackTransactionWired>()
    .property("wtid", codecForString())
    .property("execution_time", codecForTimestamp)
    .property("coin_contribution", codecForAmountString())
    .property("exchange_sig", codecForString())
    .property("exchange_pub", codecForString())
    .build("TackTransactionWired");

interface TrackTransactionAccepted {
  // Legitimization target that the merchant should
  // use to check for its KYC status using
  // the /kyc-check/$REQUIREMENT_ROW/... endpoint.
  // Optional, not present if the deposit has not
  // yet been aggregated to the point that a KYC
  // need has been evaluated.
  requirement_row?: number;

  // True if the KYC check for the merchant has been
  // satisfied.  False does not mean that KYC
  // is strictly needed, unless also a
  // legitimization_uuid is provided.
  kyc_ok: boolean;

  // Time by which the exchange currently thinks the deposit will be executed.
  // Actual execution may be later if the KYC check is not satisfied by then.
  execution_time: TalerProtocolTimestamp;
}

export const codecForTackTransactionAccepted =
  (): Codec<TrackTransactionAccepted> =>
    buildCodecForObject<TrackTransactionAccepted>()
      .property("requirement_row", codecOptional(codecForNumber()))
      .property("kyc_ok", codecForBoolean())
      .property("execution_time", codecForTimestamp)
      .build("TackTransactionAccepted");

export type TrackTransaction =
  | ({ type: "accepted" } & TrackTransactionAccepted)
  | ({ type: "wired" } & TrackTransactionWired);

export interface PurseDeposit {
  /**
   * Amount to be deposited, can be a fraction of the
   * coin's total value.
   */
  amount: AmountString;

  /**
   * Hash of denomination RSA key with which the coin is signed.
   */
  denom_pub_hash: HashCodeString;

  /**
   * Exchange's unblinded RSA signature of the coin.
   */
  ub_sig: UnblindedSignature;

  /**
   * Age commitment for the coin, if the denomination is age-restricted.
   */
  age_commitment?: string[];

  /**
   * Attestation for the minimum age, if the denomination is age-restricted.
   */
  attest?: string;

  /**
   * Signature over TALER_PurseDepositSignaturePS
   * of purpose TALER_SIGNATURE_WALLET_PURSE_DEPOSIT
   * made by the customer with the
   * coin's private key.
   */
  coin_sig: EddsaSignatureString;

  /**
   * Public key of the coin being deposited into the purse.
   */
  coin_pub: EddsaPublicKeyString;
}

export interface ExchangePurseMergeRequest {
  // payto://-URI of the account the purse is to be merged into.
  // Must be of the form: 'payto://taler/$EXCHANGE_URL/$RESERVE_PUB'.
  payto_uri: string;

  // EdDSA signature of the account/reserve affirming the merge
  // over a TALER_AccountMergeSignaturePS.
  // Must be of purpose TALER_SIGNATURE_ACCOUNT_MERGE
  reserve_sig: EddsaSignatureString;

  // EdDSA signature of the purse private key affirming the merge
  // over a TALER_PurseMergeSignaturePS.
  // Must be of purpose TALER_SIGNATURE_PURSE_MERGE.
  merge_sig: EddsaSignatureString;

  // Client-side timestamp of when the merge request was made.
  merge_timestamp: TalerProtocolTimestamp;
}

export interface ExchangeGetContractResponse {
  purse_pub: string;
  econtract_sig: string;
  econtract: string;
}

export const codecForExchangeGetContractResponse =
  (): Codec<ExchangeGetContractResponse> =>
    buildCodecForObject<ExchangeGetContractResponse>()
      .property("purse_pub", codecForString())
      .property("econtract_sig", codecForString())
      .property("econtract", codecForString())
      .build("ExchangeGetContractResponse");

/**
 * Contract terms between two wallets (as opposed to a merchant and wallet).
 */
export interface PeerContractTerms {
  amount: AmountString;
  summary: string;
  purse_expiration: TalerProtocolTimestamp;
}

export interface EncryptedContract {
  // Encrypted contract.
  econtract: string;

  // Signature over the (encrypted) contract.
  econtract_sig: string;

  // Ephemeral public key for the DH operation to decrypt the encrypted contract.
  contract_pub: string;
}

/**
 * Payload for /reserves/{reserve_pub}/purse
 * endpoint of the exchange.
 */
export interface ExchangeReservePurseRequest {
  /**
   * Minimum amount that must be credited to the reserve, that is
   * the total value of the purse minus the deposit fees.
   * If the deposit fees are lower, the contribution to the
   * reserve can be higher!
   */
  purse_value: AmountString;

  // Minimum age required for all coins deposited into the purse.
  min_age: number;

  // Purse fee the reserve owner is willing to pay
  // for the purse creation. Optional, if not present
  // the purse is to be created from the purse quota
  // of the reserve.
  purse_fee: AmountString;

  // Optional encrypted contract, in case the buyer is
  // proposing the contract and thus establishing the
  // purse with the payment.
  econtract?: EncryptedContract;

  // EdDSA public key used to approve merges of this purse.
  merge_pub: EddsaPublicKeyString;

  // EdDSA signature of the purse private key affirming the merge
  // over a TALER_PurseMergeSignaturePS.
  // Must be of purpose TALER_SIGNATURE_PURSE_MERGE.
  merge_sig: EddsaSignatureString;

  // EdDSA signature of the account/reserve affirming the merge.
  // Must be of purpose TALER_SIGNATURE_WALLET_ACCOUNT_MERGE
  reserve_sig: EddsaSignatureString;

  // Purse public key.
  purse_pub: EddsaPublicKeyString;

  // EdDSA signature of the purse over
  // TALER_PurseRequestSignaturePS of
  // purpose TALER_SIGNATURE_PURSE_REQUEST
  // confirming that the
  // above details hold for this purse.
  purse_sig: EddsaSignatureString;

  // SHA-512 hash of the contact of the purse.
  h_contract_terms: HashCodeString;

  // Client-side timestamp of when the merge request was made.
  merge_timestamp: TalerProtocolTimestamp;

  // Indicative time by which the purse should expire
  // if it has not been paid.
  purse_expiration: TalerProtocolTimestamp;
}

export interface ExchangePurseDeposits {
  // Array of coins to deposit into the purse.
  deposits: PurseDeposit[];
}

/**
 * @deprecated batch deposit should be used.
 */
export interface ExchangeDepositRequest {
  // Amount to be deposited, can be a fraction of the
  // coin's total value.
  contribution: AmountString;

  // The merchant's account details.
  // In case of an auction policy, it refers to the seller.
  merchant_payto_uri: string;

  // The salt is used to hide the payto_uri from customers
  // when computing the h_wire of the merchant.
  wire_salt: string;

  // SHA-512 hash of the contract of the merchant with the customer.  Further
  // details are never disclosed to the exchange.
  h_contract_terms: HashCodeString;

  // Hash of denomination RSA key with which the coin is signed.
  denom_pub_hash: HashCodeString;

  // Exchange's unblinded RSA signature of the coin.
  ub_sig: UnblindedSignature;

  // Timestamp when the contract was finalized.
  timestamp: TalerProtocolTimestamp;

  // Indicative time by which the exchange undertakes to transfer the funds to
  // the merchant, in case of successful payment. A wire transfer deadline of 'never'
  // is not allowed.
  wire_transfer_deadline: TalerProtocolTimestamp;

  // EdDSA public key of the merchant, so that the client can identify the
  // merchant for refund requests.
  //
  // THIS FIELD WILL BE DEPRECATED, once the refund mechanism becomes a
  // policy via extension.
  merchant_pub: EddsaPublicKeyString;

  // Date until which the merchant can issue a refund to the customer via the
  // exchange, to be omitted if refunds are not allowed.
  //
  // THIS FIELD WILL BE DEPRECATED, once the refund mechanism becomes a
  // policy via extension.
  refund_deadline?: TalerProtocolTimestamp;

  // CAVEAT: THIS IS WORK IN PROGRESS
  // (Optional) policy for the deposit.
  // This might be a refund, auction or escrow policy.
  //
  // Note that support for policies is an optional feature of the exchange.
  // Optional features are so called "extensions" in Taler. The exchange
  // provides the list of supported extensions, including policies, in the
  // ExtensionsManifestsResponse response to the /keys endpoint.
  policy?: any;

  // Signature over TALER_DepositRequestPS, made by the customer with the
  // coin's private key.
  coin_sig: EddsaSignatureString;

  h_age_commitment?: string;
}

export type WireSalt = string;

export interface ExchangeBatchDepositRequest {
  // The merchant's account details.
  merchant_payto_uri: string;

  // The salt is used to hide the ``payto_uri`` from customers
  // when computing the ``h_wire`` of the merchant.
  wire_salt: WireSalt;

  // SHA-512 hash of the contract of the merchant with the customer.  Further
  // details are never disclosed to the exchange.
  h_contract_terms: HashCodeString;

  // The list of coins that are going to be deposited with this Request.
  coins: BatchDepositRequestCoin[];

  // Timestamp when the contract was finalized.
  timestamp: TalerProtocolTimestamp;

  // Indicative time by which the exchange undertakes to transfer the funds to
  // the merchant, in case of successful payment. A wire transfer deadline of 'never'
  // is not allowed.
  wire_transfer_deadline: TalerProtocolTimestamp;

  // EdDSA `public key of the merchant <merchant-pub>`, so that the client can identify the
  // merchant for refund requests.
  merchant_pub: EddsaPublicKeyString;

  // Date until which the merchant can issue a refund to the customer via the
  // exchange, to be omitted if refunds are not allowed.
  //
  // THIS FIELD WILL BE DEPRECATED, once the refund mechanism becomes a
  // policy via extension.
  refund_deadline?: TalerProtocolTimestamp;

  // CAVEAT: THIS IS WORK IN PROGRESS
  // (Optional) policy for the batch-deposit.
  // This might be a refund, auction or escrow policy.
  policy?: any;
}

export interface BatchDepositRequestCoin {
  // EdDSA public key of the coin being deposited.
  coin_pub: EddsaPublicKeyString;

  // Hash of denomination RSA key with which the coin is signed.
  denom_pub_hash: HashCodeString;

  // Exchange's unblinded RSA signature of the coin.
  ub_sig: UnblindedSignature;

  // Amount to be deposited, can be a fraction of the
  // coin's total value.
  contribution: Amounts;

  // Signature over `TALER_DepositRequestPS`, made by the customer with the
  // `coin's private key <coin-priv>`.
  coin_sig: EddsaSignatureString;

  h_age_commitment?: string;
}

export interface WalletKycUuid {
  // UUID that the wallet should use when initiating
  // the KYC check.
  requirement_row: number;

  // Hash of the payto:// account URI for the wallet.
  h_payto: string;
}

export const codecForWalletKycUuid = (): Codec<WalletKycUuid> =>
  buildCodecForObject<WalletKycUuid>()
    .property("requirement_row", codecForNumber())
    .property("h_payto", codecForString())
    .build("WalletKycUuid");

export interface MerchantUsingTemplateDetails {
  summary?: string;
  amount?: AmountString;
}

export interface ExchangeRefundRequest {
  // Amount to be refunded, can be a fraction of the
  // coin's total deposit value (including deposit fee);
  // must be larger than the refund fee.
  refund_amount: AmountString;

  // SHA-512 hash of the contact of the merchant with the customer.
  h_contract_terms: HashCodeString;

  // 64-bit transaction id of the refund transaction between merchant and customer.
  rtransaction_id: number;

  // EdDSA public key of the merchant.
  merchant_pub: EddsaPublicKeyString;

  // EdDSA signature of the merchant over a
  // TALER_RefundRequestPS with purpose
  // TALER_SIGNATURE_MERCHANT_REFUND
  // affirming the refund.
  merchant_sig: EddsaPublicKeyString;
}

export interface ExchangeRefundSuccessResponse {
  // The EdDSA :ref:signature (binary-only) with purpose
  // TALER_SIGNATURE_EXCHANGE_CONFIRM_REFUND over
  // a TALER_RecoupRefreshConfirmationPS
  // using a current signing key of the
  // exchange affirming the successful refund.
  exchange_sig: EddsaSignatureString;

  // Public EdDSA key of the exchange that was used to generate the signature.
  // Should match one of the exchange's signing keys from /keys.  It is given
  // explicitly as the client might otherwise be confused by clock skew as to
  // which signing key was used.
  exchange_pub: EddsaPublicKeyString;
}

export const codecForExchangeRefundSuccessResponse =
  (): Codec<ExchangeRefundSuccessResponse> =>
    buildCodecForObject<ExchangeRefundSuccessResponse>()
      .property("exchange_pub", codecForString())
      .property("exchange_sig", codecForString())
      .build("ExchangeRefundSuccessResponse");

export type AccountRestriction =
  | RegexAccountRestriction
  | DenyAllAccountRestriction;

export interface DenyAllAccountRestriction {
  type: "deny";
}

// Accounts interacting with this type of account
// restriction must have a payto://-URI matching
// the given regex.
export interface RegexAccountRestriction {
  type: "regex";

  // Regular expression that the payto://-URI of the
  // partner account must follow.  The regular expression
  // should follow posix-egrep, but without support for character
  // classes, GNU extensions, back-references or intervals. See
  // https://www.gnu.org/software/findutils/manual/html_node/find_html/posix_002degrep-regular-expression-syntax.html
  // for a description of the posix-egrep syntax. Applications
  // may support regexes with additional features, but exchanges
  // must not use such regexes.
  payto_regex: string;

  // Hint for a human to understand the restriction
  // (that is hopefully easier to comprehend than the regex itself).
  human_hint: string;

  // Map from IETF BCP 47 language tags to localized
  // human hints.
  human_hint_i18n?: InternationalizedString;
}

export interface ExchangeWireAccount {
  // payto:// URI identifying the account and wire method
  payto_uri: string;

  // URI to convert amounts from or to the currency used by
  // this wire account of the exchange. Missing if no
  // conversion is applicable.
  conversion_url?: string;

  // Restrictions that apply to bank accounts that would send
  // funds to the exchange (crediting this exchange bank account).
  // Optional, empty array for unrestricted.
  credit_restrictions: AccountRestriction[];

  // Restrictions that apply to bank accounts that would receive
  // funds from the exchange (debiting this exchange bank account).
  // Optional, empty array for unrestricted.
  debit_restrictions: AccountRestriction[];

  // Signature using the exchange's offline key over
  // a TALER_MasterWireDetailsPS
  // with purpose TALER_SIGNATURE_MASTER_WIRE_DETAILS.
  master_sig: EddsaSignatureString;

  // Display label wallets should use to show this
  // bank account.
  // Since protocol **v19**.
  bank_label?: string;
  priority?: number;
}

export const codecForExchangeWireAccount = (): Codec<ExchangeWireAccount> =>
  buildCodecForObject<ExchangeWireAccount>()
    .property("conversion_url", codecOptional(codecForStringURL()))
    .property("credit_restrictions", codecForList(codecForAny()))
    .property("debit_restrictions", codecForList(codecForAny()))
    .property("master_sig", codecForString())
    .property("payto_uri", codecForString())
    .property("bank_label", codecOptional(codecForString()))
    .property("priority", codecOptional(codecForNumber()))
    .build("WireAccount");

export type Integer = number;

export interface BankConversionInfoConfig {
  // libtool-style representation of the Bank protocol version, see
  // https://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning
  // The format is "current:revision:age".
  version: string;

  // Name of the API.
  name: "taler-conversion-info";

  regional_currency: string;

  fiat_currency: string;

  // Currency used by this bank.
  regional_currency_specification: CurrencySpecification;

  // External currency used during conversion.
  fiat_currency_specification: CurrencySpecification;
}

export const codecForBankConversionInfoConfig =
  (): Codec<BankConversionInfoConfig> =>
    buildCodecForObject<BankConversionInfoConfig>()
      .property("name", codecForConstString("taler-conversion-info"))
      .property("version", codecForString())
      .property("fiat_currency", codecForString())
      .property("regional_currency", codecForString())
      .property("fiat_currency_specification", codecForCurrencySpecificiation())
      .property(
        "regional_currency_specification",
        codecForCurrencySpecificiation(),
      )
      .build("BankConversionInfoConfig");

export interface DenominationExpiredMessage {
  // Taler error code.  Note that beyond
  // expiration this message format is also
  // used if the key is not yet valid, or
  // has been revoked.
  code: number;

  // Signature by the exchange over a
  // TALER_DenominationExpiredAffirmationPS.
  // Must have purpose TALER_SIGNATURE_EXCHANGE_AFFIRM_DENOM_EXPIRED.
  exchange_sig: EddsaSignatureString;

  // Public key of the exchange used to create
  // the 'exchange_sig.
  exchange_pub: EddsaPublicKeyString;

  // Hash of the denomination public key that is unknown.
  h_denom_pub: HashCodeString;

  // When was the signature created.
  timestamp: TalerProtocolTimestamp;

  // What kind of operation was requested that now
  // failed?
  oper: string;
}

export const codecForDenominationExpiredMessage = () =>
  buildCodecForObject<DenominationExpiredMessage>()
    .property("code", codecForNumber())
    .property("exchange_sig", codecForString())
    .property("exchange_pub", codecForString())
    .property("h_denom_pub", codecForString())
    .property("timestamp", codecForTimestamp)
    .property("oper", codecForString())
    .build("DenominationExpiredMessage");

export interface CoinHistoryResponse {
  // Current balance of the coin.
  balance: AmountString;

  // Hash of the coin's denomination.
  h_denom_pub: HashCodeString;

  // Transaction history for the coin.
  history: any[];
}

export const codecForCoinHistoryResponse = () =>
  buildCodecForObject<CoinHistoryResponse>()
    .property("balance", codecForAmountString())
    .property("h_denom_pub", codecForString())
    .property("history", codecForAny())
    .build("CoinHistoryResponse");