utils#bnum TypeScript Examples

The following examples show how to use utils#bnum. 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: useERC20.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
useBalance = (
  fromAddress: string,
  assetAddress: string
): BigNumber => {
  const { data, error } = useContractCalls([
    {
      address: assetAddress,
      abi: ERC20JSON.abi,
      functionName: 'balanceOf',
      params: [fromAddress],
    },
  ]);
  if (error) return bnum('0');
  else if (!data) return bnum('0');
  else return bnum(data[0]);
}
Example #2
Source File: useERC20.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
useAllowance = (
  tokenAddress: string,
  fromAddress: string,
  toAddress: string
): BigNumber => {
  const { data, error } = useContractCalls([
    {
      address: tokenAddress,
      abi: ERC20JSON.abi,
      functionName: 'allowance',
      params: [fromAddress, toAddress],
    },
  ]);
  if (error) return bnum('0');
  else if (!data) return bnum('0');
  else return bnum(data[0]);
}
Example #3
Source File: useETHBalance.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
useETHBalance = (fromAddress: string): BigNumber => {
  const {
    context: { configStore },
  } = useContext();

  const { data, error } = useContractCalls([
    {
      address: configStore.getNetworkContracts().utils.multicall,
      abi: MulticallJSON.abi,
      functionName: 'getEthBalance',
      params: [fromAddress],
    },
  ]);

  if (error) return bnum('0');
  else if (!data) return bnum('0');
  else return bnum(data[0]);
}
Example #4
Source File: usePaymentAmounts.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
usePaymentAmounts = (
  confirm: boolean,
  dxdPrice: number,
  dxdOverride: number,
  stableOverride: number,
  noRep: boolean,
  selectedLevel: any,
  totalSupply: BigNumber
): UsePaymentAmountsReturns => {
  const [dxdAmount, setDxdAmount] = useState(null);
  const [stableAmount, setStableAmount] = useState(null);
  const [repReward, setRepReward] = useState(null);
  const [discount, setDiscount] = useState(1);

  useEffect(() => {
    setDxdAmount(
      denormalizeBalance(
        bnum(
          (selectedLevel?.dxd / (dxdOverride ? dxdOverride : dxdPrice)) *
            discount
        )
      ).toString()
    );
    setStableAmount(
      denormalizeBalance(
        bnum(calculateDiscountedValue(selectedLevel?.stable, stableOverride))
      )
    );

    setRepReward(
      noRep
        ? 0
        : formatNumberValue(totalSupply.times(0.001667).times(discount), 0)
    );
  }, [
    confirm,
    discount,
    dxdPrice,
    dxdOverride,
    noRep,
    selectedLevel,
    totalSupply,
  ]);

  const calculateDiscountedValue = (amount, override = null) => {
    return override || amount * discount;
  };

  return {
    setDiscount,
    dxdAmount,
    stableAmount,
    repReward,
    discount,
    calculateDiscountedValue,
  };
}
Example #5
Source File: useRep.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
useRep = (userAddress: string = ZERO_ADDRESS): UseRepReturns => {
  const {
    context: { daoStore, providerStore },
  } = useContext();
  const [memo, setMemo] = useState<MemoInteface | undefined>(undefined);
  const cache: MemoInteface = {};
  const repEvents = daoStore.daoCache.reputation.events;

  let totalSupply: BigNumber = bnum(0);
  let userRep: BigNumber = bnum(0);

  for (let i = 0; i < repEvents.length; i++) {
    if (repEvents[i].event === 'Mint') {
      totalSupply = totalSupply.plus(repEvents[i].amount);
      cache[repEvents[i].blockNumber] = {
        totalSupply: totalSupply,
        userRep: bnum(0),
      };
      if (repEvents[i].account === userAddress)
        userRep = userRep.plus(repEvents[i].amount);
      cache[repEvents[i].blockNumber] = {
        totalSupply: totalSupply,
        userRep: userRep,
      };
      cache[repEvents[i].blockNumber]['userRep'] = userRep;
    } else if (repEvents[i].event === 'Burn') {
      totalSupply = totalSupply.minus(repEvents[i].amount);
      cache[repEvents[i].blockNumber] = {
        totalSupply: totalSupply,
        userRep: bnum(0),
      };
      if (repEvents[i].account === userAddress)
        userRep = userRep.minus(repEvents[i].amount);
      cache[repEvents[i].blockNumber] = {
        totalSupply: totalSupply,
        userRep: userRep,
      };
    }
  }

  useEffect(() => {
    setMemo(cache);
  }, [repEvents]);

  const getRep = (atBlock: number = 0) => {
    const values = memo || cache;
    if (atBlock === 0) atBlock = providerStore.getCurrentBlockNumber();
    const closest = Object.keys(values).reduce((a, b) =>
      parseInt(b) > atBlock ? a : b
    );
    const totalSupply = values[closest]['totalSupply'];
    const userRep = values[closest]['userRep'];

    return { totalSupply, userRep };
  };
  return {
    getRep,
  };
}
Example #6
Source File: RecommendedCalls.tsx    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
RecommendedCalls = ({
  to,
  from,
  recommendedCallUsed,
  callParameters,
  encodedFunctionName,
  data,
  showMore,
}: RecomendedCallsProps) => {
  const {
    context: { daoStore },
  } = useContext();

  const proposalId = useLocation().pathname.split('/')[3];
  const proposal = daoStore.getProposal(proposalId);

  const normalizeValue = (value: any, param: CallParameterDefinition) => {
    if (param.decimals) {
      return normalizeBalance(value, param.decimals).toString();
    }

    return value;
  };

  const getComponentToRender = (param: CallParameterDefinition, value: any) => {
    if (param.isRep) {
      return (
        <RepDisplay
          rep={bnum(value)}
          atBlock={proposal.creationEvent.blockNumber}
          timestamp={proposal.creationEvent.timestamp}
        />
      );
    } else {
      return normalizeValue(value, param);
    }
  };

  let decodedCallDetail: React.ReactNodeArray = [
    recommendedCallUsed.decodeText,
  ];
  if (
    recommendedCallUsed.decodeText &&
    recommendedCallUsed.decodeText.length > 0
  ) {
    recommendedCallUsed.params.forEach((param, paramIndex) => {
      const component = getComponentToRender(param, callParameters[paramIndex]);

      decodedCallDetail = reactStringReplace(
        reactStringReplace(
          decodedCallDetail,
          `[PARAM_${paramIndex}]`,
          () => component
        ),
        'FROM',
        () => proposal.scheme
      );
    });
  }

  if (showMore) {
    return (
      <div>
        <p>
          <strong>From: </strong>{' '}
          <small>
            <BlockchainLink text={from} toCopy={false} />
          </small>
        </p>
        <p>
          <strong>To: </strong>{' '}
          <small>
            <BlockchainLink text={to} toCopy={false} />
          </small>
        </p>
        <p>
          <strong>Descriptions: </strong>{' '}
          <small>{recommendedCallUsed.toName}</small>
        </p>
        <p>
          <strong>Function: </strong>
          <small>{recommendedCallUsed.functionName}</small>
        </p>
        <p>
          <strong>Function Signature: </strong>{' '}
          <small>{encodedFunctionName}</small>
        </p>
        <strong>Params: </strong>
        {Object.keys(callParameters).map((paramIndex, i) => {
          return (
            <p key={i}>
              <small>{callParameters[paramIndex]} </small>
            </p>
          );
        })}
        <strong>data: </strong>
        <small>{data} </small>
      </div>
    );
  }

  return (
    <div>
      <small>{decodedCallDetail}</small>
    </div>
  );
}
Example #7
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
Stakes = () => {
  const {
    context: { daoStore, configStore, providerStore, daoService },
  } = useContext();

  const [stakeAmount, setStakeAmount] = useState(0);
  // We should get the ID in another way
  const proposalId = useLocation().pathname.split('/')[3];

  const proposal = daoStore.getProposal(proposalId);
  const proposalEvents = daoStore.getProposalEvents(proposalId);
  const { account } = providerStore.getActiveWeb3React();
  const scheme = daoStore.getScheme(proposal.scheme);

  let stakedAmount = bnum(0);
  let positiveStakesCount = proposalEvents.stakes.filter(
    stake => stake.vote.toString() === '1'
  ).length;
  let negativeStakesCount = proposalEvents.stakes.filter(
    stake => stake.vote.toString() === '2'
  ).length;
  const networkContracts = configStore.getNetworkContracts();
  const votingMachines = networkContracts.votingMachines;

  const redeemsLeft = daoStore.getUserRedeemsLeft(account);

  const votingMachineOfProposal =
    daoStore.getVotingMachineOfProposal(proposalId);

  const votingMachineTokenName =
    votingMachines[votingMachineOfProposal.address].type == 'DXDVotingMachine'
      ? 'DXD'
      : 'GEN';

  const votingMachineTokenAllowed = useAllowance(
    votingMachines[votingMachineOfProposal.address].token,
    account,
    votingMachineOfProposal.address
  );

  const votingMachineTokenApproved = votingMachineTokenAllowed.gt(
    bnum(parseUnits('10000'))
  );

  const votingParameters =
    daoStore.getVotingMachineOfProposal(proposalId).params;

  proposalEvents.stakes.map(stake => {
    if (stake.staker === account && stake.vote.toString() === '1') {
      stakedAmount = stakedAmount.plus(stake.amount);
    } else if (stake.staker === account && stake.vote.toString() === '2') {
      stakedAmount = stakedAmount.minus(stake.amount);
    }
  });

  const { recommendedStakeToBoost, recommendedStakeToUnBoost } =
    calculateStakes(
      votingParameters.thresholdConst,
      scheme.boostedProposals,
      proposal.stateInVotingMachine === 4
        ? daoStore.getAmountOfProposalsPreBoostedInScheme(scheme.address) - 1
        : daoStore.getAmountOfProposalsPreBoostedInScheme(scheme.address),
      proposal.positiveStakes,
      proposal.negativeStakes
    );

  if (Number(votingMachineTokenApproved) > 0 && stakeAmount === 0) {
    setStakeAmount(
      Number(formatBalance(recommendedStakeToBoost, 18, 1, false))
    );
  }

  const { finishTime } = daoStore.getProposalStatus(proposalId);
  const finishTimeReached = finishTime.toNumber() < moment().unix();

  // Event Handlers
  function onStakeAmountChange(event) {
    setStakeAmount(event.target.value);
  }

  const submitStake = function (decision) {
    daoService.stake(
      decision,
      denormalizeBalance(bnum(stakeAmount)).toString(),
      proposalId
    );
  };

  const redeem = function () {
    if (
      scheme.type === 'ContributionReward' &&
      networkContracts.daostack[scheme.address].redeemer
    ) {
      daoService.redeemContributionReward(
        networkContracts.daostack[scheme.address].redeemer,
        scheme.address,
        scheme.votingMachine,
        proposalId,
        account
      );
    } else {
      daoService.redeem(proposalId, account);
    }
  };

  const redeemDaoBounty = function () {
    daoService.redeemDaoBounty(proposalId, account);
  };

  const votingMachineUsed = daoStore.getVotingMachineOfProposal(proposalId);
  const approveVotingMachineToken = function () {
    daoService.approveVotingMachineToken(votingMachineUsed);
  };

  return (
    <>
      <SpaceAroundRow>
        <strong>
          Stakes <Question question="5" />
        </strong>
      </SpaceAroundRow>
      <SpaceAroundRow>
        <PositiveSummary>
          <SummaryTotal>
            <AmountBadge color="green">{positiveStakesCount}</AmountBadge>
            {formatBalance(proposal.positiveStakes).toString()}
            {votingMachineTokenName}
          </SummaryTotal>
          <HorizontalSeparator />
          <SummaryDetails>
            {proposalEvents &&
              proposalEvents.stakes
                .filter(stakeEvent => stakeEvent?.vote?.toString() === '1')
                .map((stakeEvent, i) => (
                  <Vote key={`stakeUp${i}`} style={{ flexDirection: 'column' }}>
                    <BlockchainLink
                      size="short"
                      type="user"
                      text={stakeEvent.staker}
                    />
                    <span>
                      {formatBalance(bnum(stakeEvent.amount)).toString()}
                      {votingMachineTokenName}
                    </span>
                  </Vote>
                ))}
          </SummaryDetails>
        </PositiveSummary>

        <NegativeSummary>
          <SummaryTotal>
            <AmountBadge color="red">{negativeStakesCount}</AmountBadge>
            {formatBalance(proposal.negativeStakes).toString()}
            {votingMachineTokenName}
          </SummaryTotal>
          <HorizontalSeparator />
          <SummaryDetails>
            {proposalEvents &&
              proposalEvents.stakes
                .filter(stakeEvent => stakeEvent?.vote?.toString() === '2')
                .map((stakeEvent, i) => (
                  <Vote
                    key={`stakeDown${i}`}
                    style={{ flexDirection: 'column' }}
                  >
                    <BlockchainLink
                      size="short"
                      type="user"
                      text={stakeEvent.staker}
                    />
                    <span>
                      {formatBalance(bnum(stakeEvent.amount)).toString()}
                      {votingMachineTokenName}
                    </span>
                  </Vote>
                ))}
          </SummaryDetails>
        </NegativeSummary>
      </SpaceAroundRow>

      {stakedAmount.toNumber() > 0 ? (
        <SpaceAroundRow>
          {`Already staked ${
            stakedAmount.toNumber() > 0 ? 'for' : 'against'
          } with `}
          {formatBalance(stakedAmount).toString()} {votingMachineTokenName}
        </SpaceAroundRow>
      ) : (
        <div></div>
      )}

      {account &&
      !finishTimeReached &&
      (proposal.stateInVotingMachine === 3 ||
        proposal.stateInVotingMachine === 4) &&
      !votingMachineTokenApproved ? (
        <SpaceAroundRow>
          <ActionArea>
            <small>Approve {votingMachineTokenName} to stake</small>
            <ActionButton
              color="blue"
              onClick={() => approveVotingMachineToken()}
            >
              Approve {votingMachineTokenName}
            </ActionButton>
          </ActionArea>
        </SpaceAroundRow>
      ) : (
        account &&
        !finishTimeReached &&
        (proposal.stateInVotingMachine === 3 ||
          proposal.stateInVotingMachine === 4) && (
          <div>
            {Number(recommendedStakeToBoost) > 0 && (
              <small>
                Stake ~
                {formatBalance(
                  recommendedStakeToBoost,
                  18,
                  1,
                  false
                ).toString()}
                {votingMachineTokenName} to boost
              </small>
            )}
            {Number(recommendedStakeToUnBoost) > 0 && (
              <small>
                Stake ~
                {formatBalance(
                  recommendedStakeToUnBoost,
                  18,
                  1,
                  false
                ).toString()}
                {votingMachineTokenName} to unboost
              </small>
            )}
            <SpaceAroundRow>
              <AmountInput
                type="number"
                placeholder={votingMachineTokenName}
                name="stakeAmount"
                value={stakeAmount}
                id="stakeAmount"
                step="0.01"
                min="0"
                onChange={onStakeAmountChange}
                style={{ flex: 2 }}
              />
              <ActionButton
                style={{ flex: 1, maxWidth: '20px', textAlign: 'center' }}
                color="green"
                onClick={() => submitStake(1)}
              >
                <FiThumbsUp />
              </ActionButton>
              <ActionButton
                style={{ flex: 1, maxWidth: '20px', textAlign: 'center' }}
                color="red"
                onClick={() => submitStake(2)}
              >
                <FiThumbsDown />
              </ActionButton>
            </SpaceAroundRow>
          </div>
        )
      )}

      {proposal.stateInVotingMachine < 3 &&
        (redeemsLeft.rep.indexOf(proposalId) > -1 ||
          redeemsLeft.stake.indexOf(proposalId) > -1) && (
          <SpaceAroundRow
            style={{
              borderTop: '1px solid gray',
              margin: '0px 10px',
              justifyContent: 'center',
            }}
          >
            <ActionButton color="blue" onClick={() => redeem()}>
              Redeem
            </ActionButton>
          </SpaceAroundRow>
        )}

      {account &&
        proposal.stateInVotingMachine < 3 &&
        redeemsLeft.bounty[proposalId] && (
          <SpaceAroundRow
            style={{
              borderTop: '1px solid gray',
              margin: '0px 10px',
              justifyContent: 'center',
            }}
          >
            <ActionButton color="blue" onClick={() => redeemDaoBounty()}>
              Redeem Stake Bounty
            </ActionButton>
          </SpaceAroundRow>
        )}
    </>
  );
}
Example #8
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
Status = () => {
  const {
    context: { daoStore, configStore, providerStore, daoService },
  } = useContext();

  //State
  const networkContracts = configStore.getNetworkContracts();
  // We should get the ID in another way
  const proposalId = useLocation().pathname.split('/')[3];
  const proposal = daoStore.getProposal(proposalId);
  const { account } = providerStore.getActiveWeb3React();
  const scheme = daoStore.getScheme(proposal.scheme);

  const executionTimeoutTime = isWalletScheme(scheme)
    ? proposal.submittedTime.plus(scheme.maxSecondsForExecution)
    : bnum(0);

  const executePendingAction = function (pendingAction) {
    switch (pendingAction) {
      case PendingAction.Redeem:
        daoService.redeemContributionReward(
          networkContracts.daostack[scheme.address].redeemer,
          scheme.address,
          scheme.votingMachine,
          proposalId,
          account
        );
        break;
      case PendingAction.RedeemForBeneficiary:
        daoService.executeMulticall(scheme.address, proposalId);
        break;
      default:
        daoService.execute(proposalId);
        break;
    }
  };

  const votingMachineUsed = daoStore.getVotingMachineOfProposal(proposalId);

  const { status, boostTime, finishTime, pendingAction } =
    daoStore.getProposalStatus(proposalId);

  const autoBoost =
    networkContracts.votingMachines[votingMachineUsed.address].type ==
    'DXDVotingMachine';

  return (
    <>
      <h2 style={{ margin: '10px 0px 0px 0px', textAlign: 'center' }}>
        {status} <Question question="3" />
      </h2>
      <SpaceAroundRow style={{ margin: '0px 10px', flexDirection: 'column' }}>
        {boostTime.toNumber() > moment().unix() && (
          <span className="timeText">
            Boost in <Countdown date={boostTime.toNumber() * 1000} />{' '}
          </span>
        )}
        {finishTime.toNumber() > moment().unix() && (
          <span className="timeText">
            Finish in{' '}
            <Countdown
              autoStart={pendingAction === 1 && !autoBoost ? false : true}
              date={finishTime.toNumber() * 1000}
            />
            {pendingAction === 1 && !autoBoost && ' after boost'}
          </span>
        )}
        {status === 'Pending Execution' && executionTimeoutTime.toNumber() > 0 && (
          <span className="timeText">
            {' '}
            Execution timeout in{' '}
            <Countdown date={executionTimeoutTime.toNumber() * 1000} />{' '}
          </span>
        )}
      </SpaceAroundRow>
      {account && pendingAction > 0 && (
        <SpaceAroundRow
          style={{ flexDirection: 'column', alignItems: 'center' }}
        >
          <ActionButton
            color="blue"
            onClick={() => executePendingAction(pendingAction)}
          >
            <FiPlayCircle /> {PendingAction[pendingAction]}{' '}
          </ActionButton>
        </SpaceAroundRow>
      )}
    </>
  );
}
Example #9
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
Votes = () => {
  const {
    context: {
      configStore,
      daoStore,
      providerStore,
      daoService,
      orbitDBService,
    },
  } = useContext();

  //State
  const [signVote, setSignVote] = useState(false);
  const [decision, setDecision] = useState(0);
  const [votePercentage, setVotePercentage] = useState(0);
  const [signedVotesOfProposal, setSignedVotesOfProposal] = useState([]);
  const [loadingSignedOrbitDBVotes, setLoadingSignedOrbitDBVotes] =
    useState(true);

  // We should get the ID in another way
  const proposalId = useLocation().pathname.split('/')[3];

  const proposal = daoStore.getProposal(proposalId);
  const proposalEvents = daoStore.getProposalEvents(proposalId);
  const { account } = providerStore.getActiveWeb3React();
  const signedVoteMessageId = utils.id(`dxvote:${proposalId}`);
  const { finishTime } = daoStore.getProposalStatus(proposalId);
  const votingMachineOfProposal =
    daoStore.getVotingMachineOfProposal(proposalId);
  const finishTimeReached = finishTime.toNumber() < moment().unix();
  const isDXDVotingMachine =
    configStore.getNetworkContracts().votingMachines[
      votingMachineOfProposal.address
    ].type == 'DXDVotingMachine';

  orbitDBService.getLogs(signedVoteMessageId).then(signedVoteMessages => {
    console.debug('[OrbitDB messages]', signedVoteMessages);
    signedVoteMessages.map(signedVoteMessageRaw => {
      const signedVoteMessage = parseSignedVoteMessage(signedVoteMessageRaw);
      if (signedVoteMessage.valid) {
        const alreadyAdded =
          signedVotesOfProposal.findIndex(
            s => s.voter == signedVoteMessage.voter
          ) > -1 ||
          proposalEvents.votes.findIndex(
            s => s.voter == signedVoteMessage.voter
          ) > -1;

        const repOfVoterForProposal = daoStore.getRepAt(
          signedVoteMessage.voter,
          proposal.creationEvent.blockNumber
        ).userRep;

        if (
          !alreadyAdded &&
          repOfVoterForProposal >= bnum(signedVoteMessage.repAmount)
        ) {
          signedVotesOfProposal.push({
            voter: signedVoteMessage.voter,
            vote: signedVoteMessage.decision,
            amount: bnum(signedVoteMessage.repAmount),
            signature: signedVoteMessage.signature,
            source: 'orbitDB',
          });
        }
      }
    });
    setSignedVotesOfProposal(signedVotesOfProposal);
    setLoadingSignedOrbitDBVotes(false);
  });

  let votedAmount = bnum(0);

  proposalEvents.votes.map(vote => {
    if (vote.voter === account) {
      votedAmount = bnum(vote.amount);
    }
  });

  let positiveVotesCount = proposalEvents.votes.filter(vote =>
    isVoteYes(vote.vote)
  ).length;

  let negativeVotesCount = proposalEvents.votes.filter(vote =>
    isVoteNo(vote.vote)
  ).length;

  const {
    userRep: userRepAtProposalCreation,
    totalSupply: totalRepAtProposalCreation,
  } = daoStore.getRepAt(account, proposal.creationEvent.blockNumber);

  const repPercentageAtCreation = toPercentage(
    userRepAtProposalCreation.div(totalRepAtProposalCreation)
  ).toFixed(2);

  const positiveVotes = toPercentage(
    proposal.positiveVotes.div(totalRepAtProposalCreation)
  ).toFixed(2, 4);

  const negativeVotes = toPercentage(
    proposal.negativeVotes.div(totalRepAtProposalCreation)
  ).toFixed(2, 4);

  const totalPositiveSignedVotes = toPercentage(
    signedVotesOfProposal
      .filter(signedVote => isVoteYes(signedVote.vote))
      .reduce(function (acc, obj) {
        return acc.plus(obj.amount);
      }, bnum(0))
      .div(totalRepAtProposalCreation)
  ).toFixed(2, 4);

  const totalNegativeSignedVotes = toPercentage(
    signedVotesOfProposal
      .filter(signedVote => isVoteNo(signedVote.vote))
      .reduce(function (acc, obj) {
        return acc.plus(obj.amount);
      }, bnum(0))
      .div(totalRepAtProposalCreation)
  ).toFixed(2, 4);

  if (Number(repPercentageAtCreation) > 0 && votePercentage === 0) {
    setVotePercentage(Number(repPercentageAtCreation));
  }

  // Events Handlers
  const onVoteValueChange = event => {
    setVotePercentage(
      event.target.value < repPercentageAtCreation
        ? event.target.value
        : repPercentageAtCreation
    );
  };

  const executeSignedVote = function (signedVote) {
    daoService.executeSignedVote(
      votingMachineOfProposal.address,
      proposalId,
      signedVote.voter,
      signedVote.vote,
      signedVote.amount.toString(),
      signedVote.signature
    );
  };

  const submitVote = async function (voteDetails: {
    votingMachine: string;
    proposalId: string;
    voter: string;
    decision: string;
    repAmount: string;
    signVote: boolean;
    networks: boolean[];
    hashToETHMessage: boolean;
  }) {
    if (voteDetails.signVote) {
      const voteSignature = await daoService.signVote(
        voteDetails.votingMachine,
        voteDetails.proposalId,
        voteDetails.decision,
        voteDetails.repAmount,
        voteDetails.hashToETHMessage
      );
      if (
        verifySignedVote(
          voteDetails.votingMachine,
          voteDetails.proposalId,
          voteDetails.voter,
          voteDetails.decision,
          voteDetails.repAmount,
          voteSignature
        )
      ) {
        if (voteDetails.networks[0])
          orbitDBService.addLog(
            utils.id(`dxvote:${proposalId}`),
            `signedVote:${voteDetails.votingMachine}:${voteDetails.proposalId}:${voteDetails.voter}:${voteDetails.decision}:${voteDetails.repAmount}:${voteSignature}`
          );
      }
    } else {
      daoService.vote(
        voteDetails.decision,
        voteDetails.repAmount,
        voteDetails.proposalId
      );
    }

    setDecision(0);
  };

  // TODO:
  // This Component could be abstracted so much!
  // <Counts> <NewVote> each one getting proposalEvents and iterating and counting.
  // and Summary can be based on polarity <Summary polarity={positive|negative} /> and reused.
  return (
    <>
      <SpaceAroundRow>
        <strong>
          Confirmed Votes <Question question="4" />
        </strong>
      </SpaceAroundRow>
      <SpaceAroundRow>
        <PositiveSummary>
          <SummaryTotal>
            <AmountBadge color="green">{positiveVotesCount}</AmountBadge>
            {`${positiveVotes}%`}
          </SummaryTotal>
          <HorizontalSeparator />
          <SummaryDetails>
            {proposalEvents?.votes
              .filter(voteEvent => isVoteYes(voteEvent.vote))
              .map((voteEvent, i) => (
                <Vote key={`vote-pos-${i}`}>
                  <BlockchainLink
                    size="short"
                    type="user"
                    text={voteEvent.voter}
                  />
                  <span>
                    {bnum(voteEvent.amount)
                      .times('100')
                      .div(totalRepAtProposalCreation)
                      .toFixed(2, 4)}
                    %
                  </span>
                </Vote>
              ))}
          </SummaryDetails>
        </PositiveSummary>
        <NegativeSummary>
          <SummaryTotal>
            <AmountBadge color="red">{negativeVotesCount}</AmountBadge>
            <span>{`${negativeVotes}%`}</span>
          </SummaryTotal>
          <HorizontalSeparator />
          <SummaryDetails>
            {proposalEvents?.votes
              ?.filter(voteEvent => isVoteNo(voteEvent.vote))
              .map((voteEvent, i) => (
                <Vote key={`vote-neg-${i}`}>
                  <BlockchainLink
                    size="short"
                    type="user"
                    text={voteEvent.voter}
                  />
                  <span>
                    {bnum(voteEvent.amount)
                      .times('100')
                      .div(totalRepAtProposalCreation)
                      .toFixed(2, 4)}
                    %
                  </span>
                </Vote>
              ))}
          </SummaryDetails>
        </NegativeSummary>
      </SpaceAroundRow>

      {!loadingSignedOrbitDBVotes && (
        <div>
          <SpaceAroundRow>
            <strong>
              Signed Votes <Question question="4" /> <br />
              {!isDXDVotingMachine && <small>Non-Executable</small>}
            </strong>
          </SpaceAroundRow>
          <SpaceAroundRow>
            <PositiveSummary>
              <SummaryTotal>
                <AmountBadge color="green">
                  {
                    signedVotesOfProposal.filter(signedVote =>
                      isVoteYes(signedVote.vote)
                    ).length
                  }
                </AmountBadge>
                {`${totalPositiveSignedVotes}%`}
              </SummaryTotal>
              <HorizontalSeparator />
              <SummaryDetails>
                {signedVotesOfProposal
                  .filter(signedVote => isVoteYes(signedVote.vote))
                  .map((signedVote, i) => (
                    <Vote key={`vote-pos-${i}`}>
                      <BlockchainLink
                        size="short"
                        type="user"
                        text={signedVote.voter}
                      />
                      <span>
                        {bnum(signedVote.amount)
                          .times('100')
                          .div(totalRepAtProposalCreation)
                          .toFixed(2, 4)}
                        %
                      </span>
                      {isDXDVotingMachine && (
                        <ActionButton
                          style={{
                            height: '15px',
                            margin: '0px 0px 0px 2px',
                            maxWidth: '15px',
                            textAlign: 'center',
                          }}
                          color="#536DFE"
                          onClick={() => executeSignedVote(signedVote)}
                        >
                          <FiArrowUp />
                        </ActionButton>
                      )}
                    </Vote>
                  ))}
              </SummaryDetails>
            </PositiveSummary>
            <NegativeSummary>
              <SummaryTotal>
                <AmountBadge color="red">
                  {
                    signedVotesOfProposal.filter(signedVote =>
                      isVoteNo(signedVote.vote)
                    ).length
                  }
                </AmountBadge>
                {`${totalNegativeSignedVotes}%`}
              </SummaryTotal>
              <HorizontalSeparator />
              <SummaryDetails>
                {signedVotesOfProposal
                  ?.filter(signedVote => isVoteNo(signedVote.vote))
                  .map((signedVote, i) => (
                    <Vote key={`vote-neg-${i}`}>
                      <BlockchainLink
                        size="short"
                        type="user"
                        text={signedVote.voter}
                      />
                      <span>
                        {bnum(signedVote.amount)
                          .times('100')
                          .div(totalRepAtProposalCreation)
                          .toFixed(2, 4)}
                        %
                      </span>
                      {isDXDVotingMachine && (
                        <ActionButton
                          style={{
                            height: '15px',
                            margin: '0px 0px 0px 2px',
                            maxWidth: '15px',
                            textAlign: 'center',
                          }}
                          color="#536DFE"
                          onClick={() => executeSignedVote(signedVote)}
                        >
                          <FiArrowUp />
                        </ActionButton>
                      )}
                    </Vote>
                  ))}
              </SummaryDetails>
            </NegativeSummary>
          </SpaceAroundRow>
        </div>
      )}

      {Number(repPercentageAtCreation) > 0 && (
        <small>{repPercentageAtCreation} % REP at proposal creation</small>
      )}

      {(proposal.stateInVotingMachine === 3 ||
        proposal.stateInVotingMachine === 4) &&
        votingMachineOfProposal.params.votersReputationLossRatio.toNumber() >
          0 &&
        finishTime.toNumber() > 0 && (
          <TextCenter>
            <small>
              Voter REP Loss Ratio:
              {votingMachineOfProposal.params.votersReputationLossRatio.toString()}
              %
            </small>
          </TextCenter>
        )}

      {account &&
      !finishTimeReached &&
      votedAmount.toNumber() === 0 &&
      Number(repPercentageAtCreation) > 0 &&
      proposal.stateInVotingMachine >= 3 ? (
        <SpaceAroundRow>
          <ConfirmVoteModal
            voteDecision={decision}
            toAdd={votePercentage}
            positive={parseFloat(positiveVotes)}
            negative={parseFloat(negativeVotes)}
            onConfirm={submitVote}
            onCancel={() => setDecision(0)}
            voteDetails={{
              votingMachine: votingMachineOfProposal.address,
              proposalId: proposalId,
              voter: account,
              decision: decision.toString(),
              repAmount: totalRepAtProposalCreation
                .times(bnum(votePercentage))
                .div('100')
                .toFixed(0, 1)
                .toString(),
              signVote: signVote,
            }}
          />
          <AmountInput
            type="number"
            placeholder="REP"
            name="votePercentage"
            max={repPercentageAtCreation}
            value={votePercentage}
            min="0"
            step={
              votePercentage > 10
                ? '1'
                : votePercentage > 1
                ? '0.01'
                : votePercentage > 0.1
                ? '0.001'
                : '0.00001'
            }
            id="votePercentage"
            onChange={onVoteValueChange}
            style={{ flex: 2 }}
          />
          <ActionButton
            style={{ flex: 1, maxWidth: '20px', textAlign: 'center' }}
            color="green"
            onClick={() => setDecision(1)}
          >
            <FiThumbsUp />
          </ActionButton>
          <ActionButton
            style={{ flex: 1, maxWidth: '20px', textAlign: 'center' }}
            color="red"
            onClick={() => setDecision(2)}
          >
            <FiThumbsDown />
          </ActionButton>
          <ActionButton
            style={{ flex: 1, maxWidth: '20px', textAlign: 'center' }}
            color="#536DFE"
            onClick={() => setSignVote(!signVote)}
          >
            {signVote ? <FiWifiOff /> : <FiWifi />}
          </ActionButton>
        </SpaceAroundRow>
      ) : (
        votedAmount.toNumber() !== 0 && (
          <SpaceAroundRow>
            <TextCenter>
              {`
              Already voted ${votedAmount.toNumber() > 0 ? 'for' : 'against'}
              with
              ${votedAmount
                .times('100')
                .div(totalRepAtProposalCreation)
                .toFixed(2, 4)}
              % REP`}
            </TextCenter>
          </SpaceAroundRow>
        )
      )}
    </>
  );
}
Example #10
Source File: useABIService.ts    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
useABIService = (): UseABIServiceReturns => {
  const [ABI, setABI] = useState<DecodedABI>();
  const {
    context: { abiService, providerStore, configStore },
  } = useContext();

  const decodeABI = (params: DecodeABI) => {
    let contract: ContractType | undefined;
    const { data, contractType, contractABI } = params;
    if (contractType) {
      contract = contractType;
    }
    try {
      const abi = abiService.decodeCall(data, contract, contractABI);
      setABI(abi);
      return abi;
    } catch (error) {
      console.error(error);
      return {};
    }
  };

  const decodedCallData = (
    from: string,
    to: string,
    data: string,
    value: BigNumber,
    contractABI: string
  ) => {
    const { library } = providerStore.getActiveWeb3React();
    const recommendedCalls = configStore.getRecommendedCalls();
    let functionSignature = data.substring(0, 10);

    const controllerCallDecoded = abiService.decodeCall(
      data,
      ContractType.Controller
    );
    const decodedAbi = decodeABI({ data, contractABI });

    if (
      controllerCallDecoded &&
      controllerCallDecoded.function.name === 'genericCall'
    ) {
      to = controllerCallDecoded.args[0];
      data = '0x' + controllerCallDecoded.args[1].substring(10);
      value = bnum(controllerCallDecoded.args[3]);
      functionSignature = controllerCallDecoded.args[1].substring(0, 10);
    } else {
      data = '0x' + data.substring(10);
    }

    let asset = ZERO_ADDRESS;
    if (
      functionSignature === ERC20_TRANSFER_SIGNATURE ||
      functionSignature === ERC20_APPROVE_SIGNATURE
    ) {
      asset = to;
    }
    const recommendedCallUsed = recommendedCalls.find(recommendedCall => {
      return (
        asset === recommendedCall.asset &&
        (ANY_ADDRESS === recommendedCall.from ||
          from === recommendedCall.from) &&
        to === recommendedCall.to &&
        functionSignature ===
          library.eth.abi.encodeFunctionSignature(recommendedCall.functionName)
      );
    });

    if (recommendedCallUsed) {
      const callParameters = library.eth.abi.decodeParameters(
        recommendedCallUsed.params.map(param => param.type),
        data
      );

      if (callParameters.__length__) delete callParameters.__length__;

      let encodeFunctionName = library.eth.abi.encodeFunctionSignature(
        recommendedCallUsed.functionName
      );

      return {
        from: from,
        to: to,
        recommendedCallUsed: recommendedCallUsed,
        encodedFunctionName: encodeFunctionName,
        callParameters: callParameters,
        data: data,
        value: value,
        contractABI: decodedAbi,
      };
    }

    return {
      from: from,
      to: to,
      data: data,
      value: value,
      functionSignature: functionSignature,
      contractABI: decodedAbi,
    };
  };

  return {
    ABI,
    decodedCallData,
  };
}
Example #11
Source File: useFilterCriteria.ts    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
useFilterCriteria = (): useFilterCriteriaReturns => {
  const {
    context: { daoStore },
  } = useContext();

  const { getRep } = useRep(ZERO_ADDRESS);

  const [filteredProposals, setFilteredProposals] = useState<
    ProposalsExtended[]
  >([]);

  const [loading, setLoading] = useState(true);
  const timeNow = bnum(moment().unix());

  useEffect(() => {
    const allProposals = daoStore.getAllProposals();

    // Queded && positiveVotes >= 10% (Ordered from time to finish, from lower to higher)
    const stateEarliestAbove10 = allProposals
      .filter(proposal => {
        const queuedVotePeriodLimit = daoStore.getVotingMachineOfProposal(
          proposal.id
        ).params.queuedVotePeriodLimit;

        const repAtCreation = getRep(
          proposal.creationEvent.blockNumber
        ).totalSupply;

        return (
          proposal.stateInVotingMachine === VotingMachineProposalState.Queued &&
          timeNow.lt(proposal.submittedTime.plus(queuedVotePeriodLimit)) &&
          proposal.positiveVotes
            .div(repAtCreation)
            .times(100)
            .decimalPlaces(2)
            .gte(QUEUED_PRIORITY_THRESHOLD)
        );
      })
      .sort(orderByNewestTimeToFinish);

    // Proposals Boosted. (Ordered from time to finish, from lower to higher)
    const stateBoosted = allProposals
      .filter(
        (proposal): Boolean =>
          proposal.stateInVotingMachine === VotingMachineProposalState.Boosted
      )
      .sort(orderByNewestTimeToFinish);

    const stateQuiteEndingProposals = allProposals
      .filter(proposal => {
        return (
          proposal.stateInVotingMachine ===
          VotingMachineProposalState.QuietEndingPeriod
        );
      })
      .sort(orderByNewestTimeToFinish);

    const statePreBoosted = allProposals
      .filter(
        (proposal): Boolean =>
          proposal.stateInVotingMachine ===
          VotingMachineProposalState.PreBoosted
      )
      .sort(orderByNewestTimeToFinish);

    // Queded && positiveVotes < 10% (Ordered from time to finish, from lower to higher)
    const stateEarliestUnder10 = allProposals
      .filter((proposal): Boolean => {
        const queuedVotePeriodLimit = daoStore.getVotingMachineOfProposal(
          proposal.id
        ).params.queuedVotePeriodLimit;

        const repAtCreation = getRep(
          proposal.creationEvent.blockNumber
        ).totalSupply;

        return (
          proposal.stateInVotingMachine === VotingMachineProposalState.Queued &&
          timeNow.lt(proposal.submittedTime.plus(queuedVotePeriodLimit)) &&
          proposal.positiveVotes
            .div(repAtCreation)
            .times(100)
            .decimalPlaces(2)
            .lt(QUEUED_PRIORITY_THRESHOLD)
        );
      })
      .sort(orderByNewestTimeToFinish);

    //Proposals in Executed status. (Ordered in time passed since finish, from higher to lower)
    const stateExecuted = allProposals
      .filter(
        (proposal): Boolean =>
          proposal.stateInVotingMachine === VotingMachineProposalState.Executed
      )
      .sort(orderByOldestTimeToFinish);

    //Proposals finished status. (Expired in queue, rejected or passed)
    const stateFinished = allProposals
      .filter((proposal): Boolean => {
        const queuedVotePeriodLimit = daoStore.getVotingMachineOfProposal(
          proposal.id
        ).params.queuedVotePeriodLimit;
        return (
          (proposal.stateInVotingMachine ===
            VotingMachineProposalState.Queued &&
            timeNow.gt(proposal.submittedTime.plus(queuedVotePeriodLimit))) ||
          proposal.stateInVotingMachine ===
            VotingMachineProposalState.ExpiredInQueue ||
          proposal.stateInVotingMachine ===
            VotingMachineProposalState.Rejected ||
          proposal.stateInVotingMachine === VotingMachineProposalState.Passed
        );
      })
      .sort(orderByOldestTimeToFinish);

    setFilteredProposals([
      ...stateBoosted,
      ...statePreBoosted,
      ...stateQuiteEndingProposals,
      ...stateEarliestAbove10,
      ...stateEarliestUnder10,
      ...stateExecuted,
      ...stateFinished,
    ]);

    setLoading(false);
  }, []);

  return {
    proposals: filteredProposals,
    loading,
  };
}
Example #12
Source File: BlockchainStore.ts    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
async fetchData(web3React: Web3ReactContextInterface, reset: boolean) {
    if (
      (!this.activeFetchLoop || reset) &&
      web3React &&
      web3React.active &&
      isChainIdSupported(web3React.chainId)
    ) {
      const {
        providerStore,
        configStore,
        daoStore,
        notificationStore,
        cacheService,
      } = this.context;

      this.initialLoadComplete = reset ? false : this.initialLoadComplete;
      this.activeFetchLoop = true;
      if (reset) notificationStore.reset();

      try {
        const { library, chainId } = web3React;

        const networkName = configStore.getActiveChainName();

        notificationStore.setGlobalLoading(
          true,
          'Looking for latest chain configurations'
        );
        const networkConfig = await configStore.loadNetworkConfig();

        notificationStore.setGlobalLoading(
          true,
          'Looking for existing cache data'
        );
        const cache = await caches.open(`dxvote-cache`);
        let match = await cache.match(networkName);
        let networkCache: DaoNetworkCache & { baseCacheIpfsHash?: string } =
          null;
        if (match) {
          networkCache = JSON.parse(await match.text());
        }

        if (networkName === 'localhost') {
          networkCache = {
            networkId: 1337,
            version: 1,
            blockNumber: 1,
            address: '0xf89f66329e7298246de22D210Ac246DCddff4621',
            reputation: {
              events: [],
              total: bnum(0),
            },
            schemes: {},
            proposals: {},
            callPermissions: {},
            votingMachines: {},
            ipfsHashes: [],
            vestingContracts: [],
          };
        }

        if (
          networkCache &&
          (!networkCache?.version ||
            networkCache?.version !== targetCacheVersion)
        ) {
          console.log('[Upgrade Cache]');
          networkCache = null;
        }

        const blockNumber = (await library.eth.getBlockNumber()) - 5;

        const newestCacheIpfsHash = networkConfig.cache.ipfsHash;

        if (
          networkName !== 'localhost' &&
          (!networkCache ||
            !(newestCacheIpfsHash === networkCache.baseCacheIpfsHash))
        ) {
          console.debug('[IPFS Cache Fetch]', networkName, newestCacheIpfsHash);
          notificationStore.setGlobalLoading(
            true,
            'Fetching cached data from IPFS'
          );
          const ipfsCache = await cacheService.getCacheFromIPFS(
            newestCacheIpfsHash
          );
          networkCache = daoStore.parseCache(ipfsCache);
          networkCache.baseCacheIpfsHash = newestCacheIpfsHash;
        }

        const lastCheckedBlockNumber = networkCache.blockNumber;

        if (blockNumber > lastCheckedBlockNumber + 1) {
          console.debug(
            '[Fetch Loop] Fetch Blockchain Data',
            blockNumber,
            chainId
          );

          const toBlock = blockNumber;
          const networkContracts = configStore.getNetworkContracts();

          networkCache = await cacheService.getUpdatedCache(
            networkCache,
            networkContracts,
            toBlock,
            library
          );

          notificationStore.setGlobalLoading(
            true,
            `Getting proposal titles form ipfs`
          );
          const proposalTitles = await cacheService.updateProposalTitles(
            networkCache,
            getProposalTitles()
          );

          Object.keys(networkCache.proposals).map(proposalId => {
            networkCache.proposals[proposalId].title =
              networkCache.proposals[proposalId].title ||
              proposalTitles[proposalId] ||
              '';
          });

          networkCache.blockNumber = toBlock;
          providerStore.setCurrentBlockNumber(toBlock);

          notificationStore.setGlobalLoading(true, 'Saving updated cache');
          await cache.put(
            networkName,
            new Response(JSON.stringify(networkCache))
          );
        }
        daoStore.setCache(networkCache);
        this.initialLoadComplete = true;
        notificationStore.setFirstLoadComplete();
        this.activeFetchLoop = false;
      } catch (error) {
        console.error(error);
        if (!this.initialLoadComplete) {
          notificationStore.setGlobalError(true, (error as Error).message);
        } else {
          throw new CacheLoadError(error.message);
        }
        this.activeFetchLoop = false;
      }
    }
  }