-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcontextValidation.ts
More file actions
178 lines (167 loc) · 5.24 KB
/
Copy pathcontextValidation.ts
File metadata and controls
178 lines (167 loc) · 5.24 KB
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
import type { TimePeriod } from '../core/types';
import {
convertReadableDateToTimestamp,
getStartOfTodayLocal,
TIME_PERIOD_TO_SECONDS,
} from '../utils/time';
import { parseUnits, formatUnits } from '../utils/value';
export type ValidationErrors = {
[key: string]: string;
};
/**
* Converts a string to sentence case, capitalizing the first letter, and lowercasing the rest.
* @param str - The string to convert.
* @returns The converted string.
*/
const toSentenceCase = (str: string) => {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
};
/**
* Validates and parses a token amount string to BigInt.
* @param amount - The amount string to validate.
* @param decimals - Token decimals.
* @param fieldName - Name of the field for error messages.
* @param allowZero - Whether zero values are allowed (default: false).
* @returns Object containing the parsed amount and any validation error.
*/
export function validateAndParseAmount(
amount: string | undefined,
decimals: number,
fieldName: string,
allowZero = false,
): { amount: bigint | undefined; error: string | undefined } {
if (amount === null || amount === undefined) {
return { amount: undefined, error: undefined };
}
try {
const parsedAmount = parseUnits({ formatted: amount, decimals });
if (!allowZero && parsedAmount <= 0n) {
return {
amount: undefined,
error: `${toSentenceCase(fieldName)} must be greater than 0`,
};
}
if (allowZero && parsedAmount < 0n) {
return {
amount: undefined,
error: `${toSentenceCase(fieldName)} must be greater than or equal to 0`,
};
}
return { amount: parsedAmount, error: undefined };
} catch (error) {
return { amount: undefined, error: `Invalid ${fieldName}` };
}
}
/**
* Validates a start time to ensure it's today or later.
* @param startTime - The start time string to validate.
* @returns Validation error message or undefined if valid.
*/
export function validateStartTime(startTime: string): string | undefined {
try {
const startTimeDate = convertReadableDateToTimestamp(startTime);
if (startTimeDate < getStartOfTodayLocal()) {
return 'Start time must be today or later';
}
return undefined;
} catch (error) {
return 'Invalid start time';
}
}
/**
* Validates an expiry time to ensure it's in the future.
* @param expiry - The expiry time string to validate.
* @returns Validation error message or undefined if valid.
*/
export function validateExpiry(expiry: string): string | undefined {
try {
const expiryDate = convertReadableDateToTimestamp(expiry);
const nowSeconds = Math.floor(Date.now() / 1000);
if (expiryDate < nowSeconds) {
return 'Expiry must be in the future';
}
return undefined;
} catch (error) {
return 'Invalid expiry';
}
}
/**
* Validates that start time is before expiry.
* @param startTime - The start time string to validate.
* @param expiry - The expiry time string to validate.
* @returns Validation error message or undefined if valid.
*/
export function validateStartTimeVsExpiry(
startTime: string,
expiry: string,
): string | undefined {
try {
const startTimeDate = convertReadableDateToTimestamp(startTime);
const expiryDate = convertReadableDateToTimestamp(expiry);
if (startTimeDate >= expiryDate) {
return 'Start time must be before expiry';
}
return undefined;
} catch (error) {
// If date conversion fails, return undefined to let individual validation handle it
return undefined;
}
}
/**
* Validates that max amount is greater than initial amount.
* @param maxAmount - The maximum amount as BigInt.
* @param initialAmount - The initial amount as BigInt.
* @returns Validation error message or undefined if valid.
*/
export function validateMaxAmountVsInitialAmount(
maxAmount: bigint | undefined,
initialAmount: bigint | undefined,
): string | undefined {
if (
maxAmount !== undefined &&
initialAmount !== undefined &&
maxAmount < initialAmount
) {
return 'Max amount must be greater than initial amount';
}
return undefined;
}
/**
* Calculates amount per second from amount per period.
* @param amountPerPeriod - The amount per period as BigInt.
* @param timePeriod - The time period.
* @param decimals - Token decimals.
* @returns Formatted amount per second string.
*/
export function calculateAmountPerSecond(
amountPerPeriod: bigint,
timePeriod: TimePeriod,
decimals: number,
): string {
return formatUnits({
value: amountPerPeriod / TIME_PERIOD_TO_SECONDS[timePeriod],
decimals,
});
}
/**
* Validates a period duration (for periodic permissions).
* @param periodDuration - The period duration string to validate.
* @returns Object containing parsed duration and any validation error.
*/
export function validatePeriodDuration(periodDuration: string): {
duration: number | undefined;
error: string | undefined;
} {
try {
const duration = parseInt(periodDuration, 10);
if (isNaN(duration) || duration <= 0) {
return {
duration: undefined,
error: 'Period duration must be greater than 0',
};
}
return { duration, error: undefined };
} catch (error) {
return { duration: undefined, error: 'Invalid period duration' };
}
}