-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
114 lines (91 loc) · 2.39 KB
/
index.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
import { Alchemy, Network } from 'alchemy-sdk';
import { NftToolServerRequest, NftToolServerResponse, NftToolServerResponseData } from '../src/types/index';
import * as dotenv from 'dotenv';
dotenv.config();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(cors());
app.use(express.json());
/**
* Create endpoint for Alchemy API
*/
app.post('/alchemy', async (req, res) => {
try {
const { network, contractAddress, tokenId }: NftToolServerRequest = req.body;
/**
* Validate request body
*/
if (!network) {
throw new Error('"network" is required');
}
if (!contractAddress) {
throw new Error('"contractAddress" is required');
}
if (!tokenId) {
throw new Error('"tokenId" is required');
}
/**
* Set network name
*/
let networkName;
switch (network) {
case 'ethereum':
networkName = Network.ETH_MAINNET;
break;
case 'matic':
networkName = Network.MATIC_MAINNET;
break;
default:
throw new Error(`Network "${network}" is not supported yet`);
}
/**
* Initialize Alchemy SDK
*/
const alchemy = new Alchemy({
apiKey: process.env.ALCHEMY_API_KEY,
network: networkName,
});
/**
* Fetch NFT metadata
*/
const nft = {
contractAddress: contractAddress as string,
tokenId: tokenId as string,
};
const metadata = await alchemy.nft.getNftMetadata(nft.contractAddress, nft.tokenId);
/**
* Prepare response
*/
const responseToolData: NftToolServerResponseData = {
network: network,
contractAddress: nft.contractAddress,
tokenId: nft.tokenId,
title: metadata.title,
collection: metadata.contract.name as string,
media: metadata.media[0].gateway as string,
};
const response: NftToolServerResponse = {
success: true,
message: responseToolData,
};
res.send(response);
} catch (error: unknown) {
console.log(error);
let errorMessage = 'Unknown error';
if (error instanceof Error) {
errorMessage = error.message;
}
const response: NftToolServerResponse = {
success: false,
error: errorMessage,
};
res.status(400).send(response);
}
});
/**
* Start Express server
*/
app.listen(process.env.PORT || 3000, () => {
console.log('server started on port 3000');
});