Skip to content

Commit

Permalink
update faucet to queue instead
Browse files Browse the repository at this point in the history
  • Loading branch information
okedeji committed Jul 19, 2024
1 parent 64b3a3e commit 536a577
Show file tree
Hide file tree
Showing 6 changed files with 901 additions and 224 deletions.
22 changes: 22 additions & 0 deletions checker.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,26 @@ export class FrequencyChecker {
}
});
}

async updateRequestStatus(requestId, status, message, data=null) {
const db = this.db
let request
try {
request = await db.get(requestId)
request.statuses.push(status)
} catch (error) {
if (error.status == 404) {
request = {statuses: [status]}
} else {
console.log(error, 'error')
}
}
await db.put(requestId, {data, statuses: request.statuses, messsage: message ? message : ''});
}

async getRequestStatus(requestId) {
const db = this.db
const request = await db.get(requestId);
return request
}
}
2 changes: 1 addition & 1 deletion config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export default {
},
tx: {
amount: [
{ denom: "uallo", amount: "20000000000000000000" },
{ denom: "uallo", amount: "1000000000" },
],
fee: {
amount: [{ denom: "uallo", amount: "500" }],
Expand Down
49 changes: 43 additions & 6 deletions faucet.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ import { bech32 } from 'bech32';
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { SigningStargateClient } from "@cosmjs/stargate";

import { Mutex } from 'async-mutex';
import { v4 } from 'uuid';

import conf from './config/config.js'
import { FrequencyChecker } from './checker.js';

const mutex = new Mutex();

// load config
console.log("loaded config: ", conf)

Expand Down Expand Up @@ -83,8 +88,24 @@ app.get('/balance/:chain', async (req, res) => {
res.send(balance);
})

app.get('/status/:requestId', async (req, res, next) => {
return Promise.resolve().then(async () => {
const { requestId } = req.params;

const status = await checker.getRequestStatus(requestId);
if (status.statuses.length > 0) {
res.json(status);
} else {
res.status(404).json({ error: 'Request ID not found' });
}
}).catch(next)
});

app.get('/send/:chain/:address', async (req, res, next) => {
return Promise.resolve().then(async () => {
const requestId = v4();
await checker.updateRequestStatus(requestId, 'pending', 'Request received');

const {chain, address} = req.params;
const ip = req.headers['x-real-ip'] || req.headers['X-Real-IP'] || req.headers['X-Forwarded-For'] || req.ip
console.log('request tokens to ', address, ip)
Expand All @@ -93,20 +114,35 @@ app.get('/send/:chain/:address', async (req, res, next) => {
const chainConf = conf.blockchains.find(x => x.name === chain)
if (chainConf && (address.startsWith(chainConf.sender.option.prefix) || address.startsWith('0x'))) {
if( await checker.checkAddress(address, chain) && await checker.checkIp(`${chain}${ip}`, chain) ) {

res.send({ requestId, message: "Faucet processing request", recipient: address})
checker.update(`${chain}${ip}`) // get ::1 on localhost
const ret = await sendTx(address, chain);
await checker.update(address)
res.send({ result: ret, tokens: chainConf.tx.amount, recipient: address})

const release = await mutex.acquire();
let sendRes;
try {
const sendRes = await sendTx(address, chain);
await checker.updateRequestStatus(requestId, 'success', 'request processed successfully', sendRes);
await checker.update(address)
} catch (err) {
console.log(err, 'error');
await checker.updateRequestStatus(requestId, 'failed', 'Failed, Please contact to admin.');
} finally {
release();
}
}else {
await checker.updateRequestStatus(requestId, 'failed', `Too Many Requests`);
res.send({
result: {
code: 429,
requestId,
message: 'Too Many Requests',
recipient: address
}
})
}
} else {
res.send({ result: `Address [${address}] is not supported.` })
await checker.updateRequestStatus(requestId, 'failed', `Address [${address}] is not supported.`);
res.send({requestId, message: `Address [${address}] is not supported.`, recipient: address })
}
// } catch (err) {
// console.error(err);
Expand All @@ -115,7 +151,8 @@ app.get('/send/:chain/:address', async (req, res, next) => {

} else {
// send result
res.send({ result: 'address is required' });
await checker.updateRequestStatus(requestId, 'failed', `address not provided`);
res.send({requestId, message: 'address is required' });
}}).catch(next)
})

Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,14 @@
"@ethersproject/wallet": "^5.7.0",
"@hanchon/evmos-ts-wallet": "^0.2.0",
"@tharsis/transactions": "^0.2.6",
"async-mutex": "^0.5.0",
"bech32": "^2.0.0",
"ejs": "^3.1.9",
"ethers": "^5.7.1",
"evmosjs": "0.3.3",
"express": "^4.18.2",
"level": "^8.0.0",
"nodemodule": "^0.3.0"
"nodemodule": "^0.3.0",
"uuid": "^10.0.0"
}
}
7 changes: 3 additions & 4 deletions views/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,12 @@
document.getElementById("button-loading").style.display = 'none';
// show result
this.message = `
<div class="alert alert-${data.result.code === 0 ? 'success' : 'danger'} alert-dismissible show fade mt-2" role="alert">
<li>${data.result.code === 0 ? 'Tokens sent' : data.result.message || 'Request failed'}</li>
<textarea class="form-control mt-1" rows="5" style="background-color:transparent">${data.result.code === 0 ? JSON.stringify(data.tokens, null, 2) : (data.result.code === 429 ? "Sorry, you've exceeded the daily limit for requests from this address or IP": JSON.stringify(data.result, null, 2)) || 'Error details not available.'}</textarea>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
<div class="alert alert-success alert-dismissible show fade mt-2" role="alert">
<li>${data.message} with ID: ${data.requestId}</li>
</div>
`;
} catch (e) {
console.log(e)
// show request failed message
this.message = `
<div class="alert alert-danger alert-dismissible show fade mt-2" role="alert">
Expand Down
Loading

0 comments on commit 536a577

Please sign in to comment.