window.addEventListener("load", () => {
app.query(".top-sel-modal-cnt-bdy").innerHTML = app.loading();
const handleCoins = async () => {
let fetchedData = [];
const searchInput = app.query("#searchInput");
searchOnlyPattern = new RegExp("^[a-zA-Z ]+$");
let previousValue = "";
const data = async () => {
//GETTING ALL THE COIN
const fetchedCoins = await getCoins();
for (const [key, value] of Object.entries(fetchedCoins)) {
fetchedData.push({ key, ...value });
}
//FILTER ARRAY WITH SEARCH INPUT
searchInput.addEventListener("input", (e) => {
const sortInput = async () => {
let currentValue = searchInput.value;
if (
e.inputType.includes("delete") ||
searchOnlyPattern.test(currentValue)
) {
previousValue = currentValue;
}
searchInput.value = previousValue;
const searchString = searchInput.value.toLowerCase();
const filteredCoins = fetchedData.filter((data) => {
return data.abbrv.toLowerCase().includes(searchString);
});
analyseData(filteredCoins);
};
sortInput().then(() => coinSetter());
});
//LOOPING DATA INTO HTML DOM
const analyseData = (dataArr) => {
if (dataArr.length > 0) {
let eachWalletHtml = "";
//LOOPING THROUGH ARRAY AND INPUTING VALUES INTO HTML
dataArr.forEach((data) => {
eachWalletHtml += `
`;
});
app.query(".top-sel-modal-cnt-bdy").innerHTML = eachWalletHtml;
} else {
app.query(
".top-sel-modal-cnt-bdy"
).innerHTML = `
No match found
`;
}
};
analyseData(fetchedData);
};
data().then(() => {
coinSetter();
});
};
document.getElementById("coinIntVal").value = "";
document.getElementById("network").value = "";
document.getElementById("addInput").value = "";
document.getElementById("amntInput").value = "";
document.getElementById("addEmail").value = "";
handleCoins();
});
//SETTING SELECT COIN
const coinSetter = () => {
const topSelBtn = document.querySelector(".top-sel-sel");
const topSelModal = document.querySelector(".top-sel-modal");
const topSelModalCnt = document.querySelector(".top-sel-modal-cnt");
const topSelEch = document.querySelectorAll(".top-sel-ech");
const tpModCls = document.querySelector(".tpModCls");
const topSelSelCov = document.querySelector(".top-sel-sel-cover");
const btmSecCover = document.querySelector(".btm-select-sec-cover");
const searchInput = app.query("#searchInput");
//Opening and closing of modals
topSelSelCov.addEventListener("click", () => {
topSelModal.classList.add("active");
});
tpModCls.addEventListener("click", () => {
topSelModal.classList.remove("active");
searchInput.value = "";
});
topSelModal.addEventListener("click", (e) => {
if (!topSelModalCnt.contains(e.target)) {
topSelModal.classList.remove("active");
searchInput.value = "";
}
});
//Handling picking of coins
topSelEch.forEach((newCoin) => {
let newImg;
let newDet;
newCoin.addEventListener("click", () => {
newImg = newCoin.children[0].children[0].getAttribute("src");
newDet = newCoin.children[1].children[0].innerHTML;
//Setting the coin to display
// console.log(newCoin.dataset.id);
app.query(".maxSell").dataset.coin = newCoin.dataset.coin;
app.query(".maxSell").dataset.id = newCoin.dataset.id;
topSelSelCov.innerHTML = `
`;
app.query("#amntInput").value = "";
const handleCoin = () => {
btmSecCover.innerHTML = app.loading();
//GET ALL COINS
app.getCookie("azer_token", (e, r) => {
let fetchedData = [];
let btmHtml = "";
if (e) {
let netTem = "";
let symbol = newCoin.dataset.coin;
app.client
.fetch(`/api/coin/id`, "POST", { token: r, symbol: symbol })
.then((sx) => {
let a = sx[0].networks.split(",");
a.forEach((ex) => {
netTem += `
${ex}
${ex}
`;
});
app.query(".azer_net_holder").innerHTML = netTem;
handleMaxSell();
networkSetter(symbol);
});
app.client
.fetch(`/user/wallet/${newCoin.dataset.coin}`, "POST", {
token: r,
})
.then((dx) => {
//MAPPING OUT THE DATA AND PUSHING IT INTO AN ARRAY
for (const [key, value] of Object.entries(dx)) {
fetchedData.push({ key, ...value });
}
fetchedData.forEach((data) => {
btmHtml += `
${newDet}
balance:
${Number(
Number(data.totalAvailableBalance).toFixed(8)
).toLocaleString()}
${newDet}
Minimum Withdrawal:
0.00000021
${newDet}
`;
});
btmSecCover.innerHTML = btmHtml;
});
}
});
};
handleCoin();
//Replace coin button name with picked coin name
coinIntVal.value = newDet;
topSelModal.classList.remove("active");
//Calc the value of one newCoin
const calValue = async () => {
const abbvCurrVal = document.querySelector(".abbvCurrVal");
const topSelBtn = document.querySelector(".top-sel-sel");
let currencyValue = 0;
let coinValue = 0;
let coinArr = [];
const fetchCurr = await fetch("../../api/currency/id?id=ngn");
const res = await fetchCurr.json();
const fetchCoin = await fetch(
`https://api.coingecko.com/api/v3/simple/price?ids=${topSelBtn.dataset.id}%2C&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true&include_last_updated_at=true`
);
const obj = await fetchCoin.json();
for (const key of Object.keys(obj)) {
coinArr.push({ key: key, ...obj[key] });
}
coinArr.forEach((data) => {
coinValue = data.usd;
});
res.forEach((data) => {
currencyValue = data.buy_rate;
});
};
calValue();
});
});
};
//SETTING NETWORK
const networkSetter = (symbol) => {
const ultimNetSel = document.querySelector(".ultim-net-sel");
const ultimNetModal = document.querySelector(".ultim-net-modal");
const ultimNetModaCnt = document.querySelector(".ultim-net-modal-cnt");
const ultimCls = document.querySelector(".ultimCls");
const netModEch = document.querySelectorAll(".net-mod-ech");
const networkInt = document.getElementById("network");
//Opening and closing of Network Modals
ultimNetSel.addEventListener("click", () => {
ultimNetModal.classList.add("active");
});
ultimCls.addEventListener("click", () => {
ultimNetModal.classList.remove("active");
});
ultimNetModal.addEventListener("click", (e) => {
if (!ultimNetModaCnt.contains(e.target)) {
ultimNetModal.classList.remove("active");
}
});
//Handling picking of Networks
netModEch.forEach((netModEch) => {
netModEch.addEventListener("click", () => {
let newDet;
newDet = netModEch.children[1].innerHTML;
app.getCookie("azer_token", (e, r) => {
if (e) {
let obj = {
symbol: symbol,
network: newDet,
token: r,
};
}
});
ultimNetModal.classList.remove("active");
networkInt.value = newDet;
});
});
};
//VALIDATING AMOUNT INPUT
const amntInput = document.getElementById("amntInput");
currInputPattern = new RegExp("^[0-9.]+$");
let currPreviousValue = "";
amntInput.addEventListener("input", (e) => {
const currBtn = document.querySelector(".curr-btn");
const coinBtn = document.querySelector(".coin-btn");
if (!amntInput.value == "") {
let currentValue = amntInput.value;
if (e.inputType.includes("delete") || currInputPattern.test(currentValue)) {
currPreviousValue = currentValue;
}
amntInput.value = currPreviousValue;
}
});
// HANDLING MAX COIN
const handleMaxSell = () => {
const maxSell = app.query(".maxSell");
// const currSellBtn = app.query(".curr-sell-btn");
let totBalance = 0;
// coinVal = 0;
maxSell.addEventListener("click", () => {
app.getCookie("azer_token", (e, r) => {
maxSell.textContent = "loading...";
if (e) {
app.client
.fetch(`/user/wallet/${maxSell.dataset.coin}`, "POST", {
token: r,
})
.then((dx) => {
let coinerDataId = maxSell.dataset.id.toLowerCase();
totBalance = dx[coinerDataId].totalAvailableBalance;
coinVal = dx[coinerDataId].coinPrice;
console.log(totBalance);
})
.then(async () => {
maxSell.textContent = "MAX";
app.query("#amntInput").value = totBalance;
});
}
});
});
};
// handleMaxSell();
//SETTING GUIDE SECTION
const mainGuide = document.querySelector(".main-guide");
const mainGuideMain = document.querySelector(".main-guide-main");
const mainGuideClosed = document.querySelector(".main-guide-closed");
const guideCls = document.querySelector(".guideCls");
//SETTING THE BUY / SELL GUIDE SECTION
guideCls.addEventListener("click", () => {
resetGuide();
mainGuideClosed.classList.add("active");
});
mainGuideClosed.addEventListener("click", () => {
resetGuide();
mainGuideMain.classList.add("active");
});
function resetGuide() {
mainGuideMain.classList.remove("active");
mainGuideClosed.classList.remove("active");
}
//SETTING ADDRESS TYPE TO COLLECT
const btnAddrss = document.querySelector(".btn-adds-adss");
const btnAzer = document.querySelector(".btn-adds-azer");
const addAdds = document.querySelector(".add-adds");
const addAzer = document.querySelector(".add-azer");
const addInput = document.getElementById("addInput");
const addEmail = document.getElementById("addEmail");
btnAddrss.addEventListener("click", (e) => {
e.preventDefault();
resetAdds();
addAdds.classList.add("active");
btnAddrss.classList.add("active");
});
btnAzer.addEventListener("click", (e) => {
e.preventDefault();
resetAdds();
addAzer.classList.add("active");
btnAzer.classList.add("active");
});
const resetAdds = () => {
btnAzer.classList.remove("active");
btnAddrss.classList.remove("active");
addAdds.classList.remove("active");
addAzer.classList.remove("active");
addInput.value = "";
addEmail.value = "";
};
//HANDLING THE WITHDRAW FORM
const btmSecCover = app.query(".btm-select-sec-cover");
const topSelCov = app.query(".top-sel-sel-cover");
const ultimBtn = app.query(".ultimBtn");
const networkInt = app.query("#network");
const coinErr = app.query(".coin-err");
const addErr = app.query(".add-err");
const netwrkErr = app.query(".netwrk-err");
const amntErr = app.query(".amntErr");
const maxSell = app.query(".maxSell");
const confirmBtn = app.query(".confirmBtn");
const otpBtn = app.query(".otpBtn");
const conOtpSec = app.query(".conOtp-sec");
const sellComp = document.querySelector(".sell-comp");
const withdrawObj = {};
ultimBtn.addEventListener("click", async (e) => {
const ultimImg = app.query(".ultim-img").src;
const amntInput = app.query("#amntInput");
const selectedCoin = app.query(".top-sel-sel");
const address = addInput.value
? addInput.value
: addEmail.value
? addEmail.value
: null;
const addressType = addInput.value ? "Wallet Address" : "Azer Wallet";
const amountWithProfit = app.query(".mn-upper");
let validateVal = 0;
let coinVal = 0;
let coinArr = [];
e.preventDefault();
ultimBtn.innerHTML = "Processing...";
//Validate amount of coin is worth 10 dollar minimum
//Getting single coing object
const fetchedCoin = await getSingleCoin(selectedCoin.dataset.id);
for (const key of Object.keys(fetchedCoin)) {
coinArr.push({ key: key, ...fetchedCoin[key] });
}
coinArr.forEach((data) => {
coinVal = data.usd;
});
validateVal = (10 / Number(coinVal)).toFixed(8);
if (Number(amntInput.value) < validateVal) {
app.client.sweetAlertE(
"error",
`Minimum ${selectedCoin.dataset.id} to withdraw is ${validateVal} ~ $10`
);
ultimBtn.innerHTML = "Initiate Withdrawal";
return;
}
// END OF VALIDATING AMOUNT
app.getCookie("azer_token", (e, r) => {
if (e) {
app.client
.fetch(`/user/wallet/${maxSell.dataset.coin}`, "POST", { token: r })
.then((dx) => {
let coinerDataId = maxSell.dataset.id.toLowerCase();
if (amntInput.value > dx[coinerDataId].totalAvailableBalance) {
app.client.sweetAlertE(
"error",
"You do not have enough asset to complete transaction"
);
app.query(".ultimBtn").innerHTML = "Initiate Withdrawal";
return;
} else {
if (
networkInt.value &&
amntInput.value &&
(addInput.value || addEmail.value) &&
coinIntVal.value
) {
coinValUsd = 0;
coinValue = 0;
revCoinVal = 0;
let receive =
Number(amntInput.value) - 0.02 * Number(amntInput.value);
app.query(".sell-validate").classList.add("active");
app.query(
".sell-vald-bdy"
).innerHTML = `${app.loading()}`;
confirmBtn.disabled = true;
app.client
.fetch(`/user/wallet/${maxSell.dataset.coin}`, "POST", {
token: r,
})
.then(async (dx) => {
let coinerDataId = maxSell.dataset.id.toLowerCase();
coinValUsd = dx[coinerDataId].coinPrice;
//Getting single currency array
const fetchedCurrency = await getSingleCurrency("usd");
fetchedCurrency.forEach((data) => {
coinValue = data.buy_rate * coinValUsd;
revCoinVal = 1 / coinValue;
});
app.query(".sell-vald-bdy").innerHTML = `
Rate
1 ${
maxSell.dataset.coin
} = ${coinValue.toFixed()} USD
Inverse Rate
1
USD
= ${revCoinVal.toFixed(8)} ${
maxSell.dataset.coin
}
Payment Method
${addressType}
What is sent
${receive.toFixed(
8
)} ${maxSell.dataset.coin}
`;
confirmBtn.disabled = false;
})
.then(() => {
withdrawObj.coin = coinIntVal.value;
withdrawObj.receiver = addInput.value
? addInput.value
: addEmail.value
? addEmail.value
: null;
// withdrawObj.azerEmailToSendTo = addEmail.value
// ? addEmail.value
// : null;
withdrawObj.network = networkInt.value;
withdrawObj.mainunit = Number(amntInput.value);
withdrawObj.amountWithProfit = Number(receive);
withdrawObj.token = r;
//This is to remove every key where the value is null
// Object.keys(withdrawObj).forEach(
// (key) => withdrawObj[key] == null && delete withdrawObj[key]
// );
btmSecCover.innerHTML = "";
coinIntVal.value = "";
addEmail.value = "";
addInput.value = "";
amntInput.value = "";
networkInt.value = "";
});
app.query(".selVldCls").addEventListener("click", () => {
app.query(".sell-validate").classList.remove("active");
ultimBtn.innerHTML = "Initiate Withdrawal";
});
}
//Displaying all the error msgs
else if (coinIntVal.value == "") {
coinErr.classList.add("active");
setTimeout(() => coinErr.classList.remove("active"), 3000);
app.query(".ultimBtn").innerHTML = "Initiate Withdrawal";
} else if (amntInput.value == "") {
amntErr.classList.add("active");
setTimeout(() => amntErr.classList.remove("active"), 3000);
app.query(".ultimBtn").innerHTML = "Initiate Withdrawal";
} else if (addInput.value == "" && addEmail.value == "") {
resetAdds();
addErr.classList.add("active");
addAdds.classList.add("active");
btnAddrss.classList.add("active");
setTimeout(() => addErr.classList.remove("active"), 3000);
app.query(".ultimBtn").innerHTML = "Initiate Withdrawal";
} else if (networkInt.value == "") {
netwrkErr.classList.add("active");
setTimeout(() => netwrkErr.classList.remove("active"), 3000);
app.query(".ultimBtn").innerHTML = "Initiate Withdrawal";
}
}
});
}
});
});
// handling Confirm btn
confirmBtn.addEventListener("click", (e) => {
e.preventDefault();
app.query(".sell-validate-cnt").classList.remove("active");
conOtpSec.classList.add("active");
app.query(".otpBtn").style.backgroundColor = "#eee";
app.query(".otpBtn").disabled = true;
app.getCookie("azer_token", (e, r) => {
if (e) {
app.query(".azer_input").addEventListener("keyup", (e) => {
if (e.target.value.length === 6) {
let c = { code: e.target.value, token: r };
swal({
html: "Loading....",
padding: "2em",
onOpen: function () {
swal.showLoading();
},
}).then(function (result) {
result.dismiss;
});
app.client
.fetch("../../../user/bank/withdraw/auth/verify", "POST", c)
.then((e) => {
if (e.isSuccess) {
app.client
.fetch("../../../user/crypto/withdraw", "POST", withdrawObj)
.then((e) => {
if (e.isSuccess) {
app.query(".otpBtn").style.backgroundColor = "#4361ee";
app.query(".otpBtn").disabled = false;
swal.close();
conOtpSec.classList.remove("active");
sellComp.classList.add("active");
app.query(".conttt").addEventListener("click", () => {
window.location.reload();
});
}
});
} else {
swal.close();
app.query(".otp_handler").innerHTML = e.message;
// app.client.sweetAlertE(e.icon, e.message, e.title);
}
});
}
});
const Auth = () => {
app.query(".auth_resend").classList.remove(".auth_key");
app.query(".auth_resend").innerHTML = "Sending....";
app.client
.fetch("../../user/crypto/withdraw/auth", "POST", { token: r })
.then((e) => {
if (e.isSuccess) {
var timeleft = 15;
var downloadTimer = setInterval(function () {
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById("auth_resend").innerHTML =
"Request again";
app.query(".auth_resend").classList.add(".auth_key");
} else {
app.query(".auth_resend").classList.remove(".auth_key");
document.getElementById(
"auth_resend"
).innerHTML = ` Sent (${timeleft})`;
}
timeleft -= 1;
}, 1000);
} else {
app.client.sweetAlertE(e.icon, e.message, e.title);
}
});
};
Auth();
app.query(".auth_key").addEventListener("click", Auth);
}
});
});
//handling OTP btn
otpBtn.addEventListener("click", (e) => {
e.preventDefault();
conOtpSec.classList.remove("active");
sellComp.classList.add("active");
const getCurrHandler = async () => {
let withdrawableBalance = 0;
let activeCurrencyTotalBalance = 0;
app.getCookie("azer_token", (e, r) => {
if (e) {
app.query(".confirm-bdy").innerHTML = app.loading();
app.client
.fetch("/user/wallet/fiat", "POST", { token: r })
.then((dx) => {
withdrawableBalance = dx.AvailableBalance;
})
.then(async () => {
const fetchedCurrency = await getSingleCurrency(globalNewCoinId);
fetchedCurrency.forEach((data) => {
activeCurrency = data.buy_rate;
});
activeCurrencyTotalBalance = (
withdrawableBalance * activeCurrency
).toLocaleString();
})
.then(() => {
if (Number(activeCurrencyTotalBalance) < Number(validInput)) return;
if (!isNewAccountCreated) {
//Checking empty inputs
if (amntInput.value == "") {
Empterr.classList.add("active");
window.setTimeout(
() => Empterr.classList.remove("active"),
2000
);
} else if (
Number(amntInput.value) > 10000000 ||
Number(amntInput.value) < 1000
) {
amntErr.classList.add("active");
window.setTimeout(
() => amntErr.classList.remove("active"),
2000
);
return;
} else {
//Setting the object with default bank
withdrawObject.bank = newBankDet.children[0].innerHTML;
withdrawObject.accountNumber = acctNum.innerHTML;
withdrawObject.totAmount = validInput;
}
}
if (isNewAccountCreated) {
if (
Number(amntInput.value) > 10000000 ||
Number(amntInput.value) < 1000
) {
amntErr.classList.add("active");
window.setTimeout(
() => amntErr.classList.remove("active"),
2000
);
return;
} else if (!newShwDet.dataset.id) {
bnkSelerr.classList.add("active");
window.setTimeout(
() => bnkSelerr.classList.remove("active"),
2000
);
return;
} else if (newAccInput.value == "") {
newAccerr.classList.add("active");
window.setTimeout(
() => newAccerr.classList.remove("active"),
2000
);
return;
} else {
//Setting the object with new account bank
withdrawObject.bank = newShwDet.dataset.id;
withdrawObject.accountNumber = app.query("#newAccInt").value;
withdrawObject.totAmount = validInput;
app.getCookie("azer_token", (e, r) => {
let name = "";
let country = "";
let currency = "";
let keychain = "";
app.client
.fetch("../../api/token", "POST", { token: r })
.then((x) => {
name = `${x.first_name} ${x.last_name}`;
country = x.country;
currency = "ngn";
})
.then(() => {
const dataObj = {
country: country,
currency: currency,
bankName: newShwDet.dataset.id,
accountNumber: Number(app.query("#newAccInt").value),
accountName: name,
token: r,
};
console.log(dataObj);
app.client.fetch("../../user/bank/add", "POST", dataObj);
// .then((x) => {
// if (x.isSuccess) {
// app.client.toastS(
// x.icon,
// x.message,
// "../wallet/withdraw_fiat"
// );
// } else {
// app.client.toastE(x.icon, x.message);
// }
// });
})
.then(() => {
app.client
.fetch("../../user/bank/get", "POST", { token: r })
.then((x) => {
if (x.isSuccess) {
x.result.sort((a, b) => b.bank_id - a.bank_id);
x.result.forEach((e) => {
if (
Number(app.query("#newAccInt").value) ==
Number(e.bank_account)
) {
keychain = e.keychain;
}
});
} else {
app.client.sweetAlertE(x.icon, x.message, x.title);
}
})
.then(() => {
if (setDefault.checked) {
const dataObj = {
keychain: keychain,
token: r,
};
app.client.fetch(
"../../user/bank/set_default",
"POST",
dataObj
);
}
});
});
});
}
}
});
}
});
};
getCurrHandler();
});
app.query(".closeOtp").addEventListener("click", () => {
app.query(".sell-validate").classList.remove("active");
app.query(".conOtp-sec").classList.remove("active");
ultimBtn.innerHTML = "Initiate Withdrawal";
});