Viewing File: /home/ubuntu/misabloom-frontend-base/src/components/Cart/NewCheckoutWalletButton.jsx
import React, { useContext, useEffect, useState } from 'react';
import { Image, Button } from 'react-bootstrap';
import { ethers } from 'ethers';
import Token from "../../abis/Token.json";
import { authContext } from "../Auth/AuthProvider";
import Web3 from "web3";
import { getErrorNotificationMessage } from '../Helper/ToastNotification';
import configuration from "react-global-configuration";
import { connect } from 'react-redux';
import NftToken from "../../abis/Token.json";
import { ordersCheckoutStart } from '../store/actions/OrdersAction';
import { useNavigate } from 'react-router-dom';
const NewCheckoutWalletButton = (props) => {
const { auth } = useContext(authContext);
const navigate = useNavigate();
const [token, setToken] = useState("");
const [skipRender, setSkipRender] = useState(true);
const [checkoutBtn, setCheckoutBtn] = useState({
loading: false,
content: "",
})
useEffect(() => {
if (!skipRender && !props.ordersCheckout.loading && Object.keys(props.ordersCheckout.data).length > 0) {
localStorage.removeItem("addessUniqueId");
navigate("/order-placed");
}
setSkipRender(false);
}, [props.ordersCheckout]);
// setCheckoutBtn({
// ...checkoutBtn,
// loading: false,
// content: "",
// })
const web3 = new Web3(window.ethereum);
const onFormSubmit = async () => {
if (auth.BUSDXTokenData) {
setCheckoutBtn({
...checkoutBtn,
loading: true,
content: "Loading..",
})
const token = new web3.eth.Contract(Token.abi, "0xA72Eb0986c2AEACFD9A8CDcD7440579869751CFE");
setToken(token);
// Decimal
const decimals = web3.utils.toBN(18);
let allowed_tokens = props.cartFinalAmount;
// Amount of token
const tokenAmount = web3.utils.toBN(allowed_tokens);
// Amount as Hex - contract.methods.transfer(toAddress, tokenAmountHex).encodeABI();
const tokenAmountHex =
"0x" + tokenAmount.mul(web3.utils.toBN(10).pow(decimals)).toString("hex");
await token.methods
.approve(auth.accounts, tokenAmountHex)
.send({ from: auth.accounts })
.on("transactionHash", (hash) => {
console.log("Approve hash", hash);
const adminWalletAddress = "0x9a8Df595Af38106365B6e833152DdF6ED77A1BE1";
token.methods
.transferFrom(
auth.accounts,
// "0x6F73C4C39f31408Eec80AE3182bA0aCbCE4565BA", // Admin wallet address
adminWalletAddress, // Admin wallet address
tokenAmountHex
)
.send({
from: auth.accounts,
})
.on("error", (error) => {
let notificationMessage;
if (error.message == undefined) {
notificationMessage = getErrorNotificationMessage(
"transaction failed. Please try again. "
);
} else {
notificationMessage = getErrorNotificationMessage(
error.message
);
}
setCheckoutBtn({
...checkoutBtn,
loading: false,
content: "",
})
})
.once("receipt", (receipt) => {
console.log("Loading the transaction....", hash);
props.dispatch(ordersCheckoutStart({
payment_mode: "CRYPTO",
wallet_address: auth.accounts,
transaction_hash: receipt.transactionHash,
currency: "PSCN",
delivery_address_id: props.deliveryAddressId,
}));
});
//console.log()
}).on("error", (error) => {
let notificationMessage;
if (error.message == undefined) {
notificationMessage = getErrorNotificationMessage(
"transaction failed. Please try again. "
);
} else {
notificationMessage = getErrorNotificationMessage(
error.message
);
}
setCheckoutBtn({
...checkoutBtn,
loading: false,
content: "",
})
console.log("Error", error);
});
} else {
window.alert("Token contract not deployed to detected network.");
}
// const web3 = window.web3;
// let nftContractData;
// const NFTData = NftToken.networks[97];
// let sellerContract;
// if (NFTData) {
// nftContractData = await new web3.eth.Contract(
// NftToken.abi,
// contract_address
// );
// sellerContract = await new web3.eth.Contract(
// SellerContract.abi,
// configuration.get("configData.seller_contract_address")
// );
// setSellerContract(sellerContract);
// setNftContractData(nftContractData);
// } else {
// window.alert("NFT contract not deployed to detected network.");
// }
// let USDVToken = new web3.eth.Contract(
// Token.abi,
// "0xcD7509b76281223f5B7d3aD5d47F8D7Aa5C2B9bf"
// );
// let amount = "50";
// const stableTokenAmount = amount.toString();
// let stable_token_amount = window.web3.utils.toWei(stableTokenAmount, "Ether");
// USDVToken.methods
// .approve(
// // configuration.get("configData.seller_contract_address"),
// "0xcBD25127B97D1F170b5efFa36A7894FCbf43314D",
// stable_token_amount
// )
// .send({ from: auth.accounts })
// .on("receipt", (receipt) => {
// sellerContract.methods
// .purchase(token_id, contract_address, stable_token_amount)
// .send({
// from: auth.accounts,
// value: 0,
// })
// .on("receipt", (receipt) => {
// console.log("Trans", receipt);
// // props.dispatch(
// // buyNftItemStart({
// // nft_collection_item_unique_id:
// // nft_collection_item_unique_id,
// // transaction_hash:
// // receipt && receipt.transactionHash
// // ? receipt.transactionHash
// // : "",
// // contract_address: contract_address,
// // price_type: configuration.get("configData.stable_toke_symbol"),
// // })
// // );
// })
// .on("error", (error) => {
// // setButtonContent("");
// console.log("Error", error);
// });
// })
// .on("error", (error) => {
// // setButtonContent("");
// console.log("Error", error);
// if (error.message == undefined) {
// props.dispatch(getErrorNotificationMessage(
// "Unexpected error occuried, Please try again..."
// ));
// } else {
// props.dispatch(getErrorNotificationMessage(error.message));
// }
// // Send error notification.
// });
}
return (
<div className="payment-radio-btn label-bg dropdown-wallet mt-3">
<label
name="plan"
className="payment-add-money-wallet"
>
<p>
<Image
src={
window.location.origin + "/images/wallet.svg"
}
type="image/png"
/>
{auth.accounts && <span>
{auth.accounts.substr(0, 6)}
...
{auth.accounts.substr(auth.accounts.length - 4)}
</span>
}
</p>
<p>{`${auth.BUSDXTokenBalance} PSCN`}</p>
<Button
className="address-button"
disabled={auth.BUSDXTokenBalance < props.cartFinalAmount || checkoutBtn.loading}
onClick={() => onFormSubmit()}
>
{checkoutBtn.content == "" ? "Checkout" : checkoutBtn.content}
</Button>
</label>
</div>
);
}
const mapStateToPros = (state) => ({
ordersCheckout: state.orders.ordersCheckout,
});
function mapDispatchToProps(dispatch) {
return { dispatch };
}
export default connect(
mapStateToPros,
mapDispatchToProps
)(NewCheckoutWalletButton);
Back to Directory
File Manager