How to use @colony/colony-js-utils - 10 common examples

To help you get started, we’ve selected a few @colony/colony-js-utils 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 JoinColony / colonyJS / packages / colony-js-contract-client / src / __tests__ / paramValidation.js View on Github external
/* eslint-env jest */
/* eslint-disable no-underscore-dangle,no-console */

import createSandbox from 'jest-sandbox';
import { makeAssert } from '@colony/colony-js-utils';
import * as validation from '../modules/paramValidation';
import * as types from '../modules/paramTypes';

const failureMessage = 'Validation failed for SampleObject';
const assertValid = makeAssert(failureMessage);

describe('validateParams', () => {
  const sandbox = createSandbox();

  beforeEach(() => {
    sandbox.clear();
  });

  test('Empty parameters validate correctly', () => {
    expect(validation.validateParams({}, [])).toBe(true);
  });

  test('Parameters validate correctly', () => {
    const spec = [
      ['taskId', 'number'],
      ['potId', 'number'],
github JoinColony / colonyJS / packages / colony-js-client / src / ColonyClient / index.js View on Github external
async getReputation({
    skillId,
    address,
  }: {
    skillId: number,
    address: Address,
  } = {}) {
    assert(Number.isFinite(skillId), 'skillId must be a number');
    assert(isValidAddress(address), 'address must be an address');

    // Throw error if private network
    if (typeof this.network === 'undefined') {
      throw new Error('This method is not supported on a private network');
    }

    // Throw error if not goerli or mainnet
    if (
      this.network !== 'goerli' &&
      this.network !== 'mainnet' &&
      this.network !== 'homestead'
    ) {
      throw new Error('This method is only supported on goerli or mainnet');
    }

    // Get the current reputation root hash
github JoinColony / colonyJS / packages / colony-js-contract-client / src / modules / getMethodReturnValue.js View on Github external
const parseReturnValue = (value: any, type: ParamTypes) => {
  switch (type) {
    case 'number':
      if (isBigNumber(value)) return value.toNumber();
      assert(Number(value) === value, `Unexpected value "${value}"`);
      return value;
    case 'address':
      // Filter out empty addresses
      return isValidAddress(value) ? value : null;
    default:
      return value;
  }
};
github JoinColony / colonyJS / packages / colony-js-contract-client / src / classes / ContractMethodSender.js View on Github external
async _sendWithWaitingForMining(
    transaction: Transaction,
    timeoutMs: number,
  ): Promise> {
    const receipt = await raceAgainstTimeout(
      this.client.adapter.getTransactionReceipt(transaction.hash),
      timeoutMs,
    );
    const eventData = this.client.getReceiptEventData(receipt);

    // If the transaction failed, call it directly and add the revert
    // reason to the receipt.
    if (receipt && receipt.status === 0) {
      try {
        const { from, to, data, gasPrice, gasLimit, value } = transaction;
        await this.client.callTransaction({
          data,
          from,
          gasLimit,
          gasPrice,
          value,
github JoinColony / colonyJS / packages / colony-js-contract-client / src / classes / ContractMethodSender.js View on Github external
_sendWithoutWaitingForMining(
    transaction: Transaction,
    timeoutMs: number,
  ): ContractResponse {
    const receiptPromise = raceAgainstTimeout(
      this.client.adapter.getTransactionReceipt(transaction.hash),
      timeoutMs,
    );

    // Wait for the receipt before determining whether it was successful
    const successfulPromise = new Promise(async (resolve, reject) => {
      try {
        const receipt = await receiptPromise;
        resolve(receipt && receipt.status === 1);
      } catch (error) {
        reject(error.toString());
      }
    });

    // Wait for the receipt before attempting to decode event logs
    const eventDataPromise = new Promise(async (resolve, reject) => {
github JoinColony / colonyJS / packages / colony-js-contract-client / src / modules / getMethodReturnValue.js View on Github external
const parseReturnValue = (value: any, type: ParamTypes) => {
  switch (type) {
    case 'number':
      if (isBigNumber(value)) return value.toNumber();
      assert(Number(value) === value, `Unexpected value "${value}"`);
      return value;
    case 'address':
      // Filter out empty addresses
      return isValidAddress(value) ? value : null;
    default:
      return value;
  }
};
github JoinColony / colonyJS / packages / colony-js-client / src / ColonyClient / callers / GetTask.js View on Github external
convertOutputValues(result: CallResult, { taskId }: *) {
    const task = super.convertOutputValues(result);

    // Until arrays of bignumbers are supported as a parameter type,
    // take the last item of the call result (skillIds) and use the first one
    const skillId: BigNumber = [].concat(result[result.length - 1])[0];

    return Object.assign({}, task, {
      // Include the task ID
      id: taskId,
      skillId: isBigNumber(skillId) ? skillId.toNumber() : null,
    });
  }
}
github JoinColony / colonyJS / packages / colony-js-contract-client / src / modules / paramValidation.js View on Github external
/* @flow */
/* eslint-disable import/no-cycle */

import isPlainObject from 'lodash.isplainobject';
import { makeAssert } from '@colony/colony-js-utils';
import { validateValueType } from './paramTypes';
import type { Params, Param } from '../flowtypes';

const defaultAssert = makeAssert('Parameter Validation');
type AssertionMethod = (assertion: boolean, reason: string) => any;

export const isBoolean = (value: any) => typeof value === 'boolean';

export const areParamPairsEmpty = (paramPairs: Params) =>
  paramPairs == null || (Array.isArray(paramPairs) && paramPairs.length === 0);

export const isInputEmpty = (input: any) =>
  input == null ||
  (isPlainObject(input) && Object.getOwnPropertyNames(input).length === 0);

export function validateValue(
  value: any,
  [name, type]: Param,
  assertValid?: AssertionMethod = defaultAssert,
) {
github JoinColony / colonyJS / packages / colony-js-contract-client / src / modules / validate.js View on Github external
/* @flow */

import BigNumber from 'bn.js';
import isPlainObject from 'lodash.isplainobject';
import { isValidAddress, makeAssert } from '@colony/colony-js-utils';

import type { ParamTypes, ParamTypePairs } from '../flowtypes';

const assert = makeAssert('Validation failed');

const TYPE_MAP = new Map([
  ['address', isValidAddress],
  ['string', value => typeof value === 'string'], // empty strings are allowed
  ['number', value => typeof value === 'number' || BigNumber.isBN(value)],
  ['boolean', value => typeof value === 'boolean'],
]);

export const validateParam = (
  key: string,
  type: ParamTypes,
  value: any,
): boolean => {
  assert(TYPE_MAP.has(type), `Parameter type "${type}" not defined`);

  const check = TYPE_MAP.get(type);
github JoinColony / colonyJS / packages / colony-js-contract-client / src / modules / paramTypes.js View on Github external
convertOutput(value: any) {
      if (isHexStrict(value)) {
        if (isEmptyHexString(value)) return null;
        try {
          return hexToUtf8(value);
        } catch (error) {
          // ignore error: not a UTF8-encoded value
        }
      }
      return typeof value === 'string' && value.length ? value : null;
    },
    convertInput: passThrough,