forked from veridatum-labs/earnproof-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemo-normalizer.ts
More file actions
57 lines (49 loc) · 1.53 KB
/
Copy pathmemo-normalizer.ts
File metadata and controls
57 lines (49 loc) · 1.53 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
import {
HorizonTransactionRecord,
NormalizedMemo,
} from "./stellar.types";
const MAX_MEMO_TEXT_CHARACTERS = 500;
export function normalizeMemo(
transaction: HorizonTransactionRecord | null | undefined,
): NormalizedMemo {
if (!transaction || !transaction.memo || transaction.memo_type === "none") {
return { type: "none" };
}
switch (transaction.memo_type) {
case "text":
return normalizeTextMemo(transaction.memo);
case "id":
return typeof transaction.memo === "string" &&
/^\d+$/.test(transaction.memo)
? { type: "id", value: transaction.memo }
: { type: "none" };
case "hash":
return normalizeHashMemo("hash", transaction.memo);
case "return":
return normalizeHashMemo("return_hash", transaction.memo);
default:
return { type: "none" };
}
}
function normalizeTextMemo(value: string | Uint8Array): NormalizedMemo {
const decoded =
typeof value === "string" ? value : Buffer.from(value).toString("utf8");
const characters = Array.from(decoded);
const truncated = characters.length > MAX_MEMO_TEXT_CHARACTERS;
return {
type: "text",
value: characters.slice(0, MAX_MEMO_TEXT_CHARACTERS).join(""),
truncated,
};
}
function normalizeHashMemo(
type: "hash" | "return_hash",
value: string | Uint8Array,
): NormalizedMemo {
const bytes =
typeof value === "string" ? Buffer.from(value, "base64") : Buffer.from(value);
if (bytes.length !== 32) {
return { type: "none" };
}
return { type, value: bytes.toString("base64") };
}