@reyaxyz/common 0.362.1 → 0.363.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/commands/exposure/command.js +8 -22
- package/dist/commands/exposure/command.js.map +1 -1
- package/dist/incentives-api-types.js.map +1 -1
- package/dist/services/getNativeToken.js +1 -0
- package/dist/services/getNativeToken.js.map +1 -1
- package/dist/services/getSocketAddresses.js +1 -0
- package/dist/services/getSocketAddresses.js.map +1 -1
- package/dist/trading-api-types.js.map +1 -1
- package/dist/transactions/abis/Errors.json +1638 -34
- package/dist/transactions/abis/OrdersGateway.json +729 -123
- package/dist/transactions/abis/PassivePerpProxy.json +542 -0
- package/dist/transactions/buildMulticallTx.js.map +1 -1
- package/dist/transactions/consts.js +1 -2
- package/dist/transactions/consts.js.map +1 -1
- package/dist/transactions/contractAddresses.js +45 -5
- package/dist/transactions/contractAddresses.js.map +1 -1
- package/dist/transactions/sign.js +237 -111
- package/dist/transactions/sign.js.map +1 -1
- package/dist/types/commands/exposure/command.d.ts +8 -7
- package/dist/types/commands/exposure/command.d.ts.map +1 -1
- package/dist/types/incentives-api-types.d.ts +61 -5
- package/dist/types/incentives-api-types.d.ts.map +1 -1
- package/dist/types/services/getNativeToken.d.ts.map +1 -1
- package/dist/types/services/getSocketAddresses.d.ts.map +1 -1
- package/dist/types/trading-api-types.d.ts +200 -32
- package/dist/types/trading-api-types.d.ts.map +1 -1
- package/dist/types/transactions/buildMulticallTx.d.ts +1 -0
- package/dist/types/transactions/buildMulticallTx.d.ts.map +1 -1
- package/dist/types/transactions/consts.d.ts +0 -1
- package/dist/types/transactions/consts.d.ts.map +1 -1
- package/dist/types/transactions/contractAddresses.d.ts +0 -1
- package/dist/types/transactions/contractAddresses.d.ts.map +1 -1
- package/dist/types/transactions/sign.d.ts +113 -9
- package/dist/types/transactions/sign.d.ts.map +1 -1
- package/dist/types/types.d.ts +61 -65
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/utils/calculate.d.ts.map +1 -1
- package/dist/types/utils/consts.d.ts +2 -2
- package/dist/types/utils/consts.d.ts.map +1 -1
- package/dist/types/utils/error-sanitizer.d.ts +15 -0
- package/dist/types/utils/error-sanitizer.d.ts.map +1 -0
- package/dist/types/utils/index.d.ts +3 -0
- package/dist/types/utils/index.d.ts.map +1 -1
- package/dist/types/utils/network.d.ts.map +1 -1
- package/dist/types/utils/number.d.ts +5 -0
- package/dist/types/utils/number.d.ts.map +1 -1
- package/dist/types/utils/realized-balance.d.ts +54 -0
- package/dist/types/utils/realized-balance.d.ts.map +1 -0
- package/dist/types/utils/throttled-error.d.ts +42 -0
- package/dist/types/utils/throttled-error.d.ts.map +1 -0
- package/dist/types/utils/token/normalize.d.ts +2 -1
- package/dist/types/utils/token/normalize.d.ts.map +1 -1
- package/dist/types/utils/token/token-info-getters.d.ts.map +1 -1
- package/dist/types/utils/token/token-info.d.ts.map +1 -1
- package/dist/types.js +25 -11
- package/dist/types.js.map +1 -1
- package/dist/utils/calculate.js +18 -9
- package/dist/utils/calculate.js.map +1 -1
- package/dist/utils/consts.js +2 -7
- package/dist/utils/consts.js.map +1 -1
- package/dist/utils/error-sanitizer.js +135 -0
- package/dist/utils/error-sanitizer.js.map +1 -0
- package/dist/utils/index.js +3 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/network.js +4 -0
- package/dist/utils/network.js.map +1 -1
- package/dist/utils/number.js +96 -1
- package/dist/utils/number.js.map +1 -1
- package/dist/utils/realized-balance.js +126 -0
- package/dist/utils/realized-balance.js.map +1 -0
- package/dist/utils/throttled-error.js +60 -0
- package/dist/utils/throttled-error.js.map +1 -0
- package/dist/utils/token/normalize.js +2 -2
- package/dist/utils/token/normalize.js.map +1 -1
- package/dist/utils/token/token-info-getters.js +80 -5
- package/dist/utils/token/token-info-getters.js.map +1 -1
- package/dist/utils/token/token-info.js +7 -0
- package/dist/utils/token/token-info.js.map +1 -1
- package/package.json +3 -3
- package/src/commands/exposure/command.ts +8 -38
- package/src/incentives-api-types.ts +60 -5
- package/src/services/getNativeToken.ts +1 -0
- package/src/services/getSocketAddresses.ts +1 -0
- package/src/trading-api-types.ts +258 -39
- package/src/transactions/abis/Errors.json +5478 -3874
- package/src/transactions/abis/OrdersGateway.json +730 -124
- package/src/transactions/abis/PassivePerpProxy.json +542 -0
- package/src/transactions/buildMulticallTx.ts +4 -0
- package/src/transactions/consts.ts +0 -1
- package/src/transactions/contractAddresses.ts +42 -7
- package/src/transactions/sign.ts +306 -150
- package/src/types.ts +98 -83
- package/src/utils/calculate.ts +21 -8
- package/src/utils/consts.ts +4 -16
- package/src/utils/error-sanitizer.ts +137 -0
- package/src/utils/index.ts +3 -0
- package/src/utils/network.ts +4 -0
- package/src/utils/number.ts +110 -0
- package/src/utils/realized-balance.ts +163 -0
- package/src/utils/throttled-error.ts +85 -0
- package/src/utils/token/normalize.ts +6 -1
- package/src/utils/token/token-info-getters.ts +104 -6
- package/src/utils/token/token-info.ts +42 -0
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sanitizeErrorLogInfo = exports.normalizeError = void 0;
|
|
4
|
+
// Redis can echo command arguments inside an error's message. Once an error is
|
|
5
|
+
// known to carry command metadata, its message and stack must therefore be
|
|
6
|
+
// treated as tainted rather than attempting value-by-value replacement.
|
|
7
|
+
var REDACTED_COMMAND_ERROR = '[redacted: Redis command error — message/stack withheld (may echo arguments)]';
|
|
8
|
+
function commandField(source) {
|
|
9
|
+
if (source === null || typeof source !== 'object')
|
|
10
|
+
return undefined;
|
|
11
|
+
var command = source.command;
|
|
12
|
+
return command !== null && typeof command === 'object'
|
|
13
|
+
? command
|
|
14
|
+
: undefined;
|
|
15
|
+
}
|
|
16
|
+
function redactCommandBearing(source, command, depth) {
|
|
17
|
+
var out = {};
|
|
18
|
+
if (typeof source.name === 'string')
|
|
19
|
+
out.name = source.name;
|
|
20
|
+
if (typeof source.code === 'string' || typeof source.code === 'number') {
|
|
21
|
+
out.code = source.code;
|
|
22
|
+
}
|
|
23
|
+
out.command = typeof command.name === 'string' ? { name: command.name } : {};
|
|
24
|
+
out.message = REDACTED_COMMAND_ERROR;
|
|
25
|
+
// The stack is intentionally withheld because it can repeat the tainted
|
|
26
|
+
// message. Causes are projected independently so safe diagnostics survive.
|
|
27
|
+
if (source.cause !== undefined && depth < 3) {
|
|
28
|
+
out.cause = normalizeError(source.cause, depth + 1);
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Project an unknown error into a serializable diagnostic record. An ioredis
|
|
34
|
+
* error carrying `command: { name, args }` is fail-closed: arguments plus the
|
|
35
|
+
* potentially argument-bearing message/stack are withheld, while safe fields
|
|
36
|
+
* such as the error name, code, command name, and projected cause survive.
|
|
37
|
+
*/
|
|
38
|
+
function normalizeError(err, depth) {
|
|
39
|
+
if (depth === void 0) { depth = 0; }
|
|
40
|
+
if (err instanceof Error) {
|
|
41
|
+
// A logger must never throw because an error object has a hostile getter.
|
|
42
|
+
try {
|
|
43
|
+
var command = commandField(err);
|
|
44
|
+
if (command)
|
|
45
|
+
return redactCommandBearing(err, command, depth);
|
|
46
|
+
var out = {};
|
|
47
|
+
if (typeof err.name === 'string')
|
|
48
|
+
out.name = err.name;
|
|
49
|
+
if (typeof err.message === 'string')
|
|
50
|
+
out.message = err.message;
|
|
51
|
+
if (typeof err.stack === 'string')
|
|
52
|
+
out.stack = err.stack;
|
|
53
|
+
var code = err.code;
|
|
54
|
+
if (typeof code === 'string' || typeof code === 'number')
|
|
55
|
+
out.code = code;
|
|
56
|
+
var cause = err.cause;
|
|
57
|
+
if (cause !== undefined && depth < 3) {
|
|
58
|
+
out.cause = normalizeError(cause, depth + 1);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
catch (_a) {
|
|
63
|
+
return { message: '[unserializable error]' };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// Plain objects use the same command-taint rule and an allow-list projection
|
|
67
|
+
// so arbitrary password/argument fields never reach a log record.
|
|
68
|
+
if (err !== null && typeof err === 'object') {
|
|
69
|
+
try {
|
|
70
|
+
var command = commandField(err);
|
|
71
|
+
if (command) {
|
|
72
|
+
return redactCommandBearing(err, command, depth);
|
|
73
|
+
}
|
|
74
|
+
var src = err;
|
|
75
|
+
var out = {};
|
|
76
|
+
if (typeof src.message === 'string')
|
|
77
|
+
out.message = src.message;
|
|
78
|
+
if (typeof src.name === 'string')
|
|
79
|
+
out.name = src.name;
|
|
80
|
+
if (typeof src.code === 'string' || typeof src.code === 'number') {
|
|
81
|
+
out.code = src.code;
|
|
82
|
+
}
|
|
83
|
+
if (src.cause !== undefined && depth < 3) {
|
|
84
|
+
out.cause = normalizeError(src.cause, depth + 1);
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
catch (_b) {
|
|
89
|
+
return { message: '[unserializable error]' };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
return { message: String(err) };
|
|
94
|
+
}
|
|
95
|
+
catch (_c) {
|
|
96
|
+
return { message: '[unserializable error]' };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
exports.normalizeError = normalizeError;
|
|
100
|
+
/**
|
|
101
|
+
* Pure, in-place log-record sanitizer. Keeping this free of Winston types lets
|
|
102
|
+
* every package install a tiny adapter around the same implementation without
|
|
103
|
+
* introducing package cycles or forcing the shared leaf package to depend on a
|
|
104
|
+
* logging framework.
|
|
105
|
+
*/
|
|
106
|
+
function sanitizeErrorLogInfo(info) {
|
|
107
|
+
var record = info;
|
|
108
|
+
// Nested `{ error }` and `{ cause }` are the preferred contextual shapes.
|
|
109
|
+
// Primitive values cannot carry command metadata, so preserve their existing
|
|
110
|
+
// field shape rather than wrapping them in `{ message }`.
|
|
111
|
+
if (record.error !== null && typeof record.error === 'object') {
|
|
112
|
+
record.error = normalizeError(record.error);
|
|
113
|
+
}
|
|
114
|
+
if (record.cause !== null && typeof record.cause === 'object') {
|
|
115
|
+
record.cause = normalizeError(record.cause);
|
|
116
|
+
}
|
|
117
|
+
// Winston can flatten a raw Error passed as the second argument. Command
|
|
118
|
+
// presence alone makes the merged message/stack tainted, including stackless
|
|
119
|
+
// and plain-object variants.
|
|
120
|
+
var command = commandField(record);
|
|
121
|
+
if (command) {
|
|
122
|
+
record.message = REDACTED_COMMAND_ERROR;
|
|
123
|
+
record.stack = undefined;
|
|
124
|
+
try {
|
|
125
|
+
record.command =
|
|
126
|
+
typeof command.name === 'string' ? { name: command.name } : {};
|
|
127
|
+
}
|
|
128
|
+
catch (_a) {
|
|
129
|
+
record.command = {};
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return info;
|
|
133
|
+
}
|
|
134
|
+
exports.sanitizeErrorLogInfo = sanitizeErrorLogInfo;
|
|
135
|
+
//# sourceMappingURL=error-sanitizer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-sanitizer.js","sourceRoot":"/","sources":["utils/error-sanitizer.ts"],"names":[],"mappings":";;;AAAA,+EAA+E;AAC/E,2EAA2E;AAC3E,wEAAwE;AACxE,IAAM,sBAAsB,GAC1B,+EAA+E,CAAC;AAElF,SAAS,YAAY,CAAC,MAAe;IACnC,IAAI,MAAM,KAAK,IAAI,IAAI,OAAO,MAAM,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IACpE,IAAM,OAAO,GAAI,MAAgC,CAAC,OAAO,CAAC;IAC1D,OAAO,OAAO,KAAK,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ;QACpD,CAAC,CAAE,OAA8B;QACjC,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAED,SAAS,oBAAoB,CAC3B,MAA2D,EAC3D,OAA2B,EAC3B,KAAa;IAEb,IAAM,GAAG,GAA4B,EAAE,CAAC;IACxC,IAA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AY,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,OAAO,EAAE,CAAC;QACZ,MAAM,CAAC,OAAO,GAAG,sBAAsB,CAAC;QACxC,MAAM,CAAC,KAAK,GAAG,SAAS,CAAC;QACzB,IAAI,CAAC;YACH,MAAM,CAAC,OAAO;gBACZ,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACnE,CAAC;QAAC,WAAM,CAAC;YACP,MAAM,CAAC,OAAO,GAAG,EAAE,CAAC;QACtB,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AA7BD,oDA6BC","sourcesContent":["// Redis can echo command arguments inside an error's message. Once an error is\n// known to carry command metadata, its message and stack must therefore be\n// treated as tainted rather than attempting value-by-value replacement.\nconst REDACTED_COMMAND_ERROR =\n '[redacted: Redis command error — message/stack withheld (may echo arguments)]';\n\nfunction commandField(source: unknown): { name?: unknown } | undefined {\n if (source === null || typeof source !== 'object') return undefined;\n const command = (source as { command?: unknown }).command;\n return command !== null && typeof command === 'object'\n ? (command as { name?: unknown })\n : undefined;\n}\n\nfunction redactCommandBearing(\n source: { name?: unknown; code?: unknown; cause?: unknown },\n command: { name?: unknown },\n depth: number,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n if (typeof source.name === 'string') out.name = source.name;\n if (typeof source.code === 'string' || typeof source.code === 'number') {\n out.code = source.code;\n }\n out.command = typeof command.name === 'string' ? { name: command.name } : {};\n out.message = REDACTED_COMMAND_ERROR;\n // The stack is intentionally withheld because it can repeat the tainted\n // message. Causes are projected independently so safe diagnostics survive.\n if (source.cause !== undefined && depth < 3) {\n out.cause = normalizeError(source.cause, depth + 1);\n }\n return out;\n}\n\n/**\n * Project an unknown error into a serializable diagnostic record. An ioredis\n * error carrying `command: { name, args }` is fail-closed: arguments plus the\n * potentially argument-bearing message/stack are withheld, while safe fields\n * such as the error name, code, command name, and projected cause survive.\n */\nexport function normalizeError(\n err: unknown,\n depth = 0,\n): Record<string, unknown> {\n if (err instanceof Error) {\n // A logger must never throw because an error object has a hostile getter.\n try {\n const command = commandField(err);\n if (command) return redactCommandBearing(err, command, depth);\n\n const out: Record<string, unknown> = {};\n if (typeof err.name === 'string') out.name = err.name;\n if (typeof err.message === 'string') out.message = err.message;\n if (typeof err.stack === 'string') out.stack = err.stack;\n const { code } = err as { code?: unknown };\n if (typeof code === 'string' || typeof code === 'number') out.code = code;\n const { cause } = err as { cause?: unknown };\n if (cause !== undefined && depth < 3) {\n out.cause = normalizeError(cause, depth + 1);\n }\n return out;\n } catch {\n return { message: '[unserializable error]' };\n }\n }\n\n // Plain objects use the same command-taint rule and an allow-list projection\n // so arbitrary password/argument fields never reach a log record.\n if (err !== null && typeof err === 'object') {\n try {\n const command = commandField(err);\n if (command) {\n return redactCommandBearing(\n err as { name?: unknown; code?: unknown; cause?: unknown },\n command,\n depth,\n );\n }\n const src = err as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n if (typeof src.message === 'string') out.message = src.message;\n if (typeof src.name === 'string') out.name = src.name;\n if (typeof src.code === 'string' || typeof src.code === 'number') {\n out.code = src.code;\n }\n if (src.cause !== undefined && depth < 3) {\n out.cause = normalizeError(src.cause, depth + 1);\n }\n return out;\n } catch {\n return { message: '[unserializable error]' };\n }\n }\n\n try {\n return { message: String(err) };\n } catch {\n return { message: '[unserializable error]' };\n }\n}\n\n/**\n * Pure, in-place log-record sanitizer. Keeping this free of Winston types lets\n * every package install a tiny adapter around the same implementation without\n * introducing package cycles or forcing the shared leaf package to depend on a\n * logging framework.\n */\nexport function sanitizeErrorLogInfo<T extends Record<string, unknown>>(\n info: T,\n): T {\n const record = info as Record<string, unknown>;\n // Nested `{ error }` and `{ cause }` are the preferred contextual shapes.\n // Primitive values cannot carry command metadata, so preserve their existing\n // field shape rather than wrapping them in `{ message }`.\n if (record.error !== null && typeof record.error === 'object') {\n record.error = normalizeError(record.error);\n }\n if (record.cause !== null && typeof record.cause === 'object') {\n record.cause = normalizeError(record.cause);\n }\n\n // Winston can flatten a raw Error passed as the second argument. Command\n // presence alone makes the merged message/stack tainted, including stackless\n // and plain-object variants.\n const command = commandField(record);\n if (command) {\n record.message = REDACTED_COMMAND_ERROR;\n record.stack = undefined;\n try {\n record.command =\n typeof command.name === 'string' ? { name: command.name } : {};\n } catch {\n record.command = {};\n }\n }\n return info;\n}\n"]}
|
package/dist/utils/index.js
CHANGED
|
@@ -31,4 +31,7 @@ __exportStar(require("./stringify"), exports);
|
|
|
31
31
|
__exportStar(require("./delay"), exports);
|
|
32
32
|
__exportStar(require("./transaction-receipt"), exports);
|
|
33
33
|
__exportStar(require("./layerzero"), exports);
|
|
34
|
+
__exportStar(require("./throttled-error"), exports);
|
|
35
|
+
__exportStar(require("./error-sanitizer"), exports);
|
|
36
|
+
__exportStar(require("./realized-balance"), exports);
|
|
34
37
|
//# sourceMappingURL=index.js.map
|
package/dist/utils/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,2CAAyB;AACzB,8CAA4B;AAC5B,sDAAoC;AACpC,2CAAyB;AACzB,sDAAoC;AACpC,4CAA0B;AAC1B,2CAAyB;AACzB,0CAAwB;AACxB,8CAA4B;AAC5B,0CAAwB;AACxB,iDAA+B;AAC/B,wDAAsC;AACtC,8CAA4B;AAC5B,0CAAwB;AACxB,wDAAsC;AACtC,8CAA4B","sourcesContent":["export * from './consts';\nexport * from './points';\nexport * from './calculate';\nexport * from './compute-trade-pnl';\nexport * from './struct';\nexport * from './cooldown-interval';\nexport * from './network';\nexport * from './number';\nexport * from './retry';\nexport * from './timestamp';\nexport * from './token';\nexport * from './task-wrapper';\nexport * from './whitelisted-wallets';\nexport * from './stringify';\nexport * from './delay';\nexport * from './transaction-receipt';\nexport * from './layerzero';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"/","sources":["utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,2CAAyB;AACzB,8CAA4B;AAC5B,sDAAoC;AACpC,2CAAyB;AACzB,sDAAoC;AACpC,4CAA0B;AAC1B,2CAAyB;AACzB,0CAAwB;AACxB,8CAA4B;AAC5B,0CAAwB;AACxB,iDAA+B;AAC/B,wDAAsC;AACtC,8CAA4B;AAC5B,0CAAwB;AACxB,wDAAsC;AACtC,8CAA4B;AAC5B,oDAAkC;AAClC,oDAAkC;AAClC,qDAAmC","sourcesContent":["export * from './consts';\nexport * from './points';\nexport * from './calculate';\nexport * from './compute-trade-pnl';\nexport * from './struct';\nexport * from './cooldown-interval';\nexport * from './network';\nexport * from './number';\nexport * from './retry';\nexport * from './timestamp';\nexport * from './token';\nexport * from './task-wrapper';\nexport * from './whitelisted-wallets';\nexport * from './stringify';\nexport * from './delay';\nexport * from './transaction-receipt';\nexport * from './layerzero';\nexport * from './throttled-error';\nexport * from './error-sanitizer';\nexport * from './realized-balance';\n"]}
|
package/dist/utils/network.js
CHANGED
|
@@ -18,6 +18,8 @@ function getMoneyInOutNetworks(chainId) {
|
|
|
18
18
|
types_1.MoneyInOutChainId.opSepolia,
|
|
19
19
|
types_1.MoneyInOutChainId.arbitrumSepolia,
|
|
20
20
|
];
|
|
21
|
+
if (chainId === types_1.ReyaChainId.reyaLocal)
|
|
22
|
+
return [];
|
|
21
23
|
throw new Error("Unknown Reya chain id ".concat(chainId));
|
|
22
24
|
}
|
|
23
25
|
exports.getMoneyInOutNetworks = getMoneyInOutNetworks;
|
|
@@ -41,10 +43,12 @@ exports.chainIdToExplorerURL = (_a = {},
|
|
|
41
43
|
_a[types_1.MoneyInOutChainId.opSepolia] = 'https://sepolia-optimism.etherscan.io',
|
|
42
44
|
_a[types_1.MoneyInOutChainId.ethereumSepolia] = 'https://sepolia.etherscan.io',
|
|
43
45
|
_a[types_1.ReyaChainId.reyaNetwork] = 'https://explorer.reya.network',
|
|
46
|
+
_a[types_1.ReyaChainId.reyaLocal] = 'http://127.0.0.1:4000',
|
|
44
47
|
_a[types_1.ReyaChainId.reyaCronos] = 'https://reya-cronos.blockscout.com',
|
|
45
48
|
_a);
|
|
46
49
|
var ChainRpcUrls = (_b = {},
|
|
47
50
|
_b[types_1.ReyaChainId.reyaNetwork] = ['https://rpc.reya.network'],
|
|
51
|
+
_b[types_1.ReyaChainId.reyaLocal] = ['http://127.0.0.1:8545'],
|
|
48
52
|
_b[types_1.MoneyInOutChainId.ethereumMainnet] = [
|
|
49
53
|
'https://mainnet.gateway.tenderly.co',
|
|
50
54
|
'https://eth.llamarpc.com',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network.js","sourceRoot":"/","sources":["utils/network.ts"],"names":[],"mappings":";;;;AAAA,kCAA0D;AAE1D,SAAgB,qBAAqB,CACnC,OAAoB;IAEpB,IAAI,OAAO,KAAK,mBAAW,CAAC,WAAW;QACrC,OAAO;YACL,yBAAiB,CAAC,eAAe;YACjC,yBAAiB,CAAC,SAAS;YAC3B,yBAAiB,CAAC,cAAc;YAChC,yBAAiB,CAAC,WAAW;YAC7B,yBAAiB,CAAC,WAAW;SAC9B,CAAC;IAEJ,IAAI,OAAO,KAAK,mBAAW,CAAC,UAAU;QACpC,OAAO;YACL,yBAAiB,CAAC,eAAe;YACjC,yBAAiB,CAAC,SAAS;YAC3B,yBAAiB,CAAC,eAAe;SAClC,CAAC;IAEJ,MAAM,IAAI,KAAK,CAAC,gCAAyB,OAAO,CAAE,CAAC,CAAC;AACtD,CAAC;AApBD,sDAoBC;AAED,SAAgB,mCAAmC,CACjD,iBAAoC;IAEpC,IACE,qBAAqB,CAAC,mBAAW,CAAC,WAAW,CAAC,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAC1E,CAAC;QACD,OAAO,mBAAW,CAAC,WAAW,CAAC;IACjC,CAAC;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C,CAAC;IAC7E,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AAVW,QAAA,uBAAuB,2BAUlC","sourcesContent":["import { MoneyInOutChainId, ReyaChainId } from '../types';\n\nexport function getMoneyInOutNetworks(\n chainId: ReyaChainId,\n): MoneyInOutChainId[] {\n if (chainId === ReyaChainId.reyaNetwork)\n return [\n MoneyInOutChainId.ethereumMainnet,\n MoneyInOutChainId.opMainnet,\n MoneyInOutChainId.polygonMainnet,\n MoneyInOutChainId.arbitrumOne,\n MoneyInOutChainId.baseMainnet,\n ];\n\n if (chainId === ReyaChainId.reyaCronos)\n return [\n MoneyInOutChainId.ethereumSepolia,\n MoneyInOutChainId.opSepolia,\n MoneyInOutChainId.arbitrumSepolia,\n ];\n\n throw new Error(`Unknown Reya chain id ${chainId}`);\n}\n\nexport function getReyaNetworkFromMoneyInOutChainId(\n moneyInOutChainId: MoneyInOutChainId,\n): ReyaChainId {\n if (\n getMoneyInOutNetworks(ReyaChainId.reyaNetwork).includes(moneyInOutChainId)\n ) {\n return ReyaChainId.reyaNetwork;\n }\n\n if (\n getMoneyInOutNetworks(ReyaChainId.reyaCronos).includes(moneyInOutChainId)\n ) {\n return ReyaChainId.reyaCronos;\n }\n\n throw new Error(`Unknown external chain id ${moneyInOutChainId}`);\n}\n\nexport const chainIdToExplorerURL: {\n [key in MoneyInOutChainId | ReyaChainId]: string;\n} = {\n [MoneyInOutChainId.ethereumMainnet]: 'https://etherscan.io',\n [MoneyInOutChainId.opMainnet]: 'https://optimistic.etherscan.io',\n [MoneyInOutChainId.polygonMainnet]: 'https://polygonscan.com',\n [MoneyInOutChainId.arbitrumOne]: 'https://arbiscan.io',\n [MoneyInOutChainId.baseMainnet]: 'https://basescan.org',\n [MoneyInOutChainId.arbitrumSepolia]: 'https://sepolia.arbiscan.io',\n [MoneyInOutChainId.opSepolia]: 'https://sepolia-optimism.etherscan.io',\n [MoneyInOutChainId.ethereumSepolia]: 'https://sepolia.etherscan.io',\n [ReyaChainId.reyaNetwork]: 'https://explorer.reya.network',\n [ReyaChainId.reyaCronos]: 'https://reya-cronos.blockscout.com',\n};\n\nconst ChainRpcUrls: Record<MoneyInOutChainId | ReyaChainId, string[]> = {\n [ReyaChainId.reyaNetwork]: ['https://rpc.reya.network'],\n [MoneyInOutChainId.ethereumMainnet]: [\n 'https://mainnet.gateway.tenderly.co',\n 'https://eth.llamarpc.com',\n 'https://eth-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://eth-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://eth-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://mainnet.gateway.tenderly.co/69U6LoF0URUv5CfuIU7FdL',\n ],\n [MoneyInOutChainId.opMainnet]: [\n 'https://mainnet.optimism.io',\n 'https://optimism.llamarpc.com',\n 'https://opt-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://opt-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://opt-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://optimism.gateway.tenderly.co/69LkAPTI3LODcBAdtz9wQC',\n ],\n [MoneyInOutChainId.polygonMainnet]: [\n 'https://polygon-rpc.com',\n 'https://gateway.tenderly.co/public/polygon',\n 'https://polygon-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://polygon-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://polygon-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://polygon.gateway.tenderly.co/7Qw4fTY4kf3v02LjJjWyvZ',\n ],\n [MoneyInOutChainId.arbitrumOne]: [\n 'https://arb1.arbitrum.io/rpc',\n 'https://arbitrum.llamarpc.com',\n 'https://arb-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://arb-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://arb-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://arbitrum.gateway.tenderly.co/1wQGK6nNPTbSc7asucAbzA',\n ],\n [MoneyInOutChainId.baseMainnet]: [\n 'https://mainnet.base.org',\n 'https://base.llamarpc.com',\n 'https://base-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://base-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://base-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://base.gateway.tenderly.co/2LHAD54IBvgXiVQdhE9mIF',\n ],\n // Add the rest of the mainnet URLs above\n [ReyaChainId.reyaCronos]: [\n 'https://rpc-reya-cronos.t.conduit.xyz/7F8HNfECaatE8VEZGD5gcJPghXqhshTTi',\n ],\n [MoneyInOutChainId.arbitrumSepolia]: [\n 'https://sepolia-rollup.arbitrum.io/rpc',\n 'https://endpoints.omniatech.io/v1/arbitrum/sepolia/public',\n 'https://arbitrum-sepolia.gateway.tenderly.co/4YMRN8fKu2SV1JSNsGlbMZ',\n ],\n [MoneyInOutChainId.opSepolia]: [\n 'https://sepolia.optimism.io',\n 'https://optimism-sepolia.blockpi.network/v1/rpc/public',\n 'https://optimism-sepolia.gateway.tenderly.co/2nXBEGPk57CotvTJMjIMK7',\n ],\n [MoneyInOutChainId.ethereumSepolia]: [\n 'https://sepolia.gateway.tenderly.co',\n 'https://ethereum-sepolia.blockpi.network/v1/rpc/public',\n 'https://sepolia.gateway.tenderly.co/1u2yZV1rdVLpgOeHwD1Z8M',\n ],\n};\n\nconst ALCHEMY_BASE_RPC_URL: Record<MoneyInOutChainId, string> = {\n // mainnet\n [MoneyInOutChainId.ethereumMainnet]: 'https://eth-mainnet.g.alchemy.com/v2',\n [MoneyInOutChainId.opMainnet]: 'https://opt-mainnet.g.alchemy.com/v2',\n [MoneyInOutChainId.polygonMainnet]:\n 'https://polygon-mainnet.g.alchemy.com/v2',\n [MoneyInOutChainId.arbitrumOne]: 'https://arb-mainnet.g.alchemy.com/v2',\n [MoneyInOutChainId.baseMainnet]: 'https://base-mainnet.g.alchemy.com/v2',\n // testnet\n [MoneyInOutChainId.arbitrumSepolia]: 'https://arb-sepolia.g.alchemy.com/v2',\n [MoneyInOutChainId.opSepolia]: 'https://opt-sepolia.g.alchemy.com/v2',\n [MoneyInOutChainId.ethereumSepolia]: 'https://eth-sepolia.g.alchemy.com/v2',\n};\n\nconst INFURA_BASE_RPC_URL: Record<MoneyInOutChainId, string> = {\n // mainnet\n [MoneyInOutChainId.ethereumMainnet]: 'https://mainnet.infura.io/v3',\n [MoneyInOutChainId.opMainnet]: 'https://optimism-mainnet.infura.io/v3',\n [MoneyInOutChainId.polygonMainnet]: 'https://polygon-mainnet.infura.io/v3',\n [MoneyInOutChainId.arbitrumOne]: 'https://arbitrum-mainnet.infura.io/v3',\n [MoneyInOutChainId.baseMainnet]: 'https://base-mainnet.infura.io/v3',\n // testnet\n [MoneyInOutChainId.arbitrumSepolia]: 'https://arbitrum-sepolia.infura.io/v3',\n [MoneyInOutChainId.opSepolia]: 'https://optimism-sepolia.infura.io/v3',\n [MoneyInOutChainId.ethereumSepolia]: 'https://sepolia.infura.io/v3',\n};\n\nexport const getAlchemyRpcUrl = (\n apiKey: string,\n chainId: MoneyInOutChainId,\n): string | null => {\n const rpcUrl = ALCHEMY_BASE_RPC_URL[chainId];\n\n if (!rpcUrl) {\n return null;\n }\n\n return `${rpcUrl}/${apiKey}`;\n};\n\nexport const getInfuraRpcUrl = (\n apiKey: string,\n chainId: MoneyInOutChainId,\n): string | null => {\n const rpcUrl = INFURA_BASE_RPC_URL[chainId];\n\n if (!rpcUrl) {\n return null;\n }\n\n return `${rpcUrl}/${apiKey}`;\n};\n\nexport const getPublicRpcUrls = (\n chainId: MoneyInOutChainId | ReyaChainId,\n): string[] => {\n const rpcUrls = ChainRpcUrls[chainId];\n\n if (!rpcUrls) {\n return [];\n }\n\n return rpcUrls;\n};\n\nexport const getPublicRpcUrlsOrThrow = (\n chainId: MoneyInOutChainId | ReyaChainId,\n): string[] => {\n const rpcUrls = getPublicRpcUrls(chainId);\n\n if (rpcUrls.length === 0) {\n throw new Error('No public RPC URLs configured for the chain: ' + chainId);\n }\n\n return rpcUrls;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"network.js","sourceRoot":"/","sources":["utils/network.ts"],"names":[],"mappings":";;;;AAAA,kCAA0D;AAE1D,SAAgB,qBAAqB,CACnC,OAAoB;IAEpB,IAAI,OAAO,KAAK,mBAAW,CAAC,WAAW;QACrC,OAAO;YACL,yBAAiB,CAAC,eAAe;YACjC,yBAAiB,CAAC,SAAS;YAC3B,yBAAiB,CAAC,cAAc;YAChC,yBAAiB,CAAC,WAAW;YAC7B,yBAAiB,CAAC,WAAW;SAC9B,CAAC;IAEJ,IAAI,OAAO,KAAK,mBAAW,CAAC,UAAU;QACpC,OAAO;YACL,yBAAiB,CAAC,eAAe;YACjC,yBAAiB,CAAC,SAAS;YAC3B,yBAAiB,CAAC,eAAe;SAClC,CAAC;IAEJ,IAAI,OAAO,KAAK,mBAAW,CAAC,SAAS;QAAE,OAAO,EAAE,CAAC;IAEjD,MAAM,IAAI,KAAK,CAAC,gCAAyB,OAAO,CAAE,CAAC,CAAC;AACtD,CAAC;AAtBD,sDAsBC;AAED,SAAgB,mCAAmC,CACjD,iBAAoC;IAEpC,IACE,qBAAqB,CAAC,mBAAW,CAAC,WAAW,CAAC,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAC1E,CAAC;QACD,OAAO,mBAAW,CAAC,WAAW,CAAC;IACj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C;IAE1C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CAAC,+CAA+C,GAAG,OAAO,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AAVW,QAAA,uBAAuB,2BAUlC","sourcesContent":["import { MoneyInOutChainId, ReyaChainId } from '../types';\n\nexport function getMoneyInOutNetworks(\n chainId: ReyaChainId,\n): MoneyInOutChainId[] {\n if (chainId === ReyaChainId.reyaNetwork)\n return [\n MoneyInOutChainId.ethereumMainnet,\n MoneyInOutChainId.opMainnet,\n MoneyInOutChainId.polygonMainnet,\n MoneyInOutChainId.arbitrumOne,\n MoneyInOutChainId.baseMainnet,\n ];\n\n if (chainId === ReyaChainId.reyaCronos)\n return [\n MoneyInOutChainId.ethereumSepolia,\n MoneyInOutChainId.opSepolia,\n MoneyInOutChainId.arbitrumSepolia,\n ];\n\n if (chainId === ReyaChainId.reyaLocal) return [];\n\n throw new Error(`Unknown Reya chain id ${chainId}`);\n}\n\nexport function getReyaNetworkFromMoneyInOutChainId(\n moneyInOutChainId: MoneyInOutChainId,\n): ReyaChainId {\n if (\n getMoneyInOutNetworks(ReyaChainId.reyaNetwork).includes(moneyInOutChainId)\n ) {\n return ReyaChainId.reyaNetwork;\n }\n\n if (\n getMoneyInOutNetworks(ReyaChainId.reyaCronos).includes(moneyInOutChainId)\n ) {\n return ReyaChainId.reyaCronos;\n }\n\n throw new Error(`Unknown external chain id ${moneyInOutChainId}`);\n}\n\nexport const chainIdToExplorerURL: {\n [key in MoneyInOutChainId | ReyaChainId]: string;\n} = {\n [MoneyInOutChainId.ethereumMainnet]: 'https://etherscan.io',\n [MoneyInOutChainId.opMainnet]: 'https://optimistic.etherscan.io',\n [MoneyInOutChainId.polygonMainnet]: 'https://polygonscan.com',\n [MoneyInOutChainId.arbitrumOne]: 'https://arbiscan.io',\n [MoneyInOutChainId.baseMainnet]: 'https://basescan.org',\n [MoneyInOutChainId.arbitrumSepolia]: 'https://sepolia.arbiscan.io',\n [MoneyInOutChainId.opSepolia]: 'https://sepolia-optimism.etherscan.io',\n [MoneyInOutChainId.ethereumSepolia]: 'https://sepolia.etherscan.io',\n [ReyaChainId.reyaNetwork]: 'https://explorer.reya.network',\n [ReyaChainId.reyaLocal]: 'http://127.0.0.1:4000',\n [ReyaChainId.reyaCronos]: 'https://reya-cronos.blockscout.com',\n};\n\nconst ChainRpcUrls: Record<MoneyInOutChainId | ReyaChainId, string[]> = {\n [ReyaChainId.reyaNetwork]: ['https://rpc.reya.network'],\n [ReyaChainId.reyaLocal]: ['http://127.0.0.1:8545'],\n [MoneyInOutChainId.ethereumMainnet]: [\n 'https://mainnet.gateway.tenderly.co',\n 'https://eth.llamarpc.com',\n 'https://eth-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://eth-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://eth-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://mainnet.gateway.tenderly.co/69U6LoF0URUv5CfuIU7FdL',\n ],\n [MoneyInOutChainId.opMainnet]: [\n 'https://mainnet.optimism.io',\n 'https://optimism.llamarpc.com',\n 'https://opt-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://opt-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://opt-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://optimism.gateway.tenderly.co/69LkAPTI3LODcBAdtz9wQC',\n ],\n [MoneyInOutChainId.polygonMainnet]: [\n 'https://polygon-rpc.com',\n 'https://gateway.tenderly.co/public/polygon',\n 'https://polygon-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://polygon-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://polygon-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://polygon.gateway.tenderly.co/7Qw4fTY4kf3v02LjJjWyvZ',\n ],\n [MoneyInOutChainId.arbitrumOne]: [\n 'https://arb1.arbitrum.io/rpc',\n 'https://arbitrum.llamarpc.com',\n 'https://arb-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://arb-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://arb-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://arbitrum.gateway.tenderly.co/1wQGK6nNPTbSc7asucAbzA',\n ],\n [MoneyInOutChainId.baseMainnet]: [\n 'https://mainnet.base.org',\n 'https://base.llamarpc.com',\n 'https://base-mainnet.g.alchemy.com/v2/Tkk3-2tTcsCLnFa4dSSUkpZsDyOH55Ar',\n 'https://base-mainnet.g.alchemy.com/v2/Bin_D_qtJLCqvFyzt-0SxZRWTL423_tg',\n 'https://base-mainnet.g.alchemy.com/v2/A21_W1GwGu775PCAoQbj_pJgBPzIgAzv',\n 'https://base.gateway.tenderly.co/2LHAD54IBvgXiVQdhE9mIF',\n ],\n // Add the rest of the mainnet URLs above\n [ReyaChainId.reyaCronos]: [\n 'https://rpc-reya-cronos.t.conduit.xyz/7F8HNfECaatE8VEZGD5gcJPghXqhshTTi',\n ],\n [MoneyInOutChainId.arbitrumSepolia]: [\n 'https://sepolia-rollup.arbitrum.io/rpc',\n 'https://endpoints.omniatech.io/v1/arbitrum/sepolia/public',\n 'https://arbitrum-sepolia.gateway.tenderly.co/4YMRN8fKu2SV1JSNsGlbMZ',\n ],\n [MoneyInOutChainId.opSepolia]: [\n 'https://sepolia.optimism.io',\n 'https://optimism-sepolia.blockpi.network/v1/rpc/public',\n 'https://optimism-sepolia.gateway.tenderly.co/2nXBEGPk57CotvTJMjIMK7',\n ],\n [MoneyInOutChainId.ethereumSepolia]: [\n 'https://sepolia.gateway.tenderly.co',\n 'https://ethereum-sepolia.blockpi.network/v1/rpc/public',\n 'https://sepolia.gateway.tenderly.co/1u2yZV1rdVLpgOeHwD1Z8M',\n ],\n};\n\nconst ALCHEMY_BASE_RPC_URL: Record<MoneyInOutChainId, string> = {\n // mainnet\n [MoneyInOutChainId.ethereumMainnet]: 'https://eth-mainnet.g.alchemy.com/v2',\n [MoneyInOutChainId.opMainnet]: 'https://opt-mainnet.g.alchemy.com/v2',\n [MoneyInOutChainId.polygonMainnet]:\n 'https://polygon-mainnet.g.alchemy.com/v2',\n [MoneyInOutChainId.arbitrumOne]: 'https://arb-mainnet.g.alchemy.com/v2',\n [MoneyInOutChainId.baseMainnet]: 'https://base-mainnet.g.alchemy.com/v2',\n // testnet\n [MoneyInOutChainId.arbitrumSepolia]: 'https://arb-sepolia.g.alchemy.com/v2',\n [MoneyInOutChainId.opSepolia]: 'https://opt-sepolia.g.alchemy.com/v2',\n [MoneyInOutChainId.ethereumSepolia]: 'https://eth-sepolia.g.alchemy.com/v2',\n};\n\nconst INFURA_BASE_RPC_URL: Record<MoneyInOutChainId, string> = {\n // mainnet\n [MoneyInOutChainId.ethereumMainnet]: 'https://mainnet.infura.io/v3',\n [MoneyInOutChainId.opMainnet]: 'https://optimism-mainnet.infura.io/v3',\n [MoneyInOutChainId.polygonMainnet]: 'https://polygon-mainnet.infura.io/v3',\n [MoneyInOutChainId.arbitrumOne]: 'https://arbitrum-mainnet.infura.io/v3',\n [MoneyInOutChainId.baseMainnet]: 'https://base-mainnet.infura.io/v3',\n // testnet\n [MoneyInOutChainId.arbitrumSepolia]: 'https://arbitrum-sepolia.infura.io/v3',\n [MoneyInOutChainId.opSepolia]: 'https://optimism-sepolia.infura.io/v3',\n [MoneyInOutChainId.ethereumSepolia]: 'https://sepolia.infura.io/v3',\n};\n\nexport const getAlchemyRpcUrl = (\n apiKey: string,\n chainId: MoneyInOutChainId,\n): string | null => {\n const rpcUrl = ALCHEMY_BASE_RPC_URL[chainId];\n\n if (!rpcUrl) {\n return null;\n }\n\n return `${rpcUrl}/${apiKey}`;\n};\n\nexport const getInfuraRpcUrl = (\n apiKey: string,\n chainId: MoneyInOutChainId,\n): string | null => {\n const rpcUrl = INFURA_BASE_RPC_URL[chainId];\n\n if (!rpcUrl) {\n return null;\n }\n\n return `${rpcUrl}/${apiKey}`;\n};\n\nexport const getPublicRpcUrls = (\n chainId: MoneyInOutChainId | ReyaChainId,\n): string[] => {\n const rpcUrls = ChainRpcUrls[chainId];\n\n if (!rpcUrls) {\n return [];\n }\n\n return rpcUrls;\n};\n\nexport const getPublicRpcUrlsOrThrow = (\n chainId: MoneyInOutChainId | ReyaChainId,\n): string[] => {\n const rpcUrls = getPublicRpcUrls(chainId);\n\n if (rpcUrls.length === 0) {\n throw new Error('No public RPC URLs configured for the chain: ' + chainId);\n }\n\n return rpcUrls;\n};\n"]}
|
package/dist/utils/number.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.floorTo = exports.amountDenormalizer = exports.amountNormalizer = void 0;
|
|
6
|
+
exports.floorTo = exports.amountDenormalizer = exports.normalizeAmountToNumber = exports.normalizeAmountToString = exports.normalizeAmountFast = exports.amountNormalizer = void 0;
|
|
7
7
|
var bignumber_js_1 = __importDefault(require("bignumber.js"));
|
|
8
8
|
var ten = (0, bignumber_js_1.default)(10);
|
|
9
9
|
var powCache = {};
|
|
@@ -12,6 +12,101 @@ function amountNormalizer(value, decimals) {
|
|
|
12
12
|
return (0, bignumber_js_1.default)(value).div(powCache[decimals] || (powCache[decimals] = ten.pow(decimals)));
|
|
13
13
|
}
|
|
14
14
|
exports.amountNormalizer = amountNormalizer;
|
|
15
|
+
/**
|
|
16
|
+
* Divide a plain-integer decimal string by 10**decimals by shifting the decimal
|
|
17
|
+
* point, returning EXACTLY what `amountNormalizer(value, decimals).toString()`
|
|
18
|
+
* would return — or `null` when that cannot be guaranteed, so the caller falls
|
|
19
|
+
* back to BigNumber.
|
|
20
|
+
*
|
|
21
|
+
* This exists because the perp-execution row transform is the single largest
|
|
22
|
+
* CPU consumer on the api tier (PRO-1025: `transformTrade` 26% inclusive,
|
|
23
|
+
* `amountNormalizer` 19%, self time dominated by bignumber.js multiply/divide
|
|
24
|
+
* and the BigNumber constructor). Each row normalises ~30 Decimal fields and a
|
|
25
|
+
* response carries up to 100 rows, so this runs a few thousand times per
|
|
26
|
+
* request. Dividing a decimal string by a power of ten is a decimal-point
|
|
27
|
+
* shift; it does not need arbitrary-precision arithmetic.
|
|
28
|
+
*
|
|
29
|
+
* Measured: 9.8x faster than the BigNumber path on realistic devnet values,
|
|
30
|
+
* with a 100% fast-path hit rate on those shapes.
|
|
31
|
+
*
|
|
32
|
+
* TWO BigNumber behaviours make the naive shift wrong, and both are why this
|
|
33
|
+
* returns null rather than guessing. Each would have silently changed the
|
|
34
|
+
* public API's serialisation:
|
|
35
|
+
*
|
|
36
|
+
* 1. `toString()` switches to EXPONENTIAL notation outside a magnitude window.
|
|
37
|
+
* BigNumber's EXPONENTIAL_AT default is [-7, 21], so plain notation holds
|
|
38
|
+
* only for a decimal exponent in [-6, 20]; `1e-7` renders "1e-7", not
|
|
39
|
+
* "0.0000001". A plain shift would emit the long form for those.
|
|
40
|
+
* 2. `.div()` ROUNDS to DECIMAL_PLACES (default 20). So amountNormalizer is
|
|
41
|
+
* already lossy past 20 fractional digits, and an exact shift produces MORE
|
|
42
|
+
* digits than the current output. Verified: 4000164727132806080849 / 1e27
|
|
43
|
+
* is 0.00000400016472713281 through BigNumber, not the exact value.
|
|
44
|
+
*
|
|
45
|
+
* The fast path is therefore taken only when the result is provably identical:
|
|
46
|
+
* inside the plain-notation window, and with no rounding possible.
|
|
47
|
+
*/
|
|
48
|
+
var PLAIN_INTEGER = /^[0-9]+$/;
|
|
49
|
+
var BN_PLAIN_NOTATION_MIN_EXPONENT = -6;
|
|
50
|
+
var BN_PLAIN_NOTATION_MAX_EXPONENT = 20;
|
|
51
|
+
var BN_DECIMAL_PLACES = 20;
|
|
52
|
+
function normalizeAmountFast(value, decimals) {
|
|
53
|
+
var digits = value;
|
|
54
|
+
var negative = false;
|
|
55
|
+
if (digits.charCodeAt(0) === 45 /* '-' */) {
|
|
56
|
+
negative = true;
|
|
57
|
+
digits = digits.slice(1);
|
|
58
|
+
}
|
|
59
|
+
if (!PLAIN_INTEGER.test(digits))
|
|
60
|
+
return null;
|
|
61
|
+
digits = digits.replace(/^0+(?=[0-9])/, '');
|
|
62
|
+
if (digits === '0') {
|
|
63
|
+
// Negative zero: BigNumber disagrees with itself here — toString() gives
|
|
64
|
+
// "0" but toNumber() gives -0, and Object.is(-0, 0) is false. Rather than
|
|
65
|
+
// reproduce that split, decline so both wrappers fall back and inherit the
|
|
66
|
+
// exact behaviour. Costs nothing: only a literal zero input reaches here.
|
|
67
|
+
return negative ? null : '0';
|
|
68
|
+
}
|
|
69
|
+
// Decimal exponent of the result: BigNumber renders plain only inside the
|
|
70
|
+
// window, and rounds beyond BN_DECIMAL_PLACES fractional digits.
|
|
71
|
+
var exponent = digits.length - 1 - decimals;
|
|
72
|
+
if (exponent < BN_PLAIN_NOTATION_MIN_EXPONENT ||
|
|
73
|
+
exponent > BN_PLAIN_NOTATION_MAX_EXPONENT ||
|
|
74
|
+
decimals > BN_DECIMAL_PLACES) {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
if (decimals === 0)
|
|
78
|
+
return negative ? "-".concat(digits) : digits;
|
|
79
|
+
var padded = digits.length <= decimals
|
|
80
|
+
? '0'.repeat(decimals - digits.length + 1) + digits
|
|
81
|
+
: digits;
|
|
82
|
+
var integerPart = padded.slice(0, padded.length - decimals);
|
|
83
|
+
var fractionPart = padded
|
|
84
|
+
.slice(padded.length - decimals)
|
|
85
|
+
.replace(/0+$/, '');
|
|
86
|
+
var rendered = fractionPart
|
|
87
|
+
? "".concat(integerPart, ".").concat(fractionPart)
|
|
88
|
+
: integerPart;
|
|
89
|
+
if (rendered === '0')
|
|
90
|
+
return '0';
|
|
91
|
+
return negative ? "-".concat(rendered) : rendered;
|
|
92
|
+
}
|
|
93
|
+
exports.normalizeAmountFast = normalizeAmountFast;
|
|
94
|
+
/** `amountNormalizer(value, decimals).toString()`, fast path where provable. */
|
|
95
|
+
function normalizeAmountToString(value, decimals) {
|
|
96
|
+
var _a;
|
|
97
|
+
if (decimals === void 0) { decimals = 18; }
|
|
98
|
+
return ((_a = normalizeAmountFast(value, decimals)) !== null && _a !== void 0 ? _a : amountNormalizer(value, decimals).toString());
|
|
99
|
+
}
|
|
100
|
+
exports.normalizeAmountToString = normalizeAmountToString;
|
|
101
|
+
/** `amountNormalizer(value, decimals).toNumber()`, fast path where provable. */
|
|
102
|
+
function normalizeAmountToNumber(value, decimals) {
|
|
103
|
+
if (decimals === void 0) { decimals = 18; }
|
|
104
|
+
var fast = normalizeAmountFast(value, decimals);
|
|
105
|
+
return fast !== null
|
|
106
|
+
? Number(fast)
|
|
107
|
+
: amountNormalizer(value, decimals).toNumber();
|
|
108
|
+
}
|
|
109
|
+
exports.normalizeAmountToNumber = normalizeAmountToNumber;
|
|
15
110
|
function amountDenormalizer(value, decimals) {
|
|
16
111
|
if (decimals === void 0) { decimals = 18; }
|
|
17
112
|
return (0, bignumber_js_1.default)(value).times(powCache[decimals] || (powCache[decimals] = ten.pow(decimals)));
|
package/dist/utils/number.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"number.js","sourceRoot":"/","sources":["utils/number.ts"],"names":[],"mappings":";;;;;;AAAA,8DAAqC;AAErC,IAAM,GAAG,GAAG,IAAA,sBAAS,EAAC,EAAE,CAAC,CAAC;AAC1B,IAAM,QAAQ,GAA8B,EAAE,CAAC;AAE/C,SAAgB,gBAAgB,CAC9B,KAAkC,EAClC,QAAqB;IAArB,yBAAA,EAAA,aAAqB;IAErB,OAAO,IAAA,sBAAS,EAAC,KAAK,CAAC,CAAC,GAAG,CACzB,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAC/D,CAAC;AACJ,CAAC;AAPD,4CAOC;AAED,SAAgB,kBAAkB,CAChC,KAAkC,EAClC,QAAqB;IAArB,yBAAA,EAAA,aAAqB;IAErB,OAAO,IAAA,sBAAS,EAAC,KAAK,CAAC,CAAC,KAAK,CAC3B,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAC/D,CAAC;AACJ,CAAC;AAPD,gDAOC;AAED,sCAAsC;AAC/B,IAAM,OAAO,GAAG,UAAC,KAAa,EAAE,QAAgB;IACrD,IAAM,MAAM,GAAG,SAAA,EAAE,EAAI,QAAQ,CAAA,CAAC;IAC9B,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG,MAAM,CAAC;AAC7C,CAAC,CAAC;AAHW,QAAA,OAAO,WAGlB","sourcesContent":["import BigNumber from 'bignumber.js';\n\nconst ten = BigNumber(10);\nconst powCache: Record<number, BigNumber> = {};\n\nexport function amountNormalizer(\n value: BigNumber | number | string,\n decimals: number = 18,\n): BigNumber {\n return BigNumber(value).div(\n powCache[decimals] || (powCache[decimals] = ten.pow(decimals)),\n );\n}\n\nexport function amountDenormalizer(\n value: BigNumber | number | string,\n decimals: number = 18,\n): BigNumber {\n return BigNumber(value).times(\n powCache[decimals] || (powCache[decimals] = ten.pow(decimals)),\n );\n}\n\n// Floors to `decimals` decimal places\nexport const floorTo = (value: number, decimals: number) => {\n const factor = 10 ** decimals;\n return Math.floor(value * factor) / factor;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"number.js","sourceRoot":"/","sources":["utils/number.ts"],"names":[],"mappings":";;;;;;AAAA,8DAAqC;AAErC,IAAM,GAAG,GAAG,IAAA,sBAAS,EAAC,EAAE,CAAC,CAAC;AAC1B,IAAM,QAAQ,GAA8B,EAAE,CAAC;AAE/C,SAAgB,gBAAgB,CAC9B,KAAkC,EAClC,QAAqB;IAArB,yBAAA,EAAA,aAAqB;IAErB,OAAO,IAAA,sBAAS,EAAC,KAAK,CAAC,CAAC,GAAG,CACzB,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAC/D,CAAC;AACJ,CAAC;AAPD,4CAOC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,IAAM,aAAa,GAAG,UAAU,CAAC;AACjC,IAAM,8BAA8B,GAAG,CAAC,CAAC,CAAC;AAC1C,IAAM,8BAA8B,GAAG,EAAE,CAAC;AAC1C,IAAM,iBAAiB,GAAG,EAAE,CAAC;AAE7B,SAAgB,mBAAmB,CACjC,KAAa,EACb,QAAgB;IAEhB,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,SAAS,EAAE,CAAC;QAC1C,QAAQ,GAAG,IAAI,CAAC;QAChB,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC3B,CAAC;IACD,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,OAAO,IAAI,CAAC;IAE7C,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC;IAC5C,IAAI,MAAM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DAgDC;AAED,gFAAgF;AAChF,SAAgB,uBAAuB,CACrC,KAAa,EACb,QAAqB;;IAArB,yBAAA,EAAA,aAAqB;IAErB,OAAO,CACL,MAAA,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,mCACpC,gBAAgB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAC7C,CAAC;AACJ,CAAC;AARD,0DAQC;AAED,gFAAgF;AAChF,SAAgB,uBAAuB,CACrC,KAAa,EACb,QAAqB;IAArB,yBAAA,EAAA,aAAqB;IAErB,IAAM,IAAI,GAAG,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAClD,OAAO,IAAI,KAAK,IAAI;QAClB,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;QACd,CAAC,CAAC,gBAAgB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAAC;AACnD,CAAC;AARD,0DAQC;AAED,SAAgB,kBAAkB,CAChC,KAAkC,EAClC,QAAqB;IAArB,yBAAA,EAAA,aAAqB;IAErB,OAAO,IAAA,sBAAS,EAAC,KAAK,CAAC,CAAC,KAAK,CAC3B,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAC/D,CAAC;AACJ,CAAC;AAPD,gDAOC;AAED,sCAAsC;AAC/B,IAAM,OAAO,GAAG,UAAC,KAAa,EAAE,QAAgB;IACrD,IAAM,MAAM,GAAG,SAAA,EAAE,EAAI,QAAQ,CAAA,CAAC;IAC9B,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG,MAAM,CAAC;AAC7C,CAAC,CAAC;AAHW,QAAA,OAAO,WAGlB","sourcesContent":["import BigNumber from 'bignumber.js';\n\nconst ten = BigNumber(10);\nconst powCache: Record<number, BigNumber> = {};\n\nexport function amountNormalizer(\n value: BigNumber | number | string,\n decimals: number = 18,\n): BigNumber {\n return BigNumber(value).div(\n powCache[decimals] || (powCache[decimals] = ten.pow(decimals)),\n );\n}\n\n/**\n * Divide a plain-integer decimal string by 10**decimals by shifting the decimal\n * point, returning EXACTLY what `amountNormalizer(value, decimals).toString()`\n * would return — or `null` when that cannot be guaranteed, so the caller falls\n * back to BigNumber.\n *\n * This exists because the perp-execution row transform is the single largest\n * CPU consumer on the api tier (PRO-1025: `transformTrade` 26% inclusive,\n * `amountNormalizer` 19%, self time dominated by bignumber.js multiply/divide\n * and the BigNumber constructor). Each row normalises ~30 Decimal fields and a\n * response carries up to 100 rows, so this runs a few thousand times per\n * request. Dividing a decimal string by a power of ten is a decimal-point\n * shift; it does not need arbitrary-precision arithmetic.\n *\n * Measured: 9.8x faster than the BigNumber path on realistic devnet values,\n * with a 100% fast-path hit rate on those shapes.\n *\n * TWO BigNumber behaviours make the naive shift wrong, and both are why this\n * returns null rather than guessing. Each would have silently changed the\n * public API's serialisation:\n *\n * 1. `toString()` switches to EXPONENTIAL notation outside a magnitude window.\n * BigNumber's EXPONENTIAL_AT default is [-7, 21], so plain notation holds\n * only for a decimal exponent in [-6, 20]; `1e-7` renders \"1e-7\", not\n * \"0.0000001\". A plain shift would emit the long form for those.\n * 2. `.div()` ROUNDS to DECIMAL_PLACES (default 20). So amountNormalizer is\n * already lossy past 20 fractional digits, and an exact shift produces MORE\n * digits than the current output. Verified: 4000164727132806080849 / 1e27\n * is 0.00000400016472713281 through BigNumber, not the exact value.\n *\n * The fast path is therefore taken only when the result is provably identical:\n * inside the plain-notation window, and with no rounding possible.\n */\nconst PLAIN_INTEGER = /^[0-9]+$/;\nconst BN_PLAIN_NOTATION_MIN_EXPONENT = -6;\nconst BN_PLAIN_NOTATION_MAX_EXPONENT = 20;\nconst BN_DECIMAL_PLACES = 20;\n\nexport function normalizeAmountFast(\n value: string,\n decimals: number,\n): string | null {\n let digits = value;\n let negative = false;\n if (digits.charCodeAt(0) === 45 /* '-' */) {\n negative = true;\n digits = digits.slice(1);\n }\n if (!PLAIN_INTEGER.test(digits)) return null;\n\n digits = digits.replace(/^0+(?=[0-9])/, '');\n if (digits === '0') {\n // Negative zero: BigNumber disagrees with itself here — toString() gives\n // \"0\" but toNumber() gives -0, and Object.is(-0, 0) is false. Rather than\n // reproduce that split, decline so both wrappers fall back and inherit the\n // exact behaviour. Costs nothing: only a literal zero input reaches here.\n return negative ? null : '0';\n }\n\n // Decimal exponent of the result: BigNumber renders plain only inside the\n // window, and rounds beyond BN_DECIMAL_PLACES fractional digits.\n const exponent = digits.length - 1 - decimals;\n if (\n exponent < BN_PLAIN_NOTATION_MIN_EXPONENT ||\n exponent > BN_PLAIN_NOTATION_MAX_EXPONENT ||\n decimals > BN_DECIMAL_PLACES\n ) {\n return null;\n }\n\n if (decimals === 0) return negative ? `-${digits}` : digits;\n\n const padded =\n digits.length <= decimals\n ? '0'.repeat(decimals - digits.length + 1) + digits\n : digits;\n const integerPart = padded.slice(0, padded.length - decimals);\n const fractionPart = padded\n .slice(padded.length - decimals)\n .replace(/0+$/, '');\n const rendered = fractionPart\n ? `${integerPart}.${fractionPart}`\n : integerPart;\n\n if (rendered === '0') return '0';\n return negative ? `-${rendered}` : rendered;\n}\n\n/** `amountNormalizer(value, decimals).toString()`, fast path where provable. */\nexport function normalizeAmountToString(\n value: string,\n decimals: number = 18,\n): string {\n return (\n normalizeAmountFast(value, decimals) ??\n amountNormalizer(value, decimals).toString()\n );\n}\n\n/** `amountNormalizer(value, decimals).toNumber()`, fast path where provable. */\nexport function normalizeAmountToNumber(\n value: string,\n decimals: number = 18,\n): number {\n const fast = normalizeAmountFast(value, decimals);\n return fast !== null\n ? Number(fast)\n : amountNormalizer(value, decimals).toNumber();\n}\n\nexport function amountDenormalizer(\n value: BigNumber | number | string,\n decimals: number = 18,\n): BigNumber {\n return BigNumber(value).times(\n powCache[decimals] || (powCache[decimals] = ten.pow(decimals)),\n );\n}\n\n// Floors to `decimals` decimal places\nexport const floorTo = (value: number, decimals: number) => {\n const factor = 10 ** decimals;\n return Math.floor(value * factor) / factor;\n};\n"]}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __extends = (this && this.__extends) || (function () {
|
|
3
|
+
var extendStatics = function (d, b) {
|
|
4
|
+
extendStatics = Object.setPrototypeOf ||
|
|
5
|
+
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
|
6
|
+
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
|
|
7
|
+
return extendStatics(d, b);
|
|
8
|
+
};
|
|
9
|
+
return function (d, b) {
|
|
10
|
+
if (typeof b !== "function" && b !== null)
|
|
11
|
+
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
|
|
12
|
+
extendStatics(d, b);
|
|
13
|
+
function __() { this.constructor = d; }
|
|
14
|
+
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
15
|
+
};
|
|
16
|
+
})();
|
|
17
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
18
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
19
|
+
};
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
exports.calculateSettledAccountPnl = exports.calculateSettledPositionPnl = exports.SettlementTrackerError = void 0;
|
|
22
|
+
var bignumber_js_1 = __importDefault(require("bignumber.js"));
|
|
23
|
+
/** Structured cause for service metrics; calculation still fails closed. */
|
|
24
|
+
var SettlementTrackerError = /** @class */ (function (_super) {
|
|
25
|
+
__extends(SettlementTrackerError, _super);
|
|
26
|
+
function SettlementTrackerError(marketId, reason) {
|
|
27
|
+
var _newTarget = this.constructor;
|
|
28
|
+
var _this = _super.call(this, reason === 'missing'
|
|
29
|
+
? "Missing market trackers for ".concat(marketId)
|
|
30
|
+
: "Inconsistent ADL trackers for ".concat(marketId)) || this;
|
|
31
|
+
_this.marketId = marketId;
|
|
32
|
+
_this.reason = reason;
|
|
33
|
+
// common targets ES5; restore Error subclass identity after downleveling.
|
|
34
|
+
Object.setPrototypeOf(_this, _newTarget.prototype);
|
|
35
|
+
_this.name = 'SettlementTrackerError';
|
|
36
|
+
return _this;
|
|
37
|
+
}
|
|
38
|
+
return SettlementTrackerError;
|
|
39
|
+
}(Error));
|
|
40
|
+
exports.SettlementTrackerError = SettlementTrackerError;
|
|
41
|
+
var WAD = new bignumber_js_1.default('1000000000000000000');
|
|
42
|
+
var integer = function (value, field) {
|
|
43
|
+
var _a;
|
|
44
|
+
var result = new bignumber_js_1.default((_a = value === null || value === void 0 ? void 0 : value.toString()) !== null && _a !== void 0 ? _a : NaN);
|
|
45
|
+
if (!result.isInteger())
|
|
46
|
+
throw new Error("Missing or invalid ".concat(field));
|
|
47
|
+
return result;
|
|
48
|
+
};
|
|
49
|
+
var optionalBlock = function (value) {
|
|
50
|
+
if (value === null || value === undefined)
|
|
51
|
+
return undefined;
|
|
52
|
+
var result = new bignumber_js_1.default(value.toString());
|
|
53
|
+
return result.isInteger() ? result : undefined;
|
|
54
|
+
};
|
|
55
|
+
var mulWad = function (a, b) {
|
|
56
|
+
return a.times(b).dividedToIntegerBy(WAD);
|
|
57
|
+
};
|
|
58
|
+
var divWad = function (a, b) {
|
|
59
|
+
return a.times(WAD).dividedToIntegerBy(b);
|
|
60
|
+
};
|
|
61
|
+
/** Mirrors perpOB updatePerpPosition, including PRBMath truncation at each step. */
|
|
62
|
+
function calculateSettledPositionPnl(position, trackers, onGuarded) {
|
|
63
|
+
var base = integer(position.base, 'position base');
|
|
64
|
+
var realized = integer(position.realized_pnl, 'realized PnL');
|
|
65
|
+
if (base.isZero())
|
|
66
|
+
return realized;
|
|
67
|
+
if (!trackers)
|
|
68
|
+
throw new SettlementTrackerError(position.market_id.toString(), 'missing');
|
|
69
|
+
var long = base.isPositive();
|
|
70
|
+
var funding = integer(long
|
|
71
|
+
? trackers.longTrackersFundingValue
|
|
72
|
+
: trackers.shortTrackersFundingValue, 'market funding');
|
|
73
|
+
var multiplier = integer(long
|
|
74
|
+
? trackers.longTrackersBaseMultiplier
|
|
75
|
+
: trackers.shortTrackersBaseMultiplier, 'market multiplier');
|
|
76
|
+
var unwind = integer(long
|
|
77
|
+
? trackers.longTrackersAdlUnwindPrice
|
|
78
|
+
: trackers.shortTrackersAdlUnwindPrice, 'market unwind price');
|
|
79
|
+
var oldMultiplier = integer(position.base_multiplier, 'position multiplier');
|
|
80
|
+
var oldUnwind = integer(position.adl_unwind_price, 'position unwind price');
|
|
81
|
+
var oldFunding = integer(position.funding_value, 'position funding');
|
|
82
|
+
if (funding.eq(oldFunding) &&
|
|
83
|
+
multiplier.eq(oldMultiplier) &&
|
|
84
|
+
unwind.eq(oldUnwind))
|
|
85
|
+
return realized;
|
|
86
|
+
// Market trackers older than the position's own snapshot carry no new
|
|
87
|
+
// cashflow: the stored realized PnL already settled everything up to the
|
|
88
|
+
// position's block. Off-chain tracker feeds can lag the position stream, so
|
|
89
|
+
// treat that window as "nothing accrued" instead of projecting a delta
|
|
90
|
+
// backwards (wrong-sign funding, or an ADL guard failure below).
|
|
91
|
+
var positionBlock = optionalBlock(position.block_number);
|
|
92
|
+
var trackerBlock = optionalBlock(trackers.blockNumber);
|
|
93
|
+
if (positionBlock && trackerBlock && positionBlock.gt(trackerBlock)) {
|
|
94
|
+
onGuarded === null || onGuarded === void 0 ? void 0 : onGuarded();
|
|
95
|
+
return realized;
|
|
96
|
+
}
|
|
97
|
+
if (oldMultiplier.lte(0) ||
|
|
98
|
+
multiplier.lt(0) ||
|
|
99
|
+
multiplier.gt(oldMultiplier) ||
|
|
100
|
+
unwind.lt(oldUnwind)) {
|
|
101
|
+
throw new SettlementTrackerError(position.market_id.toString(), 'inconsistent');
|
|
102
|
+
}
|
|
103
|
+
var fundingCashflow = mulWad(divWad(funding.minus(oldFunding), oldMultiplier), base.negated());
|
|
104
|
+
var unwindDelta = divWad(unwind.minus(oldUnwind), oldMultiplier);
|
|
105
|
+
var initialPrice = mulWad(WAD.minus(divWad(multiplier, oldMultiplier)), integer(position.last_price, 'position price'));
|
|
106
|
+
var adlCashflow = mulWad(base, unwindDelta.minus(initialPrice));
|
|
107
|
+
return realized.plus(fundingCashflow).plus(adlCashflow);
|
|
108
|
+
}
|
|
109
|
+
exports.calculateSettledPositionPnl = calculateSettledPositionPnl;
|
|
110
|
+
/**
|
|
111
|
+
* Returns raw E18 PnL aligned to collateral units. The instrument floors EACH
|
|
112
|
+
* market's PnL to quote-token precision before Core aggregates collateral info.
|
|
113
|
+
* Funding is the stored market tracker delta; do not extrapolate it with time.
|
|
114
|
+
*/
|
|
115
|
+
function calculateSettledAccountPnl(positions, trackers, collateralDecimals, onGuarded) {
|
|
116
|
+
return positions.reduce(function (sum, position) {
|
|
117
|
+
var pnl = calculateSettledPositionPnl(position, trackers[position.market_id.toString()], onGuarded);
|
|
118
|
+
var rounded = pnl
|
|
119
|
+
.shiftedBy(collateralDecimals - 18)
|
|
120
|
+
.integerValue(bignumber_js_1.default.ROUND_FLOOR)
|
|
121
|
+
.shiftedBy(18 - collateralDecimals);
|
|
122
|
+
return sum.plus(rounded);
|
|
123
|
+
}, new bignumber_js_1.default(0));
|
|
124
|
+
}
|
|
125
|
+
exports.calculateSettledAccountPnl = calculateSettledAccountPnl;
|
|
126
|
+
//# sourceMappingURL=realized-balance.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"realized-balance.js","sourceRoot":"/","sources":["utils/realized-balance.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,8DAAqC;AA0BrC,4EAA4E;AAC5E;IAA4C,0CAAK;IAC/C,gCACkB,QAAgB,EAChB,MAAkC;;QAElD,YAAA,MAAK,YACH,MAAM,KAAK,SAAS;YAClB,CAAC,CAAC,sCAA+B,QAAQ,CAAE;YAC3C,CAAC,CAAC,wCAAiC,QAAQ,CAAE,CAChD,SAAC;QAPc,cAAQ,GAAR,QAAQ,CAAQ;QAChB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,YAAY,CAAC,CAAC,CAAC;IAClE,OAAO,QAAQ,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC1D,CAAC;AA7ED,kEA6EC;AAED;;;;GAIG;AACH,SAAgB,0BAA0B,CACxC,SAAoC,EACpC,QAA0D,EAC1D,kBAA0B,EAC1B,SAAsB;IAEtB,OAAO,SAAS,CAAC,MAAM,CAAC,UAAC,GAAG,EAAE,QAAQ;QACpC,IAAM,GAAG,GAAG,2BAA2B,CACrC,QAAQ,EACR,QAAQ,CAAC,QAAQ,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,EACvC,SAAS,CACV,CAAC;QACF,IAAM,OAAO,GAAG,GAAG;aAChB,SAAS,CAAC,kBAAkB,GAAG,EAAE,CAAC;aAClC,YAAY,CAAC,sBAAS,CAAC,WAAW,CAAC;aACnC,SAAS,CAAC,EAAE,GAAG,kBAAkB,CAAC,CAAC;QACtC,OAAO,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC,EAAE,IAAI,sBAAS,CAAC,CAAC,CAAC,CAAC,CAAC;AACvB,CAAC;AAlBD,gEAkBC","sourcesContent":["import BigNumber from 'bignumber.js';\n\n/** Raw E18 position values, from either Prisma or replication. */\nexport type RealizedBalancePosition = {\n market_id: { toString(): string };\n base: { toString(): string } | null;\n realized_pnl: { toString(): string } | null;\n funding_value: { toString(): string } | null;\n base_multiplier: { toString(): string } | null;\n adl_unwind_price: { toString(): string } | null;\n last_price: { toString(): string } | null;\n /** Block the stored trackers were written at; lets stale market trackers be ignored. */\n block_number?: { toString(): string } | null;\n};\n\nexport type RealizedBalanceTrackers = {\n longTrackersFundingValue: string;\n shortTrackersFundingValue: string;\n longTrackersBaseMultiplier: string;\n shortTrackersBaseMultiplier: string;\n longTrackersAdlUnwindPrice: string;\n shortTrackersAdlUnwindPrice: string;\n /** Block the market trackers were observed at (optional; enables the staleness guard). */\n blockNumber?: string | null;\n};\n\n/** Structured cause for service metrics; calculation still fails closed. */\nexport class SettlementTrackerError extends Error {\n constructor(\n public readonly marketId: string,\n public readonly reason: 'missing' | 'inconsistent',\n ) {\n super(\n reason === 'missing'\n ? `Missing market trackers for ${marketId}`\n : `Inconsistent ADL trackers for ${marketId}`,\n );\n // common targets ES5; restore Error subclass identity after downleveling.\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = 'SettlementTrackerError';\n }\n}\n\nconst WAD = new BigNumber('1000000000000000000');\nconst integer = (value: { toString(): string } | null, field: string) => {\n const result = new BigNumber(value?.toString() ?? NaN);\n if (!result.isInteger()) throw new Error(`Missing or invalid ${field}`);\n return result;\n};\nconst optionalBlock = (value: { toString(): string } | null | undefined) => {\n if (value === null || value === undefined) return undefined;\n const result = new BigNumber(value.toString());\n return result.isInteger() ? result : undefined;\n};\nconst mulWad = (a: BigNumber, b: BigNumber) =>\n a.times(b).dividedToIntegerBy(WAD);\nconst divWad = (a: BigNumber, b: BigNumber) =>\n a.times(WAD).dividedToIntegerBy(b);\n\n/** Mirrors perpOB updatePerpPosition, including PRBMath truncation at each step. */\nexport function calculateSettledPositionPnl(\n position: RealizedBalancePosition,\n trackers: RealizedBalanceTrackers | undefined,\n onGuarded?: () => void,\n): BigNumber {\n const base = integer(position.base, 'position base');\n const realized = integer(position.realized_pnl, 'realized PnL');\n if (base.isZero()) return realized;\n if (!trackers)\n throw new SettlementTrackerError(position.market_id.toString(), 'missing');\n\n const long = base.isPositive();\n const funding = integer(\n long\n ? trackers.longTrackersFundingValue\n : trackers.shortTrackersFundingValue,\n 'market funding',\n );\n const multiplier = integer(\n long\n ? trackers.longTrackersBaseMultiplier\n : trackers.shortTrackersBaseMultiplier,\n 'market multiplier',\n );\n const unwind = integer(\n long\n ? trackers.longTrackersAdlUnwindPrice\n : trackers.shortTrackersAdlUnwindPrice,\n 'market unwind price',\n );\n const oldMultiplier = integer(\n position.base_multiplier,\n 'position multiplier',\n );\n const oldUnwind = integer(position.adl_unwind_price, 'position unwind price');\n const oldFunding = integer(position.funding_value, 'position funding');\n if (\n funding.eq(oldFunding) &&\n multiplier.eq(oldMultiplier) &&\n unwind.eq(oldUnwind)\n )\n return realized;\n\n // Market trackers older than the position's own snapshot carry no new\n // cashflow: the stored realized PnL already settled everything up to the\n // position's block. Off-chain tracker feeds can lag the position stream, so\n // treat that window as \"nothing accrued\" instead of projecting a delta\n // backwards (wrong-sign funding, or an ADL guard failure below).\n const positionBlock = optionalBlock(position.block_number);\n const trackerBlock = optionalBlock(trackers.blockNumber);\n if (positionBlock && trackerBlock && positionBlock.gt(trackerBlock)) {\n onGuarded?.();\n return realized;\n }\n\n if (\n oldMultiplier.lte(0) ||\n multiplier.lt(0) ||\n multiplier.gt(oldMultiplier) ||\n unwind.lt(oldUnwind)\n ) {\n throw new SettlementTrackerError(\n position.market_id.toString(),\n 'inconsistent',\n );\n }\n const fundingCashflow = mulWad(\n divWad(funding.minus(oldFunding), oldMultiplier),\n base.negated(),\n );\n const unwindDelta = divWad(unwind.minus(oldUnwind), oldMultiplier);\n const initialPrice = mulWad(\n WAD.minus(divWad(multiplier, oldMultiplier)),\n integer(position.last_price, 'position price'),\n );\n const adlCashflow = mulWad(base, unwindDelta.minus(initialPrice));\n return realized.plus(fundingCashflow).plus(adlCashflow);\n}\n\n/**\n * Returns raw E18 PnL aligned to collateral units. The instrument floors EACH\n * market's PnL to quote-token precision before Core aggregates collateral info.\n * Funding is the stored market tracker delta; do not extrapolate it with time.\n */\nexport function calculateSettledAccountPnl(\n positions: RealizedBalancePosition[],\n trackers: Partial<Record<string, RealizedBalanceTrackers>>,\n collateralDecimals: number,\n onGuarded?: () => void,\n): BigNumber {\n return positions.reduce((sum, position) => {\n const pnl = calculateSettledPositionPnl(\n position,\n trackers[position.market_id.toString()],\n onGuarded,\n );\n const rounded = pnl\n .shiftedBy(collateralDecimals - 18)\n .integerValue(BigNumber.ROUND_FLOOR)\n .shiftedBy(18 - collateralDecimals);\n return sum.plus(rounded);\n }, new BigNumber(0));\n}\n"]}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sustainedDecision = exports.throttleDecision = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Pure throttle decision (`nowMs` injected for testability). Returns the next
|
|
6
|
+
* state and `emit`: the suppressed-since-previous count if the line should be
|
|
7
|
+
* emitted now (the counter resets), or `null` to suppress (incrementing the
|
|
8
|
+
* dropped counter). The first call at a key (no prior state) always emits.
|
|
9
|
+
*/
|
|
10
|
+
function throttleDecision(prev, nowMs, windowMs) {
|
|
11
|
+
var _a;
|
|
12
|
+
if (prev && nowMs - prev.lastEmitMs < windowMs) {
|
|
13
|
+
return {
|
|
14
|
+
next: { lastEmitMs: prev.lastEmitMs, suppressed: prev.suppressed + 1 },
|
|
15
|
+
emit: null,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
next: { lastEmitMs: nowMs, suppressed: 0 },
|
|
20
|
+
emit: (_a = prev === null || prev === void 0 ? void 0 : prev.suppressed) !== null && _a !== void 0 ? _a : 0,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
exports.throttleDecision = throttleDecision;
|
|
24
|
+
/**
|
|
25
|
+
* Pure sustained-gate + throttle decision (`nowMs` injected for testability).
|
|
26
|
+
* Occurrences outside the sliding window are dropped before the current
|
|
27
|
+
* occurrence is recorded. The timestamp deque is capped at `threshold`, since
|
|
28
|
+
* older entries cannot affect the next decision once the threshold is met.
|
|
29
|
+
*
|
|
30
|
+
* Emits only when at least `threshold` occurrences fall within the window and
|
|
31
|
+
* at least `windowMs` has elapsed since the previous emit. A gate-open
|
|
32
|
+
* occurrence blocked by that re-emission throttle increments `suppressed`.
|
|
33
|
+
*/
|
|
34
|
+
function sustainedDecision(prev, nowMs, windowMs, threshold) {
|
|
35
|
+
var _a, _b, _c;
|
|
36
|
+
var times = ((_a = prev === null || prev === void 0 ? void 0 : prev.times) !== null && _a !== void 0 ? _a : []).filter(function (t) { return nowMs - t < windowMs; });
|
|
37
|
+
times.push(nowMs);
|
|
38
|
+
while (times.length > threshold)
|
|
39
|
+
times.shift();
|
|
40
|
+
var prevLastEmitMs = (_b = prev === null || prev === void 0 ? void 0 : prev.lastEmitMs) !== null && _b !== void 0 ? _b : null;
|
|
41
|
+
var prevSuppressed = (_c = prev === null || prev === void 0 ? void 0 : prev.suppressed) !== null && _c !== void 0 ? _c : 0;
|
|
42
|
+
var gateOpen = times.length >= threshold;
|
|
43
|
+
var throttleElapsed = prevLastEmitMs === null || nowMs - prevLastEmitMs >= windowMs;
|
|
44
|
+
if (gateOpen && throttleElapsed) {
|
|
45
|
+
return {
|
|
46
|
+
next: { times: times, lastEmitMs: nowMs, suppressed: 0 },
|
|
47
|
+
emit: { occurrences: times.length, suppressed: prevSuppressed },
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
next: {
|
|
52
|
+
times: times,
|
|
53
|
+
lastEmitMs: prevLastEmitMs,
|
|
54
|
+
suppressed: gateOpen ? prevSuppressed + 1 : prevSuppressed,
|
|
55
|
+
},
|
|
56
|
+
emit: null,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
exports.sustainedDecision = sustainedDecision;
|
|
60
|
+
//# sourceMappingURL=throttled-error.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"throttled-error.js","sourceRoot":"/","sources":["utils/throttled-error.ts"],"names":[],"mappings":";;;AAgBA;;;;;GAKG;AACH,SAAgB,gBAAgB,CAC9B,IAA+B,EAC/B,KAAa,EACb,QAAgB;;IAEhB,IAAI,IAAI,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,GAAG,QAAQ,EAAE,CAAC;QAC/C,OAAO;YACL,IAAI,EAAE,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,GAAG,CAAC,EA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,cAAc,EAAE;SAChE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,IAAI,EAAE;YACJ,KAAK,OAAA;YACL,UAAU,EAAE,cAAc;YAC1B,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC,cAAc,GAAG,CAAC,CAAC,CAAC,CAAC,cAAc;SAC3D;QACD,IAAI,EAAE,IAAI;KACX,CAAC;AACJ,CAAC;AAnCD,8CAmCC","sourcesContent":["export interface ThrottleState {\n lastEmitMs: number;\n suppressed: number;\n}\n\n/**\n * Sustained-gate state: a sliding window of recent occurrence timestamps\n * (len-capped at `threshold`), plus the last emit time and the count dropped\n * since it (folded into the next emitted line).\n */\nexport interface SustainedState {\n times: number[];\n lastEmitMs: number | null;\n suppressed: number;\n}\n\n/**\n * Pure throttle decision (`nowMs` injected for testability). Returns the next\n * state and `emit`: the suppressed-since-previous count if the line should be\n * emitted now (the counter resets), or `null` to suppress (incrementing the\n * dropped counter). The first call at a key (no prior state) always emits.\n */\nexport function throttleDecision(\n prev: ThrottleState | undefined,\n nowMs: number,\n windowMs: number,\n): { next: ThrottleState; emit: number | null } {\n if (prev && nowMs - prev.lastEmitMs < windowMs) {\n return {\n next: { lastEmitMs: prev.lastEmitMs, suppressed: prev.suppressed + 1 },\n emit: null,\n };\n }\n return {\n next: { lastEmitMs: nowMs, suppressed: 0 },\n emit: prev?.suppressed ?? 0,\n };\n}\n\n/**\n * Pure sustained-gate + throttle decision (`nowMs` injected for testability).\n * Occurrences outside the sliding window are dropped before the current\n * occurrence is recorded. The timestamp deque is capped at `threshold`, since\n * older entries cannot affect the next decision once the threshold is met.\n *\n * Emits only when at least `threshold` occurrences fall within the window and\n * at least `windowMs` has elapsed since the previous emit. A gate-open\n * occurrence blocked by that re-emission throttle increments `suppressed`.\n */\nexport function sustainedDecision(\n prev: SustainedState | undefined,\n nowMs: number,\n windowMs: number,\n threshold: number,\n): {\n next: SustainedState;\n emit: { occurrences: number; suppressed: number } | null;\n} {\n const times = (prev?.times ?? []).filter((t) => nowMs - t < windowMs);\n times.push(nowMs);\n while (times.length > threshold) times.shift();\n\n const prevLastEmitMs = prev?.lastEmitMs ?? null;\n const prevSuppressed = prev?.suppressed ?? 0;\n\n const gateOpen = times.length >= threshold;\n const throttleElapsed =\n prevLastEmitMs === null || nowMs - prevLastEmitMs >= windowMs;\n\n if (gateOpen && throttleElapsed) {\n return {\n next: { times, lastEmitMs: nowMs, suppressed: 0 },\n emit: { occurrences: times.length, suppressed: prevSuppressed },\n };\n }\n\n return {\n next: {\n times,\n lastEmitMs: prevLastEmitMs,\n suppressed: gateOpen ? prevSuppressed + 1 : prevSuppressed,\n },\n emit: null,\n };\n}\n"]}
|
|
@@ -25,11 +25,11 @@ var normalizeDecimals = function (value, decimals) {
|
|
|
25
25
|
return value + ''.padStart(padLength, '0');
|
|
26
26
|
};
|
|
27
27
|
exports.normalizeDecimals = normalizeDecimals;
|
|
28
|
-
var normalizeAccountBalance = function (accountBalance) {
|
|
28
|
+
var normalizeAccountBalance = function (accountBalance, chainId) {
|
|
29
29
|
if (!accountBalance.collateral) {
|
|
30
30
|
return accountBalance;
|
|
31
31
|
}
|
|
32
|
-
var decimals = (0, token_info_getters_1.getTokenInfoByAddress)(accountBalance.collateral).decimals;
|
|
32
|
+
var decimals = (0, token_info_getters_1.getTokenInfoByAddress)(accountBalance.collateral, chainId).decimals;
|
|
33
33
|
return __assign(__assign({}, accountBalance), { balance: (0, exports.normalizeDecimals)(accountBalance.balance, decimals), delta: (0, exports.normalizeDecimals)(accountBalance.delta, decimals) });
|
|
34
34
|
};
|
|
35
35
|
exports.normalizeAccountBalance = normalizeAccountBalance;
|