generated from ubiquity/ts-template
-
Notifications
You must be signed in to change notification settings - Fork 6
/
register-wallet.ts
80 lines (67 loc) · 2.6 KB
/
register-wallet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { ethers, ZeroAddress } from "ethers";
import { Context } from "../types/context";
export async function registerWallet(context: Context, address: string | null) {
const payload = context.payload as Context<"issue_comment.created">["payload"];
const logger = context.logger;
const sender = payload.sender.login;
const senderID = payload.sender.id;
const body = payload.comment.body;
const adapters = context.adapters;
const ensName = extractEnsName(body.replace("/wallet", "").trim());
if (!address && ensName) {
logger.info("Trying to resolve address from ENS name", { ensName });
address = await resolveAddress(ensName);
if (!address) {
logger.fatal("Resolving address from ENS name failed", { ensName });
return false;
}
logger.info("Resolved address from ENS name", { ensName, address });
}
if (!address) {
logger.info("Skipping to register a wallet address because both address/ens doesn't exist");
return false;
}
if (address === ZeroAddress) {
logger.error("Skipping to register a wallet address because user is trying to set their address to null address");
return false;
}
if (address && senderID) {
const { wallet, user } = adapters.supabase;
const userRecord = await user.getUserById(senderID);
try {
if (!userRecord) {
await user.upsertUser(senderID, sender);
await wallet.upsertWallet(senderID, address);
} else {
await wallet.upsertWallet(senderID, address);
}
logger.info("Successfully registered wallet address", { sender, address });
return true;
} catch (err) {
logger.error("Error while registering wallet address", { sender, address, err });
}
} else {
logger.error(`No address found in comment: ${body}`);
}
return false;
}
export async function resolveAddress(ensName: string): Promise<string | null> {
// Gets the Ethereum address associated with an ENS (Ethereum Name Service) name
// Explicitly set provider to Ethereum mainnet
const provider = new ethers.JsonRpcProvider(`https://eth.llamarpc.com`); // mainnet required for ENS
return await provider.resolveName(ensName).catch((err) => {
console.trace({ err });
return null;
});
}
// Extracts ensname from raw text.
function extractEnsName(text: string) {
// Define a regular expression to match ENS names
const ensRegex = /^(?=.{3,40}$)([a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/gm;
// Find the first match of the regular expression in the input text
const match = text.match(ensRegex);
if (match) {
const ensName = match[0];
return ensName.toLowerCase();
}
}