In this tutorial, we'll discuss the Polkadot Network, an innovative multi-chain platform that enables different blockchains to interoperate seamlessly. By the end of this tutorial, you'll understand the structure of the Polkadot Network, how it enables efficient web structures, and how to interact with it using JavaScript libraries.
Polkadot's structure consists of a central Relay Chain which provides consensus and security for interconnected blockchains called parachains. For communication, Polkadot uses the Cross-Chain Message Passing (XCMP) protocol.
We will use the @polkadot/api
, a JavaScript library to interact with Polkadot.
Install the library using npm:
npm install @polkadot/api
The first step is creating a connection to a Polkadot node. Here's how you do it:
const { ApiPromise, WsProvider } = require('@polkadot/api');
async function main () {
const wsProvider = new WsProvider('wss://rpc.polkadot.io');
const api = await ApiPromise.create({ provider: wsProvider });
console.log(api.genesisHash.toHex());
}
main().catch(console.error);
Here are some more examples of what you can do with the Polkadot JavaScript API.
Here is how you can read the latest block header:
async function main () {
//...
const lastHeader = await api.rpc.chain.getHeader();
console.log(`Last block #${lastHeader.number} has hash ${lastHeader.hash}`);
}
main().catch(console.error);
To submit a transaction, you need to have an account with some DOTs (Polkadot's native cryptocurrency). Here's an example of how to submit a transaction:
async function main () {
//...
const keyring = new Keyring({ type: 'sr25519' });
const alice = keyring.addFromUri('//Alice');
const transfer = api.tx.balances.transfer(bob.address, 12345);
const hash = await transfer.signAndSend(alice);
console.log('Transfer sent with hash', hash.toHex());
}
main().catch(console.error);
In this tutorial, we introduced the Polkadot Network and learned how to interact with it using the @polkadot/api
JavaScript library. We read data from the blockchain and submitted a transaction.
To further your understanding, you should try setting up your own private Polkadot network, and deploying a smart contract on it.
For solutions and further practice, refer to the Polkadot Wiki and JavaScript API documentation.