ramda#reject JavaScript Examples

The following examples show how to use ramda#reject. 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: staking_payouts.js    From sdk with MIT License 5 votes vote down vote up
buildValidatorRewards = curry(
  ({ pointsByEra, rewardsByEra, prefsByEra }, validatorEras) => {
    const stashErasReducer = (acc, { eras, stashId }) => {
      const eraReducer = (acc, era) => {
        const eraKey = era.toString();
        const eraPoints = pointsByEra[eraKey];
        const eraRewards = rewardsByEra[eraKey];
        const eraPrefs = prefsByEra[eraKey];

        if (
          // Points must be greater than 0
          eraPoints?.eraPoints.gt(new BN(0)) &&
          // We must have a stash as a validator in the given era
          eraPoints?.validators[stashId] &&
          // Era rewards should be defined
          eraRewards &&
          // Validator commission in the given era should be acceptable
          eraPrefs.validators[stashId]?.commission?.toBn().lte(MaxCommission)
        ) {
          const reward = eraPoints.validators[stashId]
            .mul(eraRewards.eraReward)
            .div(eraPoints.eraPoints);

          if (!reward.isZero())
            return acc.concat({
              era,
              reward,
            });
        }

        return acc;
      };

      return eras.reduce(eraReducer, acc);
    };

    return o(
      // Filter out stashes with no rewards
      reject(isEmpty),
      // Reduce given stash eras by the stash id
      reduceBy(stashErasReducer, [], prop("stashId"))
    )(validatorEras);
  }
)
Example #2
Source File: NotificationStack.stories.js    From lundium with MIT License 5 votes vote down vote up
basic = () =>
	// Workaround to be able to see code in story
	React.createElement(() => {
		const [currentId, setCurrentId] = useState(1);
		const [notifications, setNotifications] = useState([getNotification(0)]);

		const addNotification = () => {
			setNotifications([...notifications, { id: currentId, type: 'success' }]);
			setCurrentId(currentId + 1);
		};

		const removeNotification = idToRemove => {
			setNotifications(reject(({ id }) => id === idToRemove, notifications));
		};

		return (
			<Fragment>
				<Button kind="primary" onClick={addNotification}>
					Open me!
				</Button>
				<NotificationStack
					notifications={notifications}
					// Default transition for ilustration, not mandatory
					transition={{
						timeout: 500,
						classNames: 'slide-from-right',
					}}
					renderNotification={({ type, id, ...rest }) => (
						<Notification
							type={type}
							onClose={() => removeNotification(id)}
							{...rest}
						>
							Notification content {id}
						</Notification>
					)}
				/>
			</Fragment>
		);
	})
Example #3
Source File: staking_payouts.js    From sdk with MIT License 4 votes vote down vote up
/**
 * Sends staking payouts for recent eras using the given sender account.
 *
 * @param {DockAPI} dock
 * @param {ErasInfo} erasInfo
 * @param {*} initiator - account to send tx from
 * @param {number} batchSize
 * @returns {Promise<boolean>} - `true` if some unpaid eras were found, `false` otherwise
 */
async function sendStakingPayouts(dock, erasInfo, initiator, batchSize) {
  const validators = pipe(
    values,
    pluck("validators"),
    chain(keys),
    (values) => new Set(values)
  )(erasInfo.pointsByEra);

  if (!validators.size) {
    console.log("- Validator set is empty.");
    return false;
  }

  console.log("- Retrieving validator eras...");
  const erasToBePaid = await lastValueFrom(
    from(validators).pipe(
      getUnclaimedStashesEras(dock.api, erasInfo),
      toArray()
    )
  );

  const rewards = pipe(buildValidatorRewards, toPairs)(erasInfo, erasToBePaid);

  if (isEmpty(rewards)) {
    console.log("- No unpaid validator rewards found for recent eras.");
    return false;
  }

  console.log("- Payouts need to be made:");

  for (const [stashId, eras] of rewards) {
    const total = eras.reduce(
      (total, { reward }) => (total != null ? total.add(reward) : reward),
      null
    );

    console.log(` * To \`${stashId}\`: ${formatDock(total)}`);
  }

  const logResult = ({ result, tx }) => {
    // Ther's a much better way to check this...
    const isBatch = tx.method.args?.[0]?.[0] instanceof Map;

    let msg = " * ";
    if (isBatch) msg += `Batch transaction`;
    else msg += `Transaction`;

    if (FinalizeTx) {
      msg += ` finalized at block \`${result.status.asFinalized}\`: `;
    } else {
      msg += ` included at block \`${result.status.asInBlock}\`: `;
    }

    const payoutsSummary = (isBatch ? tx.method.args[0] : [tx.method])
      .map((payout) => payout.get("args"))
      .map(
        ({ validator_stash, era }) =>
          `\`${validator_stash}\` rewarded for era ${era}`
      )
      .join(isBatch ? ",\n    " : ",");

    msg += isBatch ? `[\n    ${payoutsSummary}\n ]` : payoutsSummary;

    console.log(msg);
  };

  const payoutTxs$ = from(rewards).pipe(
    concatMap(([stashId, eras]) => from(eras.map(assoc("stashId", stashId)))),
    mapRx(({ stashId, era }) =>
      dock.api.tx.staking.payoutStakers(stashId, era)
    ),
    batchExtrinsics(dock.api, batchSize),
    signAndSendExtrinsics(dock, initiator),
    tap(logResult)
  );

  await new Promise((resolve, reject) =>
    payoutTxs$.subscribe({
      error: reject,
      complete: resolve,
    })
  );

  return true;
}