aboutsummaryrefslogtreecommitdiff
path: root/packages/taler-wallet-core/src/pay-peer-pull-credit.ts
blob: a92d8e764fdab7dc7c5c50889747110eec558b28 (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
/*
 This file is part of GNU Taler
 (C) 2022-2023 Taler Systems S.A.

 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/>
 */

/**
 * Imports.
 */
import {
  Amounts,
  CheckPeerPullCreditRequest,
  CheckPeerPullCreditResponse,
  ContractTermsUtil,
  ExchangeReservePurseRequest,
  ExchangeWalletKycStatus,
  HttpStatusCode,
  InitiatePeerPullCreditRequest,
  InitiatePeerPullCreditResponse,
  Logger,
  NotificationType,
  PeerContractTerms,
  ScopeInfo,
  ScopeType,
  TalerErrorCode,
  TalerErrorDetail,
  TalerPreciseTimestamp,
  TalerProtocolTimestamp,
  TalerUriAction,
  Transaction,
  TransactionAction,
  TransactionIdStr,
  TransactionMajorState,
  TransactionMinorState,
  TransactionState,
  TransactionType,
  WalletAccountMergeFlags,
  assertUnreachable,
  checkDbInvariant,
  codecForAccountKycStatus,
  codecForAny,
  codecForLegitimizationNeededResponse,
  encodeCrock,
  getRandomBytes,
  j2s,
  stringifyPayPullUri,
  stringifyTalerUri,
  talerPaytoFromExchangeReserve,
} from "@gnu-taler/taler-util";
import {
  readResponseJsonOrThrow,
  readSuccessResponseJsonOrThrow,
} from "@gnu-taler/taler-util/http";
import {
  PendingTaskType,
  TaskIdStr,
  TaskIdentifiers,
  TaskRunResult,
  TombstoneTag,
  TransactionContext,
  TransitionResult,
  TransitionResultType,
  constructTaskIdentifier,
  genericWaitForStateVal,
  requireExchangeTosAcceptedOrThrow,
  runWithClientCancellation,
} from "./common.js";
import {
  OperationRetryRecord,
  PeerPullCreditRecord,
  PeerPullPaymentCreditStatus,
  WalletDbAllStoresReadOnlyTransaction,
  WalletDbReadWriteTransaction,
  WalletDbStoresArr,
  WithdrawalGroupRecord,
  WithdrawalGroupStatus,
  WithdrawalRecordType,
  timestampPreciseFromDb,
  timestampPreciseToDb,
} from "./db.js";
import {
  BalanceThresholdCheckResult,
  checkIncomingAmountLegalUnderKycBalanceThreshold,
  fetchFreshExchange,
  getPreferredExchangeForCurrency,
  getPreferredExchangeForScope,
  getScopeForAllExchanges,
  handleStartExchangeWalletKyc,
} from "./exchanges.js";
import { checkPeerCreditHardLimitExceeded } from "./kyc.js";
import {
  codecForExchangePurseStatus,
  getMergeReserveInfo,
} from "./pay-peer-common.js";
import {
  TransitionInfo,
  constructTransactionIdentifier,
  isUnsuccessfulTransaction,
  notifyTransition,
} from "./transactions.js";
import { WalletExecutionContext } from "./wallet.js";
import {
  getExchangeWithdrawalInfo,
  internalCreateWithdrawalGroup,
  waitWithdrawalFinal,
} from "./withdraw.js";

const logger = new Logger("pay-peer-pull-credit.ts");

export class PeerPullCreditTransactionContext implements TransactionContext {
  readonly transactionId: TransactionIdStr;
  readonly taskId: TaskIdStr;

  constructor(
    public wex: WalletExecutionContext,
    public pursePub: string,
  ) {
    this.taskId = constructTaskIdentifier({
      tag: PendingTaskType.PeerPullCredit,
      pursePub,
    });
    this.transactionId = constructTransactionIdentifier({
      tag: TransactionType.PeerPullCredit,
      pursePub,
    });
  }

  /**
   * Transition a peer-pull-credit transaction.
   * Extra object stores may be accessed during the transition.
   */
  async transition<StoreNameArray extends WalletDbStoresArr = []>(
    opts: { extraStores?: StoreNameArray; transactionLabel?: string },
    f: (
      rec: PeerPullCreditRecord | undefined,
      tx: WalletDbReadWriteTransaction<
        [
          "peerPullCredit",
          "transactionsMeta",
          "operationRetries",
          "exchanges",
          "exchangeDetails",
          ...StoreNameArray,
        ]
      >,
    ) => Promise<TransitionResult<PeerPullCreditRecord>>,
  ): Promise<TransitionInfo | undefined> {
    const baseStores = [
      "peerPullCredit" as const,
      "transactionsMeta" as const,
      "operationRetries" as const,
      "exchanges" as const,
      "exchangeDetails" as const,
    ];
    const stores = opts.extraStores
      ? [...baseStores, ...opts.extraStores]
      : baseStores;

    let errorThrown: Error | undefined;
    const transitionInfo = await this.wex.db.runReadWriteTx(
      { storeNames: stores },
      async (tx) => {
        const rec = await tx.peerPullCredit.get(this.pursePub);
        let oldTxState: TransactionState;
        if (rec) {
          oldTxState = computePeerPullCreditTransactionState(rec);
        } else {
          oldTxState = {
            major: TransactionMajorState.None,
          };
        }
        let res: TransitionResult<PeerPullCreditRecord> | undefined;
        try {
          res = await f(rec, tx);
        } catch (error) {
          if (error instanceof Error) {
            errorThrown = error;
          }
          return undefined;
        }

        switch (res.type) {
          case TransitionResultType.Transition: {
            await tx.peerPullCredit.put(res.rec);
            await this.updateTransactionMeta(tx);
            const newTxState = computePeerPullCreditTransactionState(res.rec);
            return {
              oldTxState,
              newTxState,
            };
          }
          case TransitionResultType.Delete:
            await tx.peerPullCredit.delete(this.pursePub);
            await this.updateTransactionMeta(tx);
            return {
              oldTxState,
              newTxState: {
                major: TransactionMajorState.None,
              },
            };
          default:
            return undefined;
        }
      },
    );
    if (errorThrown) {
      throw errorThrown;
    }
    notifyTransition(this.wex, this.transactionId, transitionInfo);
    return transitionInfo;
  }

  async updateTransactionMeta(
    tx: WalletDbReadWriteTransaction<["peerPullCredit", "transactionsMeta"]>,
  ): Promise<void> {
    const ppcRec = await tx.peerPullCredit.get(this.pursePub);
    if (!ppcRec) {
      await tx.transactionsMeta.delete(this.transactionId);
      return;
    }
    await tx.transactionsMeta.put({
      transactionId: this.transactionId,
      status: ppcRec.status,
      timestamp: ppcRec.mergeTimestamp,
      currency: Amounts.currencyOf(ppcRec.amount),
      exchanges: [ppcRec.exchangeBaseUrl],
    });
  }

  /**
   * Get the full transaction details for the transaction.
   *
   * Returns undefined if the transaction is in a state where we do not have a
   * transaction item (e.g. if it was deleted).
   */
  async lookupFullTransaction(
    tx: WalletDbAllStoresReadOnlyTransaction,
  ): Promise<Transaction | undefined> {
    const pullCredit = await tx.peerPullCredit.get(this.pursePub);
    if (!pullCredit) {
      return undefined;
    }
    const ct = await tx.contractTerms.get(pullCredit.contractTermsHash);
    checkDbInvariant(!!ct, `no contract terms for p2p push ${this.pursePub}`);

    const peerContractTerms = ct.contractTermsRaw;

    let wsr: WithdrawalGroupRecord | undefined = undefined;
    let wsrOrt: OperationRetryRecord | undefined = undefined;
    if (pullCredit.withdrawalGroupId) {
      wsr = await tx.withdrawalGroups.get(pullCredit.withdrawalGroupId);
      if (wsr) {
        const withdrawalOpId = TaskIdentifiers.forWithdrawal(wsr);
        wsrOrt = await tx.operationRetries.get(withdrawalOpId);
      }
    }
    const pullCreditOpId =
      TaskIdentifiers.forPeerPullPaymentInitiation(pullCredit);
    let pullCreditOrt = await tx.operationRetries.get(pullCreditOpId);

    let kycUrl: string | undefined = undefined;
    if (pullCredit.kycPaytoHash) {
      kycUrl = new URL(
        `kyc-spa/${pullCredit.kycPaytoHash}`,
        pullCredit.exchangeBaseUrl,
      ).href;
    }

    if (wsr) {
      if (wsr.wgInfo.withdrawalType !== WithdrawalRecordType.PeerPullCredit) {
        throw Error(`Unexpected withdrawalType: ${wsr.wgInfo.withdrawalType}`);
      }
      /**
       * FIXME: this should be handled in the withdrawal process.
       * PeerPull withdrawal fails until reserve have funds but it is not
       * an error from the user perspective.
       */
      const silentWithdrawalErrorForInvoice =
        wsrOrt?.lastError &&
        wsrOrt.lastError.code ===
          TalerErrorCode.WALLET_WITHDRAWAL_GROUP_INCOMPLETE &&
        Object.values(wsrOrt.lastError.errorsPerCoin ?? {}).every((e) => {
          return (
            e.code === TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR &&
            e.httpStatusCode === 409
          );
        });
      const txState = computePeerPullCreditTransactionState(pullCredit);
      checkDbInvariant(wsr.instructedAmount !== undefined, "wg uninitialized");
      checkDbInvariant(wsr.denomsSel !== undefined, "wg uninitialized");
      checkDbInvariant(wsr.exchangeBaseUrl !== undefined, "wg uninitialized");
      return {
        type: TransactionType.PeerPullCredit,
        txState,
        scopes: await getScopeForAllExchanges(tx, [pullCredit.exchangeBaseUrl]),
        txActions: computePeerPullCreditTransactionActions(pullCredit),
        amountEffective: isUnsuccessfulTransaction(txState)
          ? Amounts.stringify(Amounts.zeroOfAmount(wsr.instructedAmount))
          : Amounts.stringify(wsr.denomsSel.totalCoinValue),
        amountRaw: Amounts.stringify(wsr.instructedAmount),
        exchangeBaseUrl: wsr.exchangeBaseUrl,
        timestamp: timestampPreciseFromDb(pullCredit.mergeTimestamp),
        info: {
          expiration: peerContractTerms.purse_expiration,
          summary: peerContractTerms.summary,
        },
        talerUri: stringifyPayPullUri({
          exchangeBaseUrl: wsr.exchangeBaseUrl,
          contractPriv: wsr.wgInfo.contractPriv,
        }),
        transactionId: constructTransactionIdentifier({
          tag: TransactionType.PeerPullCredit,
          pursePub: pullCredit.pursePub,
        }),
        abortReason: pullCredit.abortReason,
        failReason: pullCredit.failReason,
        // FIXME: Is this the KYC URL of the withdrawal group?!
        kycUrl: kycUrl,
        ...(wsrOrt?.lastError
          ? {
              error: silentWithdrawalErrorForInvoice
                ? undefined
                : wsrOrt.lastError,
            }
          : {}),
      };
    }

    const txState = computePeerPullCreditTransactionState(pullCredit);
    return {
      type: TransactionType.PeerPullCredit,
      txState,
      scopes: await getScopeForAllExchanges(tx, [pullCredit.exchangeBaseUrl]),
      txActions: computePeerPullCreditTransactionActions(pullCredit),
      amountEffective: isUnsuccessfulTransaction(txState)
        ? Amounts.stringify(Amounts.zeroOfAmount(peerContractTerms.amount))
        : Amounts.stringify(pullCredit.estimatedAmountEffective),
      amountRaw: Amounts.stringify(peerContractTerms.amount),
      exchangeBaseUrl: pullCredit.exchangeBaseUrl,
      timestamp: timestampPreciseFromDb(pullCredit.mergeTimestamp),
      info: {
        expiration: peerContractTerms.purse_expiration,
        summary: peerContractTerms.summary,
      },
      talerUri: stringifyPayPullUri({
        exchangeBaseUrl: pullCredit.exchangeBaseUrl,
        contractPriv: pullCredit.contractPriv,
      }),
      transactionId: constructTransactionIdentifier({
        tag: TransactionType.PeerPullCredit,
        pursePub: pullCredit.pursePub,
      }),
      kycUrl,
      kycAccessToken: pullCredit.kycAccessToken,
      kycPaytoHash: pullCredit.kycPaytoHash,
      abortReason: pullCredit.abortReason,
      failReason: pullCredit.failReason,
      ...(pullCreditOrt?.lastError ? { error: pullCreditOrt.lastError } : {}),
    };
  }

  async deleteTransaction(): Promise<void> {
    const { wex: ws, pursePub } = this;
    await ws.db.runReadWriteTx(
      {
        storeNames: [
          "withdrawalGroups",
          "peerPullCredit",
          "tombstones",
          "transactionsMeta",
        ],
      },
      async (tx) => {
        const pullIni = await tx.peerPullCredit.get(pursePub);
        if (!pullIni) {
          return;
        }
        if (pullIni.withdrawalGroupId) {
          const withdrawalGroupId = pullIni.withdrawalGroupId;
          const withdrawalGroupRecord =
            await tx.withdrawalGroups.get(withdrawalGroupId);
          if (withdrawalGroupRecord) {
            await tx.withdrawalGroups.delete(withdrawalGroupId);
            await tx.tombstones.put({
              id: TombstoneTag.DeleteWithdrawalGroup + ":" + withdrawalGroupId,
            });
          }
        }
        await tx.peerPullCredit.delete(pursePub);
        await this.updateTransactionMeta(tx);
        await tx.tombstones.put({
          id: TombstoneTag.DeletePeerPullCredit + ":" + pursePub,
        });
      },
    );

    return;
  }

  async suspendTransaction(): Promise<void> {
    const { wex, pursePub, taskId: retryTag, transactionId } = this;
    const transitionInfo = await wex.db.runReadWriteTx(
      { storeNames: ["peerPullCredit", "transactionsMeta"] },
      async (tx) => {
        const pullCreditRec = await tx.peerPullCredit.get(pursePub);
        if (!pullCreditRec) {
          logger.warn(`peer pull credit ${pursePub} not found`);
          return;
        }
        let newStatus: PeerPullPaymentCreditStatus | undefined = undefined;
        switch (pullCreditRec.status) {
          case PeerPullPaymentCreditStatus.PendingCreatePurse:
            newStatus = PeerPullPaymentCreditStatus.SuspendedCreatePurse;
            break;
          case PeerPullPaymentCreditStatus.PendingMergeKycRequired:
            newStatus = PeerPullPaymentCreditStatus.SuspendedMergeKycRequired;
            break;
          case PeerPullPaymentCreditStatus.PendingWithdrawing:
            newStatus = PeerPullPaymentCreditStatus.SuspendedWithdrawing;
            break;
          case PeerPullPaymentCreditStatus.PendingReady:
            newStatus = PeerPullPaymentCreditStatus.SuspendedReady;
            break;
          case PeerPullPaymentCreditStatus.AbortingDeletePurse:
            newStatus =
              PeerPullPaymentCreditStatus.SuspendedAbortingDeletePurse;
            break;
          case PeerPullPaymentCreditStatus.PendingBalanceKycRequired:
            newStatus = PeerPullPaymentCreditStatus.SuspendedBalanceKycRequired;
            break;
          case PeerPullPaymentCreditStatus.PendingBalanceKycInit:
            newStatus = PeerPullPaymentCreditStatus.SuspendedBalanceKycInit;
            break;
          case PeerPullPaymentCreditStatus.SuspendedBalanceKycRequired:
          case PeerPullPaymentCreditStatus.SuspendedCreatePurse:
          case PeerPullPaymentCreditStatus.SuspendedMergeKycRequired:
          case PeerPullPaymentCreditStatus.SuspendedReady:
          case PeerPullPaymentCreditStatus.SuspendedWithdrawing:
          case PeerPullPaymentCreditStatus.SuspendedBalanceKycInit:
          case PeerPullPaymentCreditStatus.SuspendedAbortingDeletePurse:
          case PeerPullPaymentCreditStatus.Done:
          case PeerPullPaymentCreditStatus.Aborted:
          case PeerPullPaymentCreditStatus.Failed:
          case PeerPullPaymentCreditStatus.Expired:
            break;
          default:
            assertUnreachable(pullCreditRec.status);
        }
        if (newStatus != null) {
          const oldTxState =
            computePeerPullCreditTransactionState(pullCreditRec);
          pullCreditRec.status = newStatus;
          const newTxState =
            computePeerPullCreditTransactionState(pullCreditRec);
          await tx.peerPullCredit.put(pullCreditRec);
          await this.updateTransactionMeta(tx);
          return {
            oldTxState,
            newTxState,
          };
        }
        return undefined;
      },
    );
    wex.taskScheduler.stopShepherdTask(retryTag);
    notifyTransition(wex, transactionId, transitionInfo);
  }

  async failTransaction(reason?: TalerErrorDetail): Promise<void> {
    const { wex, pursePub, taskId: retryTag, transactionId } = this;
    const transitionInfo = await wex.db.runReadWriteTx(
      { storeNames: ["peerPullCredit", "transactionsMeta"] },
      async (tx) => {
        const pullCreditRec = await tx.peerPullCredit.get(pursePub);
        if (!pullCreditRec) {
          logger.warn(`peer pull credit ${pursePub} not found`);
          return;
        }
        let newStatus: PeerPullPaymentCreditStatus | undefined = undefined;
        switch (pullCreditRec.status) {
          case PeerPullPaymentCreditStatus.PendingCreatePurse:
          case PeerPullPaymentCreditStatus.PendingMergeKycRequired:
          case PeerPullPaymentCreditStatus.PendingWithdrawing:
          case PeerPullPaymentCreditStatus.PendingReady:
          case PeerPullPaymentCreditStatus.Done:
          case PeerPullPaymentCreditStatus.SuspendedCreatePurse:
          case PeerPullPaymentCreditStatus.SuspendedMergeKycRequired:
          case PeerPullPaymentCreditStatus.SuspendedReady:
          case PeerPullPaymentCreditStatus.SuspendedWithdrawing:
          case PeerPullPaymentCreditStatus.Aborted:
          case PeerPullPaymentCreditStatus.Failed:
          case PeerPullPaymentCreditStatus.Expired:
          case PeerPullPaymentCreditStatus.PendingBalanceKycRequired:
          case PeerPullPaymentCreditStatus.SuspendedBalanceKycRequired:
          case PeerPullPaymentCreditStatus.PendingBalanceKycInit:
          case PeerPullPaymentCreditStatus.SuspendedBalanceKycInit:
            break;
          case PeerPullPaymentCreditStatus.AbortingDeletePurse:
          case PeerPullPaymentCreditStatus.SuspendedAbortingDeletePurse:
            newStatus = PeerPullPaymentCreditStatus.Failed;
            break;
          default:
            assertUnreachable(pullCreditRec.status);
        }
        if (newStatus != null) {
          const oldTxState =
            computePeerPullCreditTransactionState(pullCreditRec);
          pullCreditRec.status = newStatus;
          pullCreditRec.failReason = reason;
          const newTxState =
            computePeerPullCreditTransactionState(pullCreditRec);
          await tx.peerPullCredit.put(pullCreditRec);
          await this.updateTransactionMeta(tx);
          return {
            oldTxState,
            newTxState,
          };
        }
        return undefined;
      },
    );
    notifyTransition(wex, transactionId, transitionInfo);
    wex.taskScheduler.stopShepherdTask(retryTag);
  }

  async resumeTransaction(): Promise<void> {
    const { wex, pursePub, taskId: retryTag, transactionId } = this;
    const transitionInfo = await wex.db.runReadWriteTx(
      { storeNames: ["peerPullCredit", "transactionsMeta"] },
      async (tx) => {
        const pullCreditRec = await tx.peerPullCredit.get(pursePub);
        if (!pullCreditRec) {
          logger.warn(`peer pull credit ${pursePub} not found`);
          return;
        }
        let newStatus: PeerPullPaymentCreditStatus | undefined = undefined;
        switch (pullCreditRec.status) {
          case PeerPullPaymentCreditStatus.PendingCreatePurse:
          case PeerPullPaymentCreditStatus.PendingMergeKycRequired:
          case PeerPullPaymentCreditStatus.PendingWithdrawing:
          case PeerPullPaymentCreditStatus.PendingReady:
          case PeerPullPaymentCreditStatus.PendingBalanceKycRequired:
          case PeerPullPaymentCreditStatus.PendingBalanceKycInit:
          case PeerPullPaymentCreditStatus.AbortingDeletePurse:
          case PeerPullPaymentCreditStatus.Done:
          case PeerPullPaymentCreditStatus.Failed:
          case PeerPullPaymentCreditStatus.Expired:
          case PeerPullPaymentCreditStatus.Aborted:
            break;
          case PeerPullPaymentCreditStatus.SuspendedBalanceKycInit:
            newStatus = PeerPullPaymentCreditStatus.PendingBalanceKycInit;
            break;
          case PeerPullPaymentCreditStatus.SuspendedCreatePurse:
            newStatus = PeerPullPaymentCreditStatus.PendingCreatePurse;
            break;
          case PeerPullPaymentCreditStatus.SuspendedMergeKycRequired:
            newStatus = PeerPullPaymentCreditStatus.PendingMergeKycRequired;
            break;
          case PeerPullPaymentCreditStatus.SuspendedReady:
            newStatus = PeerPullPaymentCreditStatus.PendingReady;
            break;
          case PeerPullPaymentCreditStatus.SuspendedWithdrawing:
            newStatus = PeerPullPaymentCreditStatus.PendingWithdrawing;
            break;
          case PeerPullPaymentCreditStatus.SuspendedAbortingDeletePurse:
            newStatus = PeerPullPaymentCreditStatus.AbortingDeletePurse;
            break;
          case PeerPullPaymentCreditStatus.SuspendedBalanceKycRequired:
            newStatus = PeerPullPaymentCreditStatus.PendingBalanceKycRequired;
            break;
          default:
            assertUnreachable(pullCreditRec.status);
        }
        if (newStatus != null) {
          const oldTxState =
            computePeerPullCreditTransactionState(pullCreditRec);
          pullCreditRec.status = newStatus;
          const newTxState =
            computePeerPullCreditTransactionState(pullCreditRec);
          await tx.peerPullCredit.put(pullCreditRec);
          await this.updateTransactionMeta(tx);
          return {
            oldTxState,
            newTxState,
          };
        }
        return undefined;
      },
    );
    notifyTransition(wex, transactionId, transitionInfo);
    wex.taskScheduler.startShepherdTask(retryTag);
  }

  async abortTransaction(reason?: TalerErrorDetail): Promise<void> {
    const { wex, pursePub, taskId: retryTag, transactionId } = this;
    const transitionInfo = await wex.db.runReadWriteTx(
      { storeNames: ["peerPullCredit", "transactionsMeta"] },
      async (tx) => {
        const pullCreditRec = await tx.peerPullCredit.get(pursePub);
        if (!pullCreditRec) {
          logger.warn(`peer pull credit ${pursePub} not found`);
          return;
        }
        let newStatus: PeerPullPaymentCreditStatus | undefined = undefined;
        switch (pullCreditRec.status) {
          case PeerPullPaymentCreditStatus.PendingBalanceKycRequired:
          case PeerPullPaymentCreditStatus.SuspendedBalanceKycRequired:
          case PeerPullPaymentCreditStatus.PendingBalanceKycInit:
          case PeerPullPaymentCreditStatus.SuspendedBalanceKycInit:
          case PeerPullPaymentCreditStatus.PendingCreatePurse:
          case PeerPullPaymentCreditStatus.PendingMergeKycRequired:
            newStatus = PeerPullPaymentCreditStatus.AbortingDeletePurse;
            pullCreditRec.abortReason = reason;
            break;
          case PeerPullPaymentCreditStatus.PendingWithdrawing:
            throw Error("can't abort anymore");
          case PeerPullPaymentCreditStatus.PendingReady:
            pullCreditRec.abortReason = reason;
            newStatus = PeerPullPaymentCreditStatus.AbortingDeletePurse;
            break;
          case PeerPullPaymentCreditStatus.Done:
          case PeerPullPaymentCreditStatus.SuspendedCreatePurse:
          case PeerPullPaymentCreditStatus.SuspendedMergeKycRequired:
          case PeerPullPaymentCreditStatus.SuspendedReady:
          case PeerPullPaymentCreditStatus.SuspendedWithdrawing:
          case PeerPullPaymentCreditStatus.Aborted:
          case PeerPullPaymentCreditStatus.AbortingDeletePurse:
          case PeerPullPaymentCreditStatus.Failed:
          case PeerPullPaymentCreditStatus.Expired:
          case PeerPullPaymentCreditStatus.SuspendedAbortingDeletePurse:
            break;
          default:
            assertUnreachable(pullCreditRec.status);
        }
        if (newStatus != null) {
          const oldTxState =
            computePeerPullCreditTransactionState(pullCreditRec);
          pullCreditRec.status = newStatus;
          const newTxState =
            computePeerPullCreditTransactionState(pullCreditRec);
          await tx.peerPullCredit.put(pullCreditRec);
          await this.updateTransactionMeta(tx);
          return {
            oldTxState,
            newTxState,
          };
        }
        return undefined;
      },
    );
    wex.taskScheduler.stopShepherdTask(retryTag);
    notifyTransition(wex, transactionId, transitionInfo);
    wex.taskScheduler.startShepherdTask(retryTag);
  }
}

async function queryPurseForPeerPullCredit(
  wex: WalletExecutionContext,
  pullIni: PeerPullCreditRecord,
): Promise<TaskRunResult> {
  const purseDepositUrl = new URL(
    `purses/${pullIni.pursePub}/deposit`,
    pullIni.exchangeBaseUrl,
  );
  purseDepositUrl.searchParams.set("timeout_ms", "30000");
  logger.info(`querying purse status via ${purseDepositUrl.href}`);
  const resp = await wex.ws.runLongpollQueueing(
    wex,
    purseDepositUrl.hostname,
    async () => {
      return await wex.http.fetch(purseDepositUrl.href, {
        timeout: { d_ms: 60000 },
        cancellationToken: wex.cancellationToken,
      });
    },
  );
  const ctx = new PeerPullCreditTransactionContext(wex, pullIni.pursePub);

  logger.info(`purse status code: HTTP ${resp.status}`);

  switch (resp.status) {
    case HttpStatusCode.Gone: {
      // Exchange says that purse doesn't exist anymore => expired!
      const transitionInfo = await wex.db.runReadWriteTx(
        { storeNames: ["peerPullCredit", "transactionsMeta"] },
        async (tx) => {
          const finPi = await tx.peerPullCredit.get(pullIni.pursePub);
          if (!finPi) {
            logger.warn("peerPullCredit not found anymore");
            return;
          }
          const oldTxState = computePeerPullCreditTransactionState(finPi);
          if (finPi.status === PeerPullPaymentCreditStatus.PendingReady) {
            finPi.status = PeerPullPaymentCreditStatus.Expired;
          }
          await tx.peerPullCredit.put(finPi);
          await ctx.updateTransactionMeta(tx);
          const newTxState = computePeerPullCreditTransactionState(finPi);
          return { oldTxState, newTxState };
        },
      );
      notifyTransition(wex, ctx.transactionId, transitionInfo);
      return TaskRunResult.backoff();
    }
    case HttpStatusCode.NotFound:
      // FIXME: Maybe check error code? 404 could also mean something else.
      return TaskRunResult.longpollReturnedPending();
  }

  const result = await readSuccessResponseJsonOrThrow(
    resp,
    codecForExchangePurseStatus(),
  );

  logger.trace(`purse status: ${j2s(result)}`);

  const depositTimestamp = result.deposit_timestamp;

  if (!depositTimestamp || TalerProtocolTimestamp.isNever(depositTimestamp)) {
    logger.info("purse not ready yet (no deposit)");
    return TaskRunResult.backoff();
  }

  const reserve = await wex.db.runReadOnlyTx(
    { storeNames: ["reserves"] },
    async (tx) => {
      return await tx.reserves.get(pullIni.mergeReserveRowId);
    },
  );

  if (!reserve) {
    throw Error("reserve for peer pull credit not found in wallet DB");
  }

  await internalCreateWithdrawalGroup(wex, {
    amount: Amounts.parseOrThrow(pullIni.amount),
    wgInfo: {
      withdrawalType: WithdrawalRecordType.PeerPullCredit,
      contractPriv: pullIni.contractPriv,
    },
    forcedWithdrawalGroupId: pullIni.withdrawalGroupId,
    exchangeBaseUrl: pullIni.exchangeBaseUrl,
    reserveStatus: WithdrawalGroupStatus.PendingQueryingStatus,
    reserveKeyPair: {
      priv: reserve.reservePriv,
      pub: reserve.reservePub,
    },
  });
  const transitionInfo = await wex.db.runReadWriteTx(
    { storeNames: ["peerPullCredit", "transactionsMeta"] },
    async (tx) => {
      const finPi = await tx.peerPullCredit.get(pullIni.pursePub);
      if (!finPi) {
        logger.warn("peerPullCredit not found anymore");
        return;
      }
      const oldTxState = computePeerPullCreditTransactionState(finPi);
      if (finPi.status === PeerPullPaymentCreditStatus.PendingReady) {
        finPi.status = PeerPullPaymentCreditStatus.PendingWithdrawing;
      }
      await tx.peerPullCredit.put(finPi);
      await ctx.updateTransactionMeta(tx);
      const newTxState = computePeerPullCreditTransactionState(finPi);
      return { oldTxState, newTxState };
    },
  );
  notifyTransition(wex, ctx.transactionId, transitionInfo);
  return TaskRunResult.backoff();
}

async function longpollKycStatus(
  wex: WalletExecutionContext,
  pursePub: string,
  exchangeUrl: string,
  kycPaytoHash: string,
): Promise<TaskRunResult> {
  // FIXME: What if this changes? Should be part of the p2p record
  const mergeReserveInfo = await getMergeReserveInfo(wex, {
    exchangeBaseUrl: exchangeUrl,
  });

  const sigResp = await wex.cryptoApi.signWalletKycAuth({
    accountPriv: mergeReserveInfo.reservePriv,
    accountPub: mergeReserveInfo.reservePub,
  });

  const ctx = new PeerPullCreditTransactionContext(wex, pursePub);
  const url = new URL(`kyc-check/${kycPaytoHash}`, exchangeUrl);
  const kycStatusRes = await wex.ws.runLongpollQueueing(
    wex,
    url.hostname,
    async (timeoutMs) => {
      url.searchParams.set("timeout_ms", `${timeoutMs}`);
      logger.info(`kyc url ${url.href}`);
      return await wex.http.fetch(url.href, {
        method: "GET",
        headers: {
          ["Account-Owner-Signature"]: sigResp.sig,
        },
        cancellationToken: wex.cancellationToken,
      });
    },
  );
  if (
    kycStatusRes.status === HttpStatusCode.Ok ||
    // FIXME: NoContent is not expected https://docs.taler.net/core/api-exchange.html#post--purses-$PURSE_PUB-merge
    // remove after the exchange is fixed or clarified
    kycStatusRes.status === HttpStatusCode.NoContent
  ) {
    const transitionInfo = await wex.db.runReadWriteTx(
      { storeNames: ["peerPullCredit", "transactionsMeta"] },
      async (tx) => {
        const peerIni = await tx.peerPullCredit.get(pursePub);
        if (!peerIni) {
          return;
        }
        if (
          peerIni.status !== PeerPullPaymentCreditStatus.PendingMergeKycRequired
        ) {
          return;
        }
        const oldTxState = computePeerPullCreditTransactionState(peerIni);
        peerIni.status = PeerPullPaymentCreditStatus.PendingCreatePurse;
        const newTxState = computePeerPullCreditTransactionState(peerIni);
        await tx.peerPullCredit.put(peerIni);
        await ctx.updateTransactionMeta(tx);
        return { oldTxState, newTxState };
      },
    );
    notifyTransition(wex, ctx.transactionId, transitionInfo);
    return TaskRunResult.progress();
  } else if (kycStatusRes.status === HttpStatusCode.Accepted) {
    return TaskRunResult.longpollReturnedPending();
  } else {
    throw Error(`unexpected response from kyc-check (${kycStatusRes.status})`);
  }
}

async function processPeerPullCreditAbortingDeletePurse(
  wex: WalletExecutionContext,
  peerPullIni: PeerPullCreditRecord,
): Promise<TaskRunResult> {
  const { pursePub, pursePriv } = peerPullIni;
  const ctx = new PeerPullCreditTransactionContext(wex, peerPullIni.pursePub);

  const sigResp = await wex.cryptoApi.signDeletePurse({
    pursePriv,
  });
  const purseUrl = new URL(`purses/${pursePub}`, peerPullIni.exchangeBaseUrl);
  const resp = await wex.http.fetch(purseUrl.href, {
    method: "DELETE",
    headers: {
      "taler-purse-signature": sigResp.sig,
    },
    cancellationToken: wex.cancellationToken,
  });
  logger.info(`deleted purse with response status ${resp.status}`);

  const transitionInfo = await wex.db.runReadWriteTx(
    {
      storeNames: [
        "peerPullCredit",
        "refreshGroups",
        "denominations",
        "coinAvailability",
        "coins",
        "transactionsMeta",
      ],
    },
    async (tx) => {
      const ppiRec = await tx.peerPullCredit.get(pursePub);
      if (!ppiRec) {
        return undefined;
      }
      if (ppiRec.status !== PeerPullPaymentCreditStatus.AbortingDeletePurse) {
        return undefined;
      }
      const oldTxState = computePeerPullCreditTransactionState(ppiRec);
      ppiRec.status = PeerPullPaymentCreditStatus.Aborted;
      await tx.peerPullCredit.put(ppiRec);
      await ctx.updateTransactionMeta(tx);
      const newTxState = computePeerPullCreditTransactionState(ppiRec);
      return {
        oldTxState,
        newTxState,
      };
    },
  );
  notifyTransition(wex, ctx.transactionId, transitionInfo);

  return TaskRunResult.backoff();
}

async function handlePeerPullCreditWithdrawing(
  wex: WalletExecutionContext,
  pullIni: PeerPullCreditRecord,
): Promise<TaskRunResult> {
  if (!pullIni.withdrawalGroupId) {
    throw Error("invalid db state (withdrawing, but no withdrawal group ID");
  }
  await waitWithdrawalFinal(wex, pullIni.withdrawalGroupId);
  const ctx = new PeerPullCreditTransactionContext(wex, pullIni.pursePub);
  const wgId = pullIni.withdrawalGroupId;
  let finished: boolean = false;
  const transitionInfo = await wex.db.runReadWriteTx(
    { storeNames: ["peerPullCredit", "withdrawalGroups", "transactionsMeta"] },
    async (tx) => {
      const ppi = await tx.peerPullCredit.get(pullIni.pursePub);
      if (!ppi) {
        finished = true;
        return;
      }
      if (ppi.status !== PeerPullPaymentCreditStatus.PendingWithdrawing) {
        finished = true;
        return;
      }
      const oldTxState = computePeerPullCreditTransactionState(ppi);
      const wg = await tx.withdrawalGroups.get(wgId);
      if (!wg) {
        // FIXME: Fail the operation instead?
        return undefined;
      }
      switch (wg.status) {
        case WithdrawalGroupStatus.Done:
          finished = true;
          ppi.status = PeerPullPaymentCreditStatus.Done;
          break;
        // FIXME: Also handle other final states!
      }
      await tx.peerPullCredit.put(ppi);
      await ctx.updateTransactionMeta(tx);
      const newTxState = computePeerPullCreditTransactionState(ppi);
      return {
        oldTxState,
        newTxState,
      };
    },
  );
  notifyTransition(wex, ctx.transactionId, transitionInfo);
  if (finished) {
    return TaskRunResult.finished();
  } else {
    // FIXME: Return indicator that we depend on the other operation!
    return TaskRunResult.backoff();
  }
}

async function handlePeerPullCreditCreatePurse(
  wex: WalletExecutionContext,
  pullIni: PeerPullCreditRecord,
): Promise<TaskRunResult> {
  const ctx = new PeerPullCreditTransactionContext(wex, pullIni.pursePub);

  const kycCheckRes = await checkIncomingAmountLegalUnderKycBalanceThreshold(
    wex,
    pullIni.exchangeBaseUrl,
    pullIni.estimatedAmountEffective,
  );

  if (kycCheckRes.result === "violation") {
    // Do this before we transition so that the exchange is already in the right state.
    await handleStartExchangeWalletKyc(wex, {
      amount: kycCheckRes.nextThreshold,
      exchangeBaseUrl: pullIni.exchangeBaseUrl,
    });
    await ctx.transition({}, async (rec) => {
      if (!rec) {
        return TransitionResult.stay();
      }
      if (rec.status !== PeerPullPaymentCreditStatus.PendingCreatePurse) {
        return TransitionResult.stay();
      }
      rec.status = PeerPullPaymentCreditStatus.PendingBalanceKycInit;
      return TransitionResult.transition(rec);
    });
    return TaskRunResult.progress();
  }

  const purseFee = Amounts.stringify(Amounts.zeroOfAmount(pullIni.amount));
  const pursePub = pullIni.pursePub;
  const mergeReserve = await wex.db.runReadOnlyTx(
    { storeNames: ["reserves"] },
    async (tx) => {
      return tx.reserves.get(pullIni.mergeReserveRowId);
    },
  );

  if (!mergeReserve) {
    throw Error("merge reserve for peer pull payment not found in database");
  }

  const contractTermsRecord = await wex.db.runReadOnlyTx(
    { storeNames: ["contractTerms"] },
    async (tx) => {
      return tx.contractTerms.get(pullIni.contractTermsHash);
    },
  );

  if (!contractTermsRecord) {
    throw Error("contract terms for peer pull payment not found in database");
  }

  const contractTerms: PeerContractTerms = contractTermsRecord.contractTermsRaw;

  const reservePayto = talerPaytoFromExchangeReserve(
    pullIni.exchangeBaseUrl,
    mergeReserve.reservePub,
  );

  const econtractResp = await wex.cryptoApi.encryptContractForDeposit({
    contractPriv: pullIni.contractPriv,
    contractPub: pullIni.contractPub,
    contractTerms: contractTermsRecord.contractTermsRaw,
    pursePriv: pullIni.pursePriv,
    pursePub: pullIni.pursePub,
    nonce: pullIni.contractEncNonce,
  });

  const mergeTimestamp = timestampPreciseFromDb(pullIni.mergeTimestamp);

  const purseExpiration = contractTerms.purse_expiration;
  const sigRes = await wex.cryptoApi.signReservePurseCreate({
    contractTermsHash: pullIni.contractTermsHash,
    flags: WalletAccountMergeFlags.CreateWithPurseFee,
    mergePriv: pullIni.mergePriv,
    mergeTimestamp: TalerPreciseTimestamp.round(mergeTimestamp),
    purseAmount: pullIni.amount,
    purseExpiration: purseExpiration,
    purseFee: purseFee,
    pursePriv: pullIni.pursePriv,
    pursePub: pullIni.pursePub,
    reservePayto,
    reservePriv: mergeReserve.reservePriv,
  });

  const reservePurseReqBody: ExchangeReservePurseRequest = {
    merge_sig: sigRes.mergeSig,
    merge_timestamp: TalerPreciseTimestamp.round(mergeTimestamp),
    h_contract_terms: pullIni.contractTermsHash,
    merge_pub: pullIni.mergePub,
    min_age: 0,
    purse_expiration: purseExpiration,
    purse_fee: purseFee,
    purse_pub: pullIni.pursePub,
    purse_sig: sigRes.purseSig,
    purse_value: pullIni.amount,
    reserve_sig: sigRes.accountSig,
    econtract: econtractResp.econtract,
  };

  logger.info(`reserve purse request: ${j2s(reservePurseReqBody)}`);

  const reservePurseMergeUrl = new URL(
    `reserves/${mergeReserve.reservePub}/purse`,
    pullIni.exchangeBaseUrl,
  );

  const httpResp = await wex.http.fetch(reservePurseMergeUrl.href, {
    method: "POST",
    body: reservePurseReqBody,
    cancellationToken: wex.cancellationToken,
  });

  if (httpResp.status === HttpStatusCode.UnavailableForLegalReasons) {
    const respJson = await httpResp.json();
    const kycPending = codecForLegitimizationNeededResponse().decode(respJson);
    logger.info(`kyc uuid response: ${j2s(kycPending)}`);
    return processPeerPullCreditKycRequired(wex, pullIni, kycPending.h_payto);
  }

  const resp = await readSuccessResponseJsonOrThrow(httpResp, codecForAny());

  logger.info(`reserve merge response: ${j2s(resp)}`);

  const transitionInfo = await wex.db.runReadWriteTx(
    { storeNames: ["peerPullCredit", "transactionsMeta"] },
    async (tx) => {
      const pi2 = await tx.peerPullCredit.get(pursePub);
      if (!pi2) {
        return;
      }
      const oldTxState = computePeerPullCreditTransactionState(pi2);
      pi2.status = PeerPullPaymentCreditStatus.PendingReady;
      await tx.peerPullCredit.put(pi2);
      await ctx.updateTransactionMeta(tx);
      const newTxState = computePeerPullCreditTransactionState(pi2);
      return { oldTxState, newTxState };
    },
  );
  notifyTransition(wex, ctx.transactionId, transitionInfo);
  return TaskRunResult.backoff();
}

export async function processPeerPullCredit(
  wex: WalletExecutionContext,
  pursePub: string,
): Promise<TaskRunResult> {
  if (!wex.ws.networkAvailable) {
    return TaskRunResult.networkRequired();
  }

  const pullIni = await wex.db.runReadOnlyTx(
    { storeNames: ["peerPullCredit"] },
    async (tx) => {
      return tx.peerPullCredit.get(pursePub);
    },
  );
  if (!pullIni) {
    throw Error("peer pull payment initiation not found in database");
  }

  const retryTag = constructTaskIdentifier({
    tag: PendingTaskType.PeerPullCredit,
    pursePub,
  });

  logger.trace(`processing ${retryTag}, status=${pullIni.status}`);

  const ctx = new PeerPullCreditTransactionContext(wex, pullIni.pursePub);

  switch (pullIni.status) {
    case PeerPullPaymentCreditStatus.Done: {
      return TaskRunResult.finished();
    }
    case PeerPullPaymentCreditStatus.PendingReady:
      return queryPurseForPeerPullCredit(wex, pullIni);
    case PeerPullPaymentCreditStatus.PendingMergeKycRequired: {
      if (!pullIni.kycPaytoHash) {
        throw Error("invalid state, kycPaytoHash required");
      }
      return await longpollKycStatus(
        wex,
        pursePub,
        pullIni.exchangeBaseUrl,
        pullIni.kycPaytoHash,
      );
    }
    case PeerPullPaymentCreditStatus.PendingCreatePurse:
      return handlePeerPullCreditCreatePurse(wex, pullIni);
    case PeerPullPaymentCreditStatus.AbortingDeletePurse:
      return await processPeerPullCreditAbortingDeletePurse(wex, pullIni);
    case PeerPullPaymentCreditStatus.PendingWithdrawing:
      return handlePeerPullCreditWithdrawing(wex, pullIni);
    case PeerPullPaymentCreditStatus.PendingBalanceKycRequired:
    case PeerPullPaymentCreditStatus.PendingBalanceKycInit:
      return processPeerPullCreditBalanceKyc(ctx, pullIni);
    case PeerPullPaymentCreditStatus.Aborted:
    case PeerPullPaymentCreditStatus.Failed:
    case PeerPullPaymentCreditStatus.Expired:
    case PeerPullPaymentCreditStatus.SuspendedBalanceKycRequired:
    case PeerPullPaymentCreditStatus.SuspendedAbortingDeletePurse:
    case PeerPullPaymentCreditStatus.SuspendedCreatePurse:
    case PeerPullPaymentCreditStatus.SuspendedMergeKycRequired:
    case PeerPullPaymentCreditStatus.SuspendedReady:
    case PeerPullPaymentCreditStatus.SuspendedWithdrawing:
    case PeerPullPaymentCreditStatus.SuspendedBalanceKycInit:
      break;
    default:
      assertUnreachable(pullIni.status);
  }

  return TaskRunResult.finished();
}

async function processPeerPullCreditBalanceKyc(
  ctx: PeerPullCreditTransactionContext,
  peerInc: PeerPullCreditRecord,
): Promise<TaskRunResult> {
  const exchangeBaseUrl = peerInc.exchangeBaseUrl;
  const amount = peerInc.estimatedAmountEffective;

  const ret = await genericWaitForStateVal(ctx.wex, {
    async checkState(): Promise<BalanceThresholdCheckResult | undefined> {
      const checkRes = await checkIncomingAmountLegalUnderKycBalanceThreshold(
        ctx.wex,
        exchangeBaseUrl,
        amount,
      );
      logger.info(
        `balance check result for ${exchangeBaseUrl} +${amount}: ${j2s(
          checkRes,
        )}`,
      );
      if (checkRes.result === "ok") {
        return checkRes;
      }
      if (
        peerInc.status === PeerPullPaymentCreditStatus.PendingBalanceKycInit &&
        checkRes.walletKycStatus === ExchangeWalletKycStatus.Legi
      ) {
        return checkRes;
      }
      await handleStartExchangeWalletKyc(ctx.wex, {
        amount: checkRes.nextThreshold,
        exchangeBaseUrl,
      });
      return undefined;
    },
    filterNotification(notif) {
      return (
        (notif.type === NotificationType.ExchangeStateTransition &&
          notif.exchangeBaseUrl === exchangeBaseUrl) ||
        notif.type === NotificationType.BalanceChange
      );
    },
  });

  if (ret.result === "ok") {
    await ctx.transition({}, async (rec) => {
      if (!rec) {
        return TransitionResult.stay();
      }
      if (
        rec.status !== PeerPullPaymentCreditStatus.PendingBalanceKycRequired
      ) {
        return TransitionResult.stay();
      }
      rec.status = PeerPullPaymentCreditStatus.PendingCreatePurse;
      return TransitionResult.transition(rec);
    });
    return TaskRunResult.progress();
  } else if (
    peerInc.status === PeerPullPaymentCreditStatus.PendingBalanceKycInit &&
    ret.walletKycStatus === ExchangeWalletKycStatus.Legi
  ) {
    await ctx.transition({}, async (rec) => {
      if (!rec) {
        return TransitionResult.stay();
      }
      if (rec.status !== PeerPullPaymentCreditStatus.PendingBalanceKycInit) {
        return TransitionResult.stay();
      }
      rec.status = PeerPullPaymentCreditStatus.PendingBalanceKycRequired;
      rec.kycAccessToken = ret.walletKycAccessToken;
      return TransitionResult.transition(rec);
    });
    return TaskRunResult.progress();
  } else {
    throw Error("not reached");
  }
}

async function processPeerPullCreditKycRequired(
  wex: WalletExecutionContext,
  peerIni: PeerPullCreditRecord,
  kycPayoHash: string,
): Promise<TaskRunResult> {
  const ctx = new PeerPullCreditTransactionContext(wex, peerIni.pursePub);
  const { pursePub } = peerIni;

  // FIXME: What if this changes? Should be part of the p2p record
  const mergeReserveInfo = await getMergeReserveInfo(wex, {
    exchangeBaseUrl: peerIni.exchangeBaseUrl,
  });

  const sigResp = await wex.cryptoApi.signWalletKycAuth({
    accountPriv: mergeReserveInfo.reservePriv,
    accountPub: mergeReserveInfo.reservePub,
  });

  const url = new URL(`kyc-check/${kycPayoHash}`, peerIni.exchangeBaseUrl);

  logger.info(`kyc url ${url.href}`);
  const kycStatusRes = await wex.http.fetch(url.href, {
    method: "GET",
    headers: {
      ["Account-Owner-Signature"]: sigResp.sig,
    },
    cancellationToken: wex.cancellationToken,
  });

  if (
    kycStatusRes.status === HttpStatusCode.Ok ||
    kycStatusRes.status === HttpStatusCode.NoContent
  ) {
    logger.warn("kyc requested, but already fulfilled");
    return TaskRunResult.backoff();
  } else if (kycStatusRes.status === HttpStatusCode.Accepted) {
    const kycStatus = await readResponseJsonOrThrow(
      kycStatusRes,
      codecForAccountKycStatus(),
    );
    logger.info(`kyc status: ${j2s(kycStatus)}`);
    const { transitionInfo, result } = await wex.db.runReadWriteTx(
      { storeNames: ["peerPullCredit", "transactionsMeta"] },
      async (tx) => {
        const peerInc = await tx.peerPullCredit.get(pursePub);
        if (!peerInc) {
          return {
            transitionInfo: undefined,
            result: TaskRunResult.finished(),
          };
        }
        const oldTxState = computePeerPullCreditTransactionState(peerInc);
        peerInc.kycPaytoHash = kycPayoHash;
        logger.info(
          `setting peer-pull-credit kyc payto hash to ${kycPayoHash}`,
        );
        peerInc.kycAccessToken = kycStatus.access_token;
        peerInc.status = PeerPullPaymentCreditStatus.PendingMergeKycRequired;
        const newTxState = computePeerPullCreditTransactionState(peerInc);
        await tx.peerPullCredit.put(peerInc);
        await ctx.updateTransactionMeta(tx);
        return {
          transitionInfo: { oldTxState, newTxState },
          result: TaskRunResult.progress(),
        };
      },
    );
    notifyTransition(wex, ctx.transactionId, transitionInfo);
    return result;
  } else {
    throw Error(`unexpected response from kyc-check (${kycStatusRes.status})`);
  }
}

/**
 * Check fees and available exchanges for a peer push payment initiation.
 */
export async function checkPeerPullCredit(
  wex: WalletExecutionContext,
  req: CheckPeerPullCreditRequest,
): Promise<CheckPeerPullCreditResponse> {
  return runWithClientCancellation(
    wex,
    "checkPeerPullCredit",
    req.clientCancellationId,
    async () => internalCheckPeerPullCredit(wex, req),
  );
}

/**
 * Check fees and available exchanges for a peer push payment initiation.
 */
export async function internalCheckPeerPullCredit(
  wex: WalletExecutionContext,
  req: CheckPeerPullCreditRequest,
): Promise<CheckPeerPullCreditResponse> {
  // FIXME: We don't support exchanges with purse fees yet.
  // Select an exchange where we have money in the specified currency

  const instructedAmount = Amounts.parseOrThrow(req.amount);
  const currency = instructedAmount.currency;

  logger.trace(
    `checking peer push debit for ${Amounts.stringify(instructedAmount)}`,
  );

  let restrictScope: ScopeInfo;
  if (req.restrictScope) {
    restrictScope = req.restrictScope;
  } else if (req.exchangeBaseUrl) {
    restrictScope = {
      type: ScopeType.Exchange,
      currency,
      url: req.exchangeBaseUrl,
    };
  } else {
    throw Error("client must either specify exchangeBaseUrl or restrictScope");
  }

  logger.trace("checking peer-pull-credit fees");

  let exchangeUrl: string | undefined;
  if (req.exchangeBaseUrl) {
    exchangeUrl = req.exchangeBaseUrl;
  } else if (req.restrictScope) {
    exchangeUrl = await getPreferredExchangeForScope(wex, req.restrictScope);
  } else {
    exchangeUrl = await getPreferredExchangeForCurrency(wex, currency);
  }

  if (!exchangeUrl) {
    throw Error("no exchange found for initiating a peer pull payment");
  }

  logger.trace(`found ${exchangeUrl} as preferred exchange`);

  const wi = await getExchangeWithdrawalInfo(
    wex,
    exchangeUrl,
    Amounts.parseOrThrow(req.amount),
    undefined,
  );
  if (wi.selectedDenoms.selectedDenoms.length === 0) {
    throw Error(
      `unable to check pull payment from ${exchangeUrl}, can't select denominations for instructed amount (${req.amount}`,
    );
  }

  logger.trace(`got withdrawal info`);

  let numCoins = 0;
  for (let i = 0; i < wi.selectedDenoms.selectedDenoms.length; i++) {
    numCoins += wi.selectedDenoms.selectedDenoms[i].count;
  }

  return {
    exchangeBaseUrl: exchangeUrl,
    amountEffective: wi.withdrawalAmountEffective,
    amountRaw: req.amount,
    numCoins,
  };
}

/**
 * Initiate a peer pull payment.
 */
export async function initiatePeerPullPayment(
  wex: WalletExecutionContext,
  req: InitiatePeerPullCreditRequest,
): Promise<InitiatePeerPullCreditResponse> {
  const currency = Amounts.currencyOf(req.partialContractTerms.amount);
  let maybeExchangeBaseUrl: string | undefined;
  if (req.exchangeBaseUrl) {
    maybeExchangeBaseUrl = req.exchangeBaseUrl;
  } else {
    maybeExchangeBaseUrl = await getPreferredExchangeForCurrency(wex, currency);
  }

  if (!maybeExchangeBaseUrl) {
    throw Error("no exchange found for initiating a peer pull payment");
  }

  const exchangeBaseUrl = maybeExchangeBaseUrl;

  const exchange = await fetchFreshExchange(wex, exchangeBaseUrl);
  requireExchangeTosAcceptedOrThrow(exchange);

  if (
    checkPeerCreditHardLimitExceeded(exchange, req.partialContractTerms.amount)
  ) {
    throw Error("peer credit would exceed hard KYC limit");
  }

  const mergeReserveInfo = await getMergeReserveInfo(wex, {
    exchangeBaseUrl: exchangeBaseUrl,
  });

  const pursePair = await wex.cryptoApi.createEddsaKeypair({});
  const mergePair = await wex.cryptoApi.createEddsaKeypair({});

  const contractTerms = req.partialContractTerms;

  const hContractTerms = ContractTermsUtil.hashContractTerms(contractTerms);

  const contractKeyPair = await wex.cryptoApi.createEddsaKeypair({});

  const withdrawalGroupId = encodeCrock(getRandomBytes(32));

  const mergeReserveRowId = mergeReserveInfo.rowId;
  checkDbInvariant(
    !!mergeReserveRowId,
    `merge reserve for ${exchangeBaseUrl} without rowid`,
  );

  const contractEncNonce = encodeCrock(getRandomBytes(24));

  const wi = await getExchangeWithdrawalInfo(
    wex,
    exchangeBaseUrl,
    Amounts.parseOrThrow(req.partialContractTerms.amount),
    undefined,
  );
  if (wi.selectedDenoms.selectedDenoms.length === 0) {
    throw Error(
      `unable to initiate pull payment from ${exchangeBaseUrl}, can't select denominations for instructed amount (${req.partialContractTerms.amount}`,
    );
  }

  const mergeTimestamp = TalerPreciseTimestamp.now();

  const ctx = new PeerPullCreditTransactionContext(wex, pursePair.pub);

  const transitionInfo = await wex.db.runReadWriteTx(
    { storeNames: ["peerPullCredit", "contractTerms", "transactionsMeta"] },
    async (tx) => {
      const ppi: PeerPullCreditRecord = {
        amount: req.partialContractTerms.amount,
        contractTermsHash: hContractTerms,
        exchangeBaseUrl: exchangeBaseUrl,
        pursePriv: pursePair.priv,
        pursePub: pursePair.pub,
        mergePriv: mergePair.priv,
        mergePub: mergePair.pub,
        status: PeerPullPaymentCreditStatus.PendingCreatePurse,
        mergeTimestamp: timestampPreciseToDb(mergeTimestamp),
        contractEncNonce,
        mergeReserveRowId: mergeReserveRowId,
        contractPriv: contractKeyPair.priv,
        contractPub: contractKeyPair.pub,
        withdrawalGroupId,
        estimatedAmountEffective: wi.withdrawalAmountEffective,
      };
      await tx.peerPullCredit.put(ppi);
      await ctx.updateTransactionMeta(tx);
      const oldTxState: TransactionState = {
        major: TransactionMajorState.None,
      };
      const newTxState = computePeerPullCreditTransactionState(ppi);
      await tx.contractTerms.put({
        contractTermsRaw: contractTerms,
        h: hContractTerms,
      });
      return { oldTxState, newTxState };
    },
  );

  notifyTransition(wex, ctx.transactionId, transitionInfo);
  wex.taskScheduler.startShepherdTask(ctx.taskId);

  return {
    talerUri: stringifyTalerUri({
      type: TalerUriAction.PayPull,
      exchangeBaseUrl: exchangeBaseUrl,
      contractPriv: contractKeyPair.priv,
    }),
    transactionId: ctx.transactionId,
  };
}

export function computePeerPullCreditTransactionState(
  pullCreditRecord: PeerPullCreditRecord,
): TransactionState {
  switch (pullCreditRecord.status) {
    case PeerPullPaymentCreditStatus.PendingCreatePurse:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.CreatePurse,
      };
    case PeerPullPaymentCreditStatus.PendingMergeKycRequired:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.MergeKycRequired,
      };
    case PeerPullPaymentCreditStatus.PendingReady:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Ready,
      };
    case PeerPullPaymentCreditStatus.Done:
      return {
        major: TransactionMajorState.Done,
      };
    case PeerPullPaymentCreditStatus.PendingWithdrawing:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Withdraw,
      };
    case PeerPullPaymentCreditStatus.SuspendedCreatePurse:
      return {
        major: TransactionMajorState.Suspended,
        minor: TransactionMinorState.CreatePurse,
      };
    case PeerPullPaymentCreditStatus.SuspendedReady:
      return {
        major: TransactionMajorState.Suspended,
        minor: TransactionMinorState.Ready,
      };
    case PeerPullPaymentCreditStatus.SuspendedWithdrawing:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Withdraw,
      };
    case PeerPullPaymentCreditStatus.SuspendedMergeKycRequired:
      return {
        major: TransactionMajorState.Suspended,
        minor: TransactionMinorState.MergeKycRequired,
      };
    case PeerPullPaymentCreditStatus.Aborted:
      return {
        major: TransactionMajorState.Aborted,
      };
    case PeerPullPaymentCreditStatus.AbortingDeletePurse:
      return {
        major: TransactionMajorState.Aborting,
        minor: TransactionMinorState.DeletePurse,
      };
    case PeerPullPaymentCreditStatus.Failed:
      return {
        major: TransactionMajorState.Failed,
      };
    case PeerPullPaymentCreditStatus.Expired:
      return {
        major: TransactionMajorState.Expired,
      };
    case PeerPullPaymentCreditStatus.SuspendedAbortingDeletePurse:
      return {
        major: TransactionMajorState.Aborting,
        minor: TransactionMinorState.DeletePurse,
      };
    case PeerPullPaymentCreditStatus.PendingBalanceKycRequired:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.BalanceKycRequired,
      };
    case PeerPullPaymentCreditStatus.SuspendedBalanceKycRequired:
      return {
        major: TransactionMajorState.Suspended,
        minor: TransactionMinorState.BalanceKycRequired,
      };
    case PeerPullPaymentCreditStatus.PendingBalanceKycInit:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.BalanceKycInit,
      };
    case PeerPullPaymentCreditStatus.SuspendedBalanceKycInit:
      return {
        major: TransactionMajorState.Suspended,
        minor: TransactionMinorState.BalanceKycInit,
      };
  }
}

export function computePeerPullCreditTransactionActions(
  pullCreditRecord: PeerPullCreditRecord,
): TransactionAction[] {
  switch (pullCreditRecord.status) {
    case PeerPullPaymentCreditStatus.PendingCreatePurse:
      return [
        TransactionAction.Retry,
        TransactionAction.Abort,
        TransactionAction.Suspend,
      ];
    case PeerPullPaymentCreditStatus.PendingMergeKycRequired:
      return [
        TransactionAction.Retry,
        TransactionAction.Abort,
        TransactionAction.Suspend,
      ];
    case PeerPullPaymentCreditStatus.PendingReady:
      return [
        TransactionAction.Retry,
        TransactionAction.Abort,
        TransactionAction.Suspend,
      ];
    case PeerPullPaymentCreditStatus.Done:
      return [TransactionAction.Delete];
    case PeerPullPaymentCreditStatus.PendingWithdrawing:
      return [
        TransactionAction.Retry,
        TransactionAction.Abort,
        TransactionAction.Suspend,
      ];
    case PeerPullPaymentCreditStatus.SuspendedCreatePurse:
      return [TransactionAction.Resume, TransactionAction.Abort];
    case PeerPullPaymentCreditStatus.SuspendedReady:
      return [TransactionAction.Abort, TransactionAction.Resume];
    case PeerPullPaymentCreditStatus.SuspendedWithdrawing:
      return [TransactionAction.Resume, TransactionAction.Fail];
    case PeerPullPaymentCreditStatus.SuspendedMergeKycRequired:
      return [TransactionAction.Resume, TransactionAction.Fail];
    case PeerPullPaymentCreditStatus.Aborted:
      return [TransactionAction.Delete];
    case PeerPullPaymentCreditStatus.AbortingDeletePurse:
      return [
        TransactionAction.Retry,
        TransactionAction.Suspend,
        TransactionAction.Fail,
      ];
    case PeerPullPaymentCreditStatus.Failed:
      return [TransactionAction.Delete];
    case PeerPullPaymentCreditStatus.Expired:
      return [TransactionAction.Delete];
    case PeerPullPaymentCreditStatus.SuspendedAbortingDeletePurse:
      return [TransactionAction.Resume, TransactionAction.Fail];
    case PeerPullPaymentCreditStatus.PendingBalanceKycRequired:
      return [TransactionAction.Suspend, TransactionAction.Abort];
    case PeerPullPaymentCreditStatus.SuspendedBalanceKycRequired:
      return [TransactionAction.Resume, TransactionAction.Abort];
    case PeerPullPaymentCreditStatus.PendingBalanceKycInit:
      return [TransactionAction.Suspend, TransactionAction.Abort];
    case PeerPullPaymentCreditStatus.SuspendedBalanceKycInit:
      return [TransactionAction.Resume, TransactionAction.Abort];
  }
}