kohin-js
Version:
The Kohin JS is a comprehensive developer toolkit designed to integrate Kohin's decentralized insurance system seamlessly into your applications. It enables efficient interaction with Kohin smart contracts and backend APIs, facilitating management and ana
236 lines (235 loc) • 12.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleError = void 0;
exports.validateForCalculatePremium = validateForCalculatePremium;
exports.validateForAddLiquidity = validateForAddLiquidity;
exports.validateConditionIdAndOutcomeId = validateConditionIdAndOutcomeId;
exports.validateForBuyCover = validateForBuyCover;
exports.formatTime = formatTime;
exports.validateAffiliateAddress = validateAffiliateAddress;
const ActiveBetTypes_1 = require("../types/ActiveBetTypes");
const errorMessagesFn = {
removeLiquidity: {
"InvalidPercent(percent)": () => "The percentage value is invalid.",
WithdrawalTimeout: (error) => {
const timestamp = Number(error?.error?.cause?.data?.args?.[0]);
if (!timestamp) {
return "An error occurred while fetching the withdrawal timeout.";
}
const bigInTime = new Date(timestamp * 1000);
const remainingSeconds = Math.floor(bigInTime.getTime() / 1000);
const remainingTime = formatTime(remainingSeconds);
return `You must wait for the withdrawal timeout period to expire. Remaining time: ${remainingTime} seconds.`;
},
LiquidityNotOwned: (error) => {
const depositId = error?.error?.cause?.data?.args?.[0] || "";
return `You do not own the liquidity deposit with ID ${depositId}. Please verify your account and try again.`;
},
"Withdrawn amount should be greater than zero": () => `The withdrawal amount must be greater than zero. Please specify a valid amount.`,
InsufficientTotalLiquidity: () => `The requested withdrawal amount exceeds the pool's total liquidity. Please try amount lower amount.`,
InvalidWithdrawnAmount: () => `The requested withdrawal amount should be more than 0. Please try amount higher amount.`,
},
};
const errorMessages = {
calculatePremium: {
"Bet timestamp invalid": `The bet ID is either expired or not yet valid. Please use a current bet ID.`,
"Sub-bet outcome already resolved": `This bet has already been resolved. Please use an active, unresolved bet ID.`,
"InvalidBetId: Bet does not exist": `Bet does not exist`,
"Sub-bet condition RESOLVED, CANCELED or PAUSED": `This sub-bet condition is resolved, canceled, or paused. Insurance is not available for such bets.`,
InvalidConditionId: `This condition is invalid. Please verify and try again.`,
BetAlreadyPaid: `This bet has already been paid. Cannot be paid again.`,
BetConditionAlreadyResolvedAsWon: `This bet condition is already resolved as won. No further actions can be taken.`,
ComboBetHasNoSubBets: ` This bet condition is already resolved as won. No further actions can be taken.`,
ComboBetAlreadyClaimed: `This bet has already been claimed. Claims cannot be made again.`,
SubBetOutcomeAlreadyResolved: `The sub-bet outcome has already been resolved. Please check the status before proceeding.`,
GameCanceled: `This game has been canceled. Insurance cannot be purchased for canceled games.`,
ConditionStateViolation: `This sub-bet condition is resolved, canceled, or paused. Insurance is not available for such bets.`,
UnsupportedBetType: ` This sub-bet condition is resolved, canceled, or paused. Insurance is not available for such bets.`,
"Invalid odds range": `The odds must be within the valid range. Please try different bet to meet this condition.`,
"Invalid amount range": `The amount must be within the valid range. Please try different bet to meet this condition.`,
"Odds out of range": `Odds are out of the allowed range.`,
"Amount out of range": `Bet amount is out of the allowed range.`,
"Number of legs exceeds the maximum allowed limit": `Your sub-bets legs in your combo bet. The current maximum allowed is maxSubBetLimit. Please place a new bet with fewer legs and try again.`,
"Combo bet has no sub-bets": `Your combo bet must include at least one sub-bet. Please add sub-bets and try again!`,
"Invalid bet type": `The bet type selected is invalid. Please choose a valid option and try again.`,
"Odds must be at least 1.0": `The odds must be at least 1.0. Please adjust your bet to meet this condition.`,
"Premium exceeds maximum cap": `Bet can't be insured because the premium exceeds 95% of the bet amount.`,
},
addLiquidity: {
"SmallDeposit()": `The deposit amount is below the minimum required. Please increase your deposit and try again.`,
"LargeDeposit()": `The deposit amount exceeds the maximum allowed. Please reduce your deposit and try again.`,
LargeDeposit: `The deposit amount exceeds the maximum allowed. Please reduce your deposit and try again.`,
ReachedMaxPoolLimit: `The pool has reached its maximum capacity of liquidity. Please try again later.`,
"UserCapExceeded()": `The pool has reached its maximum capacity of liquidity. Please try again later.`,
},
buyCover: {
InvalidSlippagePercent: `The slippage percentage must be between 1% and the maximum allowed. Please adjust and try again.`,
"BetAlreadyInsured()": `This bet is already insured. You cannot purchase insurance for it again.`,
BetAlreadyInsured: `This bet is already insured. You cannot purchase insurance for it again.`,
NotBetSlipOwner: `You are not the owner of this bet slip. Only the owner can purchase insurance.`,
PremiumExceedsSlippageTolerance: `The premium amount exceeds your slippage tolerance. Please adjust the slippage settings.`,
InsufficientLiquidity: `There is insufficient liquidity to insure the bet amount on platform. Please try later.`,
"Details: MetaMask Tx Signature: User denied transaction signature.": `User denied transaction signature`,
"Insufficient liquidity for the bet amount": `Insufficient liquidity for the bet amount`,
},
settleClaim: {
InvalidCoverId: `The cover ID is invalid. Please verify your insurance details and try again.`,
CallerNotOwner: `You are not the owner of this insurance cover. Please verify your ownership and try again.`,
CoverAlreadyClaimed: `This insurance cover has already been claimed. Duplicate claims are not allowed.`,
CoverAlreadyExpired: `This insurance cover has expired. Claims cannot be made on expired covers.`,
CoverStateManual: `This insurance cover is in manual review. Please wait for resolution or contact support.`,
NotClaimable: `This insurance cover is not eligible for a claim at this time. Please verify the cover's status.`,
"Cover does not exist": `The cover does not exist. Please check the provided cover ID.`,
"Policy state already set": `The policy is already in the selected state. No further action is required.`,
},
};
const handleError = (error, context) => {
const contextErrors = context === "removeLiquidity"
? errorMessagesFn[context]
: errorMessages[context];
if (error?.message?.includes("User rejected the request.")) {
return { success: false, error: "User denied transaction signature." };
}
else if (contextErrors) {
for (const [key, messageFn] of Object?.entries(contextErrors)) {
if (error?.error?.cause?.reason?.includes(key) ||
error?.error?.shortMessage?.includes(key) ||
error?.error?.message?.includes(key) ||
error?.toString().includes(key)) {
const passMSG = context === "removeLiquidity" ? messageFn(error) : messageFn;
return { success: false, error: passMSG };
}
}
}
else if (context === "other") {
if (typeof error.error === "string") {
return {
success: false,
error: error.error,
};
}
}
if (error?.error?.message === "Kohin instance not initialized") {
return {
success: false,
error: `The Kohin instance is not initialized; your RPC URL might be incorrect.`,
};
}
// Fallback error response
return {
success: false,
error: `Something went wrong. Please Try Again!`,
data: error,
};
};
exports.handleError = handleError;
function validateForCalculatePremium(params) {
const { odds, betAmount, limits, betType, numLegs, maxSubBetLimit } = params; // Destructure parameters
const validations = [
{
condition: odds < limits.minOdds || odds > limits.maxOdds,
error: `Invalid odds: ${odds} is outside the allowed range of ${limits.minOdds} to ${limits.maxOdds}. Please adjust your bet to meet these requirements.`,
},
{
condition: betAmount < limits.minAmount || betAmount > limits.maxAmount,
error: `The current bet amount is ${betAmount}. To qualify for bet insurance, please place a new bet within the allowed range of ${limits.minAmount} to ${limits.maxAmount}.`,
},
{
condition: betType !== ActiveBetTypes_1.BetTypeEnum.Single && betType !== ActiveBetTypes_1.BetTypeEnum.Combo,
error: `The bet type selected is invalid. Please choose a valid option and try again.`,
},
{
condition: betType === ActiveBetTypes_1.BetTypeEnum.Combo &&
maxSubBetLimit &&
numLegs &&
numLegs > maxSubBetLimit,
error: `You've selected ${numLegs} legs in your combo bet. The current maximum allowed is ${maxSubBetLimit}. Please place a new bet with fewer legs and try again.`,
},
];
for (const { condition, error } of validations) {
if (condition) {
return { success: false, error };
}
}
return { success: true };
}
function validateForAddLiquidity(params) {
const { maxDeposit, minDeposit, amount } = params;
const minDepositFormatted = minDeposit.toFixed(2);
const maxDepositFormatted = maxDeposit.toFixed(2);
const validations = [
{
condition: !amount,
error: `Please add some amount before you proceed.`,
},
{
condition: amount < minDeposit,
error: `Minimum deposit required: ${minDepositFormatted} USDT. Your deposit of ${amount} USDT is below this threshold.`,
},
{
condition: amount > maxDeposit,
error: `Please try adding amount of less then ${maxDepositFormatted} USDT.`,
},
];
for (const { condition, error } of validations) {
if (condition) {
return { success: false, error };
}
}
return { success: true };
}
function validateConditionIdAndOutcomeId(params) {
const { conditionId, outcomeId } = params;
const validations = [
{
condition: !conditionId,
error: `conditionId is required to calculate the single bet premium.`,
},
{
condition: !outcomeId,
error: `outcomeId is required to calculate the single bet premium.`,
},
];
for (const { condition, error } of validations) {
if (condition) {
return { success: false, error };
}
}
return { success: true };
}
function validateForBuyCover(slippagePercent, maxSlippagePercent, isBooked, coverPremium, tokenBalance) {
const validations = [
{
condition: slippagePercent < 1 || slippagePercent > maxSlippagePercent,
error: `The slippage percentage must be between 1% and the maximum allowed. Please adjust and try again.`,
},
{
condition: isBooked,
error: `Cover is already booked for this bet ID.`,
},
{
condition: coverPremium > tokenBalance,
error: `Your wallet does not have enough tokens to cover the premium. Please add more tokens to continue.`,
},
];
for (const { condition, error } of validations) {
if (condition) {
return { success: false, error };
}
}
return { success: true };
}
function formatTime(remainingTimeInSeconds) {
const minutes = Math.floor(remainingTimeInSeconds / 60);
const seconds = remainingTimeInSeconds % 60;
return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
}
function validateAffiliateAddress(address) {
if (!address) {
return { success: false, error: "Kohin-JS: Invalid affiliate address." };
}
if (address.length !== 42 || !/^0x[a-fA-F0-9]{40}$/.test(address)) {
return { success: false, error: "Kohin-JS: Invalid affiliate address." };
}
return { success: true };
}