Skip to content
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

Resync points balances #4914

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
77 changes: 77 additions & 0 deletions apps/scoutgamecron/src/scripts/detectAndResolveBalanceIssues.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { log } from "@charmverse/core/log";
import { prisma } from "@charmverse/core/prisma-client";
import { currentSeason, getCurrentWeek } from "@packages/scoutgame/dates";
import { getPointStatsFromHistory } from "@packages/scoutgame/points/getPointStatsFromHistory";



async function detectBalanceIssues() {
const scouts = await prisma.scout.findMany({
orderBy: {
farcasterId: 'asc'
},
select: {
id: true,
farcasterId: true,
farcasterName: true,
currentBalance: true
}
});
const totalScouts = scouts.length;

log.info(`Checking ${totalScouts} scouts for balance issues...`);

const scoutsWithBalanceIssues = [];

for (let i = 0; i < totalScouts; i++) {
log.info(`Checking scout ${i + 1} of ${totalScouts}: fid=${scouts[i].farcasterId}, name=${scouts[i].farcasterName}`);
const scout = scouts[i];

const balances = await getPointStatsFromHistory({
userIdOrUsername: scout.id
});

if (balances.balance !== scout.currentBalance) {

log.error(`Scout (id: ${scout.id}) (fid:${scout.farcasterId}) has a balance discrepancy: ${balances.balance} (computed) vs ${scout.currentBalance} (current)`)
scoutsWithBalanceIssues.push({
farcasterId: scout.farcasterId,
scoutId: scout.id,
expectedBalance: balances.balance,
currentBalance: scout.currentBalance,
pointDetails: balances
});
}
}

return scoutsWithBalanceIssues;
}

async function resolveBalanceIssues() {
const balanceIssues = await detectBalanceIssues();

for (let i = 0; i < balanceIssues.length; i++) {
const balanceToResolve = balanceIssues[i];

await prisma.builderEvent.create({
data: {
season: currentSeason,
type: 'misc_event',
week: getCurrentWeek(),
builder: {
connect: {
id: balanceToResolve.scoutId
}
},
pointsReceipts: {
create: {
value: balanceToResolve.expectedBalance - balanceToResolve.currentBalance,
recipientId: balanceToResolve.scoutId
}
}
}
})
}
}

// detectBalanceIssues().then(console.log)
17 changes: 17 additions & 0 deletions apps/scoutgamecron/src/scripts/manualNftResync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { syncUserNFTsFromOnchainData } from "@packages/scoutgame/builderNfts/syncUserNFTsFromOnchainData";



const username = ''

export async function manualNftResync() {
if (!username) {
throw new Error('Please provide a username');
};

await syncUserNFTsFromOnchainData({username})
console.log('manualNftResync');
}


// manualNftResync().then(console.log)
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { resolveMissingPurchases } from './resolveMissingPurchases';

export async function resolveMissingPurchasesTask(ctx: Koa.Context) {
log.info('Resyncing builder NFT sales');
await resolveMissingPurchases({ minutesAgoToNow: 5 });
// This task is run every 5 minutes. Adding some padding so we don't miss any transactions
await resolveMissingPurchases({ minutesAgoToNow: 7 });
log.info(`Syncing complete`);
}
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@
"start:remote": "concurrently --names \"next,sockets\" -c \"green,yellow\" \"npm run server:remote\" \"npm run sockets:remote\"",
"start:staging": "concurrently --names \"next,sockets\" -c \"green,yellow\" \"REACT_APP_WEBSOCKETS_HOST=http://127.0.0.1:3336 npm run server:staging\" \"npm run sockets:staging\"",
"prepare": "husky install",
"db-tool": "npx prisma studio",
"db-tool:dev": "dotenv -e .env.local -- npx prisma studio",
"db-tool:test": "dotenv -e .env.test.local -- npx prisma studio",
"db-tool": "npx prisma studio --schema=node_modules/@charmverse/core/src/prisma/schema.prisma",
"db-tool:dev": "dotenv -e .env.local -- npx prisma studio --schema=node_modules/@charmverse/core/src/prisma/schema.prisma",
"db-tool:test": "dotenv -e .env.test.local -- npx prisma studio --schema=node_modules/@charmverse/core/src/prisma/schema.prisma",
"serverless:build": "dotenv -e .env.local -- npx serverless package",
"serverless:start": "dotenv -e .env.test.local -- serverless offline start --httpPort=3020",
"typecheck": "NODE_OPTIONS=\"--max_old_space_size=4096\" node_modules/typescript/bin/tsc --project tsconfig.json --noEmit",
Expand Down
36 changes: 25 additions & 11 deletions packages/scoutgame/src/builderNfts/syncUserNFTsFromOnchainData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,37 +35,51 @@ export async function syncUserNFTsFromOnchainData({
const txRequiringReconciliation = userPurchases.filter((p) => !p.nftPurchase);

for (let i = 0; i < txRequiringReconciliation.length; i++) {
log.info(`Processing missing tx ${i + 1} / ${txRequiringReconciliation.length}`);
const txToReconcile = txRequiringReconciliation[i];

const tx = txRequiringReconciliation[i];
log.error(`Processing missing txToReconcile ${i + 1} / ${txRequiringReconciliation.length}`, {
sourceTransaction: txToReconcile.pendingTransaction?.sourceChainTxHash,
sourceChain: txToReconcile.pendingTransaction?.sourceChainId,
optimismTxHash: txToReconcile.txHash,
tokenId: txToReconcile.tokenId,
scoutId: txToReconcile.scoutId,
tokensToPurchase: txToReconcile.amount
});
const expectedPrice =
tx.pendingTransaction?.targetAmountReceived ??
txToReconcile.pendingTransaction?.targetAmountReceived ??
(await getTokenPurchasePrice({
args: {
amount: BigInt(tx.amount),
tokenId: BigInt(tx.tokenId)
amount: BigInt(txToReconcile.amount),
tokenId: BigInt(txToReconcile.tokenId)
},
blockNumber: BigInt(tx.blockNumber) - BigInt(1)
blockNumber: BigInt(txToReconcile.blockNumber) - BigInt(1)
}));

if (!txToReconcile.pendingTransaction) {
log.error('No pending transaction found for txToReconcile', {
scoutId: txToReconcile.scoutId,
tokenId: txToReconcile.tokenId,
tokensToPurchase: txToReconcile.amount
});
}
const pendingTx =
tx.pendingTransaction ??
txToReconcile.pendingTransaction ??
(await savePendingTransaction({
user: {
scoutId: scout.id,
walletAddress: tx.transferEvent.to
walletAddress: txToReconcile.transferEvent.to
},
transactionInfo: {
destinationChainId: 10,
sourceChainId: 10,
sourceChainTxHash: tx.txHash
sourceChainTxHash: txToReconcile.txHash
},
purchaseInfo: {
quotedPriceCurrency: optimismUsdcContractAddress,
builderContractAddress: realOptimismMainnetBuildersContract,
tokenId: parseInt(tx.tokenId),
tokenId: parseInt(txToReconcile.tokenId),
quotedPrice: Number(expectedPrice.toString()),
tokenAmount: Number(tx.amount)
tokenAmount: Number(txToReconcile.amount)
}
}));

Expand Down
Loading