08BuildingDappsDexOld - InjectiveLabs/injective-ts GitHub Wiki

⚠️ The Docs have been moved to https://docs.ts.injective.network/building-dapps/dapps-examples/dex ⚠️

Within these short series we are going to showcase how easy it is to build a DEX on top of Injective. There is an open-sourced DEX which everyone can reference and use to build on top of Injective. For those who want to start from scratch, this is the right place to start.

The series will include:

  • Setting up the API clients and environment,
  • Connecting to the Chain and the Indexer API,
  • Connect to a user wallet and get their address,
  • Fetching Spot and Derivative markets and their orderbooks,
  • Placing market orders on both spot and a derivative market,
  • View all trading accounts for an Injective address,
  • View all positions for an Injective address.

Setup

To get started, we need to setup the API clients and the environment. To build our DEX we are going to query data from both the Injective Chain and the Indexer API. In this example, we are going to use the existing testnet environment.

To establish connection, we can use the following code snippet:

// filename: Services.ts
import {
  ChainGrpcBankApi,
  IndexerGrpcDerivativesApi,
  IndexerGrpcSpotApi,
  IndexerGrpcAccountApi,
} from "@injectivelabs/sdk-ts";
import { getNetworkEndpoints, Network } from "@injectivelabs/networks";

// Getting the pre-defined endpoints for the Testnet environment
// (using TestnetK8s here because we want to use the Kubernetes infra)
export const endpoints = getNetworkEndpoints(Network.TestnetK8s);

export const chainBankApi = new ChainGrpcBankApi(endpoints.grpc);
export const indexerDerivativesApi = new IndexerGrpcDerivativesApi(
  endpoints.indexer
);
export const indexerSpotApi = new IndexerGrpcSpotApi(endpoints.indexer);
export const indexerAccountApi = new IndexerGrpcAccountApi(endpoints.indexer);

Then, we also need to setup a wallet connection to allow the user to connect to our DEX and start signing transactions. To make this happen we are going to use our @injectivelabs/wallet-ts package which allows users to connect with a various of different wallet providers and use them to sign transactions on Injective.

// filename: Wallet.ts
import { WalletStrategy, Wallet } from "@injectivelabs/wallet-ts";
import { ChainId, EthereumChainId } from "@injectivelabs/ts-types";

const chainId = ChainId.Testnet; // The Injective Chain chainId
const ethereumChainId = EthereumChainId.Goerli; // The Ethereum Chain ID

export const alchemyRpcEndpoint = IS_TESTNET
  ? `https://eth-goerli.alchemyapi.io/v2/${process.env.APP_ALCHEMY_GOERLI_KEY}`
  : `https://eth-mainnet.alchemyapi.io/v2/${process.env.APP_ALCHEMY_KEY}`;

const rpcUrl = IS_TESTNET
  ? `https://eth-goerli.alchemyapi.io/v2/${process.env.APP_ALCHEMY_GOERLI_KEY}`
  : `https://eth-mainnet.alchemyapi.io/v2/${process.env.APP_ALCHEMY_KEY}`;

const wsRpcUrl = IS_TESTNET
  ? `wss://eth-goerli.ws.alchemyapi.io/v2/${process.env.APP_ALCHEMY_GOERLI_KEY}`
  : `https://eth-mainnet.ws.alchemyapi.io/v2/${process.env.APP_ALCHEMY_KEY}`;

export const alchemyKey = (
  IS_TESTNET ? process.env.APP_ALCHEMY_GOERLI_KEY : process.env.APP_ALCHEMY_KEY
) as string;

export const walletStrategy = new WalletStrategy({
  chainId: CHAIN_ID,
  ethereumOptions: {
    rpcUrl,
    wsRpcUrl,
    ethereumChainId: ETHEREUM_CHAIN_ID,
    disabledWallets: [Wallet.WalletConnect],
  },
});

If we don't want to use Ethereum native wallets, we can use CosmosWalletStrategy from the @injectivelabs/wallet-ts package and use Cosmos native wallets only.

// filename: CosmosWallet.ts
import { ChainId } from "@injectivelabs/ts-types";
import { CosmosWalletStrategy, Wallet } from "@injectivelabs/wallet-ts";

export const cosmosWalletStrategy = new CosmosWalletStrategy({
  wallet: Wallet.Leap,
  chainId: ChainId.Testnet,
});

We are going to use the Cosmos Wallet Strategy in our series moving forward.

Connect to the user's wallet

Since we are using the WalletStrategy to handle the connection with the user's wallet, we can use its methods to handle some use cases like getting the user's addresses, sign/broadcast a transaction, etc. To find out more about the wallet strategy, you can explore the documentation interface and the method the WalletStrategy offers.

Note: We can switch between the "active" wallet within the WalletStrategy using the setWallet method.

// filename: WalletConnection.ts
import {
  WalletException,
  UnspecifiedErrorCode,
  ErrorType,
} from "@injectivelabs/exceptions";
import { Wallet } from "@injectivelabs/wallet-ts";
import { cosmosWalletStrategy } from "./CosmosWallet.ts";

export const getAddresses = async (wallet: Wallet): Promise<string[]> => {
  cosmosWalletStrategy.setWallet(wallet);

  const addresses = await cosmosWalletStrategy.getAddresses();

  if (addresses.length === 0) {
    throw new WalletException(
      new Error("There are no addresses linked in this wallet."),
      {
        code: UnspecifiedErrorCode,
        type: ErrorType.WalletError,
      }
    );
  }

  if (!addresses.every((address) => !!address)) {
    throw new WalletException(
      new Error("There are no addresses linked in this wallet."),
      {
        code: UnspecifiedErrorCode,
        type: ErrorType.WalletError,
      }
    );
  }

  // If we are using Ethereum native wallets the 'addresses' are the hex addresses
  // If we are using Cosmos native wallets the 'addresses' are bech32 injective addresses,
  return addresses;
};
⚠️ **GitHub.com Fallback** ⚠️