Skip to content

Instantly share code, notes, and snippets.

@ferostabio
Last active August 1, 2023 15:13
Show Gist options
  • Save ferostabio/3f2d078c80782f987d56af14b73fae72 to your computer and use it in GitHub Desktop.
Save ferostabio/3f2d078c80782f987d56af14b73fae72 to your computer and use it in GitHub Desktop.
referrals.js
const axios = require('axios');
const API_KEY = process.env.REFERRAL_API_KEY;
const CAMPAIGN_ID = process.env.REFERRAL_CAMPAIGN_ID;
const REQUIREMENT_ID = process.env.REFERRAL_REQUIREMENT_ID;
const BASE_URL = process.env.REFERRAL_BASE_URL;
const SYNC_USER_PATH = '/users';
const UPDATE_TRACKED_BALANCE_PATH = (userId) =>
`/users/${userId}/campaign/${CAMPAIGN_ID}/tracked/balance`;
async function callReferralApi(url, requestBody) {
return await axios.post(url, requestBody, {
headers: {
'Content-Type': 'application/json',
'x-api-key': API_KEY,
},
});
}
async function syncUser(walletAddress) {
const url = `${BASE_URL}${SYNC_USER_PATH}`;
try {
const response = callReferralApi(url, { wallet_address: walletAddress });
return response.data;
} catch (error) {
throw new Error('Failed to sync user: ' + error.message);
}
}
async function updateTrackedBalance(userId, amount, tx_hash) {
// TODO: chain_id missing from the library at the moment
const url = `${BASE_URL}${UPDATE_TRACKED_BALANCE_PATH(userId)}`;
const requestBody = {
id: REQUIREMENT_ID,
amount,
tx_hash,
};
try {
const response = await callReferralApi(url, requestBody);
return response.data;
} catch (error) {
throw new Error('Failed to update tracked balance: ' + error.message);
}
}
exports.synchronizeReferralAfterEvent = async function (
walletAddress,
amount,
txHash,
chainId,
) {
try {
const data = {
walletAddress,
txHash,
chainId,
};
const user = await syncUser(walletAddress);
console.log('referral-user-synced: ', {
...data,
user: user.id,
});
const updatedBalance = await updateTrackedBalance(
user.id,
amount,
txHash,
chainId,
);
console.log('referral-balance-updated: ', {
...data,
updatedBalance,
});
} catch (error) {
console.log('referral-error: ', { error: error.message });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment