Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
/* 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'],
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
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;
}
};
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,
_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) => {
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;
}
};
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,
});
}
}
/* @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,
) {
/* @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);
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,