-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
229 lines (194 loc) · 7.44 KB
/
Copy pathapp.js
File metadata and controls
229 lines (194 loc) · 7.44 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
const ARC_RPC_URL = "https://rpc.testnet.arc.network";
const ANS_REGISTRY_ADDRESS = "0xf5e0E328119D16c75Fb4a001282a3a7b733EF6db";
const ANS_API_BASE_URL = new URLSearchParams(window.location.search).get("ansApi") || "http://localhost:8787";
const HASHPAY_PAY_URL = "https://hashpaylink.com/pay";
const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
const form = document.querySelector("#request-form");
const nameInput = document.querySelector("#recipient-name");
const amountInput = document.querySelector("#amount");
const memoInput = document.querySelector("#memo");
const expiryInput = document.querySelector("#expires");
const nameError = document.querySelector("#recipient-error");
const amountError = document.querySelector("#amount-error");
const statusCard = document.querySelector("#status-card");
const resultPanel = document.querySelector("#result-panel");
const resolvedName = document.querySelector("#resolved-name");
const resolvedAddress = document.querySelector("#resolved-address");
const paylinkOutput = document.querySelector("#paylink-output");
const copyButton = document.querySelector("#copy-button");
const openLink = document.querySelector("#open-link");
const generateButton = document.querySelector("#generate-button");
function normalizeArcName(value) {
return value.trim().toLowerCase().replace(/^@/, "").replace(/\s+/g, "");
}
function isArcName(value) {
return /^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]\.arc$/.test(value);
}
function isValidAmount(value) {
return /^(?:0|[1-9]\d*)(?:\.\d{1,6})?$/.test(value.trim()) && Number(value) > 0;
}
function formatAddress(address) {
return `${address.slice(0, 8)}...${address.slice(-6)}`;
}
function setStatus(kind, title, message) {
statusCard.className = `status-card ${kind === "error" ? "error-state" : kind === "success" ? "success-state" : "empty"}`;
statusCard.querySelector("strong").textContent = title;
statusCard.querySelector("p").textContent = message;
}
function setBusy(isBusy) {
generateButton.disabled = isBusy;
generateButton.textContent = isBusy ? "Resolving ARC name..." : "Resolve name and create request";
form.setAttribute("aria-busy", String(isBusy));
}
function buildPayLink({ name, address, amount, memo }) {
const url = new URL(HASHPAY_PAY_URL);
// HashPay's existing URL-parameter surface from the bundled index:
// n/net = selected network, e/evm = EVM recipient, a/amt = amount, m/memo = memo.
url.searchParams.set("n", "arc");
url.searchParams.set("e", address);
url.searchParams.set("a", amount);
if (memo) url.searchParams.set("memo", memo);
if (memo) url.searchParams.set("m", memo);
// Extra metadata for the joint flow. HashPay can safely ignore unknown params today.
url.searchParams.set("arcName", name);
url.searchParams.set("source", "arc-names");
return url.toString();
}
function stringToHex(value) {
return Array.from(new TextEncoder().encode(value))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
function encodeResolveCall(name) {
const selector = "461a4478";
const encodedName = stringToHex(name.replace(/\.arc$/, ""));
const byteLength = (encodedName.length / 2).toString(16).padStart(64, "0");
const offset = (32).toString(16).padStart(64, "0");
const paddedLength = Math.ceil(encodedName.length / 64) * 64;
const paddedName = encodedName.padEnd(paddedLength, "0");
return `0x${selector}${offset}${byteLength}${paddedName}`;
}
function decodeAddress(result) {
if (!/^0x[0-9a-fA-F]{64}$/.test(result)) return null;
const address = `0x${result.slice(-40)}`;
return address === ZERO_ADDRESS ? null : address;
}
async function resolveViaApi(name) {
const response = await fetch(`${ANS_API_BASE_URL.replace(/\/$/, "")}/resolve/${encodeURIComponent(name)}`, {
headers: { accept: "application/json" },
});
if (!response.ok) throw new Error(`ANS API returned ${response.status}`);
const payload = await response.json();
if (!payload.address || payload.address === ZERO_ADDRESS) return null;
return payload.address;
}
async function resolveViaRpc(name) {
const response = await fetch(ARC_RPC_URL, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "eth_call",
params: [
{
to: ANS_REGISTRY_ADDRESS,
data: encodeResolveCall(name),
},
"latest",
],
}),
});
if (!response.ok) throw new Error(`Arc RPC returned ${response.status}`);
const payload = await response.json();
if (payload.error) throw new Error(payload.error.message || "Arc RPC error");
return decodeAddress(payload.result);
}
async function resolveArcName(name) {
const attempts = [];
try {
return await resolveViaApi(name);
} catch (error) {
attempts.push(`ANS API: ${error.message}`);
}
try {
return await resolveViaRpc(name);
} catch (error) {
attempts.push(`Arc RPC: ${error.message}`);
}
throw new Error(attempts.join(" | "));
}
function validate() {
const name = normalizeArcName(nameInput.value);
const amount = amountInput.value.trim();
let valid = true;
nameError.textContent = "";
amountError.textContent = "";
nameInput.removeAttribute("aria-invalid");
amountInput.removeAttribute("aria-invalid");
if (!isArcName(name)) {
nameError.textContent = "Use a valid .arc name, for example bob256.arc.";
nameInput.setAttribute("aria-invalid", "true");
valid = false;
}
if (!isValidAmount(amount)) {
amountError.textContent = "Enter a USDC amount greater than 0 with up to 6 decimals.";
amountInput.setAttribute("aria-invalid", "true");
valid = false;
}
return { valid, name, amount };
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
const { valid, name, amount } = validate();
if (!valid) {
setStatus("error", "Check the request", "Fix the highlighted fields, then create the PayLink again.");
const firstInvalid = form.querySelector('[aria-invalid="true"]');
if (firstInvalid) firstInvalid.focus();
return;
}
setBusy(true);
setStatus("empty", "Resolving on ARC Name Service", "Looking up the wallet behind this .arc name.");
try {
const address = await resolveArcName(name);
if (!address) {
throw new Error(`${name} is not registered or does not resolve to an active wallet.`);
}
const link = buildPayLink({
name,
address,
amount,
memo: memoInput.value.trim(),
expires: expiryInput.value,
});
resolvedName.textContent = name;
resolvedAddress.textContent = `${formatAddress(address)} (${address})`;
paylinkOutput.value = link;
openLink.href = link;
resultPanel.hidden = false;
setStatus("success", "Live name resolved", `${name} resolved on ARC and was converted into a HashPay checkout link.`);
} catch (error) {
resultPanel.hidden = true;
setStatus("error", "Could not resolve live name", error.message);
} finally {
setBusy(false);
}
});
copyButton.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(paylinkOutput.value);
copyButton.textContent = "Copied";
setTimeout(() => {
copyButton.textContent = "Copy link";
}, 1200);
} catch {
paylinkOutput.focus();
paylinkOutput.select();
}
});
nameInput.addEventListener("blur", () => {
nameInput.value = normalizeArcName(nameInput.value);
});
amountInput.addEventListener("input", () => {
amountInput.value = amountInput.value.replace(",", ".").replace(/[^\d.]/g, "");
});