-
Notifications
You must be signed in to change notification settings - Fork 55
/
util.ts
70 lines (66 loc) · 2.15 KB
/
util.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
import { Cardano, HealthCheckResponse } from '@cardano-sdk/core';
import {
ConnectionConfig,
InteractionContext,
InteractionType,
ServerHealth,
createInteractionContext
} from '@cardano-ogmios/client';
import { Logger } from 'ts-log';
import { Percent } from '@cardano-sdk/util';
/**
* Converts an Ogmios connection URL to an Ogmios ConnectionConfig Object
*
* @param {URL} connectionURL Ogmios connection URL
* @returns {ConnectionConfig} the ConnectionConfig Object
*/
export const urlToConnectionConfig = (connectionURL?: URL): ConnectionConfig => ({
host: connectionURL?.hostname,
port: connectionURL ? Number.parseInt(connectionURL.port) : undefined,
tls: connectionURL?.protocol === 'wss'
});
type CreateInteractionContextOptions = {
connection?: ConnectionConfig;
interactionType?: InteractionType;
};
/**
* Creates an Ogmios InteractionContext with close logic
*
* @param {Logger} logger Logger instance
* @param {CreateInteractionContextOptions} options Options passed to the createInteractionContext function
* @param {Function} onUnexpectedClose Optional callback to trigger an action when an unexpected close event occurs
* @returns {Promise<InteractionContext>} Promise resolving an Ogmios InteractionContext
*/
export const createInteractionContextWithLogger = (
logger: Logger,
options?: CreateInteractionContextOptions,
onUnexpectedClose?: () => Promise<void>
): Promise<InteractionContext> =>
createInteractionContext(
(error) => {
logger.error({ error }, error.message);
},
async (code, reason) => {
if (code === 1000) {
logger.info({ code }, reason);
} else {
logger.error({ code }, 'Connection closed');
await onUnexpectedClose?.();
}
},
options
);
export const ogmiosServerHealthToHealthCheckResponse = ({
lastKnownTip,
networkSynchronization
}: ServerHealth): HealthCheckResponse => ({
localNode: {
ledgerTip: {
blockNo: Cardano.BlockNo(lastKnownTip.blockNo),
hash: Cardano.BlockId(lastKnownTip.hash),
slot: Cardano.Slot(lastKnownTip.slot)
},
networkSync: Percent(networkSynchronization)
},
ok: networkSynchronization > 0.99
});