-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
83 lines (64 loc) · 2.15 KB
/
server.js
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
const
{createServer} = require('http'),
{Wallet} = require('@ethersproject/wallet'),
{InfuraProvider} = require('@ethersproject/providers'),
{Contract} = require('@ethersproject/contracts'),
{parseUnits} = require('@ethersproject/units'),
{isAddress} = require('@ethersproject/address'),
{log} = console,
[, , serverPort = 1337] = process.argv,
{INFURA_API_KEY, MINTER_PRIV_KEY,
TOKEN_CONTRACT_ADDR, TOKEN_DECIMALS, SEND_AMOUNT} = process.env
const abi = [{
inputs: [
{
internalType: 'address',
name: 'account',
type: 'address',
},
{
internalType: 'uint256',
name: 'amount',
type: 'uint256',
},
],
name: 'mint',
outputs: [],
stateMutability: 'nonpayable',
type: 'function',
}]
const serve = async () => {
const
provider = new InfuraProvider(4, INFURA_API_KEY),
minterWallet = new Wallet(MINTER_PRIV_KEY, provider),
tokenContract = new Contract(TOKEN_CONTRACT_ADDR, abi, minterWallet)
createServer(async (req, res) => {
const targetAddr = req.url.slice(1)
log('request received for', targetAddr)
if (!isAddress(targetAddr)) {
log('invalid address')
return reply(res, JSON.stringify({msg: 'invalid address'}), 400)
}
const mintResp =
await tokenContract.mint(
targetAddr,
parseUnits(String(SEND_AMOUNT), TOKEN_DECIMALS),
)
log('mint txn sent, waiting for the network...', mintResp)
const
mintRecp = await mintResp.wait(),
report = {
blockHash: mintRecp.blockHash,
transactionHash: mintRecp.transactionHash,
tokensSent: SEND_AMOUNT,
}
log('minting successful!')
reply(res, JSON.stringify(report))
})
.listen(serverPort, () => log('listening on port', serverPort))
}
const reply = (res, body, status = 200, headers = {}) =>
res
.writeHead(status, {'content-type': 'application/json', ...headers})
.end(body)
serve()