Skip to content
This repository has been archived by the owner on Jan 7, 2025. It is now read-only.

Commit

Permalink
Helius Connection Cleanup (#503)
Browse files Browse the repository at this point in the history
* removed payment helius

* better backend helius connection

* process.env in test
  • Loading branch information
harshasomisetty authored Aug 4, 2023
1 parent 9755e08 commit 285e4f5
Show file tree
Hide file tree
Showing 11 changed files with 54 additions and 177 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import * as Sentry from '@sentry/serverless';
import { PublicKey } from '@solana/web3.js';
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';
import { InvalidInputError } from '../../errors/invalid-input.error.js';
import { MissingEnvError } from '../../errors/missing-env.error.js';
import { parseAndValidateProductSetupRequestBody } from '../../models/transaction-requests/product-setup-request.model.js';
import { MerchantService } from '../../services/database/merchant-service.database.service.js';
import { fetchGasKeypair } from '../../services/fetch-gas-keypair.service.js';
Expand Down Expand Up @@ -43,12 +42,6 @@ export const productsSetupTransaction = Sentry.AWSLambda.wrapHandler(
const merchant = await merchantService.getMerchant({ id: merchantAuthToken.id });
let gasKeypair = await fetchGasKeypair();

const heliusApiKey = process.env.HELIUS_API_KEY;

if (heliusApiKey == null) {
throw new MissingEnvError('helius api');
}

let newMintAddress;
let instructions;
let base;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
import * as web3 from '@solana/web3.js';
import axios from 'axios';
import pkg from 'bs58';
import { MissingEnvError } from '../errors/missing-env.error.js';
import { getConnectionUrl } from '../utilities/connection.utility.js';
const { decode } = pkg;

export const fetchTransaction = async (transactionId: string): Promise<web3.Transaction | null> => {
const heliusApiKey = process.env.HELIUS_API_KEY;

if (heliusApiKey == null) {
throw new MissingEnvError('helius api key');
}

try {
const response = await axios({
url: 'https://rpc.helius.xyz/?api-key=' + heliusApiKey,
url: getConnectionUrl(),
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({
Expand Down
11 changes: 2 additions & 9 deletions apps/backend-serverless/src/services/helius.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
HeliusEnhancedTransactionArray,
parseAndValidateHeliusEnchancedTransaction,
} from '../models/dependencies/helius-enhanced-transaction.model.js';
import { getConnectionUrl } from '../utilities/connection.utility.js';

export const fetchEnhancedTransaction = async (transactionId: string): Promise<HeliusEnhancedTransaction | null> => {
let heliusEnhancedTransactions: HeliusEnhancedTransactionArray;
Expand Down Expand Up @@ -81,16 +82,8 @@ export const fetchBalance = async (publicKey: string, mint: string): Promise<num
export const getAccountInfo = async (pubkey: string): Promise<GetAccountInfo> => {
let response: AxiosResponse;

const apiKey = process.env.HELIUS_API_KEY;

if (apiKey == null) {
throw new Error('No API key found');
}

const getAccountInfoUrl = `https://rpc.helius.xyz/?api-key=${apiKey}`;

try {
response = await axios.post(getAccountInfoUrl, {
response = await axios.post(getConnectionUrl(), {
jsonrpc: '2.0',
id: 1,
method: 'getAccountInfo',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { GuestIdentityDriver, Metaplex } from '@metaplex-foundation/js';
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import { MissingEnvError } from '../../errors/missing-env.error.js';
import { Keypair, PublicKey } from '@solana/web3.js';
import { getConnection } from '../../utilities/connection.utility.js';

type TransactionData = {
base: string;
Expand All @@ -14,13 +14,7 @@ export const fetchCreateTiersTransaction = async (
discount: number,
threshold: number
): Promise<TransactionData> => {
const heliusApiKey = process.env.HELIUS_API_KEY;

if (heliusApiKey == null) {
throw new MissingEnvError('helius api');
}

const connection = new Connection(`https://rpc.helius.xyz/?api-key=${heliusApiKey}`);
let connection = getConnection();
let metaplex = Metaplex.make(connection);

let merchantIdentity = new GuestIdentityDriver(merchantAddress);
Expand Down Expand Up @@ -61,13 +55,7 @@ export const fetchUpdateTiersTransaction = async (
discount: number,
threshold: number
): Promise<string | null> => {
const heliusApiKey = process.env.HELIUS_API_KEY;

if (heliusApiKey == null) {
throw new MissingEnvError('helius api');
}

const connection = new Connection(`https://rpc.helius.xyz/?api-key=${heliusApiKey}`);
let connection = getConnection();
let metaplex = Metaplex.make(connection);

let merchantIdentity = new GuestIdentityDriver(merchantAddress);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,13 @@ import {
getAssociatedTokenAddress,
getMinimumBalanceForRentExemptMint,
} from '@solana/spl-token';
import { Connection, Keypair, PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js';
import { Keypair, PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js';
import axios from 'axios';
import crypto from 'crypto';
import Jimp from 'jimp';
import { MissingEnvError } from '../../errors/missing-env.error.js';
import { getConnection } from '../../utilities/connection.utility.js';

const heliusApiKey = process.env.HELIUS_API_KEY;

if (heliusApiKey == null) {
throw new MissingEnvError('helius api');
}

const connection = new Connection(`https://rpc.helius.xyz/?api-key=${heliusApiKey}`);
let connection = getConnection();

export async function getCompressedNftSeeds(merchantAddress: PublicKey) {
const tree_seed = 'treeseed3';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { PaymentRecord, Tier } from '@prisma/client';
import { getAccount, getAssociatedTokenAddress } from '@solana/spl-token';
import { Connection, PublicKey } from '@solana/web3.js';
import { PublicKey } from '@solana/web3.js';
import { USDC_MINT } from '../../configs/tokens.config.js';
import { MissingEnvError } from '../../errors/missing-env.error.js';
import { MerchantService } from '../../services/database/merchant-service.database.service.js';
import { fetchBalance } from '../../services/helius.service.js';
import { getConnection } from '../connection.utility.js';
import { ProductDetail, createProductsNftResponse } from './create-products-response.utility.js';

export interface CustomerResponse {
Expand Down Expand Up @@ -83,12 +83,7 @@ async function customerOwnsTier(customerWallet: string, tierMint: string): Promi
let customerAddress = new PublicKey(customerWallet);
let customerTokenAddress = await getAssociatedTokenAddress(tierMintPubKey, customerAddress);

const heliusApiKey = process.env.HELIUS_API_KEY;
if (heliusApiKey == null) {
throw new MissingEnvError('helius api');
}

const connection = new Connection(`https://rpc.helius.xyz/?api-key=${heliusApiKey}`);
let connection = getConnection();
await getAccount(connection, customerTokenAddress);
customerOwns = true;
} catch {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { PublicKey } from '@solana/web3.js';
import axios from 'axios';
import { fetchGasKeypair } from '../../services/fetch-gas-keypair.service.js';
import { getCompressedAccounts } from '../../services/transaction-request/products-transaction.service.js';
import { getConnectionUrl } from '../connection.utility.js';

interface Item {
id: string;
content: {
json_uri: string;
metadata: {
name: string;
description: string;
Expand All @@ -28,11 +30,8 @@ interface Result {
}

async function fetchAssetsByGroup(page: number, mint: PublicKey): Promise<Result> {
const heliusApiKey = process.env.HELIUS_API_KEY;
if (!heliusApiKey) throw new Error('Helius API Key not found');

const response = await axios({
url: `https://rpc.helius.xyz/?api-key=${heliusApiKey}`,
url: getConnectionUrl(),
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down Expand Up @@ -93,10 +92,8 @@ export const createProductsNftResponse = async (merchant: Merchant): Promise<Pro
let page = 1;
while (true) {
const result = await fetchAssetsByGroup(page, mint);
// console.log('RESULT', result.items);
result.items.forEach(item => {
uniqueOwners.add(item.ownership.owner);

// Product View
const productType = item.content.json_uri;
if (!productView[productType]) {
Expand Down
20 changes: 20 additions & 0 deletions apps/backend-serverless/src/utilities/connection.utility.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Connection } from '@solana/web3.js';
import { MissingEnvError } from '../errors/missing-env.error.js';

export const getConnection = () => {
const heliusApiKey = process.env.HELIUS_API_KEY;
if (heliusApiKey == null) {
throw new MissingEnvError('helius api');
}

return new Connection(`https://rpc.helius.xyz/?api-key=${heliusApiKey}`);
};

export const getConnectionUrl = () => {
const heliusApiKey = process.env.HELIUS_API_KEY;
if (heliusApiKey == null) {
throw new MissingEnvError('helius api');
}

return `https://rpc.helius.xyz/?api-key=${heliusApiKey}`;
};
25 changes: 4 additions & 21 deletions apps/backend-serverless/src/utilities/transaction.utility.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,16 @@
import { TOKEN_PROGRAM_ID, createCloseAccountInstruction } from '@solana/spl-token';
import * as web3 from '@solana/web3.js';
import { USDC_MINT } from '../configs/tokens.config.js';
import { MissingEnvError } from '../errors/missing-env.error.js';
import { getConnection } from './connection.utility.js';
import { findAssociatedTokenAddress } from './pubkeys.utility.js';

export const createSweepingTransaction = async (
sendingKeypair: web3.PublicKey,
receivingKeypair: web3.PublicKey
): Promise<web3.Transaction> => {
const heliusApiKey = process.env.HELIUS_API_KEY;

if (heliusApiKey == null) {
throw new MissingEnvError('helius api');
}

const ata = await findAssociatedTokenAddress(sendingKeypair, USDC_MINT);

const connection = new web3.Connection(`https://rpc.helius.xyz/?api-key=${heliusApiKey}`);
let connection = getConnection();
const blockhash = await connection.getLatestBlockhash();
const transaction = new web3.Transaction({
feePayer: receivingKeypair,
Expand All @@ -28,13 +22,7 @@ export const createSweepingTransaction = async (
};

export const constructTransaction = async (instructions: web3.TransactionInstruction[], feePayer: web3.PublicKey) => {
const heliusApiKey = process.env.HELIUS_API_KEY;

if (heliusApiKey == null) {
throw new MissingEnvError('helius api key');
}

const connection = new web3.Connection(`https://rpc.helius.xyz/?api-key=${heliusApiKey}`);
let connection = getConnection();

const blockhash = await connection.getLatestBlockhash();
const transaction = new web3.Transaction({
Expand All @@ -47,13 +35,8 @@ export const constructTransaction = async (instructions: web3.TransactionInstruc
};

export const sendTransaction = async (transaction: web3.Transaction) => {
const heliusApiKey = process.env.HELIUS_API_KEY;

if (heliusApiKey == null) {
throw new MissingEnvError('helius api key');
}
let connection = getConnection();

const connection = new web3.Connection(`https://rpc.helius.xyz/?api-key=${heliusApiKey}`);
// const simulatedTx = await connection.simulateTransaction(transaction);
// console.log('Simulated transaction', simulatedTx);

Expand Down
6 changes: 2 additions & 4 deletions apps/payment-ui/src/components/BuyButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { getLoyaltyDetails, getPaymentDetails, getPaymentId } from '@/features/p
import { resetSession } from '@/features/payment-session/paymentSessionSlice';
import { AppDispatch } from '@/store';
import { buildTransactionRequestEndpoint } from '@/utility/endpoints.utility';
import { useWallet } from '@solana/wallet-adapter-react';
import { useConnection, useWallet } from '@solana/wallet-adapter-react';
import * as web3 from '@solana/web3.js';
import axios from 'axios';
import { useState } from 'react';
Expand All @@ -25,6 +25,7 @@ const BuyButton = () => {
const pointsBalance = useSelector(getPointsBalance);
const loyaltyDetails = useSelector(getLoyaltyDetails);
const usdcCost = useSelector(getPaymentDetails)?.usdcSize;
const { connection } = useConnection();

const fetchAndSendTransaction = async (points: boolean = false) => {
const getErrorType = (error: any) => {
Expand Down Expand Up @@ -78,9 +79,6 @@ const BuyButton = () => {
throw new Error('Failed to parse transaction string');
}

const connection = new web3.Connection(
'https://rpc.helius.xyz/?api-key=5f70b753-57cb-422b-a018-d7df67b4470e'
);
await sendTransaction(transaction, connection);
} catch (error) {
const errorType = getErrorType(error);
Expand Down
Loading

1 comment on commit 285e4f5

@vercel
Copy link

@vercel vercel bot commented on 285e4f5 Aug 4, 2023

Choose a reason for hiding this comment

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

Please sign in to comment.