react-share#TelegramShareButton JavaScript Examples

The following examples show how to use react-share#TelegramShareButton. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ShareButtons.jsx    From koronawirus.lol with GNU Affero General Public License v3.0 6 votes vote down vote up
ShareButtons = ({ }) => (
    <>
        <ShareButtonContainer>
            <FacebookShareButton url={url}>
                <FacebookIcon size={32} round />
            </FacebookShareButton>
            <button className="react-share__ShareButton" style={{ background: 'white', border: 0, margin: 0, paddingLeft: 0 }} onClick={() => {
                window.location.href = `fb-messenger://share?link=${url}`
            }}>
                <FacebookMessengerIcon size={32} round />
            </button>
            <TwitterShareButton url={url}>
                <TwitterIcon size={32} round />
            </TwitterShareButton>
            <TelegramShareButton url={url}>
                <TelegramIcon size={32} round />
            </TelegramShareButton>
            <LinkedinShareButton url={url}>
                <LinkedinIcon size={32} round />
            </LinkedinShareButton>
        </ShareButtonContainer>
    </>
)
Example #2
Source File: ShareButtons.jsx    From Corona-tracker with MIT License 6 votes vote down vote up
ShareButtons = () => {
  const url = 'https://coronatracker.squarespace.com';

  return (
    <>
      <FacebookShareButton url={url}>
        <FacebookIcon size={32} round />
      </FacebookShareButton>
      <LinkedinShareButton url={url}>
        <LinkedinIcon size={32} round />
      </LinkedinShareButton>
      <TwitterShareButton url={url}>
        <TwitterIcon size={32} round />
      </TwitterShareButton>
      <RedditShareButton url={url}>
        <RedditIcon size={32} round />
      </RedditShareButton>
      <TelegramShareButton url={url}>
        <TelegramIcon size={32} round />
      </TelegramShareButton>
    </>
  );
}
Example #3
Source File: ShareComponent.js    From paras-landing with GNU General Public License v3.0 6 votes vote down vote up
ShareComponent = ({ title, shareUrl }) => {
	const { localeLn } = useIntl()
	return (
		<div className="flex items-center space-x-2 justify-between">
			<div className="text-white text-sm opacity-80 pr-4">{localeLn('ShareNow')}</div>
			<div className="flex space-x-3">
				<FacebookShareButton
					url={shareUrl}
					quote={title}
					className="Demo__some-network__share-button"
				>
					<FacebookIcon size={24} round />
				</FacebookShareButton>

				<TwitterShareButton
					url={shareUrl}
					title={title}
					className="Demo__some-network__share-button"
				>
					<TwitterIcon size={24} round />
				</TwitterShareButton>
				<TelegramShareButton
					url={shareUrl}
					title={title}
					className="Demo__some-network__share-button"
				>
					<TelegramIcon size={24} round />
				</TelegramShareButton>
			</div>
		</div>
	)
}
Example #4
Source File: TokenShareModal.js    From paras-landing with GNU General Public License v3.0 6 votes vote down vote up
Share = ({ show, onClose, tokenData }) => {
	const ShareList = [
		{
			name: (
				<FacebookShareButton url={window.location.href} className="flex text-white">
					<FacebookIcon size={24} round />
					<p className="ml-3">Facebook</p>
				</FacebookShareButton>
			),
			onClick: () => {},
		},
		{
			name: (
				<TwitterShareButton
					title={`Checkout ${tokenData.metadata.title} from collection ${tokenData.metadata.collection} on @ParasHQ\n\n#paras #cryptoart #digitalart #tradingcards`}
					url={window.location.href}
					className="flex text-white"
				>
					<TwitterIcon size={24} round />
					<p className="ml-3">Twitter</p>
				</TwitterShareButton>
			),
			onClick: () => {},
		},
		{
			name: (
				<TelegramShareButton url={window.location.href} className="flex text-white">
					<TelegramIcon size={24} round />
					<p className="ml-3">Telegram</p>
				</TelegramShareButton>
			),
			onClick: () => {},
		},
	]

	return <ListModal show={show} onClose={onClose} list={ShareList} />
}
Example #5
Source File: ShareModal.js    From mern-social-media with MIT License 5 votes vote down vote up
ShareModal = ({ url, theme, setIsShare }) => {
  return (
    <div className="share_modal">
      <div className="share_modal-container">
        <div className="share_modal-header">
          <span>Share to...</span>
          <span onClick={() => setIsShare(false)}>&times;</span>
        </div>
        <div
          className=" share_modal-body"
          style={{ filter: theme ? "invert(1)" : "invert(0)" }}
        >
          <FacebookShareButton url={url}>
            <FacebookIcon round={true} size={32} />
          </FacebookShareButton>

          <TwitterShareButton url={url}>
            <TwitterIcon round={true} size={32} />
          </TwitterShareButton>

          <EmailShareButton url={url}>
            <EmailIcon round={true} size={32} />
          </EmailShareButton>

          <TelegramShareButton url={url}>
            <TelegramIcon round={true} size={32} />
          </TelegramShareButton>

          <WhatsappShareButton url={url}>
            <WhatsappIcon round={true} size={32} />
          </WhatsappShareButton>

          <PinterestShareButton url={url}>
            <PinterestIcon round={true} size={32} />
          </PinterestShareButton>

          <RedditShareButton url={url}>
            <RedditIcon round={true} size={32} />
          </RedditShareButton>

          <LinkedinShareButton url={url}>
            <LineIcon round={true} size={32} />
          </LinkedinShareButton>
        </div>
      </div>
    </div>
  );
}
Example #6
Source File: ShareModal.js    From gophie-web with MIT License 4 votes vote down vote up
ShareModal = (props) => {
  const [btnCopyText, setBtnCopyText] = useState(copy.defaultText);
  const [isUrlCopied, setUrlCopied] = useState(false);

  const copyURLToClipboard = () => {
    setUrlCopied(true);
  };

  useEffect(() => {
    if (isUrlCopied === true) {
      setBtnCopyText(copy.copiedText);

      setTimeout(() => {
        setBtnCopyText(copy.defaultText);
        setUrlCopied(false);
      }, 2000);
    }
  }, [isUrlCopied])

  const { movie } = props;
  let url = "";
  // console.log(movie.referral_id);
  if (window.location.hostname === "localhost") {
    url = `localhost:${window.location.port}/shared/${movie.referral_id}`;
  } else {
    url = `https://gophie.cam/shared/${movie.referral_id}`;
  }

  return (
    <>
      <Modal
        show={props.display}
        onHide={props.onHide}
        className="share-card"
        centered
        aria-labelledby="contained-modal-title-vcenter"
      >
        <Modal.Header closeButton>
          <Modal.Title>Share Movie</Modal.Title>
        </Modal.Header>
        <Modal.Body className="show-grid mt-5">
          <Container>
            <Row className="justify-content-between">
              <FacebookShareButton
                url={url}
                quote={movie.name}
                className="mb-2 mr-3"
              >
                <FacebookIcon size={50} round={true} />
              </FacebookShareButton>

              <TwitterShareButton
                url={url}
                title={movie.name}
                className="mb-2 mr-3"
              >
                <TwitterIcon size={50} round={true} />
              </TwitterShareButton>

              <WhatsappShareButton
                url={url}
                title={movie.name}
                className="mb-2 mr-3"
              >
                <WhatsappIcon size={50} round={true} />
              </WhatsappShareButton>

              <TelegramShareButton
                url={url}
                title={movie.name}
                className="mb-2 mr-3"
              >
                <TelegramIcon size={50} round={true} />
              </TelegramShareButton>

              <RedditShareButton url={url} title={movie.name} className="mb-2">
                <RedditIcon size={50} round={true} />
              </RedditShareButton>
            </Row>
            <Row className="justify-content-center mt-3 eoErth">
              <CopyToClipboard text={url}
                onCopy={() => copyURLToClipboard(true)}>
                <button
                  className={isUrlCopied ? copy.copiedClass : copy.defaultClass}
                  onClick={copyURLToClipboard}
                  type="button"
                >
                  {btnCopyText}
                </button>
              </CopyToClipboard>
            </Row>
          </Container>
        </Modal.Body>
      </Modal>
    </>
  );
}
Example #7
Source File: SuccessTransactionModal.js    From paras-landing with GNU General Public License v3.0 4 votes vote down vote up
SuccessTransactionModal = () => {
	const [showModal, setShowModal] = useState(false)
	const [token, setToken] = useState(null)
	const [txDetail, setTxDetail] = useState(null)
	const { currentUser, transactionRes, setTransactionRes } = useStore()
	const router = useRouter()
	const toast = useToast()

	useEffect(() => {
		const checkTxStatus = async () => {
			const txHash = router.query.transactionHashes.split(',')
			const txStatus = await near.getTransactionStatus({
				accountId: near.currentUser.accountId,
				txHash: txHash[txHash.length - 1],
			})
			if (window.sessionStorage.getItem('categoryToken')) {
				await submitCategoryCard(txStatus)
			}
			await processTransaction(txStatus)
		}

		if (currentUser && router.query.transactionHashes) {
			checkTxStatus()
		}
	}, [currentUser, router.query.transactionHashes])

	useEffect(() => {
		if (transactionRes) {
			const txLast = transactionRes[transactionRes.length - 1]
			if (txLast) {
				processTransaction(txLast)
			} else if (transactionRes.error) {
				processTransactionError(transactionRes.error.kind.ExecutionError)
			}
		}
	}, [transactionRes])

	const processTransactionError = (err) => {
		toast.show({
			text: <div className="font-semibold text-center text-sm">{err}</div>,
			type: 'error',
			duration: null,
		})
	}

	const processTransaction = async (txStatus) => {
		if (txStatus?.status?.SuccessValue !== undefined) {
			const { receipts_outcome } = txStatus
			const { actions, receiver_id } = txStatus.transaction

			for (const action of actions) {
				const { FunctionCall } = action
				const args = JSON.parse(decodeBase64(FunctionCall.args))

				if (FunctionCall.method_name === 'nft_buy') {
					const res = await axios.get(`${process.env.V2_API_URL}/token-series`, {
						params: {
							contract_id: receiver_id,
							token_series_id: args.token_series_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'buy') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'add_offer') {
					const res = await axios.get(
						`${process.env.V2_API_URL}/${args.token_id ? 'token' : 'token-series'}`,
						{
							params: {
								contract_id: args.nft_contract_id,
								token_id: args.token_id,
								token_series_id: args.token_series_id,
							},
						}
					)
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'add_bid') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'cancel_bid') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'accept_bid') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'cancel_auction') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'nft_set_series_price') {
					const res = await axios.get(`${process.env.V2_API_URL}/token-series`, {
						params: {
							contract_id: receiver_id,
							token_series_id: args.token_series_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'nft_approve') {
					const msgParse = JSON.parse(args?.msg)
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id:
								msgParse.market_type === 'accept_trade' ||
								msgParse.market_type === 'accept_trade_paras_series'
									? msgParse?.buyer_nft_contract_id
									: receiver_id,
							token_id:
								msgParse?.market_type === 'accept_trade' ||
								msgParse?.market_type === 'accept_trade_paras_series'
									? msgParse?.buyer_token_id
									: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'delete_market_data') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'nft_create_series') {
					const logs = JSON.parse(receipts_outcome[0].outcome?.logs?.[0])
					const res = await axios.get(`${process.env.V2_API_URL}/token-series`, {
						params: {
							contract_id: receiver_id,
							token_series_id: logs.params.token_series_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args, logs })
					setShowModal(true)
				}
			}
		}
	}

	const onCloseModal = () => {
		const key = `${token.contract_id}::${token.token_series_id}${
			token.token_id ? `/${token.token_id}` : ''
		}`
		mutate(key)
		setShowModal(false)
		setToken(null)
		if (WalletHelper.activeWallet === walletType.sender) {
			setTransactionRes(null)
		} else {
			removeTxHash()
		}
	}

	const removeTxHash = () => {
		const query = router.query
		delete query.transactionHashes
		router.replace({ pathname: router.pathname, query }, undefined, { shallow: true })
	}

	const submitCategoryCard = async (res) => {
		const _categoryId = window.sessionStorage.getItem(`categoryToken`)
		const txLast = res
		const resFromTxLast = txLast.receipts_outcome[0].outcome.logs[0]
		const resOutcome = await JSON.parse(`${resFromTxLast}`)
		await retry(
			async () => {
				const res = await axios.post(
					`${process.env.V2_API_URL}/categories/tokens`,
					{
						account_id: currentUser,
						contract_id: txLast?.transaction?.receiver_id,
						token_series_id: resOutcome?.params?.token_series_id,
						category_id: _categoryId,
						storeToSheet: _categoryId === 'art-competition' ? `true` : `false`,
					},
					{
						headers: {
							authorization: await WalletHelper.authToken(),
						},
					}
				)
				if (res.status === 403 || res.status === 400) {
					sentryCaptureException(res.data?.message || `Token series still haven't exist`)
					return
				}
				window.sessionStorage.removeItem('categoryToken')
			},
			{
				retries: 20,
				factor: 2,
			}
		)
	}

	if (!showModal || !token) return null

	const tokenUrl = `${window.location.hostname}/token/${token.contract_id}::${
		token.token_series_id
	}${token.token_id ? `/${token.token_id}` : ''}`

	const explorerUrl = (txhash) =>
		getConfig(process.env.APP_ENV || 'development').explorerUrl + '/transactions/' + txhash

	const onClickSeeToken = () => {
		const url = `/token/${token.contract_id}::${token.token_series_id}${
			token.token_id ? `/${token.token_id}` : ''
		}${txDetail.method_name === 'add_offer' ? '?tab=offers' : ''}`
		router.push(url)
		onCloseModal()
	}

	const titleText = () => {
		if (txDetail.method_name === 'add_offer') {
			return 'Offer Success'
		} else if (txDetail.method_name === 'add_bid') {
			return 'Place Bid Success'
		} else if (txDetail.method_name === 'cancel_bid') {
			return 'Success Remove Bid'
		} else if (txDetail.method_name === 'accept_bid') {
			return 'Accept Bid Success'
		} else if (txDetail.method_name === 'nft_buy' || txDetail.method_name === 'buy') {
			return 'Purchase Success'
		} else if (txDetail.method_name === 'nft_set_series_price') {
			return 'Update Price Success'
		} else if (txDetail.method_name === 'nft_approve') {
			const msg = JSON.parse(txDetail.args.msg)
			if (msg.market_type === 'sale' && !msg.is_auction) {
				return 'Update Listing Success'
			} else if (msg.market_type === 'accept_offer') {
				return 'Accept Offer Success'
			} else if (msg.market_type === 'add_trade') {
				return 'Add Trade Success'
			} else if (msg.is_auction) {
				return 'Create Auction Success'
			} else if (
				msg.market_type === 'accept_trade' ||
				msg.market_type === 'accept_trade_paras_series'
			) {
				return 'Accept Trade Success'
			}
		} else if (txDetail.method_name === 'delete_market_data') {
			const args = txDetail.args
			if (args.is_auction) {
				return 'Remove Auction Success'
			}
			return 'Remove Listing Success'
		} else if (txDetail.method_name === 'nft_create_series') {
			return 'Create Card Success'
		} else {
			return 'Transaction Success'
		}
	}

	const descText = () => {
		if (txDetail.method_name === 'add_offer') {
			return (
				<>
					You successfully offer <b>{token.metadata.title}</b> for{' '}
					{formatNearAmount(txDetail.args.price)} Ⓝ
				</>
			)
		} else if (txDetail.method_name === 'add_bid') {
			return (
				<>
					You successfully bid of auction <b>{token.metadata.title}</b> for{' '}
					{prettyBalance(txDetail.args.amount, 24, 2)} Ⓝ
				</>
			)
		} else if (txDetail.method_name === 'cancel_bid') {
			return (
				<>
					You successfully remove bid auction <b>{token.metadata.title}</b> for{' '}
					{formatNearAmount(txDetail.args.amount)} Ⓝ
				</>
			)
		} else if (txDetail.method_name === 'accept_bid') {
			return (
				<>
					You successfully accept bid auction <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'cancel_auction') {
			return (
				<>
					You successfully remove auction <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'nft_buy' || txDetail.method_name === 'buy') {
			return (
				<>
					You successfully purchase <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'nft_set_series_price') {
			if (txDetail.args.price) {
				return (
					<>
						You successfully update <b>{token.metadata.title}</b> price to{' '}
						{formatNearAmount(txDetail.args.price)} Ⓝ
					</>
				)
			}
			return (
				<>
					You successfully remove the listing <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'nft_approve') {
			const msg = JSON.parse(txDetail.args.msg)
			if (msg.market_type === 'sale') {
				return (
					<>
						You successfully {msg.is_auction ? 'create auction' : 'update'}{' '}
						<b>{token.metadata.title}</b> with starting price {formatNearAmount(msg.price || 0)} Ⓝ
					</>
				)
			} else if (msg.market_type === 'accept_offer') {
				return (
					<>
						You successfully accept offer <b>{token.metadata.title}</b>
					</>
				)
			} else if (msg.market_type === 'add_trade') {
				return (
					<>
						You successfully trade your NFT <b>{token.metadata.title}</b>
					</>
				)
			} else if (
				msg.market_type === 'accept_trade' ||
				msg.market_type === 'accept_trade_paras_series'
			) {
				return (
					<>
						You successfully accept NFT <b>{token.metadata.title}</b>
					</>
				)
			}
		} else if (txDetail.method_name === 'delete_market_data') {
			return (
				<>
					You successfully remove the listing <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'nft_create_series') {
			return (
				<>
					You successfully create <b>{token.metadata.title}</b>
				</>
			)
		}
	}

	return (
		<Modal isShow={showModal} close={onCloseModal} className="p-8">
			<div className="max-w-sm w-full p-4 bg-gray-800 md:m-auto rounded-md relative">
				<div className="absolute right-0 top-0 pr-4 pt-4">
					<div className="cursor-pointer" onClick={onCloseModal}>
						<IconX />
					</div>
				</div>
				<div>
					<h1 className="text-2xl font-bold text-white tracking-tight">{titleText()}</h1>
					<p className="text-white mt-2">{descText()}</p>
					<div className="p-4">
						<div className="w-2/3 m-auto h-56">
							<Media
								className="rounded-lg overflow-hidden h-full w-full"
								url={token.metadata.media}
								videoControls={true}
								videoLoop={true}
								videoMuted={true}
								videoPadding={false}
							/>
						</div>
					</div>
					{router.query.transactionHashes && (
						<div className="p-3 bg-gray-700 rounded-md mt-2 mb-4">
							<p className="text-gray-300 text-sm">Transaction Hash</p>
							{router.query.transactionHashes.split(',').map((txhash) => (
								<a href={explorerUrl(txhash)} key={txhash} target="_blank" rel="noreferrer">
									<p className="text-white hover:underline cursor-pointer overflow-hidden text-ellipsis">
										{txhash}
									</p>
								</a>
							))}
						</div>
					)}
					<div className="flex justify-between px-1 mb-4">
						<p className="text-sm text-white">Share to:</p>
						<div className="flex gap-2">
							<FacebookShareButton url={tokenUrl} className="flex text-white">
								<FacebookIcon size={24} round />
							</FacebookShareButton>
							<TelegramShareButton url={tokenUrl} className="flex text-white">
								<TelegramIcon size={24} round />
							</TelegramShareButton>{' '}
							<TwitterShareButton
								title={`Checkout ${token.metadata.title} from collection ${token.metadata.collection} on @ParasHQ\n\n#paras #cryptoart #digitalart #tradingcards`}
								url={tokenUrl}
								className="flex text-white"
							>
								<TwitterIcon size={24} round />
							</TwitterShareButton>
						</div>
					</div>
					<Button size="md" isFullWidth onClick={onClickSeeToken}>
						See Token
					</Button>
				</div>
			</div>
		</Modal>
	)
}
Example #8
Source File: artist-verification.js    From paras-landing with GNU General Public License v3.0 4 votes vote down vote up
Verify = () => {
	const { localeLn } = useIntl()
	const router = useRouter()
	const store = useStore()
	const toast = useToast()
	const recaptchaRef = useRef()

	const [profile, setProfile] = useState('')
	const [isSubmitting, setIsSubmitting] = useState(false)
	const [isDisable, setIsDisable] = useState(false)
	const [totalQuota, setTotalQuota] = useState(0)
	const [totalCurrent, setTotalCurrent] = useState(0)
	const [isQuotaAvail, setIsQuotaAvail] = useState(true)
	const [formState, setFormState] = useState('loading')
	const [verifyStatus, setVerifyStatus] = useState({})
	const [scheduleTimestamp, setScheduleTimestamp] = useState('')
	const {
		formState: { errors },
		register,
		handleSubmit,
		setError,
		setValue,
	} = useForm()

	useEffect(() => {
		if (router.isReady && store.currentUser) {
			setProfile(`${window.location.origin}/${store.currentUser}`)
			checkStatusVerification()
			checkQuota()
			checkFinishSchedule()
		} else if (store.initialized && store.currentUser === null) {
			router.push('/login')
		}
	}, [store])

	useEffect(() => {
		register({ name: 'captchaToken' }, { required: true })
	})

	const checkQuota = async () => {
		try {
			const resp = await axios.get(`${process.env.V2_API_URL}/verifications/check-quota`, {
				headers: {
					authorization: await WalletHelper.authToken(),
				},
			})
			const data = resp.data.data
			setTotalCurrent(data.totalCurrent > data.totalQuota ? data.totalQuota : data.totalCurrent)
			setTotalQuota(data.totalQuota)

			const status = data.totalCurrent >= data.totalQuota ? false : true
			if (!status) {
				setIsDisable(true)
				setIsQuotaAvail(false)
			}
			return status
		} catch (err) {
			sentryCaptureException(err)
			const errMsg = 'SomethingWentWrong'
			toast.show({
				text: <div className="font-semibold text-center text-sm">{localeLn(errMsg)}</div>,
				type: 'error',
				duration: 2500,
			})
			return false
		}
	}

	const checkFinishSchedule = async () => {
		try {
			const resp = await axios.get(`${process.env.V2_API_URL}/verifications/scheduled-finish`, {
				headers: {
					authorization: await WalletHelper.authToken(),
				},
			})
			const data = resp.data.data
			setScheduleTimestamp(data.timestamp)
		} catch (err) {
			sentryCaptureException(err)
			const errMsg = 'SomethingWentWrong'
			toast.show({
				text: <div className="font-semibold text-center text-sm">{localeLn(errMsg)}</div>,
				type: 'error',
				duration: 2500,
			})
		}
	}

	const checkStatusVerification = async () => {
		try {
			const resp = await axios.get(
				`${process.env.V2_API_URL}/verifications?accountId=${store.currentUser}`,
				{
					headers: {
						authorization: await WalletHelper.authToken(),
					},
				}
			)
			const data = resp.data.data.results
			if (data.length > 0) {
				setVerifyStatus(data)
				setFormState('status')
			} else if (store.userProfile.isCreator) {
				setFormState('verified')
			} else {
				setFormState('form')
			}
		} catch (err) {
			sentryCaptureException(err)
			const errMsg = 'SomethingWentWrong'
			toast.show({
				text: <div className="font-semibold text-center text-sm">{localeLn(errMsg)}</div>,
				type: 'error',
				duration: 2500,
			})
		}
	}

	const _submit = async (data) => {
		setIsSubmitting(true)
		setIsDisable(true)

		if (data.instagram && checkSocialMediaUrl(data.instagram)) {
			setError('instagram', { type: 'invalid-url' }, { shouldFocus: true })
			setIsSubmitting(false)
			setIsDisable(false)
			return
		}

		if (data.twitter && checkSocialMediaUrl(data.twitter)) {
			setError('twitter', { type: 'invalid-url' }, { shouldFocus: true })
			setIsSubmitting(false)
			setIsDisable(false)
			return
		}

		const dataPost = {
			name: data.name,
			email: data.email,
			telegram_discord: data.telegramDiscord,
			paras_profile: profile,
			instagram: data.instagram,
			twitter: data.twitter,
			captcha_token: data.captchaToken,
		}

		try {
			await axios.post(`${process.env.V2_API_URL}/verifications`, dataPost, {
				headers: {
					authorization: await WalletHelper.authToken(),
				},
			})
			toast.show({
				text: (
					<div className="font-semibold text-center text-sm">
						{localeLn('success submit submission')}
					</div>
				),
				type: 'success',
				duration: 2500,
			})
			checkStatusVerification()
			setIsSubmitting(false)
			setIsDisable(false)
		} catch (err) {
			sentryCaptureException(err)
			const errMsg = err.response.data.message || 'SomethingWentWrong'
			toast.show({
				text: <div className="font-semibold text-center text-sm">{localeLn(errMsg)}</div>,
				type: 'error',
				duration: 2500,
			})
			setIsSubmitting(false)
			setIsDisable(false)
		}
	}

	const _goToProfile = async (e) => {
		e.preventDefault()
		router.push(`/${store.currentUser}`)
	}

	const _renderLoading = () => {
		return (
			<div className="max-w-4xl relative m-auto py-12 px-4">
				<div className="flex items-center justify-center h-64 text-gray-100">
					{localeLn('LoadingLoading')}
				</div>
			</div>
		)
	}

	const _renderForm = () => {
		return (
			<div className="max-w-4xl relative m-auto py-12 px-4">
				<h1 className="text-4xl font-bold text-gray-100 text-center">
					{localeLn('ParasArtistVerification')}
				</h1>
				<div className="mt-6 text-justify text-l text-gray-300">
					<p>{localeLn('TextFormParagraph1')}</p>
					<br></br>
					<p>{localeLn('TextFormParagraph2')}</p>
					<br></br>

					<ol className="list-decimal ml-6">
						<li>{localeLn('Step1')}</li>
						<li>{localeLn('Step2')}</li>
						<li>{localeLn('Step3')}</li>
						<li>{localeLn('Step4')}</li>
						<li>{localeLn('Step5')}</li>
						<li>{localeLn('Step6')}</li>
					</ol>
					<br></br>
					<p>
						{localeLn(
							`It’s also extremely important to remember that becoming verified artist does not grant you instant success. It’s a method to introduce yourself to a bigger community of Paras.`
						)}
					</p>
				</div>
				<form onSubmit={handleSubmit(_submit)}>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Email')}</label>
						<input
							type="email"
							name="email"
							className="focus:border-gray-100"
							placeholder="Email"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.email?.type === 'required' && 'Email is required'}
						</div>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Name')}</label>
						<input
							type="text"
							name="name"
							className="focus:border-gray-100"
							placeholder="Name"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.name?.type === 'required' && 'Name is required'}
						</div>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">
							{localeLn('Telegram/Discord Account')}
						</label>
						<input
							type="text"
							name="telegramDiscord"
							className="focus:border-gray-100"
							placeholder="Telegram/Discord Account"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.telegramDiscord?.type === 'required' &&
								'Telegram/Discord Account is required'}
						</div>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Paras Profile')}</label>
						<input
							type="text"
							name="paras-profile"
							value={profile}
							disabled
							className="bg-gray-400"
							placeholder="Paras Profile"
						/>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Instagram')}</label>
						<input
							type="text"
							name="instagram"
							className="focus:border-gray-100"
							placeholder="Instagram"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.instagram?.type === 'required' && 'Instagram is required'}
							{errors.instagram?.type === 'invalid-url' &&
								localeLn('Please enter only your instagram username')}
						</div>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Twitter')}</label>
						<input
							type="text"
							name="twitter"
							className="focus:border-gray-100"
							placeholder="Twitter"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.twitter?.type === 'required' && 'Twitter is required'}
							{errors.twitter?.type === 'invalid-url' &&
								localeLn('Please enter only your twitter username')}
						</div>
					</div>
					<div className="mt-6">
						<ReCAPTCHA
							size="normal"
							ref={recaptchaRef}
							sitekey={process.env.RECAPTCHA_SITE_KEY}
							onChange={(token) => setValue('captchaToken', token)}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.captchaToken?.type === 'required' && 'Captcha is required'}
						</div>
					</div>
					{!isQuotaAvail && (
						<p className="mt-6 block text-lg text-red-600">
							<strong>Quota:</strong> {totalCurrent} / {totalQuota} Quota full. Please wait for the
							next cycle {scheduleTimestamp !== '' && `at ${scheduleTimestamp} UTC+7`}
						</p>
					)}
					{isQuotaAvail && (
						<p className="mt-6 block text-lg text-gray-50">
							<strong>Quota:</strong> {totalCurrent} / {totalQuota}
						</p>
					)}
					<div className="mt-6">
						<button
							disabled={isDisable}
							className="w-full outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
							type="submit"
						>
							{!isSubmitting ? 'Submit' : 'Submiting...'}
						</button>
					</div>
				</form>
			</div>
		)
	}

	const _renderCheckStat = () => {
		const dataStatus = verifyStatus[0]
		const submittedDate = dataStatus?.createdAt
			? new Date(dataStatus?.createdAt).toISOString().substring(0, 10)
			: ''
		const inReviewDate = dataStatus?.reviewedAt
			? new Date(dataStatus?.reviewedAt).toISOString().substring(0, 10)
			: ''
		const resultDate = dataStatus?.resultAt
			? new Date(dataStatus?.resultAt).toISOString().substring(0, 10)
			: ''

		return (
			<div className="max-w-4xl relative m-auto py-12 px-4">
				<h1 className="text-4xl font-bold text-gray-100 text-center">
					{localeLn('VerificationStatus')}
				</h1>
				<div className="mt-6 text-justify text-l text-gray-300 mb-20">
					<p>{localeLn('TextStatusParagraph1')}</p>
					<br></br>
					<p>{localeLn('TextStatusParagraph2')}</p>
					{resultDate && dataStatus.status === 'verified' && (
						<div className="text-center ">
							<h3 className="text-2xl font-bold text-green-500 mt-20">
								{localeLn('YouAreVerified')}
							</h3>
						</div>
					)}
				</div>
				<div className="p-5">
					<div className="mx-4 p-4">
						<div className="flex items-center">
							<div className="flex items-center text-white relative">
								<div className="absolute -ml-10 text-center mb-20 w-32 text-xs font-medium text-teal-600">
									<p className="text-sm text-gray-50">{submittedDate}</p>
									<br></br>
								</div>
								{submittedDate != '' ? (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600 bg-blue-700"></div>
								) : (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600  bg-gray-300"></div>
								)}
								<div className="absolute top-0 -ml-10 text-center mt-16 w-32 text-xs font-medium text-teal-600">
									<p className="text-lg text-gray-50">{localeLn('Submitted')}</p>
									<p className="mt-2 text-md text-gray-50">{localeLn('SubmittedDesc')}</p>
								</div>
							</div>
							<div className="flex-auto border-t-2 transition duration-500 ease-in-out border-teal-600"></div>
							<div className="flex items-center text-white relative">
								<div className="absolute -ml-10 text-center mb-20 w-32 text-xs font-medium text-teal-600">
									<p className="text-sm text-gray-50">{inReviewDate}</p>
									<br></br>
								</div>
								{inReviewDate != '' ? (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600 bg-blue-700"></div>
								) : (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600  bg-gray-300"></div>
								)}
								<div className="absolute top-0 -ml-10 text-center mt-16 w-32 text-xs font-medium text-teal-600">
									<p className="text-lg text-gray-50">{localeLn('InReview')}</p>
									<p className="mt-2 text-md text-gray-50">{localeLn('InReviewDesc')}</p>
								</div>
							</div>
							<div className="flex-auto border-t-2 transition duration-500 ease-in-out border-gray-300"></div>
							<div className="flex items-center text-gray-500 relative">
								<div className="absolute -ml-10 text-center mb-20 w-32 text-xs font-medium text-teal-600">
									<p className="text-sm text-gray-50">{resultDate}</p>
									<br></br>
								</div>
								{resultDate != '' ? (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600 bg-blue-700"></div>
								) : (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600  bg-gray-300"></div>
								)}
								<div className="absolute top-0 -ml-10 text-center mt-16 w-32 text-xs font-medium text-gray-500">
									<p className="text-lg text-gray-50">{localeLn('Result')}</p>
									<p className="mt-2 text-md text-gray-50">{localeLn('ResultDesc')}</p>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div className="p-5 mt-20">
					<center>
						<button
							className="w-6/12  outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
							onClick={_goToProfile}
						>
							Profile
						</button>
					</center>
				</div>
			</div>
		)
	}

	const _renderVerified = () => {
		const verifiedDate = store.userProfile?.verifiedAt
			? new Date(store.userProfile?.verifiedAt).toISOString().substring(0, 10)
			: ''
		const urlShare = `${process.env.BASE_URL}/${store.currentUser}/creation`

		return (
			<div className="max-w-4xl relative m-auto py-12 px-4">
				<h1 className="text-4xl font-bold text-gray-100 text-center">
					{localeLn('VerificationStatus')}
				</h1>
				<div className="mt-6 text-justify text-l text-gray-300 mb-12">
					<div className=" text-center ">
						<h3 className="text-2xl font-bold text-green-500 mt-20">
							{localeLn('YouAreVerified')}
						</h3>
						<p className="mt-3">{verifiedDate && `${localeLn('Since')} ${verifiedDate}`}</p>
						<p className="mt-16 mb-3">{localeLn('ShareNow')}</p>
						<div className="flex flex-row items-center justify-center gap-3">
							<TwitterShareButton
								title={`Hey I'm verified creator on Paras. Check out my creation only on @ParasHQ\n\n#paras #cryptoart #digitalart #tradingcards`}
								url={urlShare}
								className="flex text-white"
							>
								<TwitterIcon size={24} round />
								<p className="ml-2">Twitter</p>
							</TwitterShareButton>
							<FacebookShareButton url={urlShare} className="flex text-white">
								<FacebookIcon size={24} round />
								<p className="ml-2">Facebook</p>
							</FacebookShareButton>
							<TelegramShareButton url={urlShare} className="flex text-white">
								<TelegramIcon size={24} round />
								<p className="ml-2">Telegram</p>
							</TelegramShareButton>
						</div>
					</div>
				</div>
				<center>
					<button
						className="w-6/12  outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
						onClick={_goToProfile}
					>
						Profile
					</button>
				</center>
			</div>
		)
	}

	return (
		<div className="min-h-screen bg-black">
			<div
				className="fixed inset-0 opacity-75"
				style={{
					zIndex: 0,
					backgroundImage: `url('/bg.jpg')`,
					backgroundRepeat: 'no-repeat',
					backgroundSize: 'cover',
				}}
			></div>
			<Head>
				<title>{localeLn('ArtistVerification')}</title>
				<meta
					name="description"
					content="Create, Trade, and Collect Digital Collectibles. All-in-one social NFT marketplace for creators and collectors. Discover the best and latest NFT collectibles on NEAR."
				/>

				<meta
					name="twitter:title"
					content="Paras - NFT Marketplace for Digital Collectibles on NEAR"
				/>
				<meta name="twitter:card" content="summary_large_image" />
				<meta name="twitter:site" content="@ParasHQ" />
				<meta name="twitter:url" content="https://paras.id" />
				<meta
					name="twitter:description"
					content="Create, Trade, and Collect Digital Collectibles. All-in-one social NFT marketplace for creators and collectors. Discover the best and latest NFT collectibles on NEAR."
				/>
				<meta
					name="twitter:image"
					content="https://paras-media.s3-ap-southeast-1.amazonaws.com/paras-v2-twitter-card-large.png"
				/>
				<meta property="og:type" content="website" />
				<meta
					property="og:title"
					content="Paras - NFT Marketplace for Digital Collectibles on NEAR"
				/>
				<meta
					property="og:site_name"
					content="Paras - NFT Marketplace for Digital Collectibles on NEAR"
				/>
				<meta
					property="og:description"
					content="Create, Trade, and Collect Digital Collectibles. All-in-one social NFT marketplace for creators and collectors. Discover the best and latest NFT collectibles on NEAR."
				/>
				<meta property="og:url" content="https://paras.id" />
				<meta
					property="og:image"
					content="https://paras-media.s3-ap-southeast-1.amazonaws.com/paras-v2-twitter-card-large.png"
				/>
			</Head>
			<Nav />
			{formState === 'form' && _renderForm()}
			{formState === 'status' && _renderCheckStat()}
			{formState === 'verified' && _renderVerified()}
			{formState === 'loading' && _renderLoading()}
			<Footer />
		</div>
	)
}
Example #9
Source File: index.js    From proof-of-humanity-web with MIT License 4 votes vote down vote up
export default function SubmissionDetailsCard({
  submission,
  contract,
  vouchers,
}) {
  const {
    requests: [request],
    latestRequest: [latestRequest],
    id,
    name,
    vouchees,
    ...rest
  } = (submission = useFragment(
    submissionDetailsCardFragments.submission,
    submission
  ));

  const orderedVouchees = lodashOrderBy(
    vouchees,
    (a) => a.requests[a.requests.length - 1].lastStatusChange,
    "desc"
  );

  const [accounts] = useWeb3("eth", "getAccounts");
  const isSelf =
    accounts?.[0] && accounts[0].toLowerCase() === id.toLowerCase();

  const { lastStatusChange } = request;
  const {
    submissionBaseDeposit,
    submissionDuration,
    requiredNumberOfVouches,
    challengePeriodDuration,
  } = (contract = useFragment(
    submissionDetailsCardFragments.contract,
    contract
  ));

  const status = submissionStatusEnum.parse({ ...rest, submissionDuration });
  const { challenges } = latestRequest || {};
  const activeChallenges = challenges.filter(
    ({ disputeID }) => disputeID !== null
  );

  // Note that there is a challenge object with first round data even if there
  // is no challenge.
  const challenge = (challenges && challenges[0]) || {};
  const { rounds, lastRoundID } = challenge || {};
  const round = (rounds && rounds[0]) || {};
  const { hasPaid } = round || {};

  const evidence = useEvidenceFile()(request.evidence[0].URI);
  const contributions = useMemo(
    () =>
      round.contributions.map((contribution) =>
        partyEnum.parse(contribution.values)
      ),
    [round.contributions]
  );

  const compoundName =
    [evidence?.file?.firstName, evidence?.file?.lastName]
      .filter(Boolean)
      .join(" ") || name;
  const displayName =
    compoundName === name ? name : `${compoundName} (${name})`;

  const [arbitrationCost] = useContract(
    "klerosLiquid",
    "arbitrationCost",
    useMemo(
      () => ({
        address: request.arbitrator,
        args: [request.arbitratorExtraData],
      }),
      [request]
    )
  );
  const { web3 } = useWeb3();
  const totalCost = useMemo(
    () => arbitrationCost?.add(web3.utils.toBN(submissionBaseDeposit)),
    [arbitrationCost, web3.utils, submissionBaseDeposit]
  );
  const totalContribution = useMemo(
    () =>
      contributions.reduce(
        (acc, { Requester }) => acc.add(web3.utils.toBN(Requester)),
        web3.utils.toBN(0)
      ),
    [contributions, web3.utils]
  );

  const [offChainVouches, setOffChainVouches] = useState([]);
  useEffect(() => {
    if (!id) return;
    (async () => {
      const res = await (
        await fetch(
          `${process.env.NEXT_PUBLIC_VOUCH_DB_URL}/vouch/search?submissionId=${id}`
        )
      ).json();
      if (res && res.vouches && res.vouches.length > 0)
        setOffChainVouches(res.vouches[0].vouchers);
    })();
  }, [id]);

  const registeredGraphVouchers = useFragment(
    submissionDetailsCardFragments.vouchers,
    vouchers
  ).filter(
    (voucher) =>
      Date.now() / 1000 - voucher.submissionTime < submissionDuration &&
      voucher.id !== id.toLowerCase()
  );

  const currentGraphVouchers = request.vouches.filter(
    (voucher) =>
      Date.now() / 1000 - voucher.submissionTime < submissionDuration &&
      voucher.id !== id.toLowerCase()
  );

  const [registeredVouchers, currentVouchers] = useMemo(() => {
    const completeSet = new Set();
    const onlyCurrentSet = new Set();

    offChainVouches.forEach((v) => {
      if (v !== id.toLowerCase()) {
        completeSet.add(v);
        onlyCurrentSet.add(v);
      }
    });
    registeredGraphVouchers.forEach((v) => completeSet.add(v.id));
    currentGraphVouchers.forEach((v) => onlyCurrentSet.add(v.id));

    return [[...completeSet], [...onlyCurrentSet]];
  }, [offChainVouches, registeredGraphVouchers, currentGraphVouchers, id]);

  const shareTitle =
    status === submissionStatusEnum.Vouching
      ? "Register and vouch for this profile on Proof Of Humanity."
      : "Check out this profile on Proof Of Humanity.";

  const firstRoundFullyFunded = Number(lastRoundID) === 0 && hasPaid[0];

  return (
    <Card
      mainSx={{
        alignItems: "stretch",
        flexDirection: ["column", null, null, "row"],
        padding: 0,
      }}
    >
      <Flex
        sx={{
          alignItems: "center",
          backgroundColor: "muted",
          flexDirection: "column",
          maxWidth: [null, null, null, 300],
          paddingX: 3,
          paddingY: 4,
          textAlign: "center",
        }}
      >
        <Image
          sx={{ objectFit: "contain" }}
          variant="avatar"
          src={evidence?.file?.photo}
        />
        <Text
          sx={{
            fontSize: 2,
            fontWeight: "bold",
            marginY: 2,
            overflowWrap: "anywhere",
          }}
        >
          {evidence instanceof Error
            ? "We are doing some maintenance work and will be online again soon."
            : evidence?.file?.name &&
              (name.replaceAll(/[^\s\w]/g, "") ===
              evidence.file.name.replaceAll(/[^\s\w]/g, "")
                ? evidence.file.name
                : "We are doing some maintenance work and will be online again soon.")}
        </Text>
        <Text sx={{ wordBreak: "break-word" }} count={2}>
          {evidence?.file ? evidence.file.bio || " " : null}
        </Text>
        <Box sx={{ marginY: 2, width: "100%" }}>
          {status === submissionStatusEnum.Vouching && (
            <>
              {((totalCost?.gt(totalContribution) && Number(lastRoundID) > 0) ||
                (Number(lastRoundID) === 0 && !hasPaid[0])) && (
                <FundButton
                  totalCost={totalCost}
                  totalContribution={totalContribution}
                  contract="proofOfHumanity"
                  method="fundSubmission"
                  args={[id]}
                >
                  Fund Submission
                </FundButton>
              )}
              {!isSelf && <GaslessVouchButton submissionID={id} />}
              {!isSelf && <VouchButton submissionID={id} />}
            </>
          )}
        </Box>
        <Flex sx={{ width: "100%" }}>
          <Box
            sx={{
              flex: 1,
              marginBottom: 3,
              paddingX: 1,
            }}
          >
            <Text>Vouchers</Text>
            <Text sx={{ fontWeight: "bold", paddingX: 1 }}>
              {String(currentVouchers.length)}/{requiredNumberOfVouches}
            </Text>
          </Box>
          {status !== submissionStatusEnum.Registered && (
            <Box
              sx={{
                flex: 1,
                borderLeftColor: "text",
                borderLeftStyle: "solid",
                borderLeftWidth: 1,
              }}
            >
              <Text>Deposit</Text>
              <Text sx={{ fontWeight: "bold" }}>
                {firstRoundFullyFunded
                  ? "100%"
                  : totalCost
                  ? `${(
                      totalContribution
                        .mul(web3.utils.toBN(10000)) // Basis points.
                        .div(totalCost)
                        .toNumber() / 100
                    ).toFixed(2)}%`
                  : "0%"}
              </Text>
            </Box>
          )}
        </Flex>
        {challenges?.length > 0 && challenge.disputeID !== null && (
          <Flex
            sx={{
              alignItems: "center",
              flexDirection: "column",
              marginTop: 3,
            }}
          >
            <Text sx={{ fontWeight: "bold" }}>
              {`Dispute${activeChallenges?.length > 1 ? "s" : ""}:`}
            </Text>
            {activeChallenges.map(
              ({ disputeID, reason, duplicateSubmission }, i) => (
                <Flex
                  key={i}
                  sx={{
                    flexDirection: "row",
                  }}
                >
                  <Link
                    newTab
                    href={`https://resolve.kleros.io/cases/${disputeID}`}
                    sx={{ marginLeft: 1 }}
                  >
                    #{disputeID}{" "}
                    {challengeReasonEnum.parse(reason).startCase !== "None"
                      ? challengeReasonEnum.parse(reason).startCase
                      : null}
                    {challengeReasonEnum.parse(reason).startCase === "Duplicate"
                      ? " of-"
                      : null}
                  </Link>
                  {challengeReasonEnum.parse(reason).startCase ===
                  "Duplicate" ? (
                    <SmallAvatar submissionId={duplicateSubmission.id} />
                  ) : null}
                </Flex>
              )
            )}
          </Flex>
        )}
        <Box sx={{ marginTop: "auto" }}>
          <Deadlines
            submission={submission}
            contract={contract}
            status={status}
          />
        </Box>
      </Flex>
      <Box sx={{ flex: 1, padding: 4 }}>
        <Flex
          sx={{
            alignItems: "center",
            gap: 8,
            marginBottom: "4px",
          }}
        >
          <User />
          <Text as="span" sx={{ fontWeight: "bold" }}>
            {displayName}
          </Text>
        </Flex>
        <EthereumAccount
          diameter={16}
          address={id}
          sx={{
            marginBottom: 2,
            fontWeight: "bold",
          }}
        />
        <Video url={evidence?.file?.video} />
        <UBICard
          submissionID={id}
          lastStatusChange={lastStatusChange}
          challengePeriodDuration={challengePeriodDuration}
          status={status}
          registeredVouchers={registeredVouchers}
          firstRoundFullyFunded={firstRoundFullyFunded}
        />
        {status === submissionStatusEnum.Vouching && (
          <Alert
            type="muted"
            title="Something wrong with this submission?"
            sx={{ mt: 3, wordWrap: "break-word" }}
          >
            <Text>
              There is still time to save this submitter&apos;s deposit! Send
              them an email to{" "}
              <Link href={`mailto:${id}@ethmail.cc`}>{id}@ethmail.cc</Link>. It
              may save the submitter&apos;s deposit!
            </Text>
          </Alert>
        )}
        {registeredVouchers.length > 0 && (
          <>
            <Text
              sx={{
                marginTop: 2,
                marginBottom: 1,
                opacity: 0.45,
              }}
            >
              Vouched by:
            </Text>
            <Flex sx={{ flexWrap: "wrap" }}>
              {registeredVouchers.map((voucherId) => (
                <SmallAvatar key={voucherId} submissionId={voucherId} />
              ))}
            </Flex>
          </>
        )}
        {vouchees.length > 0 && (
          <>
            <Text
              sx={{
                marginTop: 2,
                marginBottom: 1,
                opacity: 0.45,
              }}
            >
              Vouched for:
            </Text>
            <Flex sx={{ flexWrap: "wrap" }}>
              {orderedVouchees.map(({ id: address }) => (
                <SmallAvatar key={address} submissionId={address} />
              ))}
            </Flex>
          </>
        )}

        <Flex sx={{ justifyContent: "flex-end" }}>
          <RedditShareButton url={location.href} title={shareTitle}>
            <RedditIcon size={32} />
          </RedditShareButton>
          <TelegramShareButton url={location.href} title={shareTitle}>
            <TelegramIcon size={32} />
          </TelegramShareButton>
          <TwitterShareButton
            url={location.href}
            title={shareTitle}
            via="Kleros_io"
            hashtags={["kleros", "proofofhumanity"]}
          >
            <TwitterIcon size={32} />
          </TwitterShareButton>
        </Flex>
      </Box>
    </Card>
  );
}
Example #10
Source File: appeal.js    From proof-of-humanity-web with MIT License 4 votes vote down vote up
function AppealTabPanel({
  sharedStakeMultiplier,
  winnerStakeMultiplier,
  loserStakeMultiplier,
  arbitrator,
  challenge: {
    challengeID,
    disputeID,
    parties: [party1, party2],
    rounds: [{ paidFees, hasPaid }],
  },
  arbitratorExtraData,
  contract,
  args,
}) {
  const { web3 } = useWeb3();
  sharedStakeMultiplier = web3.utils.toBN(sharedStakeMultiplier);
  winnerStakeMultiplier = web3.utils.toBN(winnerStakeMultiplier);
  loserStakeMultiplier = web3.utils.toBN(loserStakeMultiplier);
  const divisor = web3.utils.toBN(10000);
  const hundred = web3.utils.toBN(100);
  const undecided = {
    label: "Previous round undecided.",
    reward: sharedStakeMultiplier.mul(hundred).div(sharedStakeMultiplier),
  };
  const winner = {
    label: "Previous round winner.",
    reward: loserStakeMultiplier.mul(hundred).div(winnerStakeMultiplier),
  };
  const loser = {
    label: "Previous round loser.",
    reward: winnerStakeMultiplier.mul(hundred).div(loserStakeMultiplier),
  };

  const [appealCost] = useContract(
    "klerosLiquid",
    "appealCost",
    useMemo(
      () => ({ address: arbitrator, args: [disputeID, arbitratorExtraData] }),
      [arbitrator, disputeID, arbitratorExtraData]
    )
  );
  if (appealCost) {
    undecided.cost = appealCost.add(
      appealCost.mul(sharedStakeMultiplier).div(divisor)
    );
    winner.cost = appealCost.add(
      appealCost.mul(winnerStakeMultiplier).div(divisor)
    );
    loser.cost = appealCost.add(
      appealCost.mul(loserStakeMultiplier).div(divisor)
    );
  }

  const [appealPeriod] = useContract(
    "klerosLiquid",
    "appealPeriod",
    useMemo(
      () => ({ address: arbitrator, args: [disputeID] }),
      [arbitrator, disputeID]
    )
  );
  if (appealPeriod) {
    undecided.deadline = appealPeriod.end;
    winner.deadline = appealPeriod.end;
    loser.deadline = appealPeriod.start.add(
      appealPeriod.end.sub(appealPeriod.start).div(web3.utils.toBN(2))
    );
  }

  let [currentRuling] = useContract(
    "klerosLiquid",
    "currentRuling",
    useMemo(
      () => ({ address: arbitrator, args: [disputeID] }),
      [arbitrator, disputeID]
    )
  );
  currentRuling = currentRuling?.toNumber();
  const shareTitle = `Crowdfunding Appeal Fees for ${party1} vs ${party2}.`;
  return (
    <>
      <Text sx={{ marginBottom: 2 }}>
        Help fund a side’s appeal fees to win part of the other side’s deposit
        when your side ultimately wins. If only one side manages to fund their
        fees, it automatically wins. (Rewards only apply to rounds where both
        sides are fully funded.)
      </Text>
      <Grid sx={{ marginBottom: 3 }} gap={2} columns={[1, 1, 1, 2]}>
        <AppealTabPanelCard
          address={party1}
          {...[undecided, winner, loser][currentRuling]}
          paidFees={paidFees[1]}
          hasPaid={hasPaid[0]}
          oppositeHasPaid={hasPaid[1]}
          loserDeadline={loser.deadline}
          isWinner={currentRuling === 1}
          contract={contract}
          args={[...args, challengeID, 1]}
          partyLabel="Submitter"
        />
        <AppealTabPanelCard
          address={party2}
          {...[undecided, loser, winner][currentRuling]}
          paidFees={paidFees[2]}
          hasPaid={hasPaid[1]}
          oppositeHasPaid={hasPaid[0]}
          loserDeadline={loser.deadline}
          isWinner={currentRuling === 2}
          contract={contract}
          args={[...args, challengeID, 2]}
          partyLabel="Challenger"
        />
      </Grid>
      <Flex sx={{ justifyContent: "center" }}>
        <RedditShareButton url={location.href} title={shareTitle}>
          <RedditIcon size={32} />
        </RedditShareButton>
        <TelegramShareButton url={location.href} title={shareTitle}>
          <TelegramIcon size={32} />
        </TelegramShareButton>
        <TwitterShareButton
          url={location.href}
          title={shareTitle}
          via="Kleros_io"
          hashtags={["kleros", "appeals"]}
        >
          <TwitterIcon size={32} />
        </TwitterShareButton>
      </Flex>
    </>
  );
}
Example #11
Source File: ClubEvent.jsx    From club-connect with GNU General Public License v3.0 4 votes vote down vote up
ShareModal = (props) => {
  const { onRequestClose, shareModalIsOpen, shareData } = props;

  Modal.setAppElement('#__next');

  return (
    <Modal
      className={clubEventStyles.ShareModal}
      isOpen={shareModalIsOpen}
      onRequestClose={onRequestClose}
      shouldCloseOnOverlayClick={true}
      closeTimeoutMS={200}
    >
      <h2>Share This Event</h2>
      <input type="text" value={shareData.eventUrl} readOnly />
      <div className={clubEventStyles.sharePlatforms}>
        <FacebookShareButton
          url={shareData.eventUrl}
          quote={shareData.shareDescription}
          hashtag={'#bccompsciclub'}
          disabled
        >
          <FacebookIcon size={32} round />
        </FacebookShareButton>

        <TwitterShareButton
          url={shareData.eventUrl}
          title={shareData.shareDescription}
          hashtags={['bccompsciclub']}
        >
          <TwitterIcon size={32} round />
        </TwitterShareButton>

        <LinkedinShareButton
          url={shareData.eventUrl}
          title={shareData.shareTitle}
          summary={shareData.shareDescription}
        >
          <LinkedinIcon size={32} round />
        </LinkedinShareButton>

        <FacebookMessengerShareButton url={shareData.eventUrl} disabled>
          <FacebookMessengerIcon size={32} round />
        </FacebookMessengerShareButton>

        <WhatsappShareButton
          url={shareData.eventUrl}
          title={shareData.shareDescription}
        >
          <WhatsappIcon size={32} round />
        </WhatsappShareButton>

        <TelegramShareButton
          url={shareData.eventUrl}
          title={shareData.shareDescription}
        >
          <TelegramIcon size={32} round />
        </TelegramShareButton>

        <LineShareButton
          url={shareData.eventUrl}
          title={shareData.shareDescription}
        >
          <LineIcon size={32} round />
        </LineShareButton>

        <EmailShareButton
          url={shareData.eventUrl}
          subject={shareData.shareTitle}
          body={`${shareData.shareDescription}\n\n`}
        >
          <EmailIcon size={32} round />
        </EmailShareButton>
      </div>
      <button className={clubEventStyles.closeButton} onClick={onRequestClose}>
        Close
      </button>
      <p>
        Sharing to Facebook and Facebook Messenger are currently unavailable.
        Sorry about that!
      </p>
    </Modal>
  );
}
Example #12
Source File: RefPage.js    From bonded-stablecoin-ui with MIT License 4 votes vote down vote up
RefPage = ({ setWalletModalVisibility }) => {
  const { activeWallet } = useSelector(state => state.settings);
  const [loading, setLoading] = useState(true);
  const { t } = useTranslation();
  const [info, setInfo] = useState({});
  const [scale, setScale] = useState(0);

  const currentYear = moment().year();
  const countDays = moment(`${currentYear + 1}-01-01`, "YYYY-MM-DD").diff(`${currentYear}-01-01`, "days");
  const countWeeks = countDays / 7;

  const refUrl = `https://${config.TESTNET ? "testnet." : ""}ostable.org/?r=${activeWallet}`;
  const appInfo = {
    url: refUrl,
    title: "Obyte bonded stablecoins: earn 16% interest in USD, 11% in BTC",
    hashtag: "#obyte"
  }
  const columns = [
    {
      title: t("ref.address", "Address"),
      dataIndex: "address",
      key: "address",
      ellipsis: {
        showTitle: true,
      },
    },
    {
      title: t("ref.usd_balance", "USD balance"),
      dataIndex: "usd_balance",
      key: "usd_balance",
      render: (value) => {
        return Number(value).toFixed(2) || <span>—</span>
      }
    }
  ];

  useEffect(() => {
    (async () => {
      let error = false;
      const infoData = await axios.get(`${config.REFERRAL_URL}/referrals/${activeWallet}`).catch((e) => {
        error = true;
        console.log("e", e);
      });

      if (!infoData || ("error" in infoData)) return setLoading(false);

      if (infoData) {
        const info = { ...infoData.data.data };
        const total = info && info.referrals && info.referrals.reduce((acc, value) => acc + value.usd_balance, 0);
        info.total = Number(total).toFixed(2);
        
        const distributionInfoData = await axios.get(`${config.REFERRAL_URL}/distributions/next`).catch((e) => {
          error = true;
          console.log("e", e);
        });
        
        if (!distributionInfoData || ("error" in distributionInfoData)) return setLoading(false)
       
        const {data: {data : {total_unscaled_rewards, total_rewards}}} = distributionInfoData;

        const scale = (total_rewards / total_unscaled_rewards) || 0;

        setScale(scale);
        
        if(!error){
          setLoading(false);
          setInfo(info);
        }
        
      }

    })();
  }, [activeWallet]);

  const pReferrerRewards = +Number(10 * scale).toFixed(3);
  const pReferrerRewardsAPY = +Number(10 * scale * countWeeks).toPrecision(4);
  const pReferralRewards = +Number(5 * scale).toFixed(3);

  return <>
    <Helmet title="Bonded stablecoins - Referral program" />
    <Title level={1} style={{ marginBottom: 30 }}>{t("ref.title", "Referral program")}</Title>
    <Row style={{ fontSize: 18 }}>
      <Col xl={{ offset: 1, span: 8 }} sm={{ span: 24 }} xs={{ span: 24 }}>
        <img className={styles.image} src={RefImage} alt="Referral program" />
        {activeWallet && info && !loading && <Paragraph className={styles.myInfo}>
          {info.distribution_date && <div>{t("ref.next_payment", "The next payment is on ")} {info.distribution_date}.</div>}
          {"my_info" in info && <div>{t("ref.expected_reward", "Your expected reward is")} {Number(info.my_info.usd_reward).toFixed(2)} IUSD.
          {info.referrer_address && t("ref.you_were_referred", "You were referred by {{referrer_address}} and this includes a reward for your own balance {{balance}}.", { balance: info.my_info.usd_balance, referrer_address: info.my_info.referrer_address })}</div>}
        </Paragraph>}
      </Col>
      <Col xl={{ offset: 1, span: 14 }} sm={{ span: 24 }} xs={{ span: 24 }}>
        {activeWallet ? <div>
          {t("ref.your_link", "This is your referral link")}:
          <div>
            <div className={styles.urlWrap}>
              <Text copyable={{ onCopy: () => message.success(t("ref.clipboard_link", "Your link was copied to the clipboard")) }}>{refUrl}</Text>
            </div>
          </div>
        </div> : <div className={styles.urlWrap_empty}><Trans i18nKey="ref.no_auth">To get a referral link, <span onClick={setWalletModalVisibility} className={styles.addWallet}>add your wallet address</span></Trans></div>}
        <div className={styles.info}>
          <Paragraph>
            {t("ref.your_link_desc", "Use it in your blogs, tweets, posts, newsletters, public profiles, videos, etc and earn referral rewards for bringing new holders into Bonded Stablecoins.")}
          </Paragraph>
          {activeWallet && <Paragraph>
            <Space style={{ justifyContent: "center", width: "100%" }}>
              <FacebookShareButton {...appInfo}>
                <FacebookIcon size={36} round={true} />
              </FacebookShareButton>
              <VKShareButton {...appInfo}>
                <VKIcon size={36} round={true} />
              </VKShareButton>
              <TwitterShareButton {...appInfo}>
                <TwitterIcon size={36} round={true} />
              </TwitterShareButton>
              <TelegramShareButton {...appInfo}>
                <TelegramIcon size={36} round={true} />
              </TelegramShareButton>
            </Space>
          </Paragraph>}
          <Trans i18nKey="ref.info" pReferrerRewards={pReferrerRewards} pReferrerRewardsAPY={pReferrerRewardsAPY} pReferralRewards={pReferralRewards}>
            <Paragraph>
              The referral rewards are paid in IUSD every Sunday and are proportional to dollar balances of the referred
              users in all tokens (stablecoins, interest tokens, growth tokens) issued on this website, as well as other
              tokens based on them: shares in <a target="_blank" rel="noopener" href="https://oswap.io/">oswap</a> liquidity pools and shares in arbitrage bots.
              The larger the total balances at the end of the weekly period, the larger the reward. Your weekly reward increases if the referred users accumulate more, decreases if they redeem or sell their tokens.
            </Paragraph>
            <Paragraph>
              The current weekly reward is <b>{{pReferrerRewards}}% of the balances of all referred users</b> at the end of the week (<b>{{pReferrerRewardsAPY}}% per year</b>).
            </Paragraph>
            <Paragraph>
              Your referrals also get rewarded for buying tokens through your link — they are expected to get <b>{{pReferralRewards}}% of their balances</b> every week.
            </Paragraph>
            <Paragraph>
              The total amount paid to all referrers and referred users is <b>$3,000 weekly</b> and is distributed in proportion to the referrals balances.
            </Paragraph>
          </Trans>
          {activeWallet && <Paragraph>
            {t("ref.title_list", "Here is the list of your referrals and their current balances")}:
          </Paragraph>}
        </div>
      </Col>
    </Row>

    {activeWallet && <Table
      loading={loading}
      columns={columns}
      footer={() => info && info.total && Number(info.total) !== 0 && <div style={{ display: "flex", justifyContent: "flex-end" }} ><b>{t("ref.total", "Total")}: {info.total} IUSD</b></div>}
      dataSource={((info && info.referrals) || []).map((r) => ({ ...r, key: r.address }))}
      locale={{
        emptyText: t("ref.empty", "no referrals yet"),
      }}
      pagination={{ pageSize: 20, hideOnSinglePage: true }}
    />}

  </>
}
Example #13
Source File: ShareButton.js    From warsinhk with MIT License 4 votes vote down vote up
function ShareButton(props) {
  const [anchorEl, setAnchorEl] = React.useState(null)
  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            siteUrl
          }
        }
      }
    `
  )

  function getPageUrl() {
    let url = `${site.siteMetadata.siteUrl}${fullPath}`

    if (props.caseId) {
      url = `${site.siteMetadata.siteUrl}${fullPath}/${props.caseId}`
    }

    if (!isSSR()) {
      url = url + decodeURIComponent(window.location.hash)
    }

    return url
  }

  function handleShareButtonClick(event) {
    if (!isSSR() && isWebShareAPISupported()) {
      const data = getWebShareData(getPageUrl())
      if (navigator.canShare(data)) {
        navigator.share(data).then(() => {
          trackCustomEvent({
            category: "general",
            action: "click",
            label: "share",
          })
        })

        return
      }
    }

    setAnchorEl(event.currentTarget)
  }

  function handleShareButtonClose(media) {
    setAnchorEl(null)
    if (typeof media === "string") {
      trackCustomEvent({
        category: "general",
        action: "click",
        label: `share_${media}`,
      })
    }
  }
  const { pathname: fullPath } = useLocation()

  const url = getPageUrl()

  return (
    <>
      <StyledIconButton
        color="inherit"
        aria-label="Share"
        aria-controls="share-menu"
        aria-haspopup="true"
        onClick={handleShareButtonClick}
      >
        <ShareIcon />
      </StyledIconButton>
      <Menu
        id="share-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleShareButtonClose}
      >
        <MenuItem onClick={() => handleShareButtonClose("facebook")}>
          <FacebookShareButton
            url={getShareUrl(url, "facebook")}
            children={<FacebookIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("telegram")}>
          <TelegramShareButton
            url={getShareUrl(url, "telegram")}
            children={<TelegramIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("whatsapp")}>
          <WhatsappShareButton
            url={getShareUrl(url, "whatsapp")}
            children={<WhatsappIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("twitter")}>
          <TwitterShareButton
            url={getShareUrl(url, "twitter")}
            children={<TwitterIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("link")}>
          <StyledCopyIcon
            onClick={() => {
              navigator.clipboard.writeText(url)
            }}
          />
        </MenuItem>
      </Menu>
    </>
  )
}