Reward Distribution
This guide explains how to programmatically distribute rewards in SoyCap.io after a new conversion was registered. The process involves retrieving transaction details via the SoyCap.io API and then signing the transaction using the campaign owner’s keypair with @solana/web3.js.
Prerequisites
- Merchant Authentication: Ensure you have an
auth_tokenby authenticating your merchant with the/merchants/authenticateendpoint. This token will be required to authorize the SoyCap.io API requests. - Campaign Owner’s Keypair: The campaign owner’s
keypairmust be securely loaded and ready to sign the transaction. - Positive
SOLbalance on campaign owner’s wallet - Sufficient
USDCbalance in campaign’s rewards pool to make the rewards distribution
Step 1: Get Reward Distribution Transaction Details
With the auth_token, request transaction details from SoyCap.io’s /distributions/onchain/create endpoint. This information is needed to construct the on-chain transaction for reward distribution.
Endpoint: /distributions/onchain/create
Request Parameters (sent in the body):
campaignId: The campaign ID associated with the reward distributionreferralId: The referral ID tied to the conversionconversionId: The conversion ID for which the reward is distributed.owner: The public key of the campaign owner’skeypair.
You can obtain campaignId, referralId and conversionId parameters from the metadata property of the conversion registration transaction details object.
Headers:
Authorization: Bearer token obtained during merchant authentication.
const getRewardDistributionTransactionInstruction = async (campaignId, referralId, conversionId, publicKey, token) => { const requestUrl = `${apiUrl}/distributions/onchain/create`;
const response = await fetch(requestUrl, { method: 'POST', body: JSON.stringify({ campaignId, referralId, conversionId, owner: publicKey, }), headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, }, });
if (!response.ok) { const errorResponse = await response.json(); throw new Error(`Error: ${errorResponse.error} - ${errorResponse.message}`); }
const data = await response.json(); return data; // Contains transaction instruction and metadata};
// Usageconst campaignId = '01JA2SXQGP1Z4XMR4MXTYZGC76';const referralId = '01JA2SZ20RX8WWGX1360HVPKMD';const conversionId = '01JCMK12RS4A5PQPFCSYDE4HDT';const transactionData = await getRewardDistributionTransactionInstruction(campaignId, referralId, conversionId, publicKey, auth_token);Step 2: Sign and Send the Reward Distribution Transaction
Once you have the transaction details, use the Solana @solana/web3.js library to sign and send the transaction on-chain. The transaction should be signed by the campaign owner’s keypair to complete the reward distribution in USDC.
import { Connection, sendAndConfirmTransaction, Transaction, TransactionInstruction } from '@solana/web3.js';
const connection = new Connection(clusterApiUrl('mainnet'), 'confirmed');
const signAndSendTransaction = async (txnInstruction, keypair) => { const { blockhash } = await connection.getLatestBlockhash(); const feePayer = keypair.publicKey;
const instruction = new TransactionInstruction({ keys: txnInstruction.keys.map(key => ({ pubkey: new PublicKey(key.pubkey), isSigner: key.isSigner, isWritable: key.isWritable, })), programId: new PublicKey(txnInstruction.programId), data: Buffer.from(txnInstruction.data), });
const transaction = new Transaction().add(instruction); transaction.feePayer = feePayer; transaction.recentBlockhash = blockhash;
const signature = await sendAndConfirmTransaction(connection, transaction, [keypair]); return signature;};
// Usageconst keypair = loadKeypair(); // Ensure the keypair is securely loadedconst txnSignature = await signAndSendTransaction(transactionData.instruction, keypair);console.log('Reward distribution successful with transaction signature:', txnSignature);Once reward distribution transaction is confirmed on blockchain it effectively sets associated conversion status to Paid and transferring USDC from campaign rewards pool to associated affiliate USDC account. Be careful as that operation is irreversible.
Strategies for Automating Reward Distribution
Reward distributions can be automated effectively using the following strategies:
- Instant Reward Distribution: Implemented by combining the processes of registering conversions and distributing rewards.
- Scheduled Reward Distribution: Utilizes
cronexpressions to automate payouts on a defined schedule. Learn more in this Scheduled Reward Distribution guide. - Threshold-Based Reward Distribution: Triggers payouts when a specified USDC payout threshold is met. Details can be found Threshold-Based Reward Distribution guide.