-
Notifications
You must be signed in to change notification settings - Fork 34
/
api.ts
433 lines (382 loc) · 12.1 KB
/
api.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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import { isProduction } from "../../environment";
import { fetchWithTimeout } from "../../lib";
import { NFTcollection, POAP, NFT } from "./core";
import { EIP4361Message, createEIP4361Message } from "./EIP4361";
import { Buffer } from "buffer";
declare let window: any;
// the subscriptions service is forwarded by CloudFront onto talk.brave* so we're not
// making a cross domain call - see https://github.com/brave/devops/issues/5445.
const SIMPLEHASH_PROXY_ROOT_URL = "/api/v1/simplehash";
export type Web3PermissionType = "POAP" | "NFT-collection" | "balance";
export interface Web3Authentication {
method: string;
proof: {
signer: string;
signature: any;
payload: any;
};
}
export interface Web3Authorization {
method: string;
POAPs: Web3AuthList;
Collections: Web3AuthList;
Balances: Web3BalancesList;
Addresses: Web3AddressExclusionList;
}
export interface Web3AddressExclusionList {
participantADs: Web3AddressIdentifierList;
moderatorADs: Web3AddressIdentifierList;
}
export interface Web3AddressIdentifierList {
allow: string[] | undefined;
deny: string[] | undefined;
}
export interface Web3BalancesList {
participants: Web3BalancesRequireList;
moderators: Web3BalancesRequireList;
}
export interface Web3BalancesRequireList {
network: "ETH"; // "ETH" | "SOL" in the future probably
token?: string;
minimum: string; // in wei, e.g. 10e-18
}
export interface Web3SolAuthorization {
method: string;
Collections: Web3AuthList;
}
export interface Web3AuthList {
participantADs: Web3ResourceIdentifierList;
moderatorADs: Web3ResourceIdentifierList;
}
export interface Web3ResourceIdentifierList {
allow: string[];
deny: string[];
}
export interface Web3RequestBody {
web3Authentication: Web3Authentication;
web3Authorization?: Web3Authorization;
avatarURL: string | null;
}
export interface Web3SolRequestBody {
web3Authentication: Web3Authentication;
web3Authorization?: Web3SolAuthorization;
avatarURL: string | null;
}
export const web3Login = async (): Promise<string> => {
const allAddresses: string[] = await window.ethereum.request({
method: "eth_requestAccounts",
});
console.log(`!!! allAddresses`, allAddresses);
return allAddresses[0];
};
export const web3LoginSol = async (): Promise<string> => {
try {
const result = await window.braveSolana.connect();
console.log("!!! allAddresses", result);
return result.publicKey.toBase58();
} catch {
const result = await window.phantom.solana.connect();
console.log("!!! allAddresses", result);
return result.publicKey.toBase58();
}
};
export const web3NFTs = async (address: string): Promise<NFT[]> => {
try {
const getNFTsURL = `${SIMPLEHASH_PROXY_ROOT_URL}/api/v0/nfts/owners_v2?chains=ethereum,solana,polygon&wallet_addresses=${encodeURIComponent(
address,
)}&order_by=spam_score__asc&limit=50`;
console.log(`>>> GET ${getNFTsURL}`);
const response = await fetchWithTimeout(getNFTsURL, {
method: "GET",
headers: {
accept: "application/json",
},
});
const { status } = response;
console.log(`<<< GET ${getNFTsURL} ${status}`);
if (status !== 200) {
throw new Error(`Request failed: ${status} ${response.statusText}`);
}
const nfts = await response.json();
if (!isProduction) {
console.warn(`!!! response`, nfts);
}
const result: NFT[] = [];
nfts.nfts.forEach((nft: any) => {
result.push({
image_url: nft.previews?.image_small_url
? nft.previews.image_small_url
: nft.image_url,
name: nft.name,
id: nft.nft_id,
chain: nft.chain,
collection: {
collection_id: nft.collection?.collection_id,
name: nft.collection?.name,
image_url: nft.collection?.image_url,
spam_score: nft.collection.spam_score,
},
});
});
return result;
} catch (error: any) {
console.error("!!! web3NFTs", error);
throw error;
}
};
export function splitAddresses(addr: string): string[] {
return addr.split(/,|\s/).map((address) => address.trim());
}
export const web3NFTcollections = async (
address: string,
): Promise<NFTcollection[]> => {
const getNFTs = async (url: string): Promise<NFTcollection[]> => {
const response = await fetchWithTimeout(url, {
method: "GET",
headers: {
accept: "application/json",
},
});
const { status } = response;
if (status !== 200) {
throw new Error(`Request failed: ${status} ${response.statusText}`);
}
const page = await response.json();
let { nfts } = page;
const { next } = page;
if (next) {
nfts = nfts.concat(await getNFTs(next));
}
const collections = nfts.reduce(
(collections: { [key: string]: NFTcollection }, nft: NFT) => {
if (
nft?.collection?.collection_id &&
!collections[nft.collection.collection_id]
) {
collections[nft.collection.collection_id] = {
id: nft.collection.collection_id,
name: nft.collection.name,
chain: nft.chain,
image_url: nft.previews?.image_small_url
? nft.previews.image_small_url
: nft.image_url
? nft.image_url
: nft.collection?.image_url,
};
}
return collections;
},
{},
);
return Object.values(collections);
};
try {
const getNFTsByWalletURL = `${SIMPLEHASH_PROXY_ROOT_URL}/api/v0/nfts/owners_v2?chains=ethereum,solana,polygon&wallet_addresses=${encodeURIComponent(
address,
)}&order_by=spam_score__asc&limit=50`;
console.log(`>>> GET ${getNFTsByWalletURL}`);
return getNFTs(getNFTsByWalletURL);
} catch (error: any) {
console.error("!!! web3NFTcollections", error);
throw error;
}
};
const getNonce = async (): Promise<string> => {
const getNonceURL = "/api/v1/nonce";
const response = await fetchWithTimeout(getNonceURL, {
method: "GET",
headers: {
accept: "application/json",
},
});
const { nonce } = await response.json();
return nonce;
};
export const web3Prove = async (
web3Address: string,
): Promise<Web3Authentication> => {
if (!web3Address) {
throw new Error("not logged into Web3");
}
const { ethers } = await import("ethers");
window.web3 = new ethers.BrowserProvider(window.ethereum);
if (!window.web3) {
throw new Error("unable to create ethers.BrowserProvider object");
}
const nonce = await getNonce();
console.log("!!! nonce", nonce);
const message: EIP4361Message = {
domain: window.location.host,
address: web3Address,
statement:
"Please sign this message so Brave Talk knows that you own this address",
uri: window.location.toString(),
version: "1",
chainId: 1,
// HT:https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex/40031979
// btoa has some characters not allowed by the EIP-4361 ABNF
nonce: nonce,
issuedAt: new Date().toISOString(),
};
const payload = createEIP4361Message(message, "Ethereum");
const payloadBytes = new TextEncoder().encode(payload);
const { hexlify } = await import("ethers");
const hexPayload = hexlify(payloadBytes);
const signer = await window.web3.getSigner(web3Address);
const signature = await signer.signMessage(payload);
console.log(`!!! web3 signature=${signature}`);
const result = {
method: "EIP-4361-json",
proof: {
signer: web3Address,
signature: signature,
payload: hexPayload,
},
};
return result;
};
export const web3SolProve = async (
web3Address: string,
): Promise<Web3Authentication> => {
if (!web3Address) {
throw new Error("not logged into Web3");
}
const nonce = await getNonce();
console.log("!!! nonce", nonce);
const message: EIP4361Message = {
domain: window.location.host,
address: web3Address,
statement:
"Please sign this message so Brave Talk knows that you own this address",
uri: window.location.toString(),
version: "1",
chainId: 1,
// HT:https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex/40031979
// btoa has some characters not allowed by the EIP-4361 ABNF
nonce: nonce,
issuedAt: new Date().toISOString(),
};
const payload = createEIP4361Message(message, "Solana");
const payloadBytes = new TextEncoder().encode(payload);
const { hexlify } = await import("ethers");
const hexPayload = hexlify(payloadBytes);
try {
const { publicKey, signature } =
await window.braveSolana.signMessage(payloadBytes);
const result = {
method: "CAIP-122-json",
proof: {
signer: publicKey.toBase58(),
signature: Buffer.from(signature).toString("hex"),
payload: hexPayload,
},
};
return result;
} catch {
const { publicKey, signature } =
await window.phantom.solana.signMessage(payloadBytes);
const result = {
method: "CAIP-122-json",
proof: {
signer: publicKey.toBase58(),
signature: Buffer.from(signature).toString("hex"),
payload: hexPayload,
},
};
return result;
}
};
const poapContractAddress = "0x22c1f6050e56d2876009903609a2cc3fef83b415";
const poapContractChain = "gnosis";
export const web3POAPs = async (address: string): Promise<POAP[]> => {
try {
const getPOAPsURL = `${SIMPLEHASH_PROXY_ROOT_URL}/api/v0/nfts/owners?chains=${poapContractChain}&wallet_addresses=${encodeURIComponent(
address,
)}&contract_addresses=${poapContractAddress}`;
console.log(`>>> GET ${getPOAPsURL}`);
const response = await fetchWithTimeout(getPOAPsURL, {
method: "GET",
headers: {
accept: "application/json",
},
});
const { status } = response;
console.log(`<<< GET ${getPOAPsURL} ${status}`);
if (status !== 200) {
throw new Error(`Request failed: ${status} ${response.statusText}`);
}
const data = await response.json();
if (!isProduction) {
console.warn(`!!! response`, data);
}
const result: any[] = [];
data.nfts.forEach((nft: any) => {
const parts: string[] = nft.external_url.split("/");
const eventID = parts[parts.length - 2];
result.push({
event: { id: eventID, name: nft.name, image_url: nft.image_url },
tokenId: nft.token_id,
});
});
return result;
} catch (error: any) {
console.error("!!! web3POAPs", error);
throw error;
}
};
export const web3POAPevent = async (eventID: number): Promise<boolean> => {
try {
const getPOAPsURL = `${SIMPLEHASH_PROXY_ROOT_URL}/api/v0/nfts/${poapContractChain}/${poapContractAddress}/${encodeURIComponent(
eventID,
)}`;
console.log(`>>> GET ${getPOAPsURL}`);
const response = await fetchWithTimeout(getPOAPsURL, {
method: "GET",
headers: {
accept: "application/json",
},
});
const { status } = response;
console.log(`<<< GET ${getPOAPsURL} ${status}`);
if (status !== 200) {
throw new Error(`Request failed: ${status} ${response.statusText}`);
}
const data = await response.json();
if (!isProduction) {
console.warn(`!!! response`, data);
}
return !!data.nft_id;
} catch (error: any) {
console.error(error);
return false;
}
};
export const web3NFTcollection = async (
collectionID: string,
): Promise<boolean> => {
try {
const getNFTcollectionsURL = `${SIMPLEHASH_PROXY_ROOT_URL}/api/v0/nfts/collections/ids?collection_ids=${encodeURIComponent(
collectionID,
)}`;
console.log(`>>> GET ${getNFTcollectionsURL}`);
const response = await fetchWithTimeout(getNFTcollectionsURL, {
method: "GET",
headers: {
accept: "application/json",
},
});
const { status } = response;
console.log(`<<< GET ${getNFTcollectionsURL} ${status}`);
if (status !== 200) {
throw new Error(`Request failed: ${status} ${response.statusText}`);
}
const collections: any[] = await response.json();
if (!isProduction) {
console.warn(`!!! response`, collections);
}
return collections.length > 0;
} catch (error: any) {
console.error(error);
return false;
}
};