Injective TypeScript SDK

repository·master·Indexed 41 days ago

https://github.com/injectivelabs/injective-ts

A TypeScript monorepo providing tools and abstractions to interact with the Injective blockchain protocol. Includes @injectivelabs/sdk-ts for building cross-platform applications (Node.js, browser, React Native), @injectivelabs/networks for environment endpoints, @injectivelabs/exceptions for human-readable errors, and @injectivelabs/ts-types for protocol type definitions.

Tokens
54.4K
Snippets
198
Records
253
Agent score
99%

What's inside Injective TS

  1. Overview of @injectivelabs/sdk-ts

    master

    The @injectivelabs/sdk-ts is a TypeScript SDK that allows developers to build applications on the Injective chain. It is compatible with Node.js, web browsers, and React Native.

    Key capabilities include:

    • Full TypeScript support with type definitions for enhanced developer experience.
    • Access to both on-chain data and exchange-api data.
    • Automatic parsing of API responses into native JavaScript types.
    • Cross-platform compatibility (Node, Browser, React Native).
  2. Overview of injective-ts

    master

    The injective-ts monorepo provides a suite of TypeScript packages designed for interacting with the Injective protocol in both Node.js and browser environments. It offers abstractions for:

    • Core data structures
    • Serialization
    • Key management
    • API request generation

    Each package is an independent npm module published to the npm registry. For detailed implementation guides and API references, refer to the official Injective TypeScript Documentation.

  3. Use @injectivelabs/networks for protocol endpoints

    master

    The @injectivelabs/networks package provides a pre-defined set of endpoints for different environments (such as Mainnet, Testnet, and Devnet). These endpoints can be used to:

    • Fetch data from various data sources.
    • Broadcast transactions to sentry nodes.
    • Access the Tendermint RPC.

    It is designed to work across Web, Node.js, and React Native environments.

  4. Understand the gRPC-over-WebSocket protocol framing

    master

    The RFQ streaming implementation uses the grpc-ws subprotocol with a specific 5-byte binary framing format for gRPC messages over WebSockets.

    Frame Format: [compressionFlag: 1 byte][length: 4 bytes BE][payload: N bytes]

    • compressionFlag (1 byte):
      • 0x00: No compression (standard data frame).
      • 0x80: Trailer frame (indicates the end of a stream).
    • length (4 bytes): Big-endian unsigned 32-bit integer representing the payload length.
    • payload (N bytes): The protobuf-encoded message.

    Endpoints:

    • Taker Stream: /injective_rfqrpc.InjectiveRFQRPC/TakerStream
    • Maker Stream: /injective_rfqrpc.InjectiveRFQRPC/MakerStream
  5. Manage wallet strategies with lazy loading

    master

    In v1.17.x, WalletStrategy requires explicit loading of a wallet strategy. You can check if a strategy is loaded using isStrategyLoaded(), load a specific wallet using loadStrategy(), or use setWallet() to combine loading and setting the active wallet.

    import { WalletStrategy, Wallet } from '@injectivelabs/wallet-ts'
    
    const walletStrategy = new WalletStrategy({ chainId: 'injective-1' })
    
    // Check if a strategy is loaded
    if (!walletStrategy.isStrategyLoaded()) {
      // Load a specific wallet strategy
      await walletStrategy.loadStrategy(Wallet.Metamask)
    }
    
    // Or use setWallet (combines load + set)
    await walletStrategy.setWallet(Wallet.Keplr)
    
    // Get currently active wallet
    const currentWallet = walletStrategy.getWallet()
  6. Replace Buffer with Encoding Utilities in v1.17.x

    master

    The buffer polyfill has been removed in v1.17.x. You must replace all Buffer usage with the encoding utilities provided by @injectivelabs/sdk-ts/utils.

    import {
      hexToUint8Array, 
      uint8ArrayToHex, 
      utf8ToUint8Array, 
      base64ToUint8Array, 
      concatUint8Arrays
    } from '@injectivelabs/sdk-ts/utils'
    
    // Converting hex to bytes
    const bytes = hexToUint8Array('deadbeef')
    
    // Converting bytes to hex
    const hex = uint8ArrayToHex(bytes)
    
    // Converting string to bytes
    const utf8Bytes = utf8ToUint8Array('Hello')
    
    // Converting base64 to bytes
    const base64Bytes = base64ToUint8Array('SGVsbG8=')
    
    // Concatenating arrays
    const combined = concatUint8Arrays([bytes, utf8Bytes])
  7. Migrate setMetadata() to Async in v1.17.x

    master

    In @injectivelabs/sdk-ts v1.17.x, the setMetadata() method on WalletStrategy has changed from synchronous to asynchronous. You must now use the await keyword when calling this method. Ensure the containing function is marked as async.

    import { WalletStrategy } from '@injectivelabs/wallet-ts'
    
    const walletStrategy = new WalletStrategy({ chainId: 'injective-1' })
    
    // Must use await
    await walletStrategy.setMetadata({
      privateKey: { privateKey: '0x...' },
    })
  8. Update Deprecated Type Imports from @injectivelabs/ts-types

    master

    Several types previously imported from @injectivelabs/ts-types have been moved to @injectivelabs/sdk-ts/types. While the old imports may still work temporarily, you should update them to the new location to avoid future breaking changes.

    Deprecated types include:

    • TradeExecutionType
    • TradeExecutionSide
    • TradeDirection
    • OrderState
    • OrderSide
    • StreamStatusResponse
    • StreamOperation
    // ✅ After (Recommended)
    import { 
      TradeExecutionType, 
      TradeExecutionSide, 
      TradeDirection, 
      OrderState, 
      OrderSide, 
      StreamStatusResponse, 
      StreamOperation 
    } from '@injectivelabs/sdk-ts/types'
  9. Generate TypeScript code from Proto definitions in ProtoV2

    master

    ProtoV2 uses @protobuf-ts to generate TypeScript code from Protocol Buffer definitions. You can generate code for all packages at once or target specific packages.

    To generate all packages, run the top-level script:

    ./run-all-gen.sh

    To generate a specific package, navigate to its directory and run the generate script:

    cd <package-name> && npm run generate

    Available packages include:

    • core: Injective, Cosmos, IBC, CometBFT protos
    • indexer: Indexer gRPC API definitions
    • abacus: Abacus points service
    • mito: Mito finance API
    • olp: OLP/DMM API
    # Generate all packages
    ./run-all-gen.sh
    
    # Generate specific package (e.g., core)
    cd core && npm run generate
  10. Replace Apollo GraphQL Client with HttpClient in v1.17.x

    master

    The Apollo GraphQL client has been removed from @injectivelabs/sdk-ts. To perform GraphQL queries, use HttpClient from @injectivelabs/utils. You can configure headers (like authorization) using client.setConfig({ headers: { ... } }) and then use client.post to send your query as a JSON-stringified object.

    import { HttpClient } from '@injectivelabs/utils'
    
    const client = new HttpClient('YOUR_GRAPHQL_ENDPOINT')
    
    // Optional: Set auth headers if required
    client.setConfig({
      headers: {
        authorization: 'Bearer YOUR_API_KEY',
      },
    })
    
    // Make a query
    const query = JSON.stringify({
      query: `
        query GetData($id: ID!) {
          entity(id: $id) {
            id
            name
            value
          }
        }
      `,
      variables: { id: '123' },
    })
    
    const response = await client.post<string, { data: { data: YourResponseType } }>('', query)
    console.log(response.data.data)