Skip to content

Commit

Permalink
Merge pull request #333 from P4-Games/feature/services-refactor
Browse files Browse the repository at this point in the history
merge feature/services-refactor into develop
  • Loading branch information
dappsar authored Jan 18, 2025
2 parents 2adeb80 + eaf7f7b commit b5fc713
Show file tree
Hide file tree
Showing 63 changed files with 1,077 additions and 1,094 deletions.
2 changes: 0 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ ARG NFT_UPLOAD_IMAGE_IPFS
ARG GCP_BUCKET_BASE_URL
ARG CHATIZALO_TOKEN
ARG FRONTEND_TOKEN
ARG ARBITRUM_SEPOLIA_RPC_URL
ARG PUSH_ENABLED
ARG PUSH_NETWORK
ARG PUSH_ENVIRONMENT
Expand Down Expand Up @@ -55,7 +54,6 @@ ENV BOT_DATA_TOKEN $BOT_DATA_TOKEN
ENV NFT_UPLOAD_IMAGE_ICP $NFT_UPLOAD_IMAGE_ICP
ENV NFT_UPLOAD_IMAGE_IPFS $NFT_UPLOAD_IMAGE_IPFS
ENV GCP_BUCKET_BASE_URL $GCP_BUCKET_BASE_URL
ENV ARBITRUM_SEPOLIA_RPC_URL $ARBITRUM_SEPOLIA_RPC_URL
ENV CHATIZALO_TOKEN $CHATIZALO_TOKEN
ENV FRONTEND_TOKEN $FRONTEND_TOKEN
ENV PUSH_ENABLED $PUSH_ENABLED
Expand Down
Binary file modified bun.lockb
Binary file not shown.
2 changes: 0 additions & 2 deletions cloudbuild.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,6 @@ steps:
'--build-arg',
'GCP_BUCKET_BASE_URL=${_GCP_BUCKET_BASE_URL}',
'--build-arg',
'ARBITRUM_SEPOLIA_RPC_URL=${_ARBITRUM_SEPOLIA_RPC_URL}',
'--build-arg',
'CHATIZALO_TOKEN=$$CHATIZALO_TOKEN',
'--build-arg',
'FRONTEND_TOKEN=$$FRONTEND_TOKEN',
Expand Down
3 changes: 0 additions & 3 deletions example_env
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ MONGO_URI=
PRIVATE_KEY=
SIGNING_KEY=

# Blockchain URLs
ARBITRUM_SEPOLIA_RPC_URL=

# Blockchain gas fees
MAX_FEE_PER_GAS='30'
MAX_PRIORITY_FEE_PER_GAS='5'
Expand Down
5 changes: 4 additions & 1 deletion src/config/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import dotenv from 'dotenv';
import { ENV } from '@pushprotocol/restapi/src/lib/constants';

import { LogLevelType, validLogLevels } from '../types/logger';
import { LogLevelType, validLogLevels } from '../types/loggerType';

dotenv.config();

Expand Down Expand Up @@ -125,3 +125,6 @@ export const QUEUE_GAS_INTERVAL = 10000; // 10 Seg

export const FASTIFY_REFRESH_TOKENS_INTERVAL_MS: number = Number(fastifyRefreshNetworksIntervalMs);
export const FASTIFY_REFRESH_NETWORKS_INTERVAL_MS: number = Number(fastifyRefreshTokensIntervalMs);

export const WHATSAPP_API_URL = 'https://api.whatsapp.com';
export const CHATIZALO_PHONE_NUMBER = IS_DEVELOPMENT ? 5491164629653 : 5491164629653;
6 changes: 3 additions & 3 deletions src/config/plugins/networkConfigPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { FastifyInstance } from 'fastify';
import { Logger } from '../../helpers/loggerHelper';
import Token, { IToken } from '../../models/tokenModel';
import { IBlockchain } from '../../models/blockchainModel';
import { getNetworkConfig } from '../../services/networkService';
import { mongoBlockchainService } from '../../services/mongo/mongoBlockchainService';
import {
FASTIFY_REFRESH_TOKENS_INTERVAL_MS,
FASTIFY_REFRESH_NETWORKS_INTERVAL_MS
Expand All @@ -28,7 +28,7 @@ export async function setupNetworkConfigPlugin(server: FastifyInstance): Promise
const initialTokens = await Token.find();

// Fetch the network configuration once during server startup
const networkConfig = await getNetworkConfig();
const networkConfig = await mongoBlockchainService.getNetworkConfig();

// Decorate Fastify instance with network configuration and tokens
// eslint-disable-next-line no-param-reassign
Expand Down Expand Up @@ -58,7 +58,7 @@ export async function setupNetworkConfigPlugin(server: FastifyInstance): Promise
*/
server.decorate('refreshBlockchains', async () => {
try {
const updatedConfig = await getNetworkConfig();
const updatedConfig = await mongoBlockchainService.getNetworkConfig();
// eslint-disable-next-line no-param-reassign
server.networkConfig = updatedConfig;
Logger.info('refreshBlockchains', 'Network config refreshed successfully');
Expand Down
12 changes: 7 additions & 5 deletions src/controllers/ImageController.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { FastifyReply, FastifyRequest, RouteHandlerMethod } from 'fastify';

import { Logger } from '../helpers/loggerHelper';
import { getUser } from '../services/mongo/mongoService';
import { icpService } from '../services/icp/icpService';
import { isShortUrl } from '../helpers/validationHelper';
import { uploadToICP, uploadToIpfs, downloadAndProcessImage } from '../services/uploadService';
import { ipfsService } from '../services/ipfs/ipfsService';
import { downloadAndProcessImage } from '../services/imageService';
import { mongoUserService } from '../services/mongo/mongoUserService';
import {
returnErrorResponse,
returnSuccessResponse,
Expand Down Expand Up @@ -33,8 +35,8 @@ async function processAndUploadImage(imageUrl: string, fileName: string): Promis
try {
const processedImageBuffer = await downloadAndProcessImage(imageUrl);

const icpUrl = await uploadToICP(processedImageBuffer, fileName);
const ipfsUrl = await uploadToIpfs(processedImageBuffer, fileName);
const icpUrl = await icpService.uploadToICP(processedImageBuffer, fileName);
const ipfsUrl = await ipfsService.uploadToIpfs(processedImageBuffer, fileName);

return {
success: true,
Expand Down Expand Up @@ -84,7 +86,7 @@ export const uploadImage: RouteHandlerMethod = async (
return await returnErrorResponse(reply, 400, 'Short Url not allowed');
}

const user = await getUser(phone_number);
const user = await mongoUserService.getUser(phone_number);
if (!user) {
Logger.warn('uploadImage', `User not found: ${phone_number}`);
return await returnErrorResponse(reply, 404, 'User not found');
Expand Down
16 changes: 8 additions & 8 deletions src/controllers/balanceController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,22 @@ import { FastifyReply, FastifyRequest, FastifyInstance } from 'fastify';

import { getPhoneNFTs } from './nftController';
import { Logger } from '../helpers/loggerHelper';
import { getUser } from '../services/mongo/mongoService';
import { IUser, IUserWallet } from '../models/userModel';
import { getUserWalletByChainId } from '../services/userService';
import { getFiatQuotes } from '../services/criptoya/criptoYaService';
import { mongoUserService } from '../services/mongo/mongoUserService';
import { fetchExternalDeposits } from '../services/externalDepositsService';
import { isValidPhoneNumber, isValidEthereumWallet } from '../helpers/validationHelper';
import {
getTokenBalances,
calculateBalances,
calculateBalancesTotals
} from '../services/balanceService';
import {
returnErrorResponse,
returnSuccessResponse,
returnErrorResponse500
} from '../helpers/requestHelper';
import {
getFiatQuotes,
getTokenBalances,
calculateBalances,
calculateBalancesTotals
} from '../services/walletService';

/**
* Route handler for checking external deposits
Expand Down Expand Up @@ -123,7 +123,7 @@ export const balanceByPhoneNumber = async (
}

try {
const user: IUser | null = await getUser(phone);
const user: IUser | null = await mongoUserService.getUser(phone);
if (!user) {
Logger.warn('balanceByPhoneNumber', `User not found for phone number: ${phone}`);
return await returnErrorResponse(reply, 404, `User not found for phone number: ${phone}`);
Expand Down
29 changes: 19 additions & 10 deletions src/controllers/nftController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,28 @@ import mongoose, { ObjectId } from 'mongoose';
import { FastifyReply, FastifyRequest } from 'fastify';

import { Logger } from '../helpers/loggerHelper';
import { icpService } from '../services/icp/icpService';
import { IUser, IUserWallet } from '../models/userModel';
import { getDynamicGas } from '../helpers/paymasterHelper';
import { ConcurrentOperationsEnum } from '../types/common';
import { getNetworkConfig } from '../services/networkService';
import { ipfsService } from '../services/ipfs/ipfsService';
import { ConcurrentOperationsEnum } from '../types/commonType';
import NFTModel, { INFT, INFTMetadata } from '../models/nftModel';
import { downloadAndProcessImage } from '../services/imageService';
import { sendMintNotification } from '../services/notificationService';
import { SIGNING_KEY, defaultNftImage, DEFAULT_CHAIN_ID } from '../config/constants';
import { mongoBlockchainService } from '../services/mongo/mongoBlockchainService';
import { isShortUrl, isValidUrl, isValidPhoneNumber } from '../helpers/validationHelper';
import { uploadToICP, uploadToIpfs, downloadAndProcessImage } from '../services/uploadService';
import {
returnErrorResponse,
returnSuccessResponse,
returnErrorResponse500
} from '../helpers/requestHelper';
import {
SIGNING_KEY,
defaultNftImage,
DEFAULT_CHAIN_ID,
WHATSAPP_API_URL,
CHATIZALO_PHONE_NUMBER
} from '../config/constants';
import {
getUserWallet,
openOperation,
Expand Down Expand Up @@ -66,7 +74,7 @@ const mintNftOriginal = async (
bddIdToUseAsUri: string
): Promise<NFTData> => {
try {
const networkConfig = await getNetworkConfig(DEFAULT_CHAIN_ID);
const networkConfig = await mongoBlockchainService.getNetworkConfig(DEFAULT_CHAIN_ID);
const provider = new ethers.providers.JsonRpcProvider(networkConfig.rpc);
const backendSigner = new ethers.Wallet(SIGNING_KEY!, provider);
const nftContract = new ethers.Contract(
Expand Down Expand Up @@ -123,7 +131,7 @@ const mintNftCopy = async (
bddIdToUseAsUri: string
): Promise<NFTData> => {
try {
const networkConfig = await getNetworkConfig(DEFAULT_CHAIN_ID);
const networkConfig = await mongoBlockchainService.getNetworkConfig(DEFAULT_CHAIN_ID);
const provider = new ethers.providers.JsonRpcProvider(networkConfig.rpc);
const backendSigner = new ethers.Wallet(SIGNING_KEY!, provider);
const nftContract = new ethers.Contract(
Expand Down Expand Up @@ -342,7 +350,7 @@ export const generateNftOriginal = async (
let icpImageUrl = '';

try {
ipfsImageUrl = await uploadToIpfs(processedImage, fileName);
ipfsImageUrl = await ipfsService.uploadToIpfs(processedImage, fileName);
} catch (error) {
Logger.warn(
'generateNftOriginal',
Expand All @@ -353,7 +361,7 @@ export const generateNftOriginal = async (
}

try {
icpImageUrl = await uploadToICP(processedImage, fileName);
icpImageUrl = await icpService.uploadToICP(processedImage, fileName);
} catch (error) {
Logger.warn(
'generateNftOriginal',
Expand Down Expand Up @@ -610,7 +618,8 @@ export const getLastNFT = async (

// Check postman requests
const isPostman = request.headers['user-agent']?.includes('Postman');
const returnUrl = `https://api.whatsapp.com/send/?phone=5491164629653&text=Me%20gustar%C3%ADa%20mintear%20el%20NFT%20${nft.id}`;

const returnUrl = `${WHATSAPP_API_URL}/send/?phone=${CHATIZALO_PHONE_NUMBER}&text=Me%20gustar%C3%ADa%20mintear%20el%20NFT%20${nft.id}`;

if (isPostman) {
return await returnSuccessResponse(reply, 'URL para compartir el NFT', { url: returnUrl });
Expand All @@ -633,7 +642,7 @@ export const getPhoneNFTs = async (
phone_number: string
): Promise<{ count: number; nfts: NFTInfo[] }> => {
try {
const networkConfig = await getNetworkConfig(DEFAULT_CHAIN_ID);
const networkConfig = await mongoBlockchainService.getNetworkConfig(DEFAULT_CHAIN_ID);
const nfts = await NFTModel.find({ channel_user_id: phone_number });

return {
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/rampController.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { FastifyReply, FastifyRequest } from 'fastify';

import { Logger } from '../helpers/loggerHelper';
import { MantecaUserBalance } from '../types/manteca';
import { MantecaUserBalance } from '../types/mantecaType';
import { mantecaUserService } from '../services/manteca/user/mantecaUserService';
import { mantecaPriceService } from '../services/manteca/market/mantecaPriceService';
import { returnErrorResponse, returnSuccessResponse } from '../helpers/requestHelper';
Expand Down Expand Up @@ -81,7 +81,7 @@ export const createRampUser = async (request: FastifyRequest, reply: FastifyRepl
};
*/

// TO-REVIEW: Falla el create User en el sandbox, porque no tiene el campo address y no está en la documentación como se completa.
// TO-REVIEW: Falla el create User en el sandbox, porque no tiene el campo address y no está en la documentación como se completa.
// https://docs.manteca.dev/api-runner/mantecadev/cripto/gestion-de-usuarios/usuarios-1/crear-usuario
const userCreated =
// await mantecaUserService.createUser(mockCreateUser);
Expand Down
12 changes: 4 additions & 8 deletions src/controllers/supportController.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import { FastifyReply, FastifyRequest } from 'fastify';

import { Logger } from '../helpers/loggerHelper';
import { mongoUserService } from '../services/mongo/mongoUserService';
import { returnSuccessResponse, returnErrorResponse500 } from '../helpers/requestHelper';
import {
resetUserOperationsCounter,
getUsersWithOperationsInProgress,
resetUserOperationsCounterWithTimeCondition
} from '../services/mongo/mongoService';

/**
* Handler to check for users with open operations in progress.
Expand All @@ -21,7 +17,7 @@ export const checkUsersWithOpenOperations = async (
reply: FastifyReply
): Promise<FastifyReply> => {
try {
const users = await getUsersWithOperationsInProgress();
const users = await mongoUserService.getUsersWithOperationsInProgress();
return await returnSuccessResponse(reply, '', { users });
} catch (error) {
Logger.error('checkUsersWithOpenOperations', error);
Expand All @@ -42,7 +38,7 @@ export const resetUsersOperations = async (
reply: FastifyReply
): Promise<FastifyReply> => {
try {
const updatedCount = await resetUserOperationsCounter();
const updatedCount = await mongoUserService.resetUserOperationsCounter();
return await returnSuccessResponse(
reply,
`${updatedCount} users' operations has been reset to 0.`
Expand All @@ -67,7 +63,7 @@ export const resetUsersOperationsWithTimeCondition = async (
reply: FastifyReply
): Promise<FastifyReply> => {
try {
const updatedCount = await resetUserOperationsCounterWithTimeCondition();
const updatedCount = await mongoUserService.resetUserOperationsCounterWithTimeCondition();
return await returnSuccessResponse(
reply,
`${updatedCount} users' operations have been reset to 0 based on the time condition.`
Expand Down
12 changes: 6 additions & 6 deletions src/controllers/swapController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { FastifyReply, FastifyRequest, FastifyInstance } from 'fastify';

import { Logger } from '../helpers/loggerHelper';
import { SIGNING_KEY } from '../config/constants';
import { executeSwap } from '../services/swapService';
import { setupERC20 } from '../services/contractSetupService';
import { saveTransaction } from '../services/transferService';
import { isValidPhoneNumber } from '../helpers/validationHelper';
import { executeSwap } from '../services/web3/simpleSwapService';
import { setupERC20 } from '../services/web3/contractSetupService';
import { computeProxyAddressFromPhone } from '../services/predictWalletService';
import { mongoTransactionService } from '../services/mongo/mongoTransactionService';
import { returnErrorResponse, returnSuccessResponse } from '../helpers/requestHelper';
import { getTokensAddresses, checkBlockchainConditions } from '../services/blockchainService';
import {
Expand All @@ -20,7 +20,7 @@ import {
ExecuteSwapResultType,
ConcurrentOperationsEnum,
CheckBalanceConditionsResultType
} from '../types/common';
} from '../types/commonType';
import {
sendSwapNotification,
sendInternalErrorNotification,
Expand Down Expand Up @@ -205,7 +205,7 @@ export const swap = async (request: FastifyRequest<{ Body: SwapBody }>, reply: F

// Save transactions OUT
Logger.log('swap', 'Updating swap transactions in database.');
await saveTransaction(
await mongoTransactionService.saveTransaction(
executeSwapResult.approveTransactionHash,
proxyAddress,
networkConfig.contracts.simpleSwapAddress,
Expand All @@ -216,7 +216,7 @@ export const swap = async (request: FastifyRequest<{ Body: SwapBody }>, reply: F
);

// Save transactions IN
await saveTransaction(
await mongoTransactionService.saveTransaction(
executeSwapResult.swapTransactionHash,
networkConfig.contracts.simpleSwapAddress,
proxyAddress,
Expand Down
13 changes: 7 additions & 6 deletions src/controllers/transactionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@ import { Span, Tracer } from '@google-cloud/trace-agent/build/src/plugin-types';

import { Logger } from '../helpers/loggerHelper';
import { IUser, IUserWallet } from '../models/userModel';
import { getUser } from '../services/mongo/mongoService';
import { verifyWalletBalanceInRpc } from '../services/walletService';
import { sendUserOperation } from '../services/transferService';
import { verifyWalletBalanceInRpc } from '../services/balanceService';
import { mongoUserService } from '../services/mongo/mongoUserService';
import Transaction, { ITransaction } from '../models/transactionModel';
import { INFURA_API_KEY, GCP_CLOUD_TRACE_ENABLED } from '../config/constants';
import { saveTransaction, sendUserOperation } from '../services/transferService';
import { mongoTransactionService } from '../services/mongo/mongoTransactionService';
import { returnErrorResponse, returnSuccessResponse } from '../helpers/requestHelper';
import { isValidPhoneNumber, isValidEthereumWallet } from '../helpers/validationHelper';
import { getTokenAddress, checkBlockchainConditions } from '../services/blockchainService';
import {
ConcurrentOperationsEnum,
ExecueTransactionResultType,
CheckBalanceConditionsResultType
} from '../types/common';
} from '../types/commonType';
import {
openOperation,
closeOperation,
Expand Down Expand Up @@ -301,7 +302,7 @@ export const makeTransaction = async (
return await returnErrorResponse(reply, 400, 'Error making transaction', validationError);
}

const fromUser: IUser | null = await getUser(channel_user_id);
const fromUser: IUser | null = await mongoUserService.getUser(channel_user_id);
if (!fromUser) {
validationError = 'User not found. You must have an account to make a transaction';
rootSpan?.endSpan();
Expand Down Expand Up @@ -478,7 +479,7 @@ export const makeTransaction = async (
: undefined;

Logger.log('makeTransaction', 'Updating transaction in database.');
await saveTransaction(
await mongoTransactionService.saveTransaction(
executeTransactionResult.transactionHash,
userWallet.wallet_proxy,
toAddress,
Expand Down
Loading

0 comments on commit b5fc713

Please sign in to comment.