How to use @0x/utils - 10 common examples

To help you get started, we’ve selected a few @0x/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 0xProject / 0x-monorepo / packages / migrations / src / testnet_migrations.ts View on Github external
await zrxVault.setStakingProxy(stakingProxy.address).awaitTransactionSuccessAsync();
    await zrxVault.removeAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync();
    await zrxVault.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync();
    await zrxVault.transferOwnership(governor.address).awaitTransactionSuccessAsync();
    logUtils.log('ZrxVault configured!');

    logUtils.log('Configuring StakingProxy...');
    await stakingProxy.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync();
    const staking = new StakingContract(stakingProxy.address, provider, txDefaults);
    await staking.addExchangeAddress(exchange.address).awaitTransactionSuccessAsync();
    await stakingProxy.removeAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync();
    await stakingProxy.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync();
    await stakingProxy.transferOwnership(governor.address).awaitTransactionSuccessAsync();
    logUtils.log('StakingProxy configured!');

    logUtils.log('Transfering ownership of 2.0 contracts...');
    const oldAssetProxyOwner = new ZeroExGovernorContract(deployedAddresses.assetProxyOwner, provider, txDefaults);
    await submitAndExecuteTransactionAsync(
        oldAssetProxyOwner,
        deployedAddresses.exchangeV2, // Exchange 2.1 address
        ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(),
    );
    await submitAndExecuteTransactionAsync(
        oldAssetProxyOwner,
        deployedAddresses.erc20Proxy,
        ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(),
    );
    await submitAndExecuteTransactionAsync(
        oldAssetProxyOwner,
        deployedAddresses.erc721Proxy,
        ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(),
    );
github 0xProject / 0x-monorepo / contracts / test-utils / src / assertions.ts View on Github external
// remove it, there is an uncaught exception and the Node process will
    // forcibly exit. It's possible this is a false positive in
    // make-promises-safe.
    p.catch(e => {
        _.noop(e);
    });

    if (nodeType === undefined) {
        nodeType = await web3Wrapper.getNodeTypeAsync();
    }
    switch (nodeType) {
        case NodeType.Ganache:
            const rejectionMessageRegex = new RegExp(`^VM Exception while processing transaction: revert ${reason}$`);
            return expect(p).to.be.rejectedWith(rejectionMessageRegex);
        case NodeType.Geth:
            logUtils.warn(
                'WARNING: Geth does not support revert reasons for sendTransaction. This test will pass if the transaction fails for any reason.',
            );
            return expectTransactionFailedWithoutReasonAsync(p);
        default:
            throw new Error(`Unknown node type: ${nodeType}`);
    }
}
github 0xProject / 0x-monorepo / contracts / tec / generated-wrappers / test_mixins.ts View on Github external
constructor(abi: ContractAbi, address: string, supportedProvider: SupportedProvider, txDefaults?: Partial) {
        super('TestMixins', abi, address, supportedProvider, txDefaults);
        classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', 'abi', '_web3Wrapper']);
    }
} // tslint:disable:max-file-line-count
github 0xProject / 0x-monorepo / packages / testnet-faucets / src / ts / dispatch_queue.ts View on Github external
private _start(): void {
        this._queueIntervalIdIfExists = intervalUtils.setAsyncExcludingInterval(
            async () => {
                const taskAsync = this._queue.shift();
                if (taskAsync === undefined) {
                    return Promise.resolve();
                }
                await taskAsync();
            },
            this._queueIntervalMs,
            (err: Error) => {
                logUtils.log(`Unexpected err: ${err} - ${JSON.stringify(err)}`);
                // tslint:disable-next-line:no-floating-promises
                errorReporter.reportAsync(err);
            },
        );
    }
}
github 0xProject / 0x-monorepo / packages / migrations / src / testnet_migrations.ts View on Github external
export async function runMigrationsAsync(supportedProvider: SupportedProvider, txDefaults: TxData): Promise {
    const provider = providerUtils.standardizeOrThrow(supportedProvider);
    const chainId = new BigNumber(await providerUtils.getChainIdAsync(provider));
    const deployedAddresses = getContractAddressesForChainOrThrow(chainId.toNumber());
    const configs = getConfigsByChainId(chainId.toNumber());

    // NOTE: This must be deployed before running these migrations, since its address is hard coded in the
    // staking logic contract.
    const zrxVault = new ZrxVaultContract(deployedAddresses.zrxVault, provider, txDefaults);

    const stakingLogic = await StakingContract.deployFrom0xArtifactAsync(
        stakingArtifacts.Staking,
        provider,
        txDefaults,
        stakingArtifacts,
    );

    const exchange = await ExchangeContract.deployFrom0xArtifactAsync(
        exchangeArtifacts.Exchange,
github 0xProject / 0x-monorepo / packages / pipeline / src / data_sources / ohlcv_external / crypto_compare.ts View on Github external
const fetchPromise: Promise = this._promiseLimit(() => {
            // tslint:disable-next-line:no-console
            console.log(`Scraping Crypto Compare at ${url}`);
            return fetchAsync(url);
        });
github 0xProject / 0x-monorepo / packages / sol-compiler / src / compiler.ts View on Github external
// add input to the right version batch
            for (const resolvedContractSource of spyResolver.resolvedContractSources) {
                versionToInputs[solcVersion].standardInput.sources[resolvedContractSource.absolutePath] = {
                    content: resolvedContractSource.source,
                };
            }
            resolvedContractSources.push(...spyResolver.resolvedContractSources);
            versionToInputs[solcVersion].contractsToCompile.push(contractSource.path);
        }

        const dependencyNameToPath = getDependencyNameToPackagePath(resolvedContractSources);

        const compilerOutputs: StandardOutput[] = [];
        for (const solcVersion of _.keys(versionToInputs)) {
            const input = versionToInputs[solcVersion];
            logUtils.warn(
                `Compiling ${input.contractsToCompile.length} contracts (${
                    input.contractsToCompile
                }) with Solidity v${solcVersion}...`,
            );
            let compilerOutput;
            let fullSolcVersion;
            input.standardInput.settings.remappings = _.map(
                dependencyNameToPath,
                (dependencyPackagePath: string, dependencyName: string) => `${dependencyName}=${dependencyPackagePath}`,
            );
            if (this._useDockerisedSolc) {
                const dockerCommand = `docker run ethereum/solc:${solcVersion} --version`;
                const versionCommandOutput = execSync(dockerCommand).toString();
                const versionCommandOutputParts = versionCommandOutput.split(' ');
                fullSolcVersion = versionCommandOutputParts[versionCommandOutputParts.length - 1].trim();
                compilerOutput = await compileDockerAsync(solcVersion, input.standardInput);
github 0xProject / 0x-monorepo / packages / website / ts / pages / governance / vote_index.tsx View on Github external
}

            const responseData = await response.json();
            let { no, yes } = responseData;
            yes = new BigNumber(yes);
            no = new BigNumber(no);
            const tally = {
                ...responseData,
                yes: new BigNumber(yes),
                no: new BigNumber(no),
            };
            return tally;
        } catch (e) {
            // Empty block
            return {
                yes: new BigNumber(0),
                no: new BigNumber(0),
            };
        }
    }
github 0xProject / 0x-monorepo / contracts / exchange-libs / src / reference_functions.ts View on Github external
export function isRoundingErrorFloor(numerator: BigNumber, denominator: BigNumber, target: BigNumber): boolean {
    if (denominator.eq(0)) {
        throw new LibMathRevertErrors.DivisionByZeroError();
    }
    if (numerator.eq(0) || target.eq(0)) {
        return false;
    }
    const remainder = numerator.times(target).mod(denominator);
    // Need to do this separately because solidity evaluates RHS of the comparison expression first.
    const rhs = safeMul(numerator, target);
    const lhs = safeMul(remainder, new BigNumber(1000));
    return lhs.gte(rhs);
}
github 0xProject / 0x-monorepo / packages / asset-buyer / src / constants.ts View on Github external
};

const DEFAULT_FORWARDER_SWAP_QUOTE_EXECUTE_OPTS: ForwarderSwapQuoteExecutionOpts = DEFAULT_FORWARDER_SWAP_QUOTE_GET_OPTS;

const DEFAULT_SWAP_QUOTE_REQUEST_OPTS: SwapQuoteRequestOpts = {
    shouldForceOrderRefresh: false,
    slippagePercentage: 0.2, // 20% slippage protection,
};

const EMPTY_ORDERS_AND_FILLABLE_AMOUNTS: OrdersAndFillableAmounts = {
    orders: [] as SignedOrder[],
    remainingFillableMakerAssetAmounts: [] as BigNumber[],
};

export const constants = {
    ZERO_AMOUNT: new BigNumber(0),
    NULL_ADDRESS,
    MAINNET_NETWORK_ID,
    ETHER_TOKEN_DECIMALS: 18,
    ONE_AMOUNT: new BigNumber(1),
    ONE_SECOND_MS,
    DEFAULT_SWAP_QUOTER_OPTS,
    DEFAULT_FORWARDER_SWAP_QUOTE_GET_OPTS,
    DEFAULT_FORWARDER_SWAP_QUOTE_EXECUTE_OPTS,
    DEFAULT_SWAP_QUOTE_REQUEST_OPTS,
    EMPTY_ORDERS_AND_FILLABLE_AMOUNTS,
};