forked from TBD54566975/workshop-mock-pfis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
295 lines (244 loc) · 8.8 KB
/
main.ts
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
import './polyfills.js'
import { HardcodedOfferingRepository } from './offerings.js'
import { Rfq, Order } from '@tbdex/http-server'
import { Quote, OrderStatus, Close } from '@tbdex/http-server'
import log from './logger.js'
import { config } from './config.js'
import { BearerDid } from '@web5/dids'
import { HttpServerShutdownHandler } from './http-shutdown-handler.js'
import { TbdexHttpServer } from '@tbdex/http-server'
import { requestCredential } from './credential-issuer.js'
import { NextFunction } from 'express-serve-static-core'
import { InMemoryExchangesApi } from './exchanges.js'
import express from 'express'
import cors from 'cors'
console.log('"AquaFinance Capital" launched: ', config.pfiDid[0].uri)
console.log('"SwiftLiquidity Solutions" launched: ', config.pfiDid[1].uri)
console.log('"Flowback Financial" launched: ', config.pfiDid[2].uri)
console.log('"Vertex Liquid Assets" launched: ', config.pfiDid[3].uri)
console.log('"Titanium Trust" launched: ', config.pfiDid[4].uri)
process.on('unhandledRejection', (reason: any, promise) => {
log.error(
`Unhandled promise rejection. Reason: ${reason}. Promise: ${JSON.stringify(promise)}. Stack: ${reason.stack}`,
)
})
process.on('uncaughtException', (err) => {
log.error('Uncaught exception:', err.stack || err)
})
// triggered by ctrl+c with no traps in between
process.on('SIGINT', async () => {
log.info('exit signal received [SIGINT]. starting graceful shutdown')
gracefulShutdown()
})
// triggered by docker, tiny etc.
process.on('SIGTERM', async () => {
log.info('exit signal received [SIGTERM]. starting graceful shutdown')
gracefulShutdown()
})
interface PFIServerConfig {
bearerDid: BearerDid,
port: string
}
function snooper() {
return function(req: Request, res: Response, next: NextFunction) {
console.log('snooper' + req.url)
return next()
}
}
// TODO: Remove this when spec clarified if should post to /exchanges... or exchanges.../rfq
function redirectPostToRfq() {
return function(req, res, next) {
// Check if the request is a POST to /exchanges/:exchangeId
if (req.method === 'POST' && req.url.match(/^\/exchanges\/\w+$/)) {
// Modify the request URL to redirect to /exchanges/:exchangeId/rfq
req.url = req.url + '/rfq'
console.log('Redirected: ' + req.url)
}
// Proceed to the next middleware
return next()
}
}
function createPFIServer(pfiConfig: PFIServerConfig) {
const ExchangeRepository = new InMemoryExchangesApi()
const activePFI = pfiConfig.bearerDid
const OfferingRepository = new HardcodedOfferingRepository(activePFI)
const httpApi = new TbdexHttpServer({
exchangesApi: ExchangeRepository,
offeringsApi: OfferingRepository,
pfiDid: activePFI.uri,
})
httpApi.api.use(snooper())
httpApi.api.use(redirectPostToRfq())
// provide the quote
httpApi.onCreateExchange(async (ctx, rfq: Rfq) => {
try {
await ExchangeRepository.addMessage(rfq)
} catch (error) {
console.log('failed to add message', error)
}
const offering = await OfferingRepository.getOffering({
id: rfq.data.offeringId,
})
// rfq.payinSubunits is USD - but as a string, convert this to a decimal and multiple but our terrible exchange rate
// convert to a string, with 2 decimal places
const payout = (
parseFloat(rfq.data.payin.amount) * Number(offering.data.payoutUnitsPerPayinUnit)
).toString()
const quote = Quote.create({
metadata: {
from: activePFI.uri,
to: rfq.from,
exchangeId: rfq.exchangeId,
protocol: '1.0'
},
data: {
expiresAt: new Date(2028, 4, 1).toISOString(),
payin: {
currencyCode: offering.data.payin.currencyCode,
amount: rfq.data.payin.amount,
},
payout: {
currencyCode: offering.data.payout.currencyCode,
amount: payout,
},
},
})
await quote.sign(activePFI)
await ExchangeRepository.addMessage(quote)
})
// When the customer accepts the order
httpApi.onSubmitOrder(async (ctx, order: Order) => {
console.log('order requested')
await ExchangeRepository.addMessage(order)
// const quote = await ExchangeRepository.getQuote({
// exchangeId: order.exchangeId,
// })
const rfq = await ExchangeRepository.getRfq({
exchangeId: order.exchangeId,
})
// Start: business logic to transfer funds
await updateOrderStatus(rfq, 'IN_PROGRESS', activePFI, ExchangeRepository)
await updateOrderStatus(rfq, 'TRANSFERING_FUNDS', activePFI, ExchangeRepository)
await updateOrderStatus(rfq, 'SUCCESS', activePFI, ExchangeRepository)
await close(rfq, 'SUCCESS', activePFI, ExchangeRepository)
// End: business logic to transfer funds
console.log('all DONE')
})
httpApi.onSubmitClose(async (ctx, close) => {
console.log('close called')
await ExchangeRepository.addMessage(close)
})
const server = httpApi.listen(pfiConfig.port, () => {
log.info(`Mock PFI listening on port ${pfiConfig.port}`)
})
httpApi.api.get('/', (req, res) => {
res.send(
'Please use the tbdex protocol to communicate with this server or a suitable library: https://github.com/TBD54566975/tbdex-protocol',
)
})
// This is just for example convenience. In the real world this would be discovered by other means.
httpApi.api.get('/did', (req, res) => {
res.send(activePFI.uri)
})
return { httpApi, server }
}
async function updateOrderStatus(rfq: Rfq, status: string, pfi: BearerDid, ExchangeRepository: InMemoryExchangesApi) {
console.log(
'----------->>>>>>>>> -------->Updating status',
status,
)
const orderStatus = OrderStatus.create({
metadata: {
from: pfi.uri,
to: rfq.from,
exchangeId: rfq.exchangeId,
},
data: {
orderStatus: status,
},
})
await orderStatus.sign(pfi)
await ExchangeRepository.addMessage(orderStatus)
}
async function close(rfq: Rfq, reason: string, pfi: BearerDid, ExchangeRepository: InMemoryExchangesApi) {
console.log('closing exchange ', reason)
const isSuccess = reason === 'SUCCESS'
const close = Close.create({
metadata: {
from: pfi.uri,
to: rfq.from,
exchangeId: rfq.exchangeId,
},
data: {
reason: reason,
...(isSuccess && { success: true })
},
})
await close.sign(pfi)
await ExchangeRepository.addMessage(close)
}
const myPFIServer1 = createPFIServer({bearerDid: config.pfiDid[0], port: config.port[0]})
const myPFIServer2 = createPFIServer({bearerDid: config.pfiDid[1], port: config.port[1]})
const myPFIServer3 = createPFIServer({bearerDid: config.pfiDid[2], port: config.port[2]})
const myPFIServer4 = createPFIServer({bearerDid: config.pfiDid[3], port: config.port[3]})
const myPFIServer5 = createPFIServer({bearerDid: config.pfiDid[4], port: config.port[4]})
// setup issuer server
const issuerApi = express()
const issuerPort = 3001
// Allow cross-origin requests
issuerApi.use(cors())
issuerApi.use(snooper())
issuerApi.get('/', (req, res) => {
res.send(
'Please make a get request to /kcc?name=yourname&country=yourcountry&did=yourdid to get a credential',
)
})
issuerApi.get('/kcc', async (req, res) => {
const credentials = await requestCredential(
req.query.name as string,
req.query.country as string,
req.query.did as string,
)
res.set('Access-Control-Allow-Origin', '*')
console.log('kcc request headers:', res.getHeaders()) // Log headers
res.send(credentials)
})
const issuerServer = issuerApi.listen(issuerPort, () => {
log.info(`Credential issuer listening on port ${issuerPort}`)
})
// PFIs shutdown services.
const httpServerShutdownHandler1 = new HttpServerShutdownHandler(myPFIServer1.server)
const httpServerShutdownHandler2 = new HttpServerShutdownHandler(myPFIServer2.server)
const httpServerShutdownHandler3 = new HttpServerShutdownHandler(myPFIServer3.server)
const httpServerShutdownHandler4 = new HttpServerShutdownHandler(myPFIServer4.server)
const httpServerShutdownHandler5 = new HttpServerShutdownHandler(myPFIServer5.server)
function stopServer(handler): Promise<void> {
return new Promise<void>((resolve, reject) => {
handler.stop((error) => {
if (error) {
log.error('Failed to stop server:', error)
reject(error)
} else {
log.info('Server stopped successfully.')
resolve()
}
})
})
}
async function gracefulShutdown() {
try {
await Promise.all([
stopServer(httpServerShutdownHandler1),
stopServer(httpServerShutdownHandler2),
stopServer(httpServerShutdownHandler3),
stopServer(httpServerShutdownHandler4),
stopServer(httpServerShutdownHandler5),
issuerServer.close(),
])
log.info('All servers stopped, exiting now.')
process.exit(0)
} catch (error) {
log.error('An error occurred during shutdown:', error)
process.exit(1)
}
}