Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified .yarn/install-state.gz
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
"deploy": "wrangler publish"
},
"dependencies": {
"@unlock-protocol/networks": "^0.0.5",
"bignumber.js": "^9.1.0"
}
}
136 changes: 85 additions & 51 deletions examples/apps/backend/cloudflare-notification-worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
* Learn more at https://developers.cloudflare.com/workers/runtime-apis/scheduled-event/
*/
import BigNumber from 'bignumber.js'
import { networks } from '@unlock-protocol/networks'
import { MINIMUM_BALANCES } from './minimum'
export interface Env {
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
Expand All @@ -28,15 +27,16 @@ export interface Env {
}

interface Options {
network: Record<string, string>
networkName: string
networkId: string
address: string
balance: string
minimum: string
user: string
}

async function sendNotification(endpoint: string, options: Options) {
const { network, address, balance, minimum, user } = options
const { networkName, networkId, address, balance, minimum, user } = options
const body = {
username: 'Unlock Alert',
allowed_mentions: {
Expand All @@ -45,18 +45,18 @@ async function sendNotification(endpoint: string, options: Options) {
content: `<@${user}>`,
embeds: [
{
title: `Low balance on ${network.name} network`,
title: `Low balance on ${networkName} network`,
type: 'rich',
description: `The balance on ${network.name} network is ${balance} which is lower the minimum threshold set at ${minimum}. Please fund it ASAP.`,
description: `The balance on ${networkName} network is ${balance} which is lower the minimum threshold set at ${minimum}. Please fund it ASAP.`,
fields: [
{
name: 'Network',
value: network.name,
value: networkName,
inline: true,
},
{
name: 'Network ID',
value: network.id,
value: networkId,
inline: true,
},
{
Expand Down Expand Up @@ -89,59 +89,93 @@ async function sendNotification(endpoint: string, options: Options) {
}
}

export default {
async scheduled(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext
): Promise<void> {
const balanceEndpoint = new URL('/purchase', env.LOCKSMITH_URL)
const lastSent = await env.NOTIFICATIONS.get('last_sent')
// If sent a notification in the last 24 hours, do not send another one
if (lastSent) {
const lastSentDate = parseInt(lastSent)
const diff = Date.now() - lastSentDate
if (diff < 1000 * 60 * 60 * 24) {
return
}
const notifyIfTooLow = async (
env: Env,
networkId: string,
networkName: string,
balance: string,
address: string
) => {
const minimumBalance = new BigNumber(MINIMUM_BALANCES[networkId])
const networkBalance = new BigNumber(balance)
if (networkBalance.gte(minimumBalance)) {
return
}

await sendNotification(env.DISCORD_WEBHOOK_URL, {
networkName,
networkId,
address,
balance: networkBalance.toString(),
minimum: minimumBalance.toString(),
user: env.DISCORD_USER_ID,
})
await env.NOTIFICATIONS.put('last_sent', Date.now()?.toString())
}

const getBalances = async (env: Env, balanceEndpoint: URL) => {
const lastSent = await env.NOTIFICATIONS.get('last_sent')
// If sent a notification in the last 24 hours, do not send another one
if (lastSent) {
const lastSentDate = parseInt(lastSent)
const diff = Date.now() - lastSentDate
if (diff < 1000 * 60 * 60 * 24) {
return
}
}

const response = await fetch(balanceEndpoint.toString(), {
method: 'GET',
headers: {
'content-type': 'application/json',
},
})
const response = await fetch(balanceEndpoint.toString(), {
method: 'GET',
headers: {
'content-type': 'application/json',
},
})

const balances: Record<
string,
Record<string, string>
> = await response.json()
const balances: Record<string, Record<string, string>> = await response.json()

for (const [networkId, config] of Object.entries(balances)) {
for (const [networkId, config] of Object.entries(balances)) {
if (!Array.isArray(config)) {
if (!Object.keys(config).length) {
continue
}

const { balance, address } = config
const network = networks[networkId]
const minimumBalance = new BigNumber(MINIMUM_BALANCES[networkId])
const networkBalance = new BigNumber(balance)
if (networkBalance.gte(minimumBalance)) {
continue
await notifyIfTooLow(
env,
networkId,
config.name,
config.balance,
config.address
)
} else {
for (let i = 0; i < config.length; i++) {
await notifyIfTooLow(
env,
networkId,
config[i].name,
config[i].balance,
config[i].address
)
}

await sendNotification(env.DISCORD_WEBHOOK_URL, {
network,
address,
balance: networkBalance.toString(),
minimum: minimumBalance.toString(),
user: env.DISCORD_USER_ID,
})
await env.NOTIFICATIONS.put('last_sent', Date.now()?.toString())
}
}
}

export default {
async scheduled(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext
): Promise<void> {
getBalances(env, new URL('/purchase', env.LOCKSMITH_URL))
},
async fetch() {
return new Response('Hello!')
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const balances = await getBalances(
env,
new URL('/purchase', env.LOCKSMITH_URL)
)
return new Response(JSON.stringify(balances), {
headers: {
'content-type': 'application/json',
},
})
},
}
8 changes: 0 additions & 8 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6901,13 +6901,6 @@ __metadata:
languageName: node
linkType: hard

"@unlock-protocol/networks@npm:^0.0.5":
version: 0.0.5
resolution: "@unlock-protocol/networks@npm:0.0.5"
checksum: b0966a11abbbff29441e3456324c8382ced622bd46eae4b42262e36787d7f7c4c041464551dc8c4ead9046256d0a1d925a44a3ffd037820bc209d3367ffdf7d8
languageName: node
linkType: hard

"@unlock-protocol/networks@npm:^0.0.8":
version: 0.0.8
resolution: "@unlock-protocol/networks@npm:0.0.8"
Expand Down Expand Up @@ -10120,7 +10113,6 @@ __metadata:
resolution: "cloudflare-notification-worker@workspace:examples/apps/backend/cloudflare-notification-worker"
dependencies:
"@cloudflare/workers-types": 3.16.0
"@unlock-protocol/networks": ^0.0.5
bignumber.js: ^9.1.0
typescript: 4.8.4
wrangler: 2.6.1
Expand Down