Skip to content

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

  1. Merchant Authentication: Obtain an auth_token using the /merchants/authenticate endpoint.
  2. Campaign Owner’s Keypair: Ensure the campaign owner’s keypair is securely loaded and ready to sign transactions.
  3. Positive SOL Balance: Ensure the campaign owner’s wallet has sufficient SOL for transaction fees.
  4. Sufficient USDC Balance: The campaign’s rewards pool must have enough USDC to cover the payouts.

Process Overview

  1. Retrieve Merchant’s Campaigns Use the SoyCap.io API to fetch merchant campaigns.
  2. Retrieve Unpaid Conversions Use the SoyCap.io API to fetch unpaid conversions for each merchant’s campaign.
  3. Prepare Reward Distribution Transactions Use the SoyCap.io API to get reward distribution transaction details for each conversion.
  4. Sign and Send Transactions Use the Solana @solana/web3.js library to sign and send the transactions.
  5. Automate Payouts with Cron Job Schedule the script using cron to 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:

Terminal window
npm install node-cron

Once 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);
}
});