react-icons/md#MdRotateLeft JavaScript Examples

The following examples show how to use react-icons/md#MdRotateLeft. 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: ShelleyHaskellStakingCalculator.js    From testnets-cardano-org with MIT License 4 votes vote down vote up
Calculator = ({
  currencies,
  content,
  initialValues,
  initialCalculator,
  origin,
  pathname,
}) => {
  const [allCurrencies, setAllCurrencies] = useState(
    JSON.parse(JSON.stringify(currencies))
  )
  const [values, setValues] = useState(
    getDefaultValues(allCurrencies[0], initialValues)
  )
  const [type, setType] = useState(initialCalculator)
  const [showAdvancedOptions, setShowAdvancedOptions] = useState(false)
  const [shareModalVisible, setShareModalVisible] = useState(false)
  const [copied, setCopied] = useState(false)
  const containerRef = useRef(null)
  const copiedTimeout = useRef(null)
  const modalContent = useRef(null)

  function getInitialCurrency(key) {
    return currencies.filter((currency) => currency.key === key).shift() || {}
  }

  function getTotalADAInCirculation(epoch, startingTotalADAInCirculation) {
    let i = 1
    let totalADAInCirculation =
      startingTotalADAInCirculation || values.totalADAInCirculation
    while (i < epoch) {
      const reserve = values.totalADA - totalADAInCirculation
      totalADAInCirculation += reserve * values.expansionRate
      i++
    }

    return totalADAInCirculation
  }

  function getEpochDistributableRewards(
    totalADAInCirculation,
    transactionFeesPerEpoch
  ) {
    const reserve = values.totalADA - totalADAInCirculation
    return (
      (reserve * values.expansionRate + transactionFeesPerEpoch) *
      (1 - values.treasuryRate)
    )
  }

  function getDistributableRewards(epoch) {
    let transactionFeesPerEpoch = parseFloat(values.transactionFeesPerEpoch)
    if (
      !transactionFeesPerEpoch ||
      isNaN(transactionFeesPerEpoch) ||
      transactionFeesPerEpoch < 0
    )
      transactionFeesPerEpoch = 0

    const totalADAInCirculation = getTotalADAInCirculation(epoch)
    const epochDistribution = getEpochDistributableRewards(
      totalADAInCirculation,
      transactionFeesPerEpoch
    )
    return epochDistribution
  }

  const setValue = (key, value) => {
    const newValues = { ...values, [key]: value }
    if (
      key === 'currency' &&
      value.exchangeRate !== values.currency.exchangeRate
    ) {
      const stakePoolFixedFeeInADA = toADA(parseFloat(values.stakePoolFixedFee))
      newValues.stakePoolFixedFee = `${fromADA(
        stakePoolFixedFeeInADA,
        value.exchangeRate
      )}`
    }

    setValues(newValues)
  }

  const updateType = (type) => (e) => {
    e.preventDefault()
    setType(type)
  }

  const fromADA = (amount, exchangeRate = null) => {
    let exchangeRateUsed = parseFloat(
      exchangeRate === null ? values.currency.exchangeRate : exchangeRate
    )
    if (isNaN(exchangeRateUsed) || exchangeRateUsed <= 0)
      exchangeRateUsed =
        getInitialCurrency(values.currency.key).exchangeRate || 1
    return amount * exchangeRateUsed
  }

  const toADA = (amount, exchangeRate = null) => {
    let exchangeRateUsed = parseFloat(
      exchangeRate === null ? values.currency.exchangeRate : exchangeRate
    )
    if (isNaN(exchangeRateUsed) || exchangeRateUsed <= 0)
      exchangeRateUsed =
        getInitialCurrency(values.currency.key).exchangeRate || 1
    return amount / exchangeRateUsed
  }

  const toggleShowAdvancedOptions = (e) => {
    e.preventDefault()
    setShowAdvancedOptions(!showAdvancedOptions)
  }

  const reset = () => {
    const currency = currencies
      .filter((currency) => currency.key === values.currency.key)
      .shift()
    setAllCurrencies(JSON.parse(JSON.stringify(currencies)))
    setValues(getDefaultValues(currency, initialValues))
  }

  const onReset = (e) => {
    e.preventDefault()
    reset()
  }

  const getCurrencySymbol = (key) =>
    (currencies.filter((currency) => currency.key === key).shift() || {})
      .symbol || null
  const normalizeLargeNumber = (number, dp = 0, preserveDP = false) => {
    let negative = number < 0
    const normalizedNumber = Math.abs((number || 0).toFixed(dp))
    if (normalizedNumber === 0) negative = false
    const asStringArray = `${normalizedNumber}`.split('.')
    const n = asStringArray[0].split('').reverse()
    let i = 3
    while (i < n.length) {
      n.splice(i, 0, ',')
      i += 4
    }

    let finalNumber = n
      .reverse()
      .join('')
      .concat(asStringArray[1] ? `.${asStringArray[1]}` : '')
    if (!preserveDP && finalNumber.indexOf('.') > -1) {
      while (finalNumber[finalNumber.length - 1] === '0') {
        finalNumber = finalNumber.substring(0, finalNumber.length - 1)
      }
    }

    return `${negative ? '-' : ''}${finalNumber.replace(/\.$/, '')}`
  }

  const getShareableLink = () => {
    const params = new URLSearchParams()
    const keys = [
      'ada',
      'stakePoolControl',
      'operatorsStake',
      'stakePoolMargin',
      'stakePoolPerformance',
      'totalStakePools',
      'influenceFactor',
      'transactionFeesPerEpoch',
      'stakePoolFixedFee',
      'treasuryRate',
      'expansionRate',
      'epochDurationInDays',
      'currentEpoch',
    ]

    keys.forEach((key) => params.set(key, values[key]))
    params.set('calculator', type)
    return `${origin}${pathname}?${params.toString()}`
  }

  const copyShareableLink = (e) => {
    e.preventDefault()
    const el = document.createElement('textarea')
    const link = getShareableLink()
    el.value = link
    el.setAttribute('readonly', 'true')
    el.setAttribute('aria-hidden', 'true')
    el.setAttribute('tab-index', '-1')
    el.style.position = 'absolute'
    el.style.left = '-999999px'
    modalContent.current.appendChild(el)
    el.select()
    document.execCommand('copy')
    modalContent.current.removeChild(el)
    clearTimeout(copiedTimeout.current)
    setCopied(true)
    copiedTimeout.current = setTimeout(() => setCopied(false), 500)
  }

  const CalculatorComponent = type === 'delegator' ? Delegator : Operator
  return (
    <Container ref={containerRef}>
      <Introduction paddingBottom={1} textAlign="center">
        <p>{content.staking_calculator.select_a_calculator}</p>
        <p>{content.staking_calculator.i_want_to}</p>
      </Introduction>
      <CalculatorPicker>
        <div>
          <Button
            variant={type === 'delegator' ? 'contained' : 'outlined'}
            onClick={updateType('delegator')}
            color="primary"
            fullWidth
          >
            <DelegatorIcon active={type === 'delegator'} />
            <span>{content.staking_calculator.delegate_my_stake}</span>
          </Button>
          <CardanoLogo active={type === 'delegator'} />
        </div>
        <div>
          <Button
            variant={type === 'operator' ? 'contained' : 'outlined'}
            onClick={updateType('operator')}
            color="primary"
            fullWidth
          >
            <OperatorIcon active={type === 'operator'} />
            <span>{content.staking_calculator.run_a_stake_pool}</span>
          </Button>
          <CardanoLogo active={type === 'operator'} />
        </div>
      </CalculatorPicker>
      <Actions>
        <div>
          <div>
            <Button
              color="primary"
              variant={showAdvancedOptions ? 'contained' : 'outlined'}
              onClick={toggleShowAdvancedOptions}
              fullWidth
            >
              {content.staking_calculator.show_advanced_options}
              <Box component="span" marginLeft={0.8}>
                {showAdvancedOptions ? <MdVisibilityOff /> : <MdVisibility />}
              </Box>
            </Button>
          </div>
          <div>
            <Button
              color="primary"
              variant="outlined"
              onClick={onReset}
              fullWidth
            >
              {content.staking_calculator.reset}
              <Box component="span" marginLeft={0.8}>
                <MdRotateLeft />
              </Box>
            </Button>
          </div>
        </div>
        <div>
          <div>
            <Button
              color="primary"
              variant="outlined"
              onClick={(e) => {
                e.preventDefault()
                setShareModalVisible(true)
              }}
              fullWidth
            >
              {content.staking_calculator.share}
              <Box component="span" marginLeft={0.8}>
                <MdFileUpload />
              </Box>
            </Button>
            {shareModalVisible && (
              <Modal
                open={shareModalVisible}
                onClose={(e) => {
                  e.preventDefault()
                  setShareModalVisible(false)
                }}
                disableScrollLock
              >
                <ModalContent ref={modalContent}>
                  <CloseModal
                    href="#"
                    onClick={(e) => {
                      e.preventDefault()
                      setShareModalVisible(false)
                    }}
                  >
                    <MdClose />
                  </CloseModal>
                  <ModalContentInner>
                    <Box textAlign="center">
                      <ShareLinks>
                        <div>
                          <TwitterLink
                            href={`https://twitter.com/intent/tweet?text=${getShareableLink()}`}
                          >
                            <FaTwitter />{' '}
                            <span>{content.staking_calculator.tweet}</span>
                          </TwitterLink>
                        </div>
                        <div>
                          <FacebookLink
                            href={`https://www.facebook.com/dialog/share?href=${getShareableLink()}&display=popup&app_id=282617186477949&redirect_uri=https://facebook.com/`}
                          >
                            <FaFacebookF />{' '}
                            <span>{content.staking_calculator.share}</span>
                          </FacebookLink>
                        </div>
                      </ShareLinks>
                      <p>
                        <CopyToClipboardLink
                          href="#copy-to-clipboard"
                          onClick={copyShareableLink}
                        >
                          <FaClipboard />{' '}
                          <span className="text">
                            {content.staking_calculator.copy_to_clipboard}
                          </span>
                          {copied && (
                            <AnimatedClipboard>
                              <FaClipboard />
                            </AnimatedClipboard>
                          )}
                        </CopyToClipboardLink>
                      </p>
                    </Box>
                  </ModalContentInner>
                </ModalContent>
              </Modal>
            )}
          </div>
          <div />
        </div>
      </Actions>
      <Inputs>
        <CalculatorComponent
          values={values}
          setValue={setValue}
          content={content}
          toADA={toADA}
          fromADA={fromADA}
          showAdvancedOptions={showAdvancedOptions}
          HalfWidthGroup={HalfWidthGroup}
          FullWidthGroup={FullWidthGroup}
          getCurrencySymbol={getCurrencySymbol}
          currencies={currencies}
          normalizeLargeNumber={normalizeLargeNumber}
          getDistributableRewards={getDistributableRewards}
          getTotalADAInCirculation={getTotalADAInCirculation}
          containerRef={containerRef}
        />
      </Inputs>
    </Container>
  )
}
Example #2
Source File: SmartContractCalculator.js    From testnets-cardano-org with MIT License 4 votes vote down vote up
export default function SmartContractCalculator () {
  const [perByteCost, setPerByteCost] = useState(44)
  const [perStepCost, setPerStepCost] = useState(0.0000721)
  const [perMemUnitCost, setMemUnitCost] = useState(0.0577)
  const [perTransactionCost, setPerTransactionCost] = useState(155381)
  const [showParams, _setShowParams] = useState(false)

  const [adaPrice, setAdaPrice] = useState()
  const [initialized, setInitialized] = useState(false)
  const [unableToGetPrice, setUnableToGetPrice] = useState(false)
  const [adaPriceScenario, setAdaPriceScenario] = useState(0)

  const [transactions, setTransactions] = useState([
    {
      txSize: 0,
      cpuSteps: 0,
      memUnits: 0
    }
  ])

  useEffect(() => {
    const getAdaPrice = async () => {
      try {
        const res = await fetch(
          'https://api.coingecko.com/api/v3/coins/cardano'
        )
        const data = await res.json()
        // eslint-disable-next-line camelcase
        const price = data?.market_data?.current_price?.usd
        setAdaPrice(parseFloat(price))
        setAdaPriceScenario(parseFloat(price))
        setInitialized(true)
      } catch (e) {
        setUnableToGetPrice(true)
        setAdaPrice(2.4)
        setInitialized(true)
      }
    }

    if (!initialized) getAdaPrice()
  }, [initialized])

  const txPrice = (t) =>
    !t.txSize && !t.cpuSteps && !t.memUnits
      ? 0
      : ((perByteCost || 0) * (t.txSize || 0) +
          (perStepCost || 0) * (t.cpuSteps || 0) +
          (perMemUnitCost || 0) * (t.memUnits || 0) +
          (perTransactionCost || 0)) /
        1000000

  const dappFee = () => {
    let fee = 0
    for (const t of transactions) fee = fee + txPrice(t)
    return fee
  }

  return initialized ? (
    <>
      <ReactTooltip />
      {showParams && (
        <Params>
          <div>
            <TextField
              label="Per Byte Cost"
              helperText="Cost of each byte"
              value={perByteCost}
              type="number"
              min="0"
              onChange={(e) => {
                let input = parseInt(e.target.value)
                if (input < 0) input = 0
                setPerByteCost(input)
              }}
              onBlur={(e) => !e.target.value && setPerByteCost(0)}
            />
          </div>

          <div>
            <TextField
              label="Per Step Cost"
              helperText="Cost of each step"
              type="number"
              min="0"
              value={perStepCost}
              onChange={(e) => {
                let input = parseInt(e.target.value)
                if (input < 0) input = 0
                setPerStepCost(input)
              }}
              onBlur={(e) => !e.target.value && setPerStepCost(0)}
            />
          </div>

          <div>
            <TextField
              label="Per Mem Unit Cost"
              helperText="Cost of each mem unit"
              type="number"
              min="0"
              value={perMemUnitCost}
              onChange={(e) => {
                let input = parseInt(e.target.value)
                if (input < 0) input = 0
                setMemUnitCost(input)
              }}
              onBlur={(e) => !e.target.value && setMemUnitCost(0)}
            />
          </div>

          <div>
            <TextField
              label="Per Transaction Cost"
              helperText="Per Transaction Cost"
              type="number"
              min="0"
              value={perTransactionCost}
              onChange={(e) => setPerTransactionCost(parseInt(e.target.value))}
              onBlur={(e) => !e.target.value && setPerTransactionCost(0)}
            />
          </div>
        </Params>
      )}
      <Transactions>
        {transactions.map((t, i) => (
          <Transaction key={i}>
            <Title>Transaction {i + 1}</Title>
            <DeleteButton
              onClick={() => {
                const txs = transactions
                txs.splice(i, 1)
                console.log(txs)
                setTransactions([...txs])
              }}
            >
              <MdClear />
            </DeleteButton>
            <Fields>
              <FieldContainer>
                <TextField
                  type="number"
                  min="0"
                  max="16384"
                  value={t.txSize}
                  label="Size (bytes)"
                  helperText="max 16KB (16384B)"
                  onChange={(e) => {
                    const txs = transactions
                    let input = parseInt(e.target.value)
                    if (input < 0) input = 0

                    txs[i].txSize = input > 16384 ? 16384 : input

                    setTransactions([...txs])
                  }}
                  onBlur={(e) => {
                    if (e.target.value) return null
                    const txs = transactions
                    txs[i].txSize = 0
                    setTransactions([...txs])
                  }}
                />
                <Tooltip
                  data-tip="The size of an on-chain transaction in bytes, which can be derived<br/> from the transaction prepared on-disk. Size varies depending on transaction content.<br/> A typical transaction for a smart contract will be between 3KB-5KB."
                  data-multiline
                >
                  ?
                </Tooltip>
              </FieldContainer>

              <FieldContainer>
                <TextField
                  type="number"
                  min="0"
                  max="10000000000"
                  value={t.cpuSteps}
                  label="CPU Steps"
                  helperText="max 10000000000"
                  onChange={(e) => {
                    const txs = transactions
                    let input = parseInt(e.target.value)
                    if (input < 0) input = 0
                    txs[i].cpuSteps = input > 10000000000 ? 10000000000 : input

                    setTransactions([...txs])
                  }}
                  onBlur={(e) => {
                    if (e.target.value) return null
                    const txs = transactions
                    txs[i].cpuSteps = 0
                    setTransactions([...txs])
                  }}
                />
                <Tooltip
                  data-tip="A variable abstraction of the time a transaction takes to execute<br/> on a reference computer. More complex contracts require more CPU steps."
                  data-multiline
                >
                  ?
                </Tooltip>
              </FieldContainer>

              <FieldContainer>
                <TextField
                  min="0"
                  max="11250000"
                  value={t.memUnits}
                  label="Memory Units (bytes)"
                  helperText="max 11250000B"
                  type="number"
                  onChange={(e) => {
                    const txs = transactions
                    let input = parseInt(e.target.value)
                    if (input < 0) input = 0
                    txs[i].memUnits = input > 11250000 ? 11250000 : input
                    setTransactions([...txs])
                  }}
                  onBlur={(e) => {
                    if (e.target.value) return null
                    const txs = transactions
                    txs[i].memUnits = 0
                    setTransactions([...txs])
                  }}
                />
                <Tooltip
                  data-tip="Memory allocated by the transaction, in bytes.<br/> More complex contracts usually require higher memory allocation."
                  data-multiline
                >
                  ?
                </Tooltip>
              </FieldContainer>
            </Fields>
            <TxPrice>
              <span>₳ {txPrice(t).toFixed(6)}</span>
              Estimated Transaction Price in ADA
            </TxPrice>
          </Transaction>
        ))}
      </Transactions>

      <Controls>
        {/* temporarily removed
        <RoundedButton
          onClick={() => setShowParams(!showParams)}
        >
          {showParams ? 'Hide' : 'Show'} network parameters
          <span>{showParams ? <MdVisibilityOff /> : <MdVisibility />}</span>
        </RoundedButton>
        */}
        <RoundedButton
          onClick={() =>
            setTransactions([
              ...transactions,
              {
                txSize: 0,
                cpuSteps: 0,
                memUnits: 0
              }
            ])
          }
        >
          Add Transaction
        </RoundedButton>
        <RoundedButton
          onClick={() => {
            setPerByteCost(44)
            setPerStepCost(0.0000721)
            setMemUnitCost(0.0577)
            setPerTransactionCost(155381)
            setTransactions([
              {
                txSize: 0,
                cpuSteps: 0,
                memUnits: 0
              }
            ])
          }}
        >
          Reset All{' '}
          <span>
            <MdRotateLeft />
          </span>
        </RoundedButton>
      </Controls>

      <FeeTitle>Total Estimated Dapp Fee:</FeeTitle>
      <Results>
        <div>
          {' '}
          <Price>${(dappFee() * adaPrice).toFixed(2)} USD</Price>
          <PriceInfo>
            When 1 ADA = ${adaPrice}
            {!unableToGetPrice && <span>Rate supplied by CoinGecko</span>}
          </PriceInfo>
          <CardanoLogo active />
        </div>
        <div>
          <Price>${(dappFee() * adaPriceScenario).toFixed(2)} USD</Price>
          <PriceInfo>
            When 1 ADA = $
            <input
              type="number"
              min="0"
              value={adaPriceScenario}
              onChange={(e) => setAdaPriceScenario(e.target.value)}
            />
          </PriceInfo>
          <CardanoLogo active={false} />
        </div>
      </Results>
      <h5>How are the costs calculated?</h5>
      <p>
        Primitive Plutus operations (the internal building blocks) are evaluated on a reference architecture to give the costs for each primitive in terms of the basic CPU and memory units that it uses.  These are scaled based on the number of each different primitive that is used by a smart contract, and overall costs for a smart contract are calculated based on the current costs for each CPU and memory unit, plus the size of the transaction (including the size of the script, plus any datums that it needs).
        <br />
        <br />
        <br />
      </p>
    </>
  ) : (
    <div>Loading...</div>
  )
}