rxjs/operators#map TypeScript Examples

The following examples show how to use rxjs/operators#map. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: app.component.ts    From gnosis.1inch.exchange with MIT License 7 votes vote down vote up
private getFilteredTokens(form: FormControl): Observable<ITokenDescriptor[]> {

        return combineLatest([
            this.sortedTokens$,
            form.valueChanges.pipe(
                startWith('')
            ),
        ]).pipe(
            map((x) => {
                const [tokens, filterText] = x;
                return filterTokens(tokens, filterText);
            })
        );
    }
Example #2
Source File: counter-notifications.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
constructor(
    private readonly authService: AuthService,
    private readonly myTradesService: MyTradesService,
    private readonly storeService: StoreService
  ) {
    this.authService
      .getCurrentUser()
      .pipe(
        map(() => this.storeService.getItem(CounterNotificationsService.storageKey)),
        filter(unreadTrades => Number(unreadTrades) > 0)
      )
      .subscribe(this._unreadTrades$);
  }
Example #3
Source File: path-payment-form.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
myAssets$: Observable<IWalletAssetModel[]> = this.selectedWalletAccount$
    .pipe(switchMap(selectedWalletAccount => {
      if (!selectedWalletAccount || !selectedWalletAccount.accountRecord) {
        return of([]);
      }

      const assetsIds = this.walletsAssetsService.filterBalancesLines(selectedWalletAccount.accountRecord.balances)
        .map(b => this.walletsAssetsService.formatBalanceLineId(b));

      return this.walletsAssetsQuery.getAssetsById(assetsIds);
    }));
Example #4
Source File: bridge-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Gets user's bridges transactions.
   * @param walletAddress User's wallet address.
   * @return Observable Trade object.
   */
  public getUserTrades(walletAddress: string): Observable<TableTrade[]> {
    return this.httpService
      .get('bridges/transactions', { walletAddress: walletAddress.toLowerCase(), t: Date.now() })
      .pipe(
        map((tradesApi: BridgeTableTradeApi[]) =>
          tradesApi
            .filter(trade =>
              this.whitelistedPolygonBridgeHashes.includes(trade.fromTransactionHash)
            )
            .map(trade => this.parseTradeApiToTableTrade(trade))
        )
      );
  }
Example #5
Source File: sign-xdr.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
// TODO: Make this dynamic with a config store
  fee$: Observable<string> = this.xdrParsed$
    .pipe(filter<Transaction>(data => !!data))
    .pipe(pluck<Transaction, string>('fee'))
    .pipe(map(fee =>
      new BigNumber(fee)
        .dividedBy('10000000')
        .toString()
    ));
Example #6
Source File: cross-chain-routing-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Gets list of user's cross chain trades.
   * @param walletAddress Wallet address of user.
   * @param page Page in pagination.
   * @param pageSize Page size in pagination.
   */
  public getUserTrades(
    walletAddress: string,
    page: number,
    pageSize: number
  ): Observable<TableData> {
    return this.httpService
      .get('trades/', { user: walletAddress, page: page + 1, page_size: pageSize }, BASE_URL)
      .pipe(
        map((trades: CrossChainTradesResponseApi) => {
          return {
            totalCount: trades.count,
            trades: trades.results.map(trade =>
              CrossChainRoutingApiService.parseTradeApiToTableTrade(trade)
            )
          };
        })
      );
  }
Example #7
Source File: asset-searcher.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
filteredDefaultAssets$ = this.searchInputControl
    .valueChanges
    .pipe(debounceTime(80))
    .pipe(startWith(''))
    .pipe(withLatestFrom(this.defaultAssets$))
    .pipe(map(([searchValue, defaultAssets]) => {
      if (!searchValue) {
        return defaultAssets;
      }

      return defaultAssets.filter(asset => {
        if (!!asset.assetIssuer) {
          return asset.assetCode === searchValue || asset.assetCode.toLowerCase().includes(searchValue.toLowerCase());
        } else {
          return asset.assetCode.toLowerCase().includes(searchValue.toLowerCase());
        }
      });
    }));
Example #8
Source File: gas-refund-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Fetches merkle tree leaves list and root index for specific action.
   * @param promotionId action id for which data will be loaded.
   * @return merkle tree leaves list and root index.
   */
  public getPromotionMerkleData(promotionId: number): Observable<MerkleData> {
    const endpointUrl = `${GasRefundApiService.baseUrl}/promotions/${promotionId}/merkle-tree`;
    const walletAddress = this.authService.userAddress;
    return this.httpService.get<MerkleResponse>(endpointUrl, { walletAddress }).pipe(
      map(response => ({
        ...response,
        amount: new BigNumber(response.amount)
      }))
    );
  }
Example #9
Source File: wallet-dashboard.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
sizeOfPortfolioGraphValues$: Observable<Array<{ name?: string; value: number }>> = this.accountBalancesRegularAssets$
    .pipe(map(balances => {
      const totalBalanceOfAssets = balances.reduce((total, current) => {
        return new BigNumber(current.balance).plus(total);
      }, new BigNumber(0));

      return balances.map(b => {
        const balanceLineId = this.walletsAssetsService.formatBalanceLineId(b);
        const asset = this.walletsAssetsService.sdkAssetFromAssetId(balanceLineId);
        return {
          name: asset.code || '',
          value: new BigNumber(b.balance).dividedBy(totalBalanceOfAssets).multipliedBy(100).toNumber(),
        };
      });
    }));
Example #10
Source File: gas-refund-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Fetches past user transactions for gas refund.
   * @return stream that emits once past user refund gas transactions, or empty list if error.
   */
  public getGasRefundTransactions(): Observable<RefundTransaction[]> {
    const endpointUrl = `${GasRefundApiService.baseUrl}/refunds`;
    const walletAddress = this.authService.userAddress;
    return this.httpService.get<RefundTransactionsResponse>(endpointUrl, { walletAddress }).pipe(
      timeout(3000),
      map(response =>
        response.map(item => ({
          ...item,
          network: FROM_BACKEND_BLOCKCHAINS[item.network],
          value: new BigNumber(item.value),
          date: new Date(item.date * 1000)
        }))
      ),
      catchError((e: unknown) => {
        console.error(e);
        return of([]);
      })
    );
  }
Example #11
Source File: wallet-dashboard.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
lpAssetsBalances$: Observable<BalanceLineLiquidityPool[]> = this.selectedAccount$
    .pipe(map(selectedAccount => {
      if (!selectedAccount || !selectedAccount.accountRecord) {
        return [];
      }

      return selectedAccount.accountRecord
        .balances
        .filter(b => b.asset_type === 'liquidity_pool_shares') as BalanceLineLiquidityPool[];
    }));
Example #12
Source File: instant-trades-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Sends request to get list of user's instant trades.
   * @param walletAddress Wallet address of user.
   * @param errorCallback Callback on error.
   * @return list List of trades.
   */
  public getUserTrades(
    walletAddress: string,
    errorCallback?: (error: unknown) => void
  ): Observable<TableTrade[]> {
    const url = instantTradesApiRoutes.getData(this.walletConnectorService.provider.walletType);
    return this.httpService.get(url, { user: walletAddress }).pipe(
      map((swaps: InstantTradesResponseApi[]) =>
        swaps.map(swap => this.parseTradeApiToTableTrade(swap))
      ),
      catchError((err: unknown) => {
        errorCallback?.(err);
        return of([]);
      })
    );
  }
Example #13
Source File: wallet-dashboard.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
lockedXLMs$: Observable<string> = this.accountBalancesRegularAssets$
    .pipe(withLatestFrom(this.selectedAccount$))
    .pipe(map(([balances, selectedAccount]) => {
      const nativeValue: BalanceLineNative = balances.find(b => b.asset_type === 'native') as BalanceLineNative;
      if (!selectedAccount.accountRecord) {
        return  '0';
      }

      return new BigNumber(nativeValue.balance)
        .minus(
          this.stellarSdkService.calculateAvailableBalance({
            account: selectedAccount.accountRecord,
            balanceLine: nativeValue
          })
        )
        .toFixed(7);
    }));
Example #14
Source File: promo-code-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Checks if at least one active promo code exists.
   */
  @Cacheable()
  public promoCodesExists(): Observable<boolean> {
    const endpoint = 'check';
    return this.httpService
      .get<PromoCodesCheckExistenceResponse>(`${PromoCodeApiService.apiUrl}/${endpoint}`)
      .pipe(
        map(response => response.exists),
        catchError((e: unknown) => {
          console.error(e);
          return of(false);
        })
      );
  }
Example #15
Source File: send-payment.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
availableFunds$ = this.selectedAsset$
    .pipe(withLatestFrom(this.selectedAccount$))
    .pipe(map(([selectedAsset, selectedAccount]) => {
      if (!selectedAsset || !selectedAccount.accountRecord) {
        console.warn('Balance or Account record is undefined');
        return new BigNumber(0).toNumber();
      }
      const filteredBalances = this.walletsAssetsService
        .filterBalancesLines(selectedAccount.accountRecord.balances);

      const targetBalance = filteredBalances.find(balance => {
        return selectedAsset._id === this.walletsAssetsService.formatBalanceLineId(balance);
      });

      if (!targetBalance) {
        console.warn(`An unexpected balance arrived in this line`);
        return 0;
      }

      return this.stellarSdkService
        .calculateAvailableBalance({
          account: selectedAccount.accountRecord,
          balanceLine: targetBalance,
        })
        .toNumber();
    }));
Example #16
Source File: tokens-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Converts {@link BackendToken} to {@link Token} List.
   * @param tokens Tokens from backend response.
   * @return List<Token> Useful tokens list.
   */
  public static prepareTokens(tokens: BackendToken[]): List<Token> {
    return List(
      tokens
        .map((token: BackendToken) => ({
          ...token,
          blockchain: FROM_BACKEND_BLOCKCHAINS[token.blockchainNetwork],
          price: token.usdPrice,
          usedInIframe: token.usedInIframe,
          hasDirectPair: token.hasDirectPair
        }))
        .filter(token => token.address && token.blockchain)
    );
  }
Example #17
Source File: send-payment.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
heldAssets$: Observable<IWalletAssetModel[]> = this.selectedAccount$
    .pipe(switchMap(selectedAccount => {
      const assetsIds = !!selectedAccount.accountRecord
        ? this.walletsAssetsService.filterBalancesLines(selectedAccount.accountRecord.balances).map(balanceLine => {
          return this.walletsAssetsService.formatBalanceLineId(balanceLine);
        })
        : [];

      return this.walletsAssetsQuery.getAssetsById(assetsIds);
    }));
Example #18
Source File: tokens-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Fetches iframe tokens from backend.
   * @param params Request params.
   * @return Observable<List<Token>> Tokens list.
   */
  private fetchIframeTokens(params: { [p: string]: unknown }): Observable<List<Token>> {
    return this.httpService
      .get(ENDPOINTS.IFRAME_TOKENS, params)
      .pipe(map((backendTokens: BackendToken[]) => TokensApiService.prepareTokens(backendTokens)));
  }
Example #19
Source File: wallet-asset-item.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
availableFunds$: Observable<string> = combineLatest([
    this.balanceLine$,
    this.walletsAccountsQuery.getSelectedAccount$,
  ])
    .pipe(filter(values => values.every(value => !!value)))
    .pipe(map(([balanceLine, selectedAccount]) => {
      if (!balanceLine || !selectedAccount?.accountRecord) {
        console.warn('Balance or Account record is undefined');
        return new BigNumber(0).toString();
      }

      return this.stellarSdkService
        .calculateAvailableBalance({
          account: selectedAccount.accountRecord,
          balanceLine
        })
        .toString();
    }));
Example #20
Source File: leaderboard.component.ts    From one-platform with MIT License 6 votes vote down vote up
ngAfterViewInit() {
    this.searchSubscription = fromEvent(this.searchInput.nativeElement, 'keyup')
      .pipe(
        map((event: InputEvent) => (event.target as HTMLInputElement).value),
        debounceTime(500),
        distinctUntilChanged()
      )
      .subscribe((search) => {
        this.searchTerm = search;
        this.pageOffset = 0;
        this.fetchLHLeaderboard();
      });
  }
Example #21
Source File: tokens-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Fetches specific tokens by symbol or address.
   * @param requestOptions Request options to search tokens by.
   * @return Observable<TokensListResponse> Tokens response from backend with count.
   */
  public fetchQueryTokens(requestOptions: TokensRequestQueryOptions): Observable<List<Token>> {
    const options = {
      network: TO_BACKEND_BLOCKCHAINS[requestOptions.network],
      ...(requestOptions.symbol && { symbol: requestOptions.symbol.toLowerCase() }),
      ...(requestOptions.address && { address: requestOptions.address.toLowerCase() })
    };
    return this.httpService
      .get(ENDPOINTS.TOKENS, options)
      .pipe(
        map((tokensResponse: BackendToken[]) =>
          tokensResponse.length ? TokensApiService.prepareTokens(tokensResponse) : List()
        )
      );
  }
Example #22
Source File: wallet-account.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
async removeAccount(): Promise<any> {
    await this.nzModalService.confirm({
      nzTitle: this.translateService.instant('SETTINGS.WALLET_ACCOUNT.REMOVE_ACCOUNT_TITLE'),
      nzContent: this.translateService.instant('SETTINGS.WALLET_ACCOUNT.REMOVE_ACCOUNT_CONTENT'),
      nzOnOk: async () => {
        const walletId = await this.walletId$.pipe(take(1)).toPromise();
        const publicKey = await this.publicKey.pipe(take(1)).toPromise();
        const accounts = await this.walletsAccountsQuery.selectAll({
          filterBy: entity => entity.publicKey === publicKey && walletId === entity.walletId,
        }).pipe(take(1))
          .toPromise();

        this.router.navigate(['/settings/wallets', walletId])
          .then(() => {
            this.walletsAccountsService.removeAccounts(accounts.map(a => a._id));
          });
      }
    });
  }
Example #23
Source File: tokens-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Fetches specific network tokens from backend.
   * @param requestOptions Request options to get tokens by.
   * @return Observable<TokensListResponse> Tokens response from backend with count.
   */
  public fetchSpecificBackendTokens(
    requestOptions: TokensRequestNetworkOptions
  ): Observable<TokensListResponse> {
    const options = {
      network: TO_BACKEND_BLOCKCHAINS[requestOptions.network],
      page: requestOptions.page,
      pageSize: DEFAULT_PAGE_SIZE
    };
    return this.httpService.get<TokensBackendResponse>(ENDPOINTS.TOKENS, options).pipe(
      map(tokensResponse => {
        return {
          total: tokensResponse.count,
          result: TokensApiService.prepareTokens(tokensResponse.results),
          next: tokensResponse.next
        };
      })
    );
  }
Example #24
Source File: registered-wallet-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
groupedWalletAccounts$: Observable<IWalletsAccount[]> = this.walletAccounts$
    .pipe(map(accounts =>
      accounts.reduce((all: { [publicKey: string]: IWalletsAccount }, current) => {
        return !all[current.publicKey]
          ? ({ ...all, [current.publicKey]: current })
          : all;
      }, {})
    ))
    .pipe(map(obj => Object.values(obj)));
Example #25
Source File: volume-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Makes request for trade volumes.
   * @return Observable trade volume.
   */
  private fetchVolume(): Observable<TradeVolume> {
    return this.httpService.get('total_values/').pipe(
      map((volume: TradeVolumeRequest) => ({
        instantTrades: new BigNumber(volume.instant_trades_amount),
        bridges: new BigNumber(volume.bridges_amount)
      }))
    );
  }
Example #26
Source File: add-account.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
groupedWalletAccounts$: Observable<IWalletsAccount[]> = this.walletAccounts$
    .pipe(map(accounts =>
      accounts.reduce((all: { [publicKey: string]: IWalletsAccount }, current) => {
        return !all[current.publicKey]
          ? ({ ...all, [current.publicKey]: current })
          : all;
      }, {})
    ))
    .pipe(map(obj => Object.values(obj)));
Example #27
Source File: eth-like-web3-public.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Sends batch request via web3.
   * @see {@link https://web3js.readthedocs.io/en/v1.3.0/web3-eth.html#batchrequest|Web3BatchRequest}
   * @param calls Web3 method calls
   * @param callsParams ethereum method transaction parameters
   * @return batch request call result sorted in order of input parameters
   */
  private web3BatchRequest<T extends string | string[]>(
    calls: { request: (...params: unknown[]) => Method }[],
    callsParams: Object[]
  ): Promise<T[]> {
    const batch = new this.web3.BatchRequest();
    const promises: Promise<T>[] = calls.map(
      (call, index) =>
        new Promise((resolve, reject) =>
          batch.add(
            call.request({ ...callsParams[index] }, (error: Error, result: T) =>
              error ? reject(error) : resolve(result)
            )
          )
        )
    );

    batch.execute();

    return Promise.all(promises);
  }
Example #28
Source File: withdraw-liquidity.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
selectedBalance$: Observable<string> = combineLatest([
    this.accountBalances$,
    this.selectedLiquidityPool$
  ])
    .pipe(map(([balances, selectedLiquidityPool]) => {
      return selectedLiquidityPool && balances.find(b => b.liquidity_pool_id === selectedLiquidityPool._id);
    }))
    .pipe(map(balanceLine => {
      return balanceLine?.balance || '0';
    }));
Example #29
Source File: eth-like-web3-public.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Sends batch request to rpc provider directly.
   * @see {@link https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/openrpc.json&uiSchema%5BappBar%5D%5Bui:splitView%5D=false&uiSchema%5BappBar%5D%5Bui:input%5D=false&uiSchema%5BappBar%5D%5Bui:examplesDropdown%5D=false|EthereumJSON-RPC}
   * @param rpcCallsData rpc methods and parameters list
   * @return rpc batch request call result sorted in order of input parameters
   */
  private async rpcBatchRequest<T extends string | string[]>(
    rpcCallsData: {
      rpcMethod: string;
      params: Object;
    }[]
  ): Promise<T[]> {
    const seed = Date.now();
    const batch = rpcCallsData.map((callData, index) => ({
      id: seed + index,
      jsonrpc: '2.0',
      method: callData.rpcMethod,
      params: [{ ...callData.params }]
    }));

    const response = await this.httpClient
      .post<RpcResponse<T>[]>((<HttpProvider>this.web3.currentProvider).host, batch)
      .toPromise();

    if (Array.isArray(response)) {
      return response.sort((a, b) => a.id - b.id).map(item => (item.error ? null : item.result));
    }
    return [response];
  }