How to use the io-ts.undefined function in io-ts

To help you get started, we’ve selected a few io-ts examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github celo-org / celo-monorepo / packages / contractkit / src / identity / claims / account.ts View on Github external
import { AddressType, PublicKeyType } from '@celo/utils/lib/io'
import { pubToAddress, toChecksumAddress } from 'ethereumjs-util'
import { either, isLeft } from 'fp-ts/lib/Either'
import * as t from 'io-ts'
import { ClaimTypes, now, TimestampType } from './types'

// Provide the type minus the validation that the public key and address are derived from the same private key
export const AccountClaimTypeH = t.type({
  type: t.literal(ClaimTypes.ACCOUNT),
  timestamp: TimestampType,
  address: AddressType,
  // io-ts way of defining optional key-value pair
  publicKey: t.union([t.undefined, PublicKeyType]),
})

export const AccountClaimType = new t.Type(
  'AccountClaimType',
  AccountClaimTypeH.is,
  (unknownValue, context) =>
    either.chain(AccountClaimTypeH.validate(unknownValue, context), (claim) => {
      if (claim.publicKey === undefined) {
        return t.success(claim)
      }
      const derivedAddress = toChecksumAddress(
        '0x' + pubToAddress(Buffer.from(claim.publicKey.slice(2), 'hex'), true).toString('hex')
      )
      return derivedAddress === claim.address
        ? t.success(claim)
        : t.failure(claim, context, 'public key did not match the address in the claim')
github buildo / avenger / src / cache / Cache.js View on Github external
import * as t from 'io-ts'
import { ThrowReporter } from 'io-ts/lib/ThrowReporter'
import debug from 'debug'

const Done = t.interface({
  value: t.any,         // il valore contenuto nella promise
  timestamp: t.number,  // il momento in cui è stato valorizzato done
  promise: t.any        // la promise che conteneva il done
}, 'Done')

export const CacheValue = t.interface({
  done: t.union([Done, t.undefined]),
  blocked: t.any
}, 'CacheValue')

export const empty = Object.freeze({})

export class Cache {

  constructor(options = {}) {
    this.name = options.name || ''
    this.map = options.map || new Map()
    this.log = debug(`avenger:${this.name}`)
    this.atok = options.atok || JSON.stringify
  }

  get(a) {
    return this.map.get(this.atok(a)) || empty
github celo-org / celo-monorepo / packages / attestation-service / src / requestHandlers / status.ts View on Github external
import { privateKeyToAddress } from '@celo/utils/lib/address'
import { AttestationServiceStatusResponseType, SignatureType } from '@celo/utils/lib/io'
import { serializeSignature, signMessage } from '@celo/utils/lib/signatureUtils'
import express from 'express'
import * as t from 'io-ts'
import { ErrorMessages, respondWithError } from '../request'
import { blacklistRegionCodes, configuredSmsProviders } from '../sms'
import { getAccountAddress, getAttestationKey } from './attestation'

export const SIGNATURE_PREFIX = 'attestation-service-status-signature:'
export const StatusRequestType = t.type({
  messageToSign: t.union([SignatureType, t.undefined]),
})

export type StatusRequest = t.TypeOf

function produceSignature(message: string | undefined) {
  if (!message) {
    return undefined
  }
  const key = getAttestationKey()
  const address = privateKeyToAddress(key)
  return serializeSignature(signMessage(SIGNATURE_PREFIX + message, key, address))
}

export async function handleStatusRequest(
  _req: express.Request,
  res: express.Response,
github AugurProject / augur-node / src / server / getters / get-market-price-candlesticks.ts View on Github external
import * as t from "io-ts";
import * as Knex from "knex";
import * as _ from "lodash";
import { BigNumber } from "bignumber.js";
import { ZERO } from "../../constants";
import { OutcomeParam } from "../../types";
import { volumeForTrade } from "../../blockchain/log-processors/order-filled/update-volumetrics";

export const MarketPriceCandlesticksParams = t.type({
  marketId: t.string,
  outcome: t.union([OutcomeParam, t.number, t.null, t.undefined]),
  start: t.union([t.number, t.null, t.undefined]),
  end: t.union([t.number, t.null, t.undefined]),
  period: t.union([t.number, t.null, t.undefined]),
});

interface MarketPriceHistoryRow {
  timestamp: number;
  outcome: number;
  price: BigNumber;
  amount: BigNumber;
  numCreatorTokens: BigNumber;
  numCreatorShares: BigNumber;
  numFillerTokens: BigNumber;
  numFillerShares: BigNumber;
}
github elastic / kibana / x-pack / legacy / plugins / ingest / server / libs / adapters / configurations / adapter_types.ts View on Github external
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */

import * as t from 'io-ts';

export const RuntimeDatasourceInput = t.interface(
  {
    id: t.string,
    meta: t.union([t.undefined, t.string]),
    config_id: t.string,
  },
  'DatasourceInput'
);

const DataSource = t.interface({
  uuid: t.string,
  ref_source: t.union([t.undefined, t.string]),
  ref: t.union([t.undefined, t.string]),
  config: t.union([t.undefined, t.string]),
  inputs: t.array(t.string),
});

export const NewRuntimeConfigurationFile = t.interface(
  {
    name: t.string,
github AugurProject / augur-node / src / server / getters / get-user-trading-positions.ts View on Github external
import Augur from "augur.js";
import { BigNumber } from "bignumber.js";
import * as t from "io-ts";
import * as Knex from "knex";
import * as _ from "lodash";
import { FrozenFunds } from "../../blockchain/log-processors/profit-loss/frozen-funds";
import { BN_WEI_PER_ETHER, ZERO } from "../../constants";
import { Address, MarketsRow, OutcomeParam, ReportingState, SortLimitParams } from "../../types";
import { fixedPointToDecimal, numTicksToTickSize } from "../../utils/convert-fixed-point-to-decimal";
import { Tokens } from "../../utils/dimension-quantity";
import { getRealizedProfitPercent, getTotalProfitPercent, getUnrealizedProfitPercent } from "../../utils/financial-math";
import { getAllOutcomesProfitLoss, ProfitLossResult } from "./get-profit-loss";

export const UserTradingPositionsParamsSpecific = t.type({
  universe: t.union([t.string, t.null, t.undefined]),
  marketId: t.union([t.string, t.null, t.undefined]),
  account: t.union([t.string, t.null, t.undefined]),
  outcome: t.union([OutcomeParam, t.number, t.null, t.undefined]),
});

export const UserTradingPositionsParams = t.intersection([
  UserTradingPositionsParamsSpecific,
  SortLimitParams,
  t.partial({
    endTime: t.number,
  }),
]);

export interface TradingPosition extends ProfitLossResult, FrozenFunds {
  position: string;
}
github AugurProject / augur / packages / augur-node / src / server / getters / get-initial-reporters.ts View on Github external
import * as t from "io-ts";
import Knex from "knex";
import { formatBigNumberAsFixed } from "../../utils/format-big-number-as-fixed";
import { InitialReportersRow, UIInitialReporters } from "../../types";

export const InitialReportersParams = t.type({
  universe: t.string,
  reporter: t.string,
  redeemed: t.union([t.boolean, t.null, t.undefined]),
  withRepBalance: t.union([t.boolean, t.null, t.undefined]),
});

export async function getInitialReporters(db: Knex, augur: {}, params: t.TypeOf) {
  const query = db("initial_reports")
    .select(["marketID", "reporter", "amountStaked", "initialReporter", "redeemed", "isDesignatedReporter", "balances.balance AS repBalance"])
    .select(["transactionHash", "initial_reports.blockNumber", "logIndex", "blocks.timestamp"])
    .join("balances", "balances.owner", "=", "initial_reports.initialReporter")
    .join("universes", "universes.reputationToken", "balances.token")
    .join("blocks", "initial_reports.blockNumber", "blocks.blockNumber")
    .where("reporter", params.reporter)
    .where("universes.universe", params.universe);
  if (params.withRepBalance) query.where("repBalance", ">", "0");
  if (params.redeemed != null) query.where("redeemed", params.redeemed);
  const initialReporters: Array> = await query;
  return initialReporters.reduce((acc: UIInitialReporters, cur) => {
github AugurProject / augur-node / src / server / getters / get-orders.ts View on Github external
import * as t from "io-ts";
import * as _ from "lodash";
import * as Knex from "knex";
import { BigNumber } from "bignumber.js";
import { OrdersRow, OrderState, UIOrder, UIOrders, Bytes32, SortLimitParams, OutcomeParam } from "../../types";
import { queryModifier } from "./database";
import { formatBigNumberAsFixed } from "../../utils/format-big-number-as-fixed";

export const OrdersParamsSpecific = t.type({
  universe: t.union([t.string, t.null, t.undefined]),
  marketId: t.union([t.string, t.null, t.undefined]),
  outcome: t.union([OutcomeParam, t.number, t.null, t.undefined]),
  orderType: t.union([t.string, t.null, t.undefined]),
  creator: t.union([t.string, t.null, t.undefined]),
  orderState: t.union([t.string, t.null, t.undefined]),
  orphaned: t.union([t.boolean, t.null, t.undefined]),
  earliestCreationTime: t.union([t.number, t.null, t.undefined]),
  latestCreationTime: t.union([t.number, t.null, t.undefined]),
});

export const OrdersParams = t.intersection([
  OrdersParamsSpecific,
  SortLimitParams,
]);

interface OrdersRowWithCreationTimeAndCanceled extends OrdersRow {
github AugurProject / augur-node / src / server / getters / get-reporting-history.ts View on Github external
import * as t from "io-ts";
import * as Knex from "knex";
import { JoinedReportsMarketsRow, SortLimitParams, UIReport } from "../../types";
import { formatBigNumberAsFixed } from "../../utils/format-big-number-as-fixed";
import { queryModifier } from "./database";

export const ReportingHistoryParamsSpecific = t.type({
  reporter: t.string,
  universe: t.union([t.string, t.null, t.undefined]),
  marketId: t.union([t.string, t.null, t.undefined]),
  feeWindow: t.union([t.string, t.null, t.undefined]),
  earliestCreationTime: t.union([t.number, t.null, t.undefined]),
  latestCreationTime: t.union([t.number, t.null, t.undefined]),
});

export const ReportingHistoryParams = t.intersection([
  ReportingHistoryParamsSpecific,
  SortLimitParams,
]);

export interface UIReports {
  [universe: string]: {
    [marketId: string]: {
      crowdsourcers: Array>;
      initialReporter: UIReport|null;
github AugurProject / augur-node / src / server / getters / get-account-transaction-history.ts View on Github external
import * as t from "io-ts";
import * as Knex from "knex";
import { AccountTransactionHistoryRow, Action, Coin, SortLimitParams } from "../../types";
import { Price, Shares, Tokens } from "../../utils/dimension-quantity";
import { getTotalFees, getTradeCost } from "../../utils/financial-math";
import { queryModifier } from "./database";

export const GetAccountTransactionHistoryParams = t.intersection([
  SortLimitParams,
  t.type({
    universe: t.string,
    account: t.string,
    earliestTransactionTime: t.number,
    latestTransactionTime: t.number,
    coin: t.string,
    action: t.union([t.string, t.null, t.undefined]),
  }),
]);
type GetAccountTransactionHistoryParamsType = t.TypeOf;

async function transformQueryResults(db: Knex, queryResults: Array>) {
  return await Promise.all(queryResults.map(async (queryResult: AccountTransactionHistoryRow) => {
    const divisor = new BigNumber(10 ** 18);
    if (queryResult.action === Action.BUY || queryResult.action === Action.SELL) {
      const { tradeCost } = getTradeCost({
        marketMinPrice: new Price(queryResult.minPrice),
        marketMaxPrice: new Price(queryResult.maxPrice),
        tradeBuyOrSell: queryResult.action === Action.BUY ? "buy" : "sell",
        tradeQuantity: new Shares(queryResult.quantity),
        tradePrice: new Price(queryResult.price),
      });
      const { totalFees } = getTotalFees({