-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathutil.ts
More file actions
346 lines (306 loc) · 9.29 KB
/
util.ts
File metadata and controls
346 lines (306 loc) · 9.29 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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import { mobileAndUnder, tabletAndUnder } from "@/constants/styles/breakpoints";
import type { OracleQueryList } from "@/contexts";
import type { DropdownItem, OracleQueryUI } from "@/types";
import { chainsById, oracleTypes } from "@shared/constants";
import type { ChainId, OracleType } from "@shared/types";
import { capitalize, orderBy, partition, words } from "lodash";
import type { ReadonlyURLSearchParams } from "next/navigation";
import { css } from "styled-components";
import type { Address } from "wagmi";
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import { isEarlyVote } from "@/constants";
import { isUnresolvable } from "./validators";
/**
* Adds an opacity value to an hsl string
* @param color - a css color string or variable
* @param opacity - a number between 0 and 1
* @returns a color-mix css color with transparency added
*/
export function addOpacityToColor(color: string, opacity: number) {
const alpha = 100 - opacity * 100;
return `color-mix(in srgb, transparent ${alpha}%, ${color})`;
}
/**
* Scales the lightness of an hsla string
* @param hsla - a string in the format of hsla(0, 0%, 0%, 0)
* @param scale - a number to scale the lightness by
* @returns a string in the format of hsla(0, 0%, 0%, 0)
*/
/**
* Determines if a link is external or internal
* @param href - the href of the link
* @returns true if the link is external, false if it is internal
*/
export const isExternalLink = (href: string) => !href.startsWith("/");
export function capitalizeFirstLetter(str: string | undefined | null) {
if (!str) return "";
return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
* Determines if a route is active.
* @param pathname - the current pathname
* @param href - the route to check
* @returns true if the route is active, false otherwise
*/
export function isActiveRoute(pathname: string, href: string) {
return pathname === href;
}
/**
* Hides content on tablet and under
*/
export const hideOnTabletAndUnder = css`
@media ${tabletAndUnder} {
display: none;
}
`;
/**
* Hides content on mobile and under
*/
export const hideOnMobileAndUnder = css`
@media ${mobileAndUnder} {
display: none;
}
`;
/**
* Hides content by default, and shows it on tablet and under.
* Defaults to display: block, but can be overridden with the --display variable.
*/
export const showOnTabletAndUnder = css`
display: none;
@media ${tabletAndUnder} {
display: var(--display, block);
}
`;
/**
* Hides content by default, and shows it on mobile and under.
* Defaults to display: block, but can be overridden with the --display variable.
*/
export const showOnMobileAndUnder = css`
display: none;
@media ${mobileAndUnder} {
display: var(--display, block);
}
`;
export function makeFilterTitle(filterName: string) {
return capitalize(words(filterName)[0]);
}
export function sortQueries({
verify,
propose,
settled,
}: {
verify: OracleQueryList;
propose: OracleQueryList;
settled: OracleQueryList;
}) {
// propose and settled are sorted by the time the query was created
// verify is sorted by when the liveness ends, so that the ones that end soonest are easy to find
return {
verify: sortVerifyQueries(verify),
propose: sortByTimeCreated(propose),
settled: sortByTimeCreated(settled),
};
}
function sortByLivenessEnds(queries: OracleQueryUI[]) {
return orderBy(queries, (query) => query.livenessEndsMilliseconds);
}
function sortByTimeCreated(queries: OracleQueryUI[]) {
return orderBy(queries, (query) => query.timeMilliseconds, ["desc"]);
}
function sortVerifyQueries(verify: OracleQueryUI[]) {
const [inLiveness, notInLiveness] = partition(
verify,
({ livenessEndsMilliseconds, disputeHash }) => {
if (disputeHash !== undefined) return false;
return (livenessEndsMilliseconds ?? 0) > Date.now();
},
);
return [
...sortByLivenessEnds(inLiveness),
...sortByTimeCreated(notInLiveness),
];
}
export function makeUrlParamsForQuery({
requestHash,
requestLogIndex,
assertionHash,
assertionLogIndex,
proposalHash,
proposalLogIndex,
disputeHash,
disputeLogIndex,
settlementHash,
settlementLogIndex,
}: OracleQueryUI) {
// Priority: request/assertion > proposal > dispute > settlement
if (requestHash && requestLogIndex) {
return { transactionHash: requestHash, eventIndex: requestLogIndex };
}
if (assertionHash && assertionLogIndex) {
return { transactionHash: assertionHash, eventIndex: assertionLogIndex };
}
if (proposalHash && proposalLogIndex) {
return { transactionHash: proposalHash, eventIndex: proposalLogIndex };
}
if (disputeHash && disputeLogIndex) {
return { transactionHash: disputeHash, eventIndex: disputeLogIndex };
}
if (settlementHash && settlementLogIndex) {
return { transactionHash: settlementHash, eventIndex: settlementLogIndex };
}
// Fallback for edge cases
return { transactionHash: "", eventIndex: "" };
}
export function getPageForQuery({ actionType }: OracleQueryUI) {
switch (actionType) {
case "propose":
return "propose";
case "dispute":
case "settle":
return "verify";
default:
return "settled";
}
}
export function mapMultipleValueOutcomes(
valueText: (string | null | undefined)[] | undefined,
options: DropdownItem[] | undefined,
) {
if (!options || !valueText) {
return;
}
// if unresolvable, we want to display "Unresolvable" for each label
if (
Array.isArray(valueText) &&
valueText.length === 1 &&
isUnresolvable(valueText[0]!)
) {
return options.map(({ label }) => {
return { label, value: "Unresolvable" };
});
}
return options.map(({ label }, i) => {
return { label, value: valueText[i] };
});
}
export function maybeGetValueTextFromOptions(
valueText: string | null | undefined,
options: DropdownItem[] | undefined,
) {
return (
options?.find(({ value }) => value === valueText)?.label ??
(isEarlyVote(valueText)
? "Early Request"
: // : isUnresolvable(valueText ?? "")
// ? "Unresolvable"
valueText)
);
}
/**
* Creates a new query string by merging with the current URLSearchParams object
* @param name - the name of the query parameter
* @param value - the value of the query parameter
*/
export function makeQueryString(
newParams: Record<string, string | null | undefined>,
pathname: string | null,
exitingSearchParams: ReadonlyURLSearchParams | null,
) {
const params = new URLSearchParams(exitingSearchParams?.toString());
Object.entries(newParams).forEach(([key, value]) => {
if (value) params.set(key, value);
});
return `${pathname}?${params.toString()}`;
}
export function hasProperty<Obj extends object>(
key: PropertyKey,
obj: Obj,
): key is keyof Obj {
return key in obj;
}
export function isTransactionHash(hash: string | undefined) {
return !!hash && hash.startsWith("0x") && hash.length === 66;
}
export function isValidChainId(
chainId: number | undefined,
): chainId is ChainId {
return !!chainId && chainId in chainsById;
}
export function isValidOracleType(
oracleType: string | undefined,
): oracleType is OracleType {
return !!oracleType && oracleType in oracleTypes;
}
export function isWagmiAddress(
maybeAddress: string | undefined,
): maybeAddress is Address {
if (!maybeAddress) return false;
return "0x" == maybeAddress.slice(0, 2);
}
export function assertWagmiAddress(
maybeAddress: string,
): asserts maybeAddress is Address {
if (!isWagmiAddress(maybeAddress))
throw new Error(`${maybeAddress} is not a valid address.`);
}
/**
* Replaces cryptic revert or error messages
*/
export function sanitizeErrorMessage(errorMessage: string) {
if (errorMessage.toLowerCase().includes("cannot estimate gas")) {
return "Transaction Failed";
}
if (errorMessage.toLowerCase().includes("rejected the request")) {
return "Transaction Rejected";
}
if (
alreadyDisputedV2([new Error(errorMessage)]) ||
alreadyDisputedV3([new Error(errorMessage)])
) {
return "Already Disputed";
}
if (alreadyProposed([new Error(errorMessage)])) {
return "Already Proposed";
}
if (
alreadySettledV2([new Error(errorMessage)]) ||
alreadySettledV3([new Error(errorMessage)])
) {
return "Already Settled";
}
return errorMessage;
}
export function errorsContain(
errors: (Error | null)[],
message: string,
): boolean {
return errors.some((e) => {
return (
e?.message && e.message.toLowerCase().includes(message.toLowerCase())
);
});
}
export function alreadyDisputedV2(errors: (Error | null)[]) {
return errorsContain(errors, "disputePriceFor: Disputed"); // v2
}
export function alreadyDisputedV3(errors: (Error | null)[]) {
return errorsContain(errors, "already disputed"); // v3
}
export function alreadyProposed(errors: (Error | null)[]) {
return errorsContain(errors, "proposePriceFor: Requested"); // v2
}
export function alreadySettledV2(errors: (Error | null)[]) {
return errorsContain(errors, "_settle: not settleable"); // v2
}
export function alreadySettledV3(errors: (Error | null)[]) {
return errorsContain(errors, "already settled"); // v3
}
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function truncateAddress(address: Address | undefined) {
if (address) {
return `${address.slice(0, 5)}...${address.slice(-5)}`;
}
}