Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
alchemy-sdk
Advanced tools
Alchemy SDK helps developers use Alchemy's APIs and endpoints more efficiently. This is a lightweight, modular SDK built as a drop-in replacement of Ethers.js that provides a superset of functionality - enabling access to the Alchemy NFT API, Websockets, and Enhanced API methods.
It also provides access to Alchemy's hardened node infrastructure, guaranteeing reliability, scalability, and quality-of-life improvements such as automatic exponential backoff retries.
As of version 2.0.0
on NPM, the Alchemy SDK is out of beta. This means that all future releases will follow semantic versioning. The upgrade from 1.x.x
to 2.x.x
will be a breaking change. See the Releases changelog for full details.
IMPORTANT: The @alch/alchemy-sdk
package is now deprecated as of the v2.0.0 release. Please use the alchemy-sdk
package instead.
To upgrade to v2.0.0 from v1.X.X, simply run one of the following:
npm uninstall @alch/alchemy-sdk
npm install alchemy-sdk@latest
npm install alchemy-sdk
After installing the app, you can then import and use the SDK:
import { Network, Alchemy } from 'alchemy-sdk';
// Optional Config object, but defaults to demo api-key and eth-mainnet.
const settings = {
apiKey: 'demo', // Replace with your Alchemy API Key.
network: Network.ETH_MAINNET, // Replace with your network.
};
const alchemy = new Alchemy(settings);
The Alchemy
object returned by new Alchemy()
provides access to the Alchemy API. An optional config object can be passed in when initializing to set your API key, change the network, or specify the max number of retries.
The Alchemy SDK currently supports three different namespaces, including:
core
: All commonly-used Ethers.js methods and Alchemy Enhanced API methodsnft
: All Alchemy NFT API methodsws
: All WebSockets methodsIf you are already using Ethers.js, you should be simply able to replace the Ethers.js object with alchemy.core
and it should just work.
import { Alchemy } from 'alchemy-sdk';
// Using default settings - pass in a settings object to specify your API key and network
const alchemy = new Alchemy();
// Access standard Ethers.js JSON-RPC node request
alchemy.core.getBlockNumber().then(console.log);
// Access Alchemy Enhanced API requests
alchemy.core.getTokenBalances("0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE").then(console.log);
// Access the Alchemy NFT API
alchemy.nft.getNftsForOwner('vitalik.eth').then(console.log);
// Access WebSockets and Alchemy-specific WS methods
alchemy.ws.on(
{
method: 'alchemy_pendingTransactions'
},
res => console.log(res)
);
The core package contains all commonly-used Ethers.js methods. If you are already using Ethers.js, you should be simply able to replace the Ethers.js object with alchemy.core
and it should just work.
It also includes the majority of Alchemy Enhanced APIs, including:
getTokenMetadata()
: Get the metadata for a token contract address.getTokenBalances()
: Gets the token balances for an owner given a list of contracts.getAssetTransfers()
: Get transactions for specific addresses.getTransactionReceipts()
: Gets all transaction receipts for a given block.To keep the package clean, we don't support certain uncommonly-used Ethers.js methods as top-level methods the Alchemy object - for example, provider.formatter
. If you'd like to access these methods, simply use the alchemy.config.getProvider()
function to configure the
Ethers.js AlchemyProvider and return it.
import { Alchemy } from 'alchemy-sdk';
const alchemy = new Alchemy();
async function runAlchemy() {
const ethersProvider = await alchemy.config.getProvider();
console.log(ethersProvider.formatter);
}
runAlchemy();
In addition to the built-in Ethers.js listeners, the Alchemy SDK includes support for Alchemy's Subscription API. This allows you to subscribe to events and receive updates as they occur.
The alchemy.ws
instance can be used can be used like the standard Ethers.js WebSocketProvider to add listeners for Alchemy events:
import { Alchemy } from 'alchemy-sdk';
const alchemy = new Alchemy();
// Listen to all new pending transactions.
alchemy.ws.on(
{
method: 'alchemy_pendingTransactions'
},
res => console.log(res)
);
// Listen to only the next transaction on the USDC contract.
alchemy.ws.once(
{
method: 'alchemy_pendingTransactions',
toAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
},
res => console.log(res)
);
// Remove all listeners.
alchemy.ws.removeAllListeners();
The SDK brings multiple improvements to ensure correct WebSocket behavior in cases of temporary network failure or
dropped connections. As with any network connection, you should not assume that a WebSocket will remain open forever
without interruption, but correctly handling dropped connections and reconnection by hand can be challenging to get
right. alchemy-sdk
automatically handles these failures with no configuration necessary. The main benefits are:
The SDK currently supports the following NFT API endpoints
under the alchemy.nft
namespace:
getNftMetadata()
: Get the NFT metadata for a contract address and tokenId.getContractMetadata()
: Get the metadata associated with an NFT contractgetNftsForOwner()
: Get NFTs for an owner address.getNftsForOwnerIterator()
: Get NFTs for an owner address as an async iterator (handles paging automatically).getNftsForContract()
: Get all NFTs for a contract address.getNftForContractIterator()
: Get all NFTs for a contract address as an async iterator (handles paging
automatically).getOwnersForNft()
: Get all the owners for a given NFT contract address and a particular token ID.getOwnersForContract()
: Get all the owners for a given NFT contract address.checkNftOwnership()
: Check that the provided owner address owns one or more of the provided NFT contract addresses.isSpamContract()
: Check whether the given NFT contract address is a spam contract as defined by Alchemy (see the NFT API FAQ)getSpamContracts()
: Returns a list of all spam contracts marked by Alchemy.findContractDeployer()
: Find the contract deployer and block number for a given NFT contract address.refreshNftMetadata()
: Refresh the cached NFT metadata for a contract address and a single tokenId.refreshContract()
: Enqueues the specified contract address to have all token ids' metadata refreshed.getFloorPrice()
: Return the floor prices of a NFT contract by marketplace.BaseNft
and Nft
The SDK currently uses the BaseNft
and Nft
classes to represent NFTs returned by the Alchemy. The BaseNft
object
does
not hold any metadata information and only contains the NFT contract and token ID. The Nft
object additionally
contains the NFT metadata, token URI information, and media.
By default, the SDK will return the Nft
object. You can optionally choose to fetch the BaseNft
object instead by
setting the omitMetadata
parameter to true
. The SDK documentation describes the different parameter and response
interfaces in more detail.
The Alchemy NFT endpoints return 100 results per page. To get the next page, you can pass in the pageKey
returned by
the
previous call. To simplify paginating through all results, the SDK provides the getNftsIterator()
and getNftsForContractIterator()
functions that automatically paginate through all NFTs and yields them via
an AsyncIterable
.
Here's an example of how to paginate through all the NFTs in Vitalik's ENS address:
import { Alchemy } from 'alchemy-sdk';
const alchemy = new Alchemy();
async function main() {
const ownerAddress = 'vitalik.eth';
for await (const nft of alchemy.nft.getNftsForOwnerIterator(ownerAddress)) {
console.log('ownedNft:', nft);
}
}
main();
The NFT API in the SDK standardizes response types to reduce developer friction, but note this results in some differences compared to the Alchemy REST endpoints:
Collection
have been renamed to use the name Contract
for greater accuracy: e.g. getNftsForContract
.getNftsForOwner()
is alchemy_getNfts
, getOwnersForNft()
is alchemy_getOwnersForToken
).omitMetadata
parameter (vs. withMetadata
).pageKey
parameter for pagination (vs. nextToken
/startToken
)TokenUri
fields are omitted.BaseNft
and Nft
.Nft
object.Nft
object are named differently than the REST response.The SDK is documented via tsdoc
comments in the source code. The generated types and documentation are included when
using an IDE. To browse the documentation separately, you can view the generated API interfaces
in etc/alchemy-sdk.api.md
. You can view generated Markdown files for each endpoint in the docs-md
directory,
or as a webpage by opening docs/index.html
in your browser.
There's a long list, but here are the main ones:
import { NftExcludeFilters, Alchemy } from 'alchemy-sdk';
const alchemy = new Alchemy();
// Get how many NFTs an address owns.
alchemy.nft.getNftsForOwner('vitalik.eth').then(nfts => {
console.log(nfts.totalCount);
});
// Get all the image urls for all the NFTs an address owns.
async function main() {
for await (const nft of alchemy.nft.getNftsForOwnerIterator('vitalik.eth')) {
console.log(nft.media);
}
}
main();
// Filter out spam NFTs.
alchemy.nft.getNftsForOwner('vitalik.eth', {
excludeFilters: [NftExcludeFilters.SPAM]
}).then(console.log);
import { Alchemy } from 'alchemy-sdk';
const alchemy = new Alchemy();
// Bored Ape Yacht Club contract address.
const baycAddress = '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D';
async function main() {
for await (const nft of alchemy.nft.getNftsForContractIterator(baycAddress, {
// Omit the NFT metadata for smaller payloads.
omitMetadata: true,
})) {
await alchemy.nft
.getOwnersForNft(nft.contract.address, nft.tokenId)
.then((response) =>
console.log("owners:", response.owners, "tokenId:", nft.tokenId)
);
}
}
main();
import { Alchemy } from 'alchemy-sdk';
const alchemy = new Alchemy();
alchemy.core.getTokenBalances('0x994b342dd87fc825f66e51ffa3ef71ad818b6893').then(
console.log
);
If you have any questions, issues, or feedback, please file an issue on GitHub, or drop us a message on our Discord channel for the SDK.
2.0.0
@alch/alchemy-sdk
to alchemy-sdk
for convenience. New command to install is npm install alchemy-sdk
initializeAlchemy(settings)
is now new Alchemy(settings)
core
, nft
, and ws
. All Ethers.js provider methods and Alchemy Enhanced APIs (other than NFT) are under core
.getNftsByOwner(alchemy, 'vitalik.eth')
, now methods are called using alchemy.nft.getNftsByOwner('vitalik.eth')
alchemy.core
alchemy.ws
alchemy.config
.alchemy.config.getProvider()
as a promise to reduce bundle size.alchemy.config.getWebSocketProvider()
as a promise to reduce bundle size.Contract
: for instance, getNftsForCollection
is now getNftsForContract
.FAQs
Extended Ethers.js SDK for Alchemy APIs
The npm package alchemy-sdk receives a total of 9,465 weekly downloads. As such, alchemy-sdk popularity was classified as popular.
We found that alchemy-sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.