@/store#vxm TypeScript Examples

The following examples show how to use @/store#vxm. 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: eosBancor.ts    From webapp with MIT License 6 votes vote down vote up
@action async getUserBalances(relayId: string): Promise<UserPoolBalances> {
    const relay = await this.relayById(relayId);
    const [[smartTokenBalance], reserves, supply] = await Promise.all([
      vxm.network.getBalances({
        tokens: [
          {
            contract: relay.smartToken.contract,
            symbol: relay.smartToken.symbol
          }
        ]
      }),
      this.fetchRelayReservesAsAssets(relayId),
      fetchTokenStats(relay.smartToken.contract, relay.smartToken.symbol)
    ]);

    const smartSupply = asset_to_number(supply.supply);
    const percent = new BigNumber(smartTokenBalance.balance).div(smartSupply);

    const maxWithdrawals: ViewAmount[] = reserves.map(reserve => ({
      id: buildTokenId({
        contract: reserve.contract,
        symbol: reserve.amount.symbol.code().to_string()
      }),
      amount: new BigNumber(asset_to_number(reserve.amount))
        .times(percent)
        .toString()
    }));

    return {
      maxWithdrawals,
      iouBalances: [{ id: "", amount: String(smartTokenBalance.balance) }]
    };
  }
Example #2
Source File: index.ts    From webapp with MIT License 6 votes vote down vote up
router.beforeEach((to, from, next) => {
  if (from.path !== to.path) {
    sendGTMPath(from.path, to.path, vxm.general.darkMode);
  }
  if (to.meta && to.meta.feature) {
    if (to.params.service === "eos") {
      next(`/${defaultModule}/data`);
      return;
    }
    if (ethService.namespace !== to.params.service) {
      next("/404");
      return;
    }
    switch (to.meta.feature) {
      case "Trade":
        if (ethService.features.includes(0)) next();
        else next("/404");
        break;
      case "Liquidity":
        if (ethService.features.includes(2)) next();
        else next("/404");
        break;
      default:
        next();
    }
  } else {
    next();
  }
});
Example #3
Source File: observables.ts    From webapp with MIT License 6 votes vote down vote up
combineLatest([onLogin$, minimalPools$]).subscribe(
  ([userAddress, minimalPools]) => {
    if (userAddress) {
      const allTokens = minimalPools.flatMap(pool => [
        ...pool.reserves,
        pool.anchorAddress
      ]);
      vxm.ethBancor.fetchAndSetTokenBalances(allTokens);
    }
  }
);
Example #4
Source File: eosNetwork.ts    From webapp with MIT License 6 votes vote down vote up
@action async transfer({ to, amount, id, memo }: TransferParam) {
    if (!this.currentUser) throw new Error("Not authenticated!");
    const symbol = id;
    const dirtyReserve = vxm.eosBancor.relaysList
      .flatMap(relay => relay.reserves)
      .find(reserve => compareString(reserve.symbol, symbol));
    if (!dirtyReserve) throw new Error("Failed finding dirty reserve");

    const { contract, precision } = dirtyReserve;

    const asset = number_to_asset(amount, new Sym(symbol, precision));

    const actions = await multiContract.tokenTransfer(contract, {
      to,
      quantity: asset.to_string(),
      memo
    });

    const originalBalances = await this.getBalances({
      tokens: [{ contract, symbol }]
    });
    await vxm.eosWallet.tx(actions);
    this.pingTillChange({ originalBalances });
  }
Example #5
Source File: index.ts    From webapp with MIT License 6 votes vote down vote up
@action async stakeRewards({
    maxAmount,
    poolId,
    onUpdate
  }: {
    maxAmount: string;
    poolId: string;
    onUpdate: OnUpdate;
  }): Promise<TxResponse> {
    const txHash = (await multiSteps({
      items: [
        {
          description: `${i18n.t("staking_rewards")}...`,
          task: async () => {
            return vxm.ethBancor.resolveTxOnConfirmation({
              tx: this.contract.methods.stakeRewards(
                expandToken(maxAmount, 18),
                poolId
              ),
              onConfirmation: async () => {
                await wait(3000);
                await this.loadData();
                vxm.ethBancor.fetchProtectionPositions();
                vxm.ethBancor.fetchAndSetLockedBalances();
                await wait(3000);
                await this.loadData();
                vxm.ethBancor.fetchProtectionPositions();
                vxm.ethBancor.fetchAndSetLockedBalances();
              },
              resolveImmediately: true
            });
          }
        }
      ],
      onUpdate
    })) as string;

    return vxm.ethBancor.createTxResponse(txHash);
  }
Example #6
Source File: index.ts    From webapp with MIT License 6 votes vote down vote up
@action async claimRewards({
    onUpdate
  }: {
    onUpdate: OnUpdate;
  }): Promise<TxResponse> {
    const txHash = (await multiSteps({
      items: [
        {
          description: `${i18n.t("withdrawing_rewards")}...`,
          task: async () => {
            return vxm.ethBancor.resolveTxOnConfirmation({
              tx: this.contract.methods.claimRewards(),
              onConfirmation: async () => {
                await wait(3000);
                await this.loadData();
                vxm.ethBancor.fetchProtectionPositions();
                vxm.ethBancor.fetchAndSetLockedBalances();
                await wait(3000);
                await this.loadData();
                vxm.ethBancor.fetchProtectionPositions();
                vxm.ethBancor.fetchAndSetLockedBalances();
              },
              resolveImmediately: true
            });
          }
        }
      ],
      onUpdate
    })) as string;

    return vxm.ethBancor.createTxResponse(txHash);
  }
Example #7
Source File: eosBancor.ts    From webapp with MIT License 6 votes vote down vote up
@action async fetchTokenBalancesIfPossible(tokens: TokenBalanceParam[]) {
    if (!this.currentUser) return;
    const tokensFetched = this.currentUserBalances;
    const allTokens = _.uniqWith(
      this.relaysList.flatMap(relay => relay.reserves),
      (a, b) => compareString(a.id, b.id)
    );
    const tokenBalancesNotYetFetched = _.differenceWith(
      allTokens,
      tokensFetched,
      compareAgnosticToBalanceParam
    );

    const tokensToAskFor = _.uniqWith(
      [
        ...tokens,
        ...tokenBalancesNotYetFetched.map(agnosticToTokenBalanceParam)
      ],
      compareToken
    );

    return vxm.eosNetwork.getBalances({ tokens: tokensToAskFor, slow: false });
  }
Example #8
Source File: eosBancor.ts    From webapp with MIT License 6 votes vote down vote up
@action async fetchBalancesFromReserves(relays: DryRelay[]) {
    const tokens = relays
      .flatMap(relay => relay.reserves)
      .map(reserve => ({
        contract: reserve.contract,
        symbol: reserve.symbol.code().to_string()
      }));

    const uniqueTokens = _.uniqWith(
      tokens,
      (a, b) =>
        compareString(a.symbol, b.symbol) &&
        compareString(a.contract, b.contract)
    );

    return vxm.eosNetwork.getBalances({
      tokens: uniqueTokens,
      slow: false
    });
  }
Example #9
Source File: observables.ts    From webapp with MIT License 6 votes vote down vote up
combineLatest([liquidityProtectionStore$, onLogin$, lockedBalancesTrigger$])
  .pipe(
    switchMapIgnoreThrow(([storeAddress, currentUser]) =>
      fetchLockedBalances(storeAddress, currentUser)
    )
  )
  .subscribe(balances => {
    vxm.ethBancor.setLockedBalances(balances);
  });
Example #10
Source File: observables.ts    From webapp with MIT License 6 votes vote down vote up
apiData$.subscribe(data => {
  vxm.ethBancor.setApiData(data);
  const minimalPools = data.pools.map(
    (pool): MinimalPool => ({
      anchorAddress: pool.pool_dlt_id,
      converterAddress: pool.converter_dlt_id,
      reserves: pool.reserves.map(r => r.address)
    })
  );
  minimalPoolBalanceReceiver$.next(minimalPools);
});
Example #11
Source File: eosBancor.ts    From webapp with MIT License 6 votes vote down vote up
@action async triggerTxAndWatchBalances({
    actions,
    tokenIds
  }: {
    actions: any[];
    tokenIds: string[];
  }) {
    const fullTokens = await Promise.all(
      tokenIds.map(tokenId => this.tokenById(tokenId))
    );
    const tokens: BaseToken[] = fullTokens;
    const [txRes, originalBalances] = await Promise.all([
      this.triggerTx(actions),
      vxm.eosNetwork.getBalances({
        tokens
      })
    ]);
    vxm.eosNetwork.pingTillChange({ originalBalances });
    return txRes;
  }
Example #12
Source File: observables.ts    From webapp with MIT License 6 votes vote down vote up
liquiditySettings$ = combineLatest([
  liquidityProtection$,
  settingsContractAddress$
]).pipe(
  switchMapIgnoreThrow(([protectionContractAddress, settingsContractAddress]) =>
    fetchLiquidityProtectionSettings({
      settingsContractAddress
    }).catch(e =>
      vxm.ethBancor.fetchLiquidityProtectionSettings({
        protectionContractAddress,
        settingsContractAddress
      })
    )
  ),
  share()
)
Example #13
Source File: eosWallet.ts    From webapp with MIT License 6 votes vote down vote up
@action async initLogin(provider: WalletProvider) {
    this.setProvider(provider);
    this.checkDevice();

    const wallet = this.accessContext.initWallet(provider);

    wallet.subscribe((walletState: any) => {
      if (walletState) this.setWalletState(walletState);
    });

    try {
      await wallet.connect();
      try {
        await wallet.login();
        this.setWallet(wallet);
        localStorage.setItem("autoLogin", provider.id);
        vxm.eosBancor.onAuthChange(
          wallet && wallet.auth! && wallet.auth!.accountName!
        );
      } catch (e) {
        console.error("auth error");
        throw e;
      }
    } catch (e) {
      console.error("connection error");
      throw e;
    }
  }
Example #14
Source File: eosWallet.ts    From webapp with MIT License 6 votes vote down vote up
@action async logout() {
    if (this.wallet) {
      this.wallet.logout();
      this.setWallet(false);
      this.setWalletState(false);
      localStorage.removeItem("autoLogin");
      vxm.network.resetBalances();
    }
  }
Example #15
Source File: contracts.ts    From webapp with MIT License 6 votes vote down vote up
contractAddresses$ = networkVars$.pipe(
  switchMapIgnoreThrow(networkVariables => {
    return fetchContractAddresses(networkVariables.contractRegistry).catch(() =>
      vxm.ethBancor.fetchContractAddresses(networkVariables.contractRegistry)
    );
  }),
  tap(x => {
    if (vxm && vxm.ethBancor) {
      vxm.ethBancor.setContractAddresses(x);
    }
  }),
  distinctUntilChanged<RegisteredContracts>(isEqual),
  shareReplay(1)
)
Example #16
Source File: auth.ts    From webapp with MIT License 6 votes vote down vote up
merge(onLogin$, onLogout$).subscribe(address => {
  const stringForm = address == false ? "" : address;
  try {
    vxm.ethBancor.onAuthChange(stringForm);
    vxm.ethWallet.setLoggedInAccount(stringForm);
  } catch (e) {
    console.error(e);
  }
});
Example #17
Source File: helpers.ts    From webapp with MIT License 6 votes vote down vote up
onboard = Onboard({
  dappId: process.env.VUE_APP_BLOCKNATIVE,
  networkId: 1,
  hideBranding: true,
  subscriptions: {
    address: address => {
      authenticatedReceiver$.next(address);
    },
    balance: balance => vxm.ethWallet.nativeBalanceChange(balance),
    network: (network: EthNetworks) => {
      if (network == EthNetworks.Mainnet || network == EthNetworks.Ropsten) {
        onboard.config({ networkId: network });
      }
      if (network) {
        networkVersionReceiver$.next(network);
        vxm.ethWallet.onNetworkChange(network);
      }
    },
    wallet: wallet => {
      if (wallet.name) {
        localStorage.setItem(selectedWeb3Wallet, wallet.name);
      }
      web3.setProvider(wallet.provider);
    }
  },
  walletSelect: {
    wallets
  },
  walletCheck: walletChecks
})
Example #18
Source File: helpers.ts    From webapp with MIT License 6 votes vote down vote up
getBankBalance = async (): Promise<
  {
    id: number;
    quantity: string;
    symbl: string;
  }[]
> => {
  const account = currentUserViaModule(vxm.eosWallet);
  const res: {
    rows: {
      id: number;
      quantity: string;
      symbl: string;
    }[];
  } = await rpc.get_table_rows({
    code: process.env.VUE_APP_MULTICONTRACT!,
    scope: account,
    table: "accounts"
  })!;
  return res.rows;
}
Example #19
Source File: helpers.ts    From webapp with MIT License 6 votes vote down vote up
getBalance = async (
  contract: string,
  symbolName: string,
  precision?: number
): Promise<string> => {
  const account = currentUserViaModule(vxm.eosWallet);
  const res: { rows: { balance: string }[] } = await rpc.get_table_rows({
    code: contract,
    scope: account,
    table: "accounts",
    limit: 99
  });
  const balance = res.rows.find(balance =>
    compareString(
      new Asset(balance.balance).symbol.code().to_string(),
      symbolName
    )
  );

  if (!balance) {
    if (typeof precision == "number") {
      return number_to_asset(0, new Sym(symbolName, precision)).to_string();
    } else {
      const symbol = await fetchTokenSymbol(contract, symbolName);
      return number_to_asset(0, symbol).to_string();
    }
  }
  return balance.balance;
}
Example #20
Source File: index.ts    From webapp with MIT License 5 votes vote down vote up
@action async refreshBalances(symbols: string[] = []) {
    if (vxm.wallet.currentUser) {
      return this.dispatcher(["refreshBalances", symbols]);
    }
  }
Example #21
Source File: ethWallet.ts    From webapp with MIT License 5 votes vote down vote up
@action async nativeBalanceChange(nativeBalance: string) {
    if (nativeBalance)
      vxm.ethBancor.updateUserBalances([
        { balance: fromWei(nativeBalance), id: ethReserveAddress }
      ]);
  }
Example #22
Source File: eosBancor.ts    From webapp with MIT License 5 votes vote down vote up
@action async removeLiquidity({
    reserves,
    id: relayId,
    onUpdate
  }: LiquidityParams): Promise<TxResponse> {
    const relay = await this.relayById(relayId);
    const smartTokenSymbol = relay.smartToken.symbol;

    const isMultiRelay = relay.isMultiContract;

    if (!isMultiRelay) {
      return this.removeLiquidityV1({ reserves, id: relayId, onUpdate });
    }

    const { smartTokenAmount } = await this.calculateOpposingWithdraw({
      id: relayId,
      reserves,
      changedReserveId: reserves[0].id
    });

    const liquidityAsset = smartTokenAmount;

    const action = multiContract.removeLiquidityAction(liquidityAsset);

    const tokenContractsAndSymbols = [
      {
        contract: process.env.VUE_APP_SMARTTOKENCONTRACT!,
        symbol: smartTokenSymbol
      },
      ...relay.reserves.map(reserve => ({
        contract: reserve.contract,
        symbol: reserve.symbol
      }))
    ];

    const [txRes, originalBalances] = await Promise.all([
      this.triggerTx([action]),
      vxm.eosNetwork.getBalances({
        tokens: tokenContractsAndSymbols
      })
    ]);
    vxm.eosNetwork.pingTillChange({ originalBalances });
    this.waitAndUpdate(6000);

    const txId = txRes.transaction_id as string;
    return {
      txId,
      blockExplorerLink: generateEosxLink(txId),
      blockExplorerName: "EOSX"
    };
  }
Example #23
Source File: eosBancor.ts    From webapp with MIT License 5 votes vote down vote up
@action async refreshBalances(tokens: BaseToken[] = []) {
    if (!this.currentUser) return;
    if (tokens.length > 0) {
      await vxm.eosNetwork.getBalances({ tokens });
      return;
    }
    await vxm.eosNetwork.getBalances();
  }
Example #24
Source File: eosBancor.ts    From webapp with MIT License 5 votes vote down vote up
@action async init(param?: ModuleParam) {
    this.pullEvents();

    if (this.initialised) return this.refresh();

    try {
      const [usdPriceOfBnt, v2Relays, tokenMeta] = await Promise.all([
        vxm.bancor.fetchUsdPriceOfBnt(),
        fetchMultiRelays(),
        getTokenMeta()
      ]);
      this.setTokenMeta(tokenMeta);
      this.setBntPrice(usdPriceOfBnt);

      const v1Relays = getHardCodedRelays();
      const allDry = [...v1Relays, ...v2Relays.map(multiToDry)].filter(
        noBlackListedReservesDry(blackListedTokens)
      );

      this.fetchTokenBalancesIfPossible(
        _.uniqWith(
          allDry.flatMap(x =>
            x.reserves.map(x => ({ ...x, symbol: x.symbol.code().to_string() }))
          ),
          compareToken
        )
      );

      const quickTrade =
        param &&
        param.tradeQuery &&
        param.tradeQuery.base &&
        param.tradeQuery.quote;
      if (quickTrade) {
        const { base: fromId, quote: toId } = param!.tradeQuery!;
        await this.bareMinimumForTrade({
          fromId,
          toId,
          v1Relays,
          v2Relays,
          tokenMeta
        });
      } else {
        await this.addPools({
          multiRelays: v2Relays,
          dryDelays: v1Relays,
          tokenMeta
        });
      }

      this.setInitialised(true);
      this.setLoadingPools(false);
    } catch (e) {
      throw new Error(`Threw inside eosBancor: ${e.message}`);
    }
  }
Example #25
Source File: ethWallet.ts    From webapp with MIT License 5 votes vote down vote up
@action async onNetworkChange(network: EthNetworks) {
    if (network !== this.currentNetwork) {
      this.setNetwork(network);
      vxm.ethBancor.onNetworkChange(network);
    }
  }
Example #26
Source File: observables.ts    From webapp with MIT License 5 votes vote down vote up
onLogout$.subscribe(() => vxm.ethBancor.wipeTokenBalances());
Example #27
Source File: helpers.ts    From webapp with MIT License 5 votes vote down vote up
buildPoolName = (poolId: string): string => {
  const pool: ViewRelay = vxm.bancor.relay(poolId);
  if (pool) {
    return buildPoolNameFromReserves(pool.reserves);
  } else return "N/A";
}
Example #28
Source File: contracts.ts    From webapp with MIT License 5 votes vote down vote up
combineLatest([govTokenAddress$, vxmTimer$]).subscribe(([govToken]) => {
  vxm.ethBancor.fetchAndSetTokenBalances([govToken]);
});
Example #29
Source File: observables.ts    From webapp with MIT License 5 votes vote down vote up
poolPrograms$ = storeRewards$.pipe(
  switchMapIgnoreThrow(storeRewardContract =>
    vxm.rewards.fetchPoolPrograms(storeRewardContract)
  ),
  share()
)