Alchemy SDK for JavaScript

repository·master·Indexed 19 days ago

https://github.com/alchemyplatform/alchemy-sdk-js

An extended Ethers.js SDK for Alchemy APIs (version 3.6.5) providing a comprehensive JavaScript library to interact with blockchains. It features specialized namespaces for NFT data, Portfolio asset views, Notify webhook management, transaction simulations via the Transact namespace, and deep transaction inspection through the Debug namespace. The SDK includes robust WebSocket support and Async Iterators for automatic pagination of NFT data.

Tokens
90.7K
Snippets
289
Records
506
Agent score
61%

What's inside alchemy-sdk

  1. Explore the Alchemy SDK module exports

    master

    The alchemy-sdk package exports a comprehensive set of namespaces, enumerations, classes, interfaces, and utility functions to interact with the Alchemy platform.

    Key areas of functionality include:

    • Core & Provider: Alchemy, AlchemyConfig, AlchemyProvider, and AlchemyWebSocketProvider for establishing connections.
    • Namespaces: Specialized modules like NftNamespace, PortfolioNamespace, TransactNamespace, PricesNamespace, and NotifyNamespace for organized API access.
    • NFTs: Extensive support for NFT metadata, collections, sales, and ownership via NftNamespace and related interfaces.
    • Portfolio: Tools for querying token balances, transfers, and address activity.
    • Transact: Capabilities for simulating transactions and sending private transactions.
    • Webhooks: Support for real-time notifications via NotifyNamespace and various webhook interfaces.
    • Utilities: Helper functions for hex conversion and logging.
  2. How to access the WebSocket namespace

    master

    The WebSocketNamespace contains all subscription-related functions for subscribing to events and receiving real-time updates. The underlying WebSocket provider automatically handles reconnections and backfills missed events.

    Important: Do not call the WebSocketNamespace constructor directly. Instead, instantiate an Alchemy object and access the namespace via the .ws property.

    import { Alchemy } from 'alchemy-sdk';
    
    const config = { ... };
    const alchemy = new Alchemy(config);
    
    // Access the WebSocket namespace here
    const ws = alchemy.ws;
  3. Update Webhooks using NotifyNamespace.updateWebhook

    master

    When calling NotifyNamespace.updateWebhook to modify existing webhooks, you must use specific parameter objects depending on the type of webhook being updated:

    • AddressActivityWebhook: Use AddressWebhookUpdate (requires at least one update field from WebhookStatusUpdate, WebhookAddressUpdate, or WebhookAddressOverride).
    • CustomGraphqlWebhook: Use CustomGraphqlWebhookUpdate (based on WebhookStatusUpdate).
    • NftActivityWebhook: Use NftWebhookUpdate (requires at least one update field from WebhookStatusUpdate, WebhookNftFilterUpdate).
    • NftMetadataUpdateWebhook: Use NftMetadataWebhookUpdate (requires at least one update field from WebhookStatusUpdate or WebhookNftMetadataFilterUpdate).
  4. Understand SDK vs REST API differences for NFTs

    master

    The SDK standardizes response types, which leads to several differences compared to the raw Alchemy REST API:

    • Renaming: Methods using Collection are renamed to Contract (e.g., getNftsForContract).
    • Naming Consistency: Method names are adjusted for a consistent SDK interface (e.g., getNftsForOwner() instead of alchemy_getNfts).
    • Parameters: The SDK uses omitMetadata (instead of withMetadata) and pageKey (instead of nextToken/startToken).
    • Data Normalization: Token IDs are always normalized to integer strings on BaseNft and Nft. Empty TokenUri fields are omitted.
  5. Understand the BaseNft interface

    master

    The BaseNft interface is a minimal representation of an NFT used when metadata is not required or provided. It serves as a base type for more detailed NFT objects.

    Key distinction:

    • BaseNft: Contains only the contractAddress and tokenId.
    • Nft: An extension of BaseNft that includes metadata, tokenUri, and media information.

    Use BaseNft when you only need to identify the specific token and its parent contract without consuming the overhead of full metadata.

  6. Understand the Alchemy SDK namespaces

    master

    The Alchemy instance provides access to several specialized namespaces:

    • core: Contains standard Ethers.js Provider methods and Alchemy Enhanced API methods (e.g., token balances, asset transfers).
    • nft: Provides access to all Alchemy NFT API methods.
    • ws: Provides access to WebSocket methods and Alchemy's Subscription API.
    • transact: Provides access to Alchemy Transaction API methods.
    • notify: Provides CRUD endpoints for modifying Alchemy Notify Webhooks.
    • debug: Provides methods to inspect and replay transactions and blocks.
    import { Alchemy, AlchemySubscription } from 'alchemy-sdk';
    
    const alchemy = new Alchemy();
    
    // Access standard Ethers.js JSON-RPC node request via core
    alchemy.core.getBlockNumber().then(console.log);
    
    // Access Alchemy Enhanced API requests via core
    alchemy.core
      .getTokenBalances('0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE')
      .then(console.log);
    
    // Access the Alchemy NFT API via nft
    alchemy.nft.getNftsForOwner('vitalik.eth').then(console.log);
    
    // Access WebSockets via ws
    alchemy.ws.on(
      {
        method: AlchemySubscription.PENDING_TRANSACTIONS
      },
      res => console.log(res)
    );
  7. Understand the Nft interface

    master

    The Nft interface is the Alchemy representation of an NFT. It is a rich object that includes not only the core contract and token ID (which are present in the BaseNft object) but also comprehensive metadata, token URI information, and media assets.

    Nft is the base type in a hierarchy that includes:

    • OwnedNft
    • TransferredNft
  8. Access the Debug namespace

    master

    The Debug namespace provides non-standard RPC methods for inspecting and debugging transactions. You should not instantiate DebugNamespace directly. Instead, create an Alchemy instance and access the debug methods via the .debug property.

    import { Alchemy, Network } from 'alchemy-sdk';
    
    const settings = { apiKey: 'YOUR_API_KEY', network: Network.ETH_MAINNET };
    const alchemy = new Alchemy(settings);
    
    // Access debug methods via alchemy.debug
    const trace = await alchemy.debug.traceTransaction('0x...');
  9. Use the NftMetadataUpdateWebhook to track NFT changes

    master

    The NftMetadataUpdateWebhook is a specialized webhook type used to track all ERC721 and ERC1155 metadata updates. Developers can use this to receive real-time notifications in their application whenever an NFT's metadata changes, allowing for immediate state synchronization.

    This interface inherits from the base Webhook interface and includes specific properties for identifying the webhook and verifying its authenticity.