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
|
/*
This file is part of GNU Taler
(C) 2020 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 {
AbsoluteTime,
AmountString,
Duration,
Logger,
TalerCorebankApiClient,
TransactionType,
WireGatewayApiClient,
WithdrawalType,
j2s,
} from "@gnu-taler/taler-util";
import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
import {
BankService,
ExchangeService,
GlobalTestState,
MerchantService,
generateRandomPayto,
setupDb,
} from "../harness/harness.js";
import { createWalletDaemonWithClient } from "../harness/helpers.js";
import { defaultCoinConfig } from "../harness/denomStructures.js";
import * as http from "node:http";
const logger = new Logger("test-withdrawal-conversion.ts");
interface TestfakeConversionService {
stop: () => void;
}
function splitInTwoAt(s: string, separator: string): [string, string] {
const idx = s.indexOf(separator);
if (idx === -1) {
return [s, ""];
}
return [s.slice(0, idx), s.slice(idx + 1)];
}
/**
* Testfake for the kyc service that the exchange talks to.
*/
async function runTestfakeConversionService(): Promise<TestfakeConversionService> {
const server = http.createServer((req, res) => {
const requestUrl = req.url!;
logger.info(`kyc: got ${req.method} request, ${requestUrl}`);
const [path, query] = splitInTwoAt(requestUrl, "?");
const qp = new URLSearchParams(query);
if (path === "/config") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
version: "0:0:0",
name: "taler-conversion-info",
regional_currency: {},
fiat_currency: {},
}),
);
} else if (path === "/cashin-rate") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
amount_debit: "FOO:123",
amount_credit: "BAR:123",
}),
);
} else {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ code: 1, message: "bad request" }));
}
});
await new Promise<void>((resolve, reject) => {
server.listen(8071, () => resolve());
});
return {
stop() {
server.close();
},
};
}
/**
* Test for currency conversion during manual withdrawal.
*/
export async function runWithdrawalConversionTest(t: GlobalTestState) {
// Set up test environment
const db = await setupDb(t);
const bank = await BankService.create(t, {
allowRegistrations: true,
currency: "TESTKUDOS",
database: db.connStr,
httpPort: 8082,
});
const exchange = ExchangeService.create(t, {
name: "testexchange-1",
currency: "TESTKUDOS",
httpPort: 8081,
database: db.connStr,
});
const merchant = await MerchantService.create(t, {
name: "testmerchant-1",
currency: "TESTKUDOS",
httpPort: 8083,
database: db.connStr,
});
const exchangeBankAccount = await bank.createExchangeAccount(
"myexchange",
"x",
);
exchangeBankAccount.conversionUrl = "http://localhost:8071/";
await exchange.addBankAccount("1", exchangeBankAccount);
await bank.start();
await bank.pingUntilAvailable();
exchange.addOfferedCoins(defaultCoinConfig);
await exchange.start();
await exchange.pingUntilAvailable();
merchant.addExchange(exchange);
await merchant.start();
await merchant.pingUntilAvailable();
await merchant.addInstanceWithWireAccount({
id: "default",
name: "Default Instance",
paytoUris: [generateRandomPayto("merchant-default")],
defaultWireTransferDelay: Duration.toTalerProtocolDuration(
Duration.fromSpec({ minutes: 1 }),
),
});
await merchant.addInstanceWithWireAccount({
id: "minst1",
name: "minst1",
paytoUris: [generateRandomPayto("minst1")],
defaultWireTransferDelay: Duration.toTalerProtocolDuration(
Duration.fromSpec({ minutes: 1 }),
),
});
const { walletClient, walletService } = await createWalletDaemonWithClient(
t,
{ name: "wallet" },
);
await runTestfakeConversionService();
// Create a withdrawal operation
const bankAccessApiClient = new TalerCorebankApiClient(
bank.corebankApiBaseUrl,
);
const user = await bankAccessApiClient.createRandomBankUser();
await walletClient.call(WalletApiOperation.AddExchange, {
exchangeBaseUrl: exchange.baseUrl,
});
const infoRes = await walletClient.call(
WalletApiOperation.GetWithdrawalDetailsForAmount,
{
exchangeBaseUrl: exchange.baseUrl,
amount: "TESTKUDOS:20" as AmountString,
},
);
console.log(`withdrawal details: ${j2s(infoRes)}`);
const checkTransferAmount = infoRes.withdrawalAccountList[0].transferAmount;
t.assertTrue(checkTransferAmount != null);
t.assertAmountEquals(checkTransferAmount, "FOO:123");
const tStart = AbsoluteTime.now();
logger.info("starting AcceptManualWithdrawal request");
// We expect this to return immediately.
const wres = await walletClient.call(
WalletApiOperation.AcceptManualWithdrawal,
{
exchangeBaseUrl: exchange.baseUrl,
amount: "TESTKUDOS:10" as AmountString,
},
);
logger.info("AcceptManualWithdrawal finished");
logger.info(`result: ${j2s(wres)}`);
const acceptedTransferAmount = wres.withdrawalAccountsList[0].transferAmount;
t.assertTrue(acceptedTransferAmount != null);
t.assertAmountEquals(acceptedTransferAmount, "FOO:123");
const txInfo = await walletClient.call(
WalletApiOperation.GetTransactionById,
{
transactionId: wres.transactionId,
},
);
t.assertDeepEqual(txInfo.type, TransactionType.Withdrawal);
t.assertDeepEqual(
txInfo.withdrawalDetails.type,
WithdrawalType.ManualTransfer,
);
t.assertTrue(!!txInfo.withdrawalDetails.exchangeCreditAccountDetails);
t.assertDeepEqual(
txInfo.withdrawalDetails.exchangeCreditAccountDetails[0].transferAmount,
"FOO:123",
);
// Check that the request did not go into long-polling.
const duration = AbsoluteTime.difference(tStart, AbsoluteTime.now());
if (typeof duration.d_ms !== "number" || duration.d_ms > 5 * 1000) {
throw Error("withdrawal took too long (longpolling issue)");
}
const reservePub: string = wres.reservePub;
const wireGatewayApiClient = new WireGatewayApiClient(
exchangeBankAccount.wireGatewayApiBaseUrl,
{
auth: {
username: exchangeBankAccount.accountName,
password: exchangeBankAccount.accountPassword,
},
},
);
await wireGatewayApiClient.adminAddIncoming({
amount: "TESTKUDOS:10",
debitAccountPayto: user.accountPaytoUri,
reservePub: reservePub,
});
await exchange.runWirewatchOnce();
await walletClient.call(WalletApiOperation.TestingWaitTransactionsFinal, {});
// Check balance
const balResp = await walletClient.call(WalletApiOperation.GetBalances, {});
t.assertAmountEquals("TESTKUDOS:9.72", balResp.balances[0].available);
}
runWithdrawalConversionTest.suites = ["wallet"];
|