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

Header styling settings page #228

Merged
merged 3 commits into from
May 4, 2024
Merged
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
335 changes: 182 additions & 153 deletions web-portal/backend/src/utils/utils.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,176 +2,205 @@
import { CustomPrismaService } from 'nestjs-prisma';
import { PrismaClient, TransactionType } from '@/.generated/client';
import { Cron, CronExpression } from '@nestjs/schedule';
import { Log, parseAbiItem, fromHex } from 'viem';
import { parseAbiItem, fromHex, isAddress } from 'viem';
import { viemClient } from './viemClient';


interface IParsedLog {
tenantId: string;
amount: number;
referenceId: string;
transactionType: TransactionType;
tenantId: string;
amount: number;
referenceId: string;
transactionType: TransactionType;
}

const portrAddress = '0x54d5f8a0e0f06991e63e46420bcee1af7d9fe944';
const event = parseAbiItem(
'event Applied(bytes32 indexed _identifier, uint256 _amount)',
'event Applied(bytes32 indexed _identifier, uint256 _amount)',
);

@Injectable()
export class UtilsService {
constructor(
@Inject('Postgres')
private prisma: CustomPrismaService<PrismaClient>, // <-- Inject the PrismaClient
) { }

async getChains() {
const chains = this.prisma.client.products.findMany({
where: {
deletedAt: null,
},
select: {
id: true,
name: true,
},
});

if (!chains)
throw new HttpException(
'No Chains/Services Found',
HttpStatus.INTERNAL_SERVER_ERROR,
);
return chains;
constructor(
@Inject('Postgres')
private prisma: CustomPrismaService<PrismaClient>, // <-- Inject the PrismaClient
) {}

async getChains() {
const chains = this.prisma.client.products.findMany({
where: {
deletedAt: null,
},
select: {
id: true,
name: true,
},
});

if (!chains)
throw new HttpException(
'No Chains/Services Found',
HttpStatus.INTERNAL_SERVER_ERROR,
);
return chains;
}

async getRuleTypes() {
const ruleTypes = await this.prisma.client.ruleType.findMany({
where: {
deletedAt: null,
},
select: {
id: true,
name: true,
description: true,
validationType: true,
validationValue: true,
isMultiple: true,
},
});

if (!ruleTypes)
throw new HttpException(
'Failed to find rules',
HttpStatus.INTERNAL_SERVER_ERROR,
);

return ruleTypes;
}
async getTokenList(chainId: string) {
if (Number(chainId) !== 8453 && Number(chainId) !== 10) {
throw new HttpException(
`Could not fetch token price`,
HttpStatus.BAD_REQUEST,
);
}

async getRuleTypes() {
const ruleTypes = await this.prisma.client.ruleType.findMany({
where: {
deletedAt: null,
},
select: {
id: true,
name: true,
description: true,
validationType: true,
validationValue: true,
isMultiple: true,
},
});

if (!ruleTypes)
throw new HttpException(
'Failed to find rules',
HttpStatus.INTERNAL_SERVER_ERROR,
);

return ruleTypes;
const res = await fetch(`https://tokens.1inch.io/v1.2/${chainId}`);
Dismissed Show dismissed Hide dismissed
if (!res.ok) {
throw new HttpException(
`Could not fetch token list`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
async getTokenList(chainId: string) {
const res = await fetch(`https://tokens.1inch.io/v1.2/${chainId}`);
if (!res.ok) {
throw new HttpException(
`Could not fetch token list`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const data = await res.json();
return data;
const data = await res.json();
return data;
}

async getTokenPrice(chainId: string, tokenAddress: string) {
if (
(Number(chainId) !== 8453 && Number(chainId) !== 10) ||
!isAddress(tokenAddress)
) {
throw new HttpException(
`Could not fetch token price`,
HttpStatus.BAD_REQUEST,
);
}

async getTokenPrice(chainId: string, tokenAddress: string) {
const res = await fetch(
`https://api.1inch.dev/price/v1.1/${chainId}/${tokenAddress}?currency=usd`,
{
headers: {
Accept: 'application/json',
Authorization: `Bearer ${process.env.ONEINCH_API_KEY!}`,
},
},
);
if (!res.ok) {
throw new HttpException(
`Could not fetch token prices`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const data = await res.json();
return data;
const res = await fetch(
`https://api.1inch.dev/price/v1.1/${chainId}/${tokenAddress}?currency=usd`,
{
headers: {
Accept: 'application/json',
Authorization: `Bearer ${process.env.ONEINCH_API_KEY!}`,
},
},
);
Dismissed Show dismissed Hide dismissed
if (!res.ok) {
throw new HttpException(
`Could not fetch token prices`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}

async get0xQuote(chainName: string, sellToken: string, sellAmount: number) {
const res = await fetch(
`https://${chainName}.api.0x.org/swap/v1/quote?sellToken=${sellToken}&buyToken=${portrAddress}&sellAmount=${sellAmount}`,
{
headers: {
Accept: 'application/json',
'0x-api-key': process.env.OX_API_KEY!,
},
},
);
if (!res.ok) {
throw new HttpException(
`Could not fetch quote`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const data = await res.json();
return data;
const data = await res.json();
return data;
}

async get0xQuote(chainName: string, sellToken: string, sellAmount: number) {
if (
(chainName !== 'base' && chainName !== 'optimism') ||
!isAddress(sellToken)
) {
throw new HttpException(`Could not fetch quote`, HttpStatus.BAD_REQUEST);
}

async get0xPrice(chainName: string, sellToken: string, sellAmount: number) {
const res = await fetch(
`https://${chainName}.api.0x.org/swap/v1/price?sellToken=${sellToken}&buyToken=${portrAddress}&sellAmount=${sellAmount}`,
{
headers: {
Accept: 'application/json',
'0x-api-key': process.env.OX_API_KEY!,
},
},
);
if (!res.ok) {
throw new HttpException(
`Could not fetch quote`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const data = await res.json();
return data;
const res = await fetch(
`https://${chainName}.api.0x.org/swap/v1/quote?sellToken=${sellToken}&buyToken=${portrAddress}&sellAmount=${sellAmount}`,
{
headers: {
Accept: 'application/json',
'0x-api-key': process.env.OX_API_KEY!,
},
},
);
if (!res.ok) {
throw new HttpException(
`Could not fetch quote`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const data = await res.json();
return data;
}

async get0xPrice(chainName: string, sellToken: string, sellAmount: number) {
if (
(chainName !== 'base' && chainName !== 'optimism') ||
!isAddress(sellToken)
) {
throw new HttpException(`Could not fetch price`, HttpStatus.BAD_REQUEST);
}

@Cron(CronExpression.EVERY_MINUTE)
async watchEvent() {
console.log('Getting Event Logs');
const blockNumber = await viemClient.getBlockNumber();
const logs = await viemClient.getLogs({
event,
address: portrAddress,
fromBlock: blockNumber - BigInt(1000),
toBlock: blockNumber,
});

const parsedLogs: IParsedLog[] = logs.map((log: any) => ({
tenantId: fromHex(log?.args?._identifier!, 'string')
.replaceAll(`\x00`, ''),
amount: Number(log?.args?._amount!),
referenceId: log.transactionHash!,
transactionType: TransactionType.CREDIT!,
}));

console.log({ parsedLogs });

if (!parsedLogs) console.log('No New Redemptions');

// Create records for unique logs
const appliedLogs = await this.prisma.client.paymentLedger.createMany({
skipDuplicates: true,
data: parsedLogs,
});

console.log({ appliedLogs });

if (!appliedLogs) console.log('Error Applying logs');

console.log('Applied New logs');
const res = await fetch(
`https://${chainName}.api.0x.org/swap/v1/price?sellToken=${sellToken}&buyToken=${portrAddress}&sellAmount=${sellAmount}`,
{
headers: {
Accept: 'application/json',
'0x-api-key': process.env.OX_API_KEY!,
},
},
);
if (!res.ok) {
throw new HttpException(
`Could not fetch quote`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const data = await res.json();
return data;
}

@Cron(CronExpression.EVERY_MINUTE)
async watchEvent() {
console.log('Getting Event Logs');
const blockNumber = await viemClient.getBlockNumber();
const logs = await viemClient.getLogs({
event,
address: portrAddress,
fromBlock: blockNumber - BigInt(1000),
toBlock: blockNumber,
});

const parsedLogs: IParsedLog[] = logs.map((log: any) => ({
tenantId: fromHex(log?.args?._identifier, 'string').replaceAll(
`\x00`,
'',
),
amount: Number(log?.args?._amount),
referenceId: log.transactionHash!,
transactionType: TransactionType.CREDIT!,
}));

console.log({ parsedLogs });

if (!parsedLogs) console.log('No New Redemptions');

// Create records for unique logs
const appliedLogs = await this.prisma.client.paymentLedger.createMany({
skipDuplicates: true,
data: parsedLogs,
});

console.log({ appliedLogs });

if (!appliedLogs) console.log('Error Applying logs');

console.log('Applied New logs');
}
}
18 changes: 18 additions & 0 deletions web-portal/frontend/components/dashboard/createApp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Button } from "@mantine/core";
import { IconPlus } from "@tabler/icons-react";

import { useViewportSize } from "@mantine/hooks";
import { usePathname, useRouter } from "next/navigation";

export default function CreateAppButton() {
const router = useRouter();
const path = usePathname();
const { width } = useViewportSize();
const isMobile = width < 600;
return (
<Button onClick={() => router.replace(path + "?new=app")} w="max-content">
{isMobile && <IconPlus />}
{!isMobile ? "CreateApp" : null}
</Button>
);
}
Loading
Loading