Skip to content

Instantly share code, notes, and snippets.

@abrkn
Last active May 18, 2019 11:29
Show Gist options
  • Save abrkn/d24c607dc6ddc222dba48243ccc8e439 to your computer and use it in GitHub Desktop.
Save abrkn/d24c607dc6ddc222dba48243ccc8e439 to your computer and use it in GitHub Desktop.
import { fromEnv as configFromEnv } from './config';
import { getRpc } from '../shared/rpcs';
import { n, runWorkerUntilShutdown } from '../shared/utils';
import { createDeposit, getConnection, Deposit, Quote } from '../shared/orm';
import { safePromise } from 'safep';
import { AxiosError } from 'axios';
const config = configFromEnv();
const depositMethod = config.depositMethod!;
const { node, asset } = depositMethod!;
const fetchActiveInvoices = async () => {
const connection = await getConnection();
return await connection
.createQueryBuilder(Quote, 'q')
.where('deposit_method = :depositMethodId', { depositMethodId: depositMethod.id })
.andWhere(
`not exists (
select 1
from deposit d
where d.quote_id = q.quote_id
)`
)
.andWhere(`now() - created_at < '7 days'`)
.getMany();
};
export const tick = async () => {
const rpc = getRpc(node);
const quotes = await fetchActiveInvoices();
for (const quote of quotes) {
const { depositAddress, id } = quote;
const { rHash: rHashBase64 }: { rHash: string | undefined } = depositAddress;
if (rHashBase64 === undefined) {
throw new Error(`rHash is missing from deposit address of quote ${quote.id}`);
}
const rHashHex = Buffer.from(rHashBase64, 'base64').toString('hex');
const [error, invoice] = await safePromise(rpc('GET', `/v1/invoice/${rHashHex}`));
if (error) {
const axiosError = (error as any).request ? (error as AxiosError) : undefined;
if (axiosError !== undefined) {
if (axiosError.response && axiosError.response.status === 404) {
console.warn(`Invoice ${rHashHex} not found`);
continue;
}
}
throw error;
}
if (invoice.settled !== true) {
continue;
}
// TODO: Does settle_index have to be checked? If paid multiple times
const amountN = n(invoice.amt_paid_sat).div(1e8);
if (amountN.eq(0)) {
console.warn(`Quote ${id} was paid with a ZERO satoshi amount. Cannot credit.`);
continue;
}
const stored = await createDeposit({
quoteId: id,
tx: { rHashHex },
amount: amountN.toString(),
uniqueId: [depositMethod.id, asset, rHashHex].join(':'),
});
if (!stored) {
return;
}
console.log(`Stored deposit. ${rHashHex}. ${amountN.toString()} ${asset} for quote ${id}`);
}
};
export default runWorkerUntilShutdown(tick, 10e3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment