Skip to content

Commit

Permalink
08.06.2024 исправил работу с настройками сетей блокчейн. Теперь всё б… (
Browse files Browse the repository at this point in the history
#178)

* 08.06.2024 исправил работу с настройками сетей блокчейн. Теперь всё берётся из коллекции chain_configs. Из env файла берётся только названия сети. Для Tron это поле TRON_CHAIN, для Ethereum - CHAIN. В коллекции chain_configs соответствующий документ должен иметь в качестве _id название нужной сети.

* 10.06.2024 решение проблемы со слишком частым обращением к API серверу Tron.

* 11.06.2024 исправление ошибок и внесение исправлений. Внёс следующие исправления. При получении информации о транзакциив Tron использую setTimeout. В случае ошибки запаминания записи о донатах в базе данных сведения об этом отсылаются на емайл администратора. За это отвечает документ с _id - "Donations not preserved in the database" в коллекции global_configs.
  • Loading branch information
jakogri authored Jun 15, 2024
1 parent d550a15 commit dba635e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 21 deletions.
15 changes: 10 additions & 5 deletions server/serverLib.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,8 @@ class ServerLib {
if (key === "HEO-Platform Confirmation Code") to_email = req.body.mydata.to_email;
else if (key === "New Campaign Alert") to_email = result.to;
else if (key === "Failed to delete picture") to_email = result.to;
else if (key === "Donations not preserved in the database") to_email = result.to;
else to_email = result.to;
await transporter.sendMail({
from: result.from, // sender address
to: to_email, // list of receivers
Expand Down Expand Up @@ -168,10 +170,9 @@ class ServerLib {
try {
const myCollection = await DB.collection('donations');
await myCollection.insertOne(ITEM);
await this.handleUpdateCampaignWallet(req, res, Sentry, DB);
res.send('success');
} catch (err) {
console.log(err);
console.log("err- ", err);
Sentry.captureException(new Error(err));
res.sendStatus(500);
}
Expand Down Expand Up @@ -299,9 +300,10 @@ class ServerLib {
try{
let pipeline = [
{$lookup: {from :"campaign_wallet", localField: "_id", foreignField: "campaign_id", as : "wallet"}},
{$lookup: {from :"donations", localField: "_id", foreignField: "campaignID", as : "donates"}},
{$match: {$or:[{successful:false },{successful:{$exists : false}}],
$or:[{deleted:{ $exists : false}}, {deleted:false}],"wallet":{ $ne : []},"active":true, complete:true}},
{$set: {wallet: {$arrayElemAt: ["$wallet.addres_base58",0]},donate_count:{$sum:{$arrayElemAt: ["$wallet.donate_count",0]}}}},
{$set: {wallet: {$arrayElemAt: ["$wallet.addres_base58",0]},donate_count:{$sum:{$arrayElemAt: ["$donates.raisedAmount",0]}}}},
{$sort: {donate_count: -1, raisedOnCoinbase: -1, _id: 1}},
{ $skip : req.body.startRec},
{ $limit: req.body.compaignsCount}
Expand Down Expand Up @@ -439,18 +441,21 @@ class ServerLib {
try {
const myCollection = await DB.collection('campaigns');
const walletColection = await DB.collection('campaign_wallet');
const configCollection = await DB.collection('chain_configs');
let config_tron = await configCollection.findOne({"_id" : process.env.TRON_CHAIN.toString()});
let config_eth = await configCollection.findOne({"_id" : process.env.CHAIN.toString()});
let result = await myCollection.findOne({"_id" : req.body.ID });
let donate = await DB.collection('donations').find({campaignID: req.body.ID}).toArray();
let campaign_wallets = await walletColection.find({"campaign_id" : req.body.ID}).
project({_id:0,wallet_ort:1,addres_base58:1,addres_hex:1,coin_name:1}).toArray();
for(let i=0; i<campaign_wallets.length; i++) {
if(campaign_wallets[i].wallet_ort === 'Tron') {
campaign_wallets[i].chainId = process.env.TRON_CHAIN.toString();
campaign_wallets[i].coin_addres = process.env.TRON_TOKEN_ADRES.toString();
campaign_wallets[i].coin_addres = config_tron.currencyOptions.value;
}
else if(campaign_wallets[i].wallet_ort === 'Etherium') {
campaign_wallets[i].chainId = process.env.CHAIN.toString();
campaign_wallets[i].coin_addres = process.env.TOKEN_ADRES.toString();
campaign_wallets[i].coin_addres = config_eth.currencyOptions.value;
}
else campaign_wallets[i].chainId = "";
}
Expand Down
26 changes: 19 additions & 7 deletions src/components/CampaignPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,8 @@ class CampaignPage extends Component {
coinAddress: coinAddress
};
}
await axios.post('/api/donate/adddanate', {mydata: donateData}, {headers: {"Content-Type": "application/json"}});
let res = await axios.post('/api/donate/adddanate', {mydata: donateData}, {headers: {"Content-Type": "application/json"}});
//if (res.data === "success")
this.setState({showModal:true, goHome: true,
modalMessage: 'thankYouDonation',
modalTitle: 'complete',
Expand All @@ -363,25 +364,35 @@ class CampaignPage extends Component {
modalButtonVariant: "#588157", waitToClose: false
});
this.setState({raisedAmount: this.state.raisedAmount + this.state.donationAmount});
if (res.data !== "success"){
let dataEmail ={key: 'Donations not preserved in the database', text:`Donation options: campaignID - ${this.state.campaignId};
blockChainOrt - ${this.blockChainOrt}; raisedAmount - ${this.state.donationAmount}; tipAmount - ${this.state.tipAmount};
transactionHash - ${transactionHash}; chainId - ${chainId}; coinAddress - ${coinAddress};donatorID - ${donateData.donatorID}`}
axios.post('/api/sendemail', dataEmail, {headers: {"Content-Type": "application/json"}});
}
}

handleDonateClick = async(wallet_ort, addres_base58, addres_hex, coin_addres, chain_name) =>{
handleDonateClick = async(wallet_ort, addres_base58, addres_hex, coin_addres, chain_name, coin_name) =>{
if(wallet_ort === "Ethereum"){
this.blockChainOrt = "ethereum";
//if (this.state.campaign.new === false) await this.handleDonateOld(chain_name, addres_hex);
await this.handleDonateNew(chain_name, addres_hex);
}
else if(wallet_ort === "Tron"){
this.blockChainOrt = "tron";
await this.handleDonateTron(chain_name, addres_base58, coin_addres);
await this.handleDonateTron(chain_name, addres_base58, coin_addres, coin_name);
}
}

handleDonateTron = async (chainId, addres_base58, coinAddress) =>{
Sleep = async(time) => {
return new Promise(resolve => setTimeout(resolve, time));
}

handleDonateTron = async (chainId, addres_base58, coinAddress, coin_name) =>{
try{
await clearTronProvider();
await initTronadapter();
await initTron(chainId);
await initTron(chainId, coin_name);
var toDonate = window.tronWeb.toSun(this.state.totalAmount);
var coinInstance = await window.tronWeb.contract(tron_abi, coinAddress);
ReactGA.event({
Expand Down Expand Up @@ -417,10 +428,11 @@ class CampaignPage extends Component {
let m = 1;
do{
console.log("Waiting for transaction record");
txnObject = await window.tronWeb.trx.getTransactionInfo(result);
txnObject = await window.tronWeb.trx.getUnconfirmedTransactionInfo(result);
if(txnObject){
if (txnObject.receipt) break;
}
await this.Sleep(1000);
}while(m !== 2);
if (txnObject.receipt.result === "SUCCESS"){
this.setState({
Expand Down Expand Up @@ -1132,7 +1144,7 @@ class CampaignPage extends Component {
}><img src={visaMcLogo} width={17} height={16} alt='some value' style={{marginRight:5}} />USD</Dropdown.Item> }
{this.state.campaign_wallets.map((item, i) =>
<Dropdown.Item key={item.wallet_ort} as="button" onClick={() =>
this.handleDonateClick(item.wallet_ort, item.addres_base58, item.addres_hex,item.coin_addres,item.chainId)}>
this.handleDonateClick(item.wallet_ort, item.addres_base58, item.addres_hex,item.coin_addres,item.chainId,item.coin_name)}>
<img src={IMG_MAP[item.coin_name]} width={16} height={16} alt='some value' style={{marginRight:5}} />{item.coin_name}
</Dropdown.Item>
)}
Expand Down
14 changes: 5 additions & 9 deletions src/util/Utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ const getTronWeb = async () => {
return tronWeb;
}

const initTron = async (chainId) => {
const initTron = async (chainId, coin_name) => {
if(!window.tronWeb)
{
window.tronWeb = await getTronWeb();
Expand All @@ -172,15 +172,11 @@ const initTron = async (chainId) => {
await initTronadapter();
}
await window.tronAdapter.connect();
let chainConfig = config.get("CHAINS")[chainId];
if(!chainConfig) {
throw new Error(`Unsupported blockchain: ${chainId}`);
}
try {
ReactGA.event({
category: "provider",
action: "switching_network",
label: chainConfig["CHAIN_NAME"],
label: coin_name,
nonInteraction: false
});

Expand All @@ -191,17 +187,17 @@ const initTron = async (chainId) => {
ReactGA.event({
category: "provider",
action: "adding_network",
label: chainConfig["CHAIN_NAME"],
label: coin_name,
nonInteraction: false
});

} catch (addError) {
console.log(`Failed to add provider for ${chainId} and ${chainConfig["WEB3_RPC_NODE_URL"]}`)
console.log(`Failed to add provider for ${chainId} and ${coin_name}`)
console.log(addError);
ReactGA.event({
category: "provider",
action: "failed_to_add_provider",
label: chainConfig["CHAIN_NAME"],
label: coin_name,
nonInteraction: false
});
}
Expand Down

0 comments on commit dba635e

Please sign in to comment.