diff --git a/prisma/migrations/20240429_224542_reverse_withdrawal_return_value/migration.sql b/prisma/migrations/20240429_224542_reverse_withdrawal_return_value/migration.sql new file mode 100644 index 00000000..38d254e4 --- /dev/null +++ b/prisma/migrations/20240429_224542_reverse_withdrawal_return_value/migration.sql @@ -0,0 +1,23 @@ +CREATE OR REPLACE FUNCTION reverse_withdrawl(wid INTEGER, wstatus "WithdrawlStatus") +RETURNS INTEGER +LANGUAGE plpgsql +AS $$ +DECLARE + msats_fee_paying BIGINT; + msats_paying BIGINT; + user_id INTEGER; +BEGIN + PERFORM ASSERT_SERIALIZED(); + + IF EXISTS (SELECT 1 FROM "Withdrawl" WHERE id = wid AND status IS NULL) THEN + SELECT "msatsPaying", "msatsFeePaying", "userId" INTO msats_paying, msats_fee_paying, user_id + FROM "Withdrawl" WHERE id = wid AND status IS NULL; + + UPDATE "Withdrawl" SET status = wstatus, updated_at = now_utc() WHERE id = wid AND status IS NULL; + + UPDATE users SET msats = msats + msats_paying + msats_fee_paying WHERE id = user_id; + RETURN 0; + END IF; + RETURN 1; +END; +$$; diff --git a/worker/wallet.js b/worker/wallet.js index ddb9f14c..80507d45 100644 --- a/worker/wallet.js +++ b/worker/wallet.js @@ -238,11 +238,11 @@ async function checkWithdrawal ({ data: { hash }, boss, models, lnd }) { ) if (code === 0) { notifyWithdrawal(dbWdrwl.userId, wdrwl) - } - if (dbWdrwl.wallet) { - // this was an autowithdrawal - const message = `autowithdrawal of ${numWithUnits(msatsToSats(paid), { abbreviate: false })} with ${numWithUnits(msatsToSats(fee), { abbreviate: false })} as fee` - await addWalletLog({ wallet: dbWdrwl.wallet.type, level: 'SUCCESS', message }, { models, me: { id: dbWdrwl.userId } }) + if (dbWdrwl.wallet) { + // this was an autowithdrawal + const message = `autowithdrawal of ${numWithUnits(msatsToSats(paid), { abbreviate: false })} with ${numWithUnits(msatsToSats(fee), { abbreviate: false })} as fee` + await addWalletLog({ wallet: dbWdrwl.wallet.type, level: 'SUCCESS', message }, { models, me: { id: dbWdrwl.userId } }) + } } } else if (wdrwl?.is_failed || notFound) { let status = 'UNKNOWN_FAILURE'; let message = 'unknown failure' @@ -260,15 +260,15 @@ async function checkWithdrawal ({ data: { hash }, boss, models, lnd }) { message = 'no route found' } - await serialize( - models.$executeRaw` + const [{ reverse_withdrawl: code }] = await serialize( + models.$queryRaw` SELECT reverse_withdrawl(${dbWdrwl.id}::INTEGER, ${status}::"WithdrawlStatus")`, { models } ) - if (dbWdrwl.wallet) { + if (code === 0 && dbWdrwl.wallet) { // add error into log for autowithdrawal - addWalletLog({ + await addWalletLog({ wallet: dbWdrwl.wallet.type, level: 'ERROR', message: 'autowithdrawal failed: ' + message