当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript utils.utils类代码示例

本文整理汇总了TypeScript中ts/utils/utils.utils的典型用法代码示例。如果您正苦于以下问题:TypeScript utils类的具体用法?TypeScript utils怎么用?TypeScript utils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了utils类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: signOrderHashAsync

    public async signOrderHashAsync(orderHash: string): Promise<ECSignature> {
        utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.');
        const makerAddress = this._userAddressIfExists;
        // If makerAddress is undefined, this means they have a web3 instance injected into their browser
        // but no account addresses associated with it.
        if (_.isUndefined(makerAddress)) {
            throw new Error('Tried to send a sign request but user has no associated addresses');
        }

        this._showFlashMessageIfLedger();
        const nodeVersion = await this._web3Wrapper.getNodeVersionAsync();
        const isParityNode = utils.isParityNode(nodeVersion);
        const isTestRpc = utils.isTestRpc(nodeVersion);
        const isLedgerSigner = !_.isUndefined(this._ledgerSubprovider);
        let shouldAddPersonalMessagePrefix = true;
        if ((isParityNode && !isLedgerSigner) || isTestRpc || isLedgerSigner) {
            shouldAddPersonalMessagePrefix = false;
        }
        const ecSignature = await this._zeroEx.signOrderHashAsync(
            orderHash,
            makerAddress,
            shouldAddPersonalMessagePrefix,
        );
        this._dispatcher.updateECSignature(ecSignature);
        return ecSignature;
    }
开发者ID:ewingrj,项目名称:0x-monorepo,代码行数:26,代码来源:blockchain.ts

示例2: _startListeningForExchangeLogFillEventsAsync

    private async _startListeningForExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues): Promise<void> {
        utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.');
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        // Fetch historical logs
        await this._fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues);

        // Start a subscription for new logs
        this._zeroEx.exchange.subscribe(
            ExchangeEvents.LogFill,
            indexFilterValues,
            async (err: Error, decodedLogEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
                if (err) {
                    // Note: it's not entirely clear from the documentation which
                    // errors will be thrown by `watch`. For now, let's log the error
                    // to rollbar and stop watching when one occurs
                    // tslint:disable-next-line:no-floating-promises
                    errorReporter.reportAsync(err); // fire and forget
                    return;
                } else {
                    const decodedLog = decodedLogEvent.log;
                    if (!this._doesLogEventInvolveUser(decodedLog)) {
                        return; // We aren't interested in the fill event
                    }
                    this._updateLatestFillsBlockIfNeeded(decodedLog.blockNumber);
                    const fill = await this._convertDecodedLogToFillAsync(decodedLog);
                    if (decodedLogEvent.isRemoved) {
                        tradeHistoryStorage.removeFillFromUser(this._userAddressIfExists, this.networkId, fill);
                    } else {
                        tradeHistoryStorage.addFillToUser(this._userAddressIfExists, this.networkId, fill);
                    }
                }
            },
        );
    }
开发者ID:ewingrj,项目名称:0x-monorepo,代码行数:35,代码来源:blockchain.ts

示例3: transferAsync

    public async transferAsync(token: Token, toAddress: string, amountInBaseUnits: BigNumber): Promise<void> {
        utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.');
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        this._showFlashMessageIfLedger();
        const txHash = await this._zeroEx.token.transferAsync(
            token.address,
            this._userAddressIfExists,
            toAddress,
            amountInBaseUnits,
            {
                gasPrice: this._defaultGasPrice,
            },
        );
        await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash);
        const etherScanLinkIfExists = sharedUtils.getEtherScanLinkIfExists(
            txHash,
            this.networkId,
            EtherscanLinkSuffixes.Tx,
        );
        this._dispatcher.showFlashMessage(
            React.createElement(TokenSendCompleted, {
                etherScanLinkIfExists,
                token,
                toAddress,
                amountInBaseUnits,
            }),
        );
    }
开发者ID:ewingrj,项目名称:0x-monorepo,代码行数:29,代码来源:blockchain.ts

示例4: startListeningForExchangeLogFillEventsAsync

    private async startListeningForExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues): Promise<void> {
        utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.');
        utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES);

        const fromBlock = tradeHistoryStorage.getFillsLatestBlock(this.userAddress, this.networkId);
        const subscriptionOpts: SubscriptionOpts = {
            fromBlock,
            toBlock: 'latest',
        };
        const exchangeAddress = this.getExchangeContractAddressIfExists();
        const exchangeLogFillEventEmitter = await this.zeroEx.exchange.subscribeAsync(
            ExchangeEvents.LogFill, subscriptionOpts, indexFilterValues, exchangeAddress,
        );
        this.exchangeLogFillEventEmitters.push(exchangeLogFillEventEmitter);
        exchangeLogFillEventEmitter.watch(async (err: Error, event: ContractEvent) => {
            if (err) {
                // Note: it's not entirely clear from the documentation which
                // errors will be thrown by `watch`. For now, let's log the error
                // to rollbar and stop watching when one occurs
                errorReporter.reportAsync(err); // fire and forget
                this.stopWatchingExchangeLogFillEventsAsync(); // fire and forget
                return;
            } else {
                const args = event.args as LogFillContractEventArgs;
                const isBlockPending = _.isNull(event.blockNumber);
                if (!isBlockPending) {
                    // Hack: I've observed the behavior where a client won't register certain fill events
                    // and lowering the cache blockNumber fixes the issue. As a quick fix for now, simply
                    // set the cached blockNumber 50 below the one returned. This way, upon refreshing, a user
                    // would still attempt to re-fetch events from the previous 50 blocks, but won't need to
                    // re-fetch all events in all blocks.
                    // TODO: Debug if this is a race condition, and apply a more precise fix
                    const blockNumberToSet = event.blockNumber - 50 < 0 ? 0 : event.blockNumber - 50;
                    tradeHistoryStorage.setFillsLatestBlock(this.userAddress, this.networkId, blockNumberToSet);
                }
                const isUserMakerOrTaker = args.maker === this.userAddress ||
                                           args.taker === this.userAddress;
                if (!isUserMakerOrTaker) {
                    return; // We aren't interested in the fill event
                }
                const blockTimestamp = await this.web3Wrapper.getBlockTimestampAsync(event.blockHash);
                const fill = {
                    filledTakerTokenAmount: args.filledTakerTokenAmount,
                    filledMakerTokenAmount: args.filledMakerTokenAmount,
                    logIndex: event.logIndex,
                    maker: args.maker,
                    orderHash: args.orderHash,
                    taker: args.taker,
                    makerToken: args.makerToken,
                    takerToken: args.takerToken,
                    paidMakerFee: args.paidMakerFee,
                    paidTakerFee: args.paidTakerFee,
                    transactionHash: event.transactionHash,
                    blockTimestamp,
                };
                tradeHistoryStorage.addFillToUser(this.userAddress, this.networkId, fill);
            }
        });
    }
开发者ID:NickMinnellaCS96,项目名称:website,代码行数:59,代码来源:blockchain.ts

示例5: providerTypeUpdatedFireAndForgetAsync

    public async providerTypeUpdatedFireAndForgetAsync(providerType: ProviderType) {
        utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.');
        // Should actually be Web3.Provider|ProviderEngine union type but it causes issues
        // later on in the logic.
        let provider;
        switch (providerType) {
            case ProviderType.LEDGER: {
                const isU2FSupported = await utils.isU2FSupportedAsync();
                if (!isU2FSupported) {
                    throw new Error('Cannot update providerType to LEDGER without U2F support');
                }

                // Cache injected provider so that we can switch the user back to it easily
                this.cachedProvider = this.web3Wrapper.getProviderObj();

                this.dispatcher.updateUserAddress(''); // Clear old userAddress

                provider = new ProviderEngine();
                this.ledgerSubProvider = ledgerWalletSubproviderFactory(this.getBlockchainNetworkId.bind(this));
                provider.addProvider(this.ledgerSubProvider);
                provider.addProvider(new FilterSubprovider());
                const networkId = configs.isMainnetEnabled ?
                    constants.MAINNET_NETWORK_ID :
                    constants.TESTNET_NETWORK_ID;
                provider.addProvider(new RedundantRPCSubprovider(
                    constants.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId],
                ));
                provider.start();
                this.web3Wrapper.destroy();
                const shouldPollUserAddress = false;
                this.web3Wrapper = new Web3Wrapper(this.dispatcher, provider, this.networkId, shouldPollUserAddress);
                await this.zeroEx.setProviderAsync(provider);
                await this.postInstantiationOrUpdatingProviderZeroExAsync();
                break;
            }

            case ProviderType.INJECTED: {
                if (_.isUndefined(this.cachedProvider)) {
                    return; // Going from injected to injected, so we noop
                }
                provider = this.cachedProvider;
                const shouldPollUserAddress = true;
                this.web3Wrapper = new Web3Wrapper(this.dispatcher, provider, this.networkId, shouldPollUserAddress);
                await this.zeroEx.setProviderAsync(provider);
                await this.postInstantiationOrUpdatingProviderZeroExAsync();
                delete this.ledgerSubProvider;
                delete this.cachedProvider;
                break;
            }

            default:
                throw utils.spawnSwitchErr('providerType', providerType);
        }

        await this.fetchTokenInformationAsync();
    }
开发者ID:NickMinnellaCS96,项目名称:website,代码行数:56,代码来源:blockchain.ts

示例6: setProxyAllowanceAsync

    public async setProxyAllowanceAsync(token: Token, amountInBaseUnits: BigNumber.BigNumber): Promise<void> {
        utils.assert(this.isValidAddress(token.address), BlockchainCallErrs.TOKEN_ADDRESS_IS_INVALID);
        utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES);
        utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.');

        await this.zeroEx.token.setProxyAllowanceAsync(
            token.address, this.userAddress, amountInBaseUnits,
        );
        const allowance = amountInBaseUnits;
        this.dispatcher.replaceTokenAllowanceByAddress(token.address, allowance);
    }
开发者ID:NickMinnellaCS96,项目名称:website,代码行数:11,代码来源:blockchain.ts

示例7: convertWrappedEthTokensToEthAsync

    public async convertWrappedEthTokensToEthAsync(etherTokenAddress: string, amount: BigNumber): Promise<void> {
        utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.');
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        this._showFlashMessageIfLedger();
        const txHash = await this._zeroEx.etherToken.withdrawAsync(
            etherTokenAddress,
            amount,
            this._userAddressIfExists,
            {
                gasPrice: this._defaultGasPrice,
            },
        );
        await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash);
    }
开发者ID:ewingrj,项目名称:0x-monorepo,代码行数:15,代码来源:blockchain.ts

示例8: updateProviderToInjectedAsync

    public async updateProviderToInjectedAsync() {
        utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.');

        if (_.isUndefined(this._cachedProvider)) {
            return; // Going from injected to injected, so we noop
        }

        this._blockchainWatcher.destroy();

        const provider = this._cachedProvider;
        this.networkId = this._cachedProviderNetworkId;

        const shouldPollUserAddress = true;
        this._web3Wrapper = new Web3Wrapper(provider);
        this._blockchainWatcher = new BlockchainWatcher(
            this._dispatcher,
            this._web3Wrapper,
            this.networkId,
            shouldPollUserAddress,
        );

        const userAddresses = await this._web3Wrapper.getAvailableAddressesAsync();
        this._userAddressIfExists = userAddresses[0];

        this._zeroEx.setProvider(provider, this.networkId);

        await this.fetchTokenInformationAsync();
        this._blockchainWatcher.startEmittingNetworkConnectionAndUserBalanceState();
        this._dispatcher.updateProviderType(ProviderType.Injected);
        delete this._ledgerSubprovider;
        delete this._cachedProvider;
    }
开发者ID:ewingrj,项目名称:0x-monorepo,代码行数:32,代码来源:blockchain.ts

示例9: pollTokenBalanceAsync

    public async pollTokenBalanceAsync(token: Token) {
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        const [currBalance] = await this.getTokenBalanceAndAllowanceAsync(this._userAddressIfExists, token.address);

        const newTokenBalancePromise = new Promise((resolve: (balance: BigNumber) => void, reject) => {
            const tokenPollInterval = intervalUtils.setAsyncExcludingInterval(
                async () => {
                    const [balance] = await this.getTokenBalanceAndAllowanceAsync(
                        this._userAddressIfExists,
                        token.address,
                    );
                    if (!balance.eq(currBalance)) {
                        intervalUtils.clearAsyncExcludingInterval(tokenPollInterval);
                        resolve(balance);
                    }
                },
                5000,
                (err: Error) => {
                    logUtils.log(`Polling tokenBalance failed: ${err}`);
                    intervalUtils.clearAsyncExcludingInterval(tokenPollInterval);
                    reject(err);
                },
            );
        });

        return newTokenBalancePromise;
    }
开发者ID:ewingrj,项目名称:0x-monorepo,代码行数:28,代码来源:blockchain.ts

示例10: fetchTokenInformationAsync

    private async fetchTokenInformationAsync() {
        utils.assert(!_.isUndefined(this.networkId),
                     'Cannot call fetchTokenInformationAsync if disconnected from Ethereum node');

        this.dispatcher.updateBlockchainIsLoaded(false);
        this.dispatcher.clearTokenByAddress();
        const tokenArrays = await Promise.all([
                this.getTokenRegistryTokensAsync(),
                this.getCustomTokensAsync(),
        ]);
        const tokens = _.flatten(tokenArrays);
        // HACK: We need to fetch the userAddress here because otherwise we cannot fetch the token
        // balances and allowances and we need to do this in order not to trigger the blockchain
        // loading dialog to show up twice. First to load the contracts, and second to load the
        // balances and allowances.
        this.userAddress = await this.web3Wrapper.getFirstAccountIfExistsAsync();
        if (!_.isEmpty(this.userAddress)) {
            this.dispatcher.updateUserAddress(this.userAddress);
        }
        await this.updateTokenBalancesAndAllowancesAsync(tokens);
        const mostPopularTradingPairTokens: Token[] = [
            _.find(tokens, {symbol: configs.mostPopularTradingPairSymbols[0]}),
            _.find(tokens, {symbol: configs.mostPopularTradingPairSymbols[1]}),
        ];
        this.dispatcher.updateChosenAssetTokenAddress(Side.deposit, mostPopularTradingPairTokens[0].address);
        this.dispatcher.updateChosenAssetTokenAddress(Side.receive, mostPopularTradingPairTokens[1].address);
        this.dispatcher.updateBlockchainIsLoaded(true);
    }
开发者ID:NickMinnellaCS96,项目名称:website,代码行数:28,代码来源:blockchain.ts


注:本文中的ts/utils/utils.utils类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。