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
5 changes: 5 additions & 0 deletions .changeset/lucky-jokes-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@exactly/server": patch
---

✨ use gcp kms for allower
5 changes: 5 additions & 0 deletions .changeset/silly-yaks-divide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@exactly/server": patch
---

✨ poke account after kyc
13 changes: 13 additions & 0 deletions .do/app.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,19 @@ services:
- key: DEBUG
scope: RUN_TIME
value: ${{ env.DEBUG }}
- key: GCP_KMS_KEY_RING
scope: RUN_TIME
value: ${{ env.GCP_KMS_KEY_RING }}
- key: GCP_KMS_KEY_VERSION
scope: RUN_TIME
value: ${{ env.GCP_KMS_KEY_VERSION }}
- key: GCP_PROJECT_ID
scope: RUN_TIME
value: ${{ env.GCP_PROJECT_ID }}
- key: GCP_BASE64_JSON
scope: RUN_TIME
type: SECRET
value: ${{ env.ENCRYPTED_GCP_BASE64_JSON || env.GCP_BASE64_JSON }}
- key: INTERCOM_IDENTITY_KEY
scope: RUN_TIME
type: SECRET
Expand Down
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@
"valibot",
"valierror",
"valkey",
"valora",
"viem",
"viewability",
"wagmi",
Expand Down
413 changes: 413 additions & 0 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

219 changes: 78 additions & 141 deletions server/hooks/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,21 @@ import createDebug from "debug";
import { eq, inArray } from "drizzle-orm";
import { Hono } from "hono";
import * as v from "valibot";
import { bytesToBigInt, hexToBigInt, withRetry } from "viem";
import { bytesToBigInt, hexToBigInt } from "viem";

import {
auditorAbi,
exaAccountFactoryAbi,
exaPluginAbi,
exaPreviewerAbi,
exaPreviewerAddress,
marketAbi,
upgradeableModularAccountAbi,
wethAddress,
} from "@exactly/common/generated/chain";
import { Address, Hash, Hex } from "@exactly/common/validation";

import database, { cards, credentials } from "../database";
import { keeper } from "../utils/accounts";
import { createWebhook, findWebhook, headerValidator, network } from "../utils/alchemy";
import appOrigin from "../utils/appOrigin";
import decodePublicKey from "../utils/decodePublicKey";
import keeper from "../utils/keeper";
import { sendPushNotification } from "../utils/onesignal";
import { autoCredit } from "../utils/panda";
import publicClient from "../utils/publicClient";
Expand Down Expand Up @@ -96,7 +92,7 @@ export default new Hono().post(
category !== "erc1155" &&
(rawContract?.rawValue && rawContract.rawValue !== "0x" ? hexToBigInt(rawContract.rawValue) > 0n : !!value),
);
const accounts = await database.query.credentials
const accountLookup = await database.query.credentials
.findMany({
columns: { account: true, publicKey: true, factory: true, source: true },
where: inArray(credentials.account, [...new Set(transfers.map(({ toAddress }) => toAddress))]),
Expand All @@ -109,18 +105,16 @@ export default new Hono().post(
),
),
);
if (Object.keys(accounts).length === 1) setUser({ id: v.parse(Address, Object.keys(accounts)[0]) });
if (Object.keys(accountLookup).length === 1) setUser({ id: v.parse(Address, Object.keys(accountLookup)[0]) });

const marketsByAsset = await publicClient
.readContract({ address: exaPreviewerAddress, functionName: "assets", abi: exaPreviewerAbi })
.then((p) => new Map<Address, Address>(p.map((m) => [v.parse(Address, m.asset), v.parse(Address, m.market)])));
const markets = new Set(marketsByAsset.values());
const pokes = new Map<
Address,
{ assets: Set<Address>; factory: Address; publicKey: Uint8Array<ArrayBuffer>; source: null | string }
>();

const accounts = new Set<Address>();
for (const { toAddress: account, rawContract, value, asset: assetSymbol } of transfers) {
if (!accounts[account]) continue;
if (!accountLookup[account]) continue;
if (rawContract?.address && markets.has(rawContract.address)) continue;
const asset = rawContract?.address ?? ETH;
const underlying = asset === ETH ? WETH : asset;
Expand All @@ -131,141 +125,84 @@ export default new Hono().post(
en: `${value ? `${value} ` : ""}${assetSymbol} received${marketsByAsset.has(underlying) ? " and instantly started earning yield" : ""}`,
},
}).catch((error: unknown) => captureException(error));

if (pokes.has(account)) {
pokes.get(account)?.assets.add(asset);
} else {
const { publicKey, factory, source } = accounts[account];
pokes.set(account, { publicKey, factory, source, assets: new Set([asset]) });
}
accounts.add(account);
}
const { "sentry-trace": sentryTrace, baggage } = getTraceData();
Promise.allSettled(
[...pokes].map(([account, { publicKey, factory, source, assets }]) =>
continueTrace({ sentryTrace, baggage }, () =>
withScope((scope) =>
startSpan(
{ name: "account activity", op: "exa.activity", attributes: { account }, forceTransaction: true },
async (span) => {
scope.setUser({ id: account });
const isDeployed = !!(await publicClient.getCode({ address: account }));
scope.setTag("exa.new", !isDeployed);
if (!isDeployed) {
try {
await keeper.exaSend(
{ name: "create account", op: "exa.account", attributes: { account } },
{
address: factory,
functionName: "createAccount",
args: [0n, [decodePublicKey(publicKey, bytesToBigInt)]],
abi: exaAccountFactoryAbi,
},
);
track({ event: "AccountFunded", userId: account, properties: { source } });
} catch (error: unknown) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: "account_failed" });
throw error;
}
}
if (assets.has(ETH)) assets.delete(WETH);
const results = await Promise.allSettled(
[...assets]
.filter((asset) => marketsByAsset.has(asset) || asset === ETH)
.map(async (asset) =>
withRetry(
() =>
keeper
.exaSend(
{ name: "poke account", op: "exa.poke", attributes: { account, asset } },
{
address: account,
abi: [...exaPluginAbi, ...upgradeableModularAccountAbi, ...auditorAbi, ...marketAbi],
...(asset === ETH
? { functionName: "pokeETH" }
: {
functionName: "poke",
args: [marketsByAsset.get(asset)!], // eslint-disable-line @typescript-eslint/no-non-null-assertion
}),
},
{ ignore: ["NoBalance()"] },
)
.then((receipt) => {
if (receipt) return receipt;
throw new Error("NoBalance()");
}),
[...accounts]
.flatMap((account) => {
const info = accountLookup[account];
return info ? [[account, info] as const] : [];
})
.map(([account, { publicKey, factory, source }]) =>
continueTrace({ sentryTrace, baggage }, () =>
withScope((scope) =>
startSpan(
{ name: "account activity", op: "exa.activity", attributes: { account }, forceTransaction: true },
async (span) => {
scope.setUser({ id: account });
scope.setTag("exa.account", account);
const isDeployed = !!(await publicClient.getCode({ address: account }));
scope.setTag("exa.new", !isDeployed);
if (!isDeployed) {
try {
await keeper.exaSend(
{ name: "create account", op: "exa.account", attributes: { account } },
{
delay: 2000,
retryCount: 5,
shouldRetry: ({ error }) => {
if (error instanceof Error && error.message === "NoBalance()") return true;
withScope((captureScope) => {
captureScope.setUser({ id: account });
captureException(error, { level: "error", fingerprint: revertFingerprint(error) });
});
return true;
},
address: factory,
functionName: "createAccount",
args: [0n, [decodePublicKey(publicKey, bytesToBigInt)]],
abi: exaAccountFactoryAbi,
},
),
),
);
for (const result of results) {
if (result.status === "fulfilled") continue;
if (result.reason instanceof Error && result.reason.message === "NoBalance()") {
withScope((captureScope) => {
captureScope.setUser({ id: account });
captureScope.addEventProcessor((event) => {
if (event.exception?.values?.[0]) event.exception.values[0].type = "NoBalance";
return event;
});
captureException(result.reason, {
level: "warning",
fingerprint: ["{{ default }}", "NoBalance"],
});
});
continue;
);
track({ event: "AccountFunded", userId: account, properties: { source } });
} catch (error: unknown) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: "account_failed" });
throw error;
}
}
span.setStatus({ code: SPAN_STATUS_ERROR, message: "poke_failed" });
throw result.reason;
}
autoCredit(account)
.then(async (auto) => {
span.setAttribute("exa.autoCredit", auto);
if (!auto) return;
const credential = await database.query.credentials.findFirst({
where: eq(credentials.account, account),
columns: {},
with: {
cards: {
columns: { id: true, mode: true },
where: inArray(cards.status, ["ACTIVE", "FROZEN"]),
await keeper
.poke(account, { ignore: [`NotAllowed(${account})`] })
.catch((error: unknown) => captureException(error, { level: "error" }));
Comment on lines +164 to +166

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚩 NoBalance() special handling removed without replacement

The old activity.ts had a specific retry-and-capture flow for NoBalance() errors: it used { ignore: ["NoBalance()"] } in exaSend, then re-threw inside .then() to trigger withRetry, and finally captured the error as a warning (not error) if all retries were exhausted.

The new code passes { ignore: [\NotAllowed(${account})`] }instead, meaningNoBalance()is no longer ignored byexaSend. If a poke reverts with NoBalance(), the withRetryinsidepoke (server/utils/accounts.ts:137-163) will retry it (default retry behavior), but each retry's failure is captured at errorlevel viaexaSend's catch block — previously it was only warning` after all retries.

The corresponding test (captures no balance once after retries) was also removed. This seems intentional per the PR's simplification goals, but changes error noise characteristics in Sentry.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

autoCredit(account)
.then(async (auto) => {
span.setAttribute("exa.autoCredit", auto);
if (!auto) return;
const credential = await database.query.credentials.findFirst({
where: eq(credentials.account, account),
columns: {},
with: {
cards: {
columns: { id: true, mode: true },
where: inArray(cards.status, ["ACTIVE", "FROZEN"]),
},
},
},
});
if (!credential || credential.cards.length === 0) return;
const card = credential.cards[0];
span.setAttribute("exa.card", card?.id);
if (card?.mode !== 0) return;
await database.update(cards).set({ mode: 1 }).where(eq(cards.id, card.id));
span.setAttribute("exa.mode", 1);
sendPushNotification({
userId: account,
headings: { en: "Card mode changed" },
contents: { en: "Credit mode activated" },
}).catch((error: unknown) => captureException(error));
})
.catch((error: unknown) => captureException(error));
span.setStatus({ code: SPAN_STATUS_OK });
},
});
if (!credential || credential.cards.length === 0) return;
const card = credential.cards[0];
span.setAttribute("exa.card", card?.id);
if (card?.mode !== 0) return;
await database.update(cards).set({ mode: 1 }).where(eq(cards.id, card.id));
span.setAttribute("exa.mode", 1);
sendPushNotification({
userId: account,
headings: { en: "Card mode changed" },
contents: { en: "Credit mode activated" },
}).catch((error: unknown) => captureException(error, { level: "error" }));
})
.catch((error: unknown) => captureException(error, { level: "error" }));
span.setStatus({ code: SPAN_STATUS_OK });
},
),
),
),
).catch((error: unknown) => {
withScope((scope) => {
scope.setUser({ id: account });
captureException(error, { level: "error", fingerprint: revertFingerprint(error) });
});
throw error;
}),
),
).catch((error: unknown) => {
withScope((captureScope) => {
captureScope.setUser({ id: account });
captureException(error, { level: "error", fingerprint: revertFingerprint(error) });
});
throw error;
}),
),
)
.then((results) => {
getActiveSpan()?.setStatus(
Expand All @@ -274,7 +211,7 @@ export default new Hono().post(
: { code: SPAN_STATUS_ERROR, message: "activity_failed" },
);
})
.catch((error: unknown) => captureException(error));
.catch((error: unknown) => captureException(error, { level: "error" }));
return c.json({});
},
);
Expand Down
2 changes: 1 addition & 1 deletion server/hooks/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ import revertReason from "@exactly/common/revertReason";
import shortenHex from "@exactly/common/shortenHex";
import { Address, Hash, Hex } from "@exactly/common/validation";

import { keeper } from "../utils/accounts";
import { headers as alchemyHeaders, createWebhook, findWebhook, headerValidator } from "../utils/alchemy";
import appOrigin from "../utils/appOrigin";
import ensClient from "../utils/ensClient";
import keeper from "../utils/keeper";
import { sendPushNotification } from "../utils/onesignal";
import publicClient from "../utils/publicClient";
import redis from "../utils/redis";
Expand Down
2 changes: 1 addition & 1 deletion server/hooks/panda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import { Address, type Hash, type Hex } from "@exactly/common/validation";
import { MATURITY_INTERVAL, splitInstallments } from "@exactly/lib";

import database, { cards, credentials, transactions } from "../database/index";
import keeper from "../utils/keeper";
import { keeper } from "../utils/accounts";
import { sendPushNotification } from "../utils/onesignal";
import { collectors, createMutex, getMutex, getUser, headerValidator, signIssuerOp, updateUser } from "../utils/panda";
import publicClient from "../utils/publicClient";
Expand Down
Loading
Loading