Scheduled Reward Distribution
This guide outlines how to programmatically schedule and distribute rewards for unpaid conversions using SoyCap.io. The process involves retrieving unpaid conversion details, preparing a transaction, and distributing rewards programmatically. A cron job is used to automate this process on a weekly (or any other) basis.
Prerequisites
- Merchant Authentication: Obtain an
auth_tokenusing the/merchants/authenticateendpoint. - Campaign Owner’s Keypair: Ensure the campaign owner’s
keypairis securely loaded and ready to sign transactions. - Positive
SOLBalance: Ensure the campaign owner’s wallet has sufficient SOL for transaction fees. - Sufficient
USDCBalance: The campaign’s rewards pool must have enough USDC to cover the payouts.
Process Overview
- Retrieve Merchant’s Campaigns Use the SoyCap.io API to fetch merchant campaigns.
- Retrieve Unpaid Conversions Use the SoyCap.io API to fetch unpaid conversions for each merchant’s campaign.
- Prepare Reward Distribution Transactions Use the SoyCap.io API to get reward distribution transaction details for each conversion.
- Sign and Send Transactions Use the Solana
@solana/web3.jslibrary to sign and send the transactions. - Automate Payouts with Cron Job Schedule the script using
cronto execute weekly.
Let’s begin by creating some helpful functions.
Step 1. Retrieve Merchant’s Campaigns
You can use SoyCap.io API merchants/:merchantId/campaigns endpoint get all merchant campaigns.
const fetchMerchantCampaigns = async (merchantId, token) => { const url = `https://soycap.io/merchants/${merchantId}/campaigns`;
const response = await fetch(url, { headers: { 'Authorization': `Bearer ${token}`, }, });
if (!response.ok) { throw new Error('Failed to fetch merchant campaigns'); }
return response.json(); // Returns an array of campaigns};Step 2. Retrieve Unpaid Conversions for Campaign
You can use SoyCap.io API campaigns/:campaignId/conversions/unpaid endpoint to get only unpaid conversion for campaignId.
const fetchUnpaidConversions = async (campaignId, token) => { const url = `https://soycap.io/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(); // Returns a list of unpaid conversions};Step 3. Create Weekly Scheduler
Install the node-cron package for scheduling:
npm install node-cronOnce fetching merchant campaigns, iterate over all unpaid conversions and use getRewardDistributionTransactionInstruction() and signAndSendTransaction() functions provided in the Reward Distribution Guide.
import cron from 'node-cron';import { Connection, clusterApiUrl } from '@solana/web3.js';
const connection = new Connection(clusterApiUrl('mainnet'), 'confirmed');
cron.schedule('0 0 * * 0', async () => { try { console.log('Starting weekly reward distribution...');
const authToken = 'YOUR_AUTH_TOKEN'; const publicKey = 'YOUR_PUBLIC_KEY'; const keypair = loadKeypair(); // Load the keypair securely
// Fetch merchant campaigns const campaigns = await fetchMerchantCampaigns(merchantId, authToken);
for (const campaign of campaigns) { // Fetch unpaid conversions const unpaidConversions = await fetchUnpaidConversions(campaign.id, authToken);
for (const conversion of unpaidConversions) { // Prepare transaction instruction const txnInstruction = await getRewardDistributionTransactionInstruction( campaign.id, conversion.id, publicKey, authToken );
// Sign and send transaction const txnSignature = await signAndSendTransaction(txnInstruction.instruction, keypair, connection); console.log(`Distributed reward for conversion ${conversion.id}: ${txnSignature}`); } } console.log('Reward distribution completed successfully.'); } catch (error) { console.error('Error in reward distribution:', error); }});