api
Promise and RxJS APIs around Polkadot and Substrate based chains via RPC calls. It is dynamically generated based on what the Substrate runtime provides in terms of metadata.
Top Related Projects
Substrate: The platform for blockchain innovators
:chains: A Framework for Building High Value Public Blockchains :sparkles:
Reference client for NEAR Protocol
Web-Scale Blockchain for fast, secure, scalable, decentralized apps and marketplaces.
Go implementation of the Ethereum protocol
Hyperledger Fabric is an enterprise-grade permissioned distributed ledger framework for developing solutions and applications. Its modular and versatile design satisfies a broad range of industry use cases. It offers a unique approach to consensus that enables performance at scale while preserving privacy.
Quick Overview
The polkadot-js/api is a JavaScript/TypeScript library that provides a powerful interface to interact with Polkadot and Substrate-based blockchain networks. It allows developers to query blockchain data, submit transactions, and build decentralized applications (dApps) on these networks.
Pros
- Comprehensive API coverage for Polkadot and Substrate-based chains
- Well-documented with extensive examples and tutorials
- Actively maintained and regularly updated
- Supports both browser and Node.js environments
Cons
- Steep learning curve for developers new to blockchain development
- Complex type system due to the dynamic nature of Substrate metadata
- Performance can be impacted when dealing with large amounts of data
- Occasional breaking changes in major version updates
Code Examples
- Connecting to a Polkadot node:
import { ApiPromise, WsProvider } from '@polkadot/api';
async function connect() {
const provider = new WsProvider('wss://rpc.polkadot.io');
const api = await ApiPromise.create({ provider });
console.log(`Connected to chain ${await api.rpc.system.chain()}`);
}
connect();
- Querying account balance:
async function getBalance(address) {
const { data: { free: balance } } = await api.query.system.account(address);
console.log(`Balance of ${address}: ${balance.toString()}`);
}
- Subscribing to new blocks:
function subscribeNewHeads() {
api.rpc.chain.subscribeNewHeads((header) => {
console.log(`New block #${header.number} has hash ${header.hash}`);
});
}
Getting Started
To start using polkadot-js/api in your project:
-
Install the package:
npm install @polkadot/api
-
Import and use the API:
import { ApiPromise, WsProvider } from '@polkadot/api'; async function main() { const provider = new WsProvider('wss://rpc.polkadot.io'); const api = await ApiPromise.create({ provider }); // Your code here const chain = await api.rpc.system.chain(); console.log(`Connected to ${chain}`); } main().catch(console.error);
This setup connects to the Polkadot mainnet. For development, consider using a local node or a testnet.
Competitor Comparisons
Substrate: The platform for blockchain innovators
Pros of Substrate
- Comprehensive blockchain development framework
- Modular architecture allowing customization
- Supports multiple programming languages
Cons of Substrate
- Steeper learning curve for beginners
- Requires more resources to run and maintain
Code Comparison
Substrate (Rust):
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(10_000)]
pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResult {
let who = ensure_signed(origin)?;
// Function logic here
Ok(())
}
}
Polkadot-js/api (JavaScript):
const api = await ApiPromise.create({ provider: wsProvider });
const transfer = api.tx.balances.transfer(recipient, amount);
const hash = await transfer.signAndSend(account);
Key Differences
- Substrate is a full blockchain development framework, while Polkadot-js/api is a JavaScript API for interacting with Substrate-based chains
- Substrate uses Rust as its primary language, whereas Polkadot-js/api is JavaScript-based
- Substrate offers more low-level control and customization, while Polkadot-js/api provides a higher-level abstraction for easier integration
Use Cases
- Substrate: Building custom blockchains or parachains
- Polkadot-js/api: Developing dApps or integrating existing applications with Substrate-based networks
:chains: A Framework for Building High Value Public Blockchains :sparkles:
Pros of cosmos-sdk
- More comprehensive blockchain development framework
- Supports multiple programming languages (Go, Rust, JavaScript)
- Extensive documentation and tutorials for developers
Cons of cosmos-sdk
- Steeper learning curve due to its complexity
- Potentially slower development process for simple applications
- Requires more resources to run and maintain
Code Comparison
cosmos-sdk (Go):
func (app *SimApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
var genesisState GenesisState
if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil {
panic(err)
}
return app.mm.InitGenesis(ctx, app.appCodec, genesisState)
}
api (JavaScript):
const api = await ApiPromise.create({ provider: wsProvider });
const chain = await api.rpc.system.chain();
console.log(`Connected to chain ${chain} on ${endpoint}`);
The cosmos-sdk example shows the initialization of a blockchain application, while the api example demonstrates connecting to a Polkadot node. cosmos-sdk provides a more comprehensive framework for building blockchain applications, whereas api focuses on interacting with existing Polkadot networks.
Reference client for NEAR Protocol
Pros of nearcore
- Written in Rust, offering better performance and memory safety
- Full node implementation, providing more control over the network
- Includes built-in sharding for improved scalability
Cons of nearcore
- Steeper learning curve due to Rust and full node complexity
- Larger codebase, potentially harder to maintain and contribute to
- More resource-intensive to run compared to a lightweight API
Code Comparison
nearcore (Rust):
pub fn process_block(
&mut self,
block: &Block,
provenance: Provenance,
) -> Result<Option<near_chain::Error>, Error> {
// Block processing logic
}
api (JavaScript):
async function subscribeNewHeads (api) {
const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => {
console.log(`Chain is at block: #${header.number}`);
});
}
Key Differences
- nearcore is a full node implementation, while api is a client-side library
- nearcore focuses on core protocol functionality, api on developer interactions
- nearcore uses Rust for systems programming, api uses JavaScript for web integration
Use Cases
- nearcore: Running a validator node, participating in consensus
- api: Building dApps, interacting with the blockchain from client-side applications
Web-Scale Blockchain for fast, secure, scalable, decentralized apps and marketplaces.
Pros of Solana
- Higher transaction throughput and lower fees
- More comprehensive ecosystem, including native programs and tools
- Stronger focus on scalability and performance optimization
Cons of Solana
- More complex architecture, potentially steeper learning curve
- Less flexible in terms of customization and parachain support
- Centralization concerns due to high hardware requirements for validators
Code Comparison
Solana (Rust):
let transaction = Transaction::new_with_payer(
&[Instruction::new_with_bincode(
program_id,
&instruction_data,
vec![AccountMeta::new(pubkey, false)],
)],
Some(&payer.pubkey()),
);
Polkadot-js/api (JavaScript):
const extrinsic = api.tx.balances.transfer(recipient, amount);
const hash = await extrinsic.signAndSend(sender);
The Solana code snippet demonstrates creating a transaction with custom instructions, while the Polkadot-js/api example shows a simple balance transfer. Solana's approach offers more granular control but requires more verbose code, whereas Polkadot-js/api provides a more abstracted and user-friendly interface for common operations.
Go implementation of the Ethereum protocol
Pros of go-ethereum
- Mature and widely adopted implementation of Ethereum protocol
- Highly performant and optimized for full node operation
- Extensive documentation and community support
Cons of go-ethereum
- Steeper learning curve for developers new to Go
- Less flexible for lightweight client implementations
- More resource-intensive for running a full node
Code Comparison
go-ethereum (Geth):
func (s *Ethereum) Start() error {
if err := s.startEthService(); err != nil {
return err
}
return nil
}
polkadot-js/api:
const api = await ApiPromise.create({ provider: wsProvider });
await api.isReady;
console.log(api.genesisHash.toHex());
The go-ethereum code snippet shows a method for starting the Ethereum service, while the polkadot-js/api example demonstrates creating an API instance and connecting to a Polkadot node.
go-ethereum is a full implementation of the Ethereum protocol in Go, offering robust node functionality. polkadot-js/api, on the other hand, is a JavaScript library for interacting with Polkadot nodes, providing a more accessible interface for developers familiar with web technologies.
While go-ethereum is optimized for running full Ethereum nodes, polkadot-js/api focuses on providing a user-friendly API for building applications on the Polkadot network. The choice between the two depends on the specific requirements of the project and the developer's familiarity with the respective ecosystems.
Hyperledger Fabric is an enterprise-grade permissioned distributed ledger framework for developing solutions and applications. Its modular and versatile design satisfies a broad range of industry use cases. It offers a unique approach to consensus that enables performance at scale while preserving privacy.
Pros of Fabric
- Enterprise-focused blockchain platform with modular architecture
- Supports multiple programming languages for smart contracts
- Provides privacy and confidentiality features for business use cases
Cons of Fabric
- Steeper learning curve due to complex architecture
- Less suitable for public blockchain applications
- Requires more resources to set up and maintain
Code Comparison
Fabric (JavaScript):
const { Gateway, Wallets } = require('fabric-network');
const path = require('path');
const ccpPath = path.resolve(__dirname, '..', 'connection.json');
const wallet = await Wallets.newFileSystemWallet('../wallet');
Polkadot-js/api (JavaScript):
const { ApiPromise, WsProvider } = require('@polkadot/api');
const wsProvider = new WsProvider('wss://rpc.polkadot.io');
const api = await ApiPromise.create({ provider: wsProvider });
Summary
Fabric is an enterprise-grade blockchain platform with a focus on modularity and privacy, while Polkadot-js/api is a JavaScript library for interacting with Polkadot and Substrate-based chains. Fabric offers more flexibility in terms of programming languages and enterprise features, but comes with increased complexity. Polkadot-js/api is more straightforward to use and better suited for public blockchain interactions, but may have limitations for enterprise use cases.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
@polkadot/api
This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the interfaces and their use, visit the documentation portal.
If you are an existing user, please be sure to track the CHANGELOG when changing versions.
tutorials
Looking for tutorials to get started? Look at examples for guides on how to use the API to make queries and submit transactions.
Top Related Projects
Substrate: The platform for blockchain innovators
:chains: A Framework for Building High Value Public Blockchains :sparkles:
Reference client for NEAR Protocol
Web-Scale Blockchain for fast, secure, scalable, decentralized apps and marketplaces.
Go implementation of the Ethereum protocol
Hyperledger Fabric is an enterprise-grade permissioned distributed ledger framework for developing solutions and applications. Its modular and versatile design satisfies a broad range of industry use cases. It offers a unique approach to consensus that enables performance at scale while preserving privacy.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot