Helpful Functions and Utilities for SoyCap.io Development
Below is a collection of useful functions and utilities to streamline development with SoyCap.io. These utilities cover key tasks such as managing keypairs, checking balances, and interacting with the SoyCap.io API.
Authenticate Merchant
const authenticateMerchant = async (apiUrl, apiKey) => { const response = await fetch(`https://soycap.io/api/merchants/authenticate`, { method: 'GET', headers: { 'X-API-Key': apiKey }, });
if (!response.ok) { throw new Error('Authentication failed'); }
const { token } = await response.json(); return token;};
// Usageconst authToken = await authenticateMerchant('YOUR_API_KEY');
Create keypair
JSON File from Phantom Secret Phrase
This utility generates a keypair JSON file from a Phantom secret phrase, making it easy to integrate with SoyCap.io.
import * as fs from 'fs';import { Keypair } from '@solana/web3.js';
const createKeypairFromPhrase = (secretPhrase, filePath) => { const seed = Uint8Array.from(Buffer.from(secretPhrase, 'hex')); const keypair = Keypair.fromSeed(seed);
fs.writeFileSync(filePath, JSON.stringify([...keypair.secretKey])); console.log(`Keypair JSON file created at ${filePath}`);};
// UsagecreateKeypairFromPhrase('<SECRET_PHRASE>', './keypair.json');
Load keypair
from JSON File
Load the keypair securely from a JSON file for signing transactions.
import { Keypair } from '@solana/web3.js';import * as fs from 'fs';
const loadKeypair = (filePath) => { const secretKey = Uint8Array.from(JSON.parse(fs.readFileSync(filePath))); return Keypair.fromSecretKey(secretKey);};
// Usageconst keypair = loadKeypair('./keypair.json');console.log('Loaded keypair:', keypair.publicKey.toString());
Check SOL
Balance For Keypair
Verify that a keypair has sufficient SOL
for transaction fees.
import { Connection, clusterApiUrl } from '@solana/web3.js';
const checkSolBalance = async (publicKey) => { const connection = new Connection(clusterApiUrl('mainnet'), 'confirmed'); const balance = await connection.getBalance(publicKey); console.log(`SOL Balance: ${balance / 1e9} SOL`); return balance / 1e9;};
// UsagecheckSolBalance(keypair.publicKey);
Check USDC
Balance By campaignId
Retrieve the USDC
balance for a specific campaign.
const checkBalanceUSDC = async (campaignId, token) => { const url = `https://soycap.io/api/campaigns/${campaignId}`;
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}`, }, });
if (!response.ok) { throw new Error('Failed to fetch campaign details'); }
const campaign = await response.json(); console.log(`USDC Balance for campaign ${campaignId}: ${campaign.balanceUSDC}`); return campaign.balanceUSDC;};
// Usageconst balanceUSDC = checkBalanceUSDC('CAMPAIGN_ID', 'YOUR_AUTH_TOKEN');
Sign and Send Transaction
Sign and send transactions to the Solana blockchain.
import { Connection, Transaction, sendAndConfirmTransaction, TransactionInstruction } from '@solana/web3.js';
const sendTransaction = async (transactionData, keypair) => { const connection = new Connection('https://api.mainnet-beta.solana.com', 'confirmed'); const transaction = new Transaction().add( new TransactionInstruction({ keys: transactionData.keys.map(key => ({ pubkey: new PublicKey(key.pubkey), isSigner: key.isSigner, isWritable: key.isWritable, })), programId: new PublicKey(transactionData.programId), data: Buffer.from(transactionData.data), }) );
transaction.feePayer = keypair.publicKey; transaction.recentBlockhash = (await connection.getRecentBlockhash()).blockhash;
return sendAndConfirmTransaction(connection, transaction, [keypair]);};
Fetch Merchant Campaigns
Retrieve all campaigns for a specific merchant.
const fetchMerchantCampaigns = async (merchantId, token) => { const response = await fetch(`https://soycap.io/api/merchants/${merchantId}/campaigns`, { headers: { Authorization: `Bearer ${token}` }, });
if (!response.ok) { throw new Error('Failed to fetch campaigns'); }
return response.json();};
Fetch Referral Links for Campaign
Retrieve all referral links for a campaign.
const fetchReferralLinks = async (campaignId, token) => { const url = `https://soycap.io/api/campaigns/${campaignId}/referrals`;
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}`, }, });
if (!response.ok) { throw new Error('Failed to fetch referral links'); }
return response.json();};
// UsagefetchReferralLinks('CAMPAIGN_ID', 'YOUR_AUTH_TOKEN');
Fetch Unpaid Conversions for Campaign
Retrieve unpaid conversions associated with a specific campaign.
const fetchUnpaidConversions = async (campaignId, token) => { const url = `https://soycap.io/api/campaigns/${campaignId}/conversions/unpaid`;
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}`, }, });
if (!response.ok) { throw new Error('Failed to fetch unpaid conversions'); }
return response.json();};
// UsagefetchUnpaidConversions('CAMPAIGN_ID', 'YOUR_AUTH_TOKEN');
Update Conversion Business Value
Update the business value (e.g., revenue amount) of a conversion.
const updateConversionBusinessValue = async (conversionId, newValue, token) => { const url = `https://soycap.io/api/conversions/${conversionId}/value`;
const response = await fetch(url, { method: 'PATCH', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, body: JSON.stringify({ businessValue: newValue }), });
if (!response.ok) { const error = await response.json(); throw new Error(`Failed to update conversion value: ${error.message}`); }
return response.json();};
// UsageupdateConversionBusinessValue('CONVERSION_ID', 150.0, 'YOUR_AUTH_TOKEN');