-
Notifications
You must be signed in to change notification settings - Fork 68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Address balance listener worker #819
Closed
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e847dd1
add optional config jsonb to webhooks table
nischitpra ee07b64
worker for balance tracking and webhook calls
nischitpra 4b1904c
basic flow working
nischitpra eed1f6f
e2e testcase for address balance listener webhook
nischitpra 1a458ef
lint fixes
nischitpra 8486fd2
minor refactoring
nischitpra 0ca6ecd
webhook config feature added
nischitpra 776398c
Merge branch 'main' into np/balanceTracking
nischitpra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
2 changes: 2 additions & 0 deletions
2
src/prisma/migrations/20241214002332_add_webhook_config/migration.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
-- AlterTable | ||
ALTER TABLE "webhooks" ADD COLUMN "config" JSONB; |
2 changes: 2 additions & 0 deletions
2
...ons/20241214005656_add_configuration_address_balance_listener_cron_schedule/migration.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
-- AlterTable | ||
ALTER TABLE "configuration" ADD COLUMN "addressBalanceListenerCronSchedule" TEXT; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import cron from "node-cron"; | ||
import { getConfig } from "../../shared/utils/cache/get-config"; | ||
import { logger } from "../../shared/utils/logger"; | ||
import { trackAddressBalance } from "../tasks/track-address-balance"; | ||
|
||
let isLocked = false; | ||
let task: cron.ScheduledTask; | ||
|
||
/** | ||
* Tracks balance of address and calls webhook if reaches a threshold. | ||
* Caveat: high chance of balance going under threshold for fast chains. Doesn't scale well for large amount of addresses. | ||
* | ||
* todo optimization: stream transactions via websocket and filter by from/to address for balance transfers. | ||
*/ | ||
export const addressBalanceListener = async (): Promise<void> => { | ||
const config = await getConfig(); | ||
if (!config.addressBalanceListenerCronSchedule) { | ||
return; | ||
} | ||
if (task) { | ||
task.stop(); | ||
} | ||
|
||
task = cron.schedule(config.addressBalanceListenerCronSchedule, async () => { | ||
if (!isLocked) { | ||
isLocked = true; | ||
try { | ||
await trackAddressBalance(); | ||
} catch (e) { | ||
logger({ | ||
service: "worker", | ||
level: "warn", | ||
message: "error on trackAddressBalance", | ||
error: e, | ||
}); | ||
} | ||
isLocked = false; | ||
} else { | ||
logger({ | ||
service: "worker", | ||
level: "warn", | ||
message: "trackAddressBalance already running, skipping", | ||
}); | ||
} | ||
}); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
import { Prisma } from "@prisma/client"; | ||
import { prisma } from "../../shared/db/client"; | ||
import { WebhooksEventTypes } from "../../shared/schemas/webhooks"; | ||
import { thirdwebClient } from "../../shared/utils/sdk"; | ||
import { getChain } from "../../shared/utils/chain"; | ||
import { SendWebhookQueue } from "../queues/send-webhook-queue"; | ||
import { logger } from "../../shared/utils/logger"; | ||
import { getWalletBalance } from "thirdweb/wallets"; | ||
|
||
type WebhookDetail = { | ||
id: number; | ||
name: string | null; | ||
url: string; | ||
secret: string; | ||
eventType: string; | ||
config: Prisma.JsonValue; | ||
createdAt: Date; | ||
updatedAt: Date; | ||
revokedAt: Date | null; | ||
}; | ||
|
||
type WebhookConfig = { | ||
address: string; | ||
chainId: number; | ||
threshold: number; | ||
}; | ||
|
||
export const trackAddressBalance = async () => { | ||
const today = Date.now(); | ||
const oneDayAgo = today - 24 * 60 * 60 * 1000; | ||
|
||
// returns new webhooks that have not been notified at all or was last notified 1 day ago | ||
const webhookDetails = await prisma.webhooks.findMany({ | ||
where: { | ||
eventType: WebhooksEventTypes.BACKEND_WALLET_BALANCE, | ||
config: { path: ["address"], not: Prisma.AnyNull }, | ||
OR: [ | ||
{ config: { path: ["lastNotify"], equals: Prisma.AnyNull } }, | ||
{ config: { path: ["lastNotify"], lt: oneDayAgo } }, | ||
], | ||
}, | ||
}); | ||
|
||
let promises = []; | ||
let ids = []; | ||
for (const webhookDetail of webhookDetails) { | ||
const config = webhookDetail.config as WebhookConfig | null; | ||
if (!config?.address) continue; | ||
if (!config?.chainId) continue; | ||
|
||
ids.push(webhookDetail.id); | ||
promises.push( | ||
_checkBalanceAndEnqueueWebhook(webhookDetail).catch((e) => | ||
logger({ | ||
service: "worker", | ||
level: "warn", | ||
message: `errored while _checkBalanceAndEnqueueWebhook for ${webhookDetail.id}`, | ||
error: e, | ||
}), | ||
), | ||
); | ||
|
||
if (ids.length >= 10) { | ||
await Promise.allSettled(promises); | ||
await _updateLastNotify(ids, today); | ||
promises = []; | ||
ids = []; | ||
} | ||
} | ||
if (ids.length) { | ||
await Promise.allSettled(promises); | ||
await _updateLastNotify(ids, today); | ||
} | ||
}; | ||
|
||
const _checkBalanceAndEnqueueWebhook = async (webhookDetail: WebhookDetail) => { | ||
const { address, chainId, threshold } = webhookDetail.config as WebhookConfig; | ||
|
||
// get native balance of address | ||
const balanceData = await getWalletBalance({ | ||
client: thirdwebClient, | ||
address, | ||
chain: await getChain(chainId), | ||
}); | ||
const currentBalance = balanceData.displayValue; | ||
|
||
// dont do anything if has enough balance | ||
if (Number.parseFloat(currentBalance) > threshold) return; | ||
|
||
await SendWebhookQueue.enqueueWebhook({ | ||
type: WebhooksEventTypes.BACKEND_WALLET_BALANCE, | ||
body: { | ||
chainId, | ||
walletAddress: address, | ||
minimumBalance: threshold.toString(), | ||
currentBalance: currentBalance, | ||
message: `LowBalance: The address ${address} on chain ${chainId} has ${Number.parseFloat( | ||
currentBalance, | ||
) | ||
.toFixed(2) | ||
.toString()}/${threshold} gas remaining.`, | ||
}, | ||
}); | ||
}; | ||
|
||
const _updateLastNotify = async (webhookIds: number[], time: number) => { | ||
// using query as only want to update a single field in config json and not replace the entire object | ||
await prisma.$executeRaw` | ||
update webhooks | ||
set config=jsonb_set(config, '{lastNotify}', ${time.toString()}::jsonb, true) | ||
where id = any(array[${webhookIds}]);`; | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is 5 minutes a good poll interval?