npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

polkamarkets-js

v4.0.0

Published

`polkamarkets-js` is a library providing JavaScript bindings to interact with Polkamarkets smart contracts. It supports functionalities like **wallet connection, ERC-20 approval,** **buying/selling shares,** **claiming winnings**, and more.

Readme

alt tag

polkamarkets-js is a library providing JavaScript bindings to interact with Polkamarkets smart contracts. It supports functionalities like wallet connection, ERC-20 approval, buying/selling shares, claiming winnings, and more.

Below is an introductory guide to installing and initializing the polkamarkets-js library, showing a typical configuration for social login and network details. You can adapt these fields and environment variables to match your own application setup.


Installation

Install the package via npm or yarn:

# npm
npm install polkamarkets-js

# yarn
yarn add polkamarkets-js

Importing the Library

In your code, import all exported modules or the parts you need:

import * as polkamarketsjs from 'polkamarkets-js';

Initializing Polkamarkets

Below is an example snippet that creates a new Polkamarkets application instance with social login and various network configurations:

const polkamarkets = new polkamarketsjs.Application({
  web3Provider,
  web3EventsProvider**,**
  web3PrivateKey
});

Once created, polkamarkets can be used throughout your app to interact with Polkamarkets smart contracts, handle user logins, track events, and more.


Configuration Fields

The table below describes each field you see in the initialization object above. Many values are derived from environment variables in this example, but you can hardcode them if you prefer.

| Field | Type | Description | | --- | --- | --- | | web3Provider | string | Primary Web3 provider endpoint or an instantiated provider object for RPC calls (e.g. MetaMask, Alchemy, Infura). | | web3PrivateKey | string | (Optional) private key of wallet to use, if you want to bypass wallet/social login authentication | | web3EventsProvider | string | (Optional) polkamarkets-rpc web3 endpoint specifically for event subscriptions. |


Logging in Polkamarkets-js

After initializing your Polkamarkets instance, you can call other methods (e.g., connecting to the user’s wallet, creating markets, buying/selling outcome shares, adding liquidity, claiming rewards, etc.). These topics can be documented in subsequent sections.

1. Connecting Wallet

Before you can check allowances or send transactions, you need to login into the application using the login method. This will trigger a wallet popup to authorize the application. If web3PrivateKey is sent when initializing polkamarkets this step is not necessary.

await service.login(); // triggers polkamarkets to connect user wallet

2. Getting the User Address

const userAddress = await polkamarkets.getAddress();
console.log(`User is logged in as: ${address}`);

Prediction Market Contract

Before calling these methods, you'll typically create a pm instance from your polkamarkets application object:

import * as polkamarketsjs from 'polkamarkets-js';

// Example snippet:
// 1) You've already instantiated `polkamarkets` (see the prior docs).
// 2) Now get the prediction market V3 contract:
const pm = polkamarkets.getPredictionMarketV3Contract({
  contractAddress: '0x1234...',       // actual PM contract
  querierContractAddress: '0xabcd...' // optional, if you have a read-only/querier contract
});

PredictionMarket Contract addresses:

PredictionMarketQuerier Contract addresses:

All subsequent calls in this guide assume you have a valid pm reference.


1. Buying and Selling

1.1 Buying

// the following method is used to calculate how many shares the user wants to purchase
const minOutcomeSharesToBuy = await pm.calcBuyAmount({
	marketId,
	outcomeId,
	value
});

await pm.buy({
  marketId,             // e.g. "123"
  outcomeId,            // e.g. 1 (Yes)
  value,                // e.g. 100
  minOutcomeSharesToBuy // slippage protection
  wrapped               // true/false (if using ETH or an ERC20 token)
});

1.2 Selling

// the following method is used to calculate how many shares the user wants to sell
const maxOutcomeSharesToSell = await pm.calcSellAmount({
	marketId,
	outcomeId,
	value
});

await pm.sell(
  marketId,
  outcomeId,
  value,                  // e.g. 50 tokens
  maxOutcomeSharesToSell, // slippage
  wrapped
);

2. Claim Winnings

2.1 Claim Winnings

Once the market is resolved, users can claim their winnings using the following snippet.

await pm.claimWinnings({
  marketId,             // e.g. "123"
  wrapped               // true/false (if using ETH or an ERC20 token)
});

2.2 Claim Voided Shares

If the market is canceled (voided), users can claim their tokens back at closing prices. The following snippet can be used.

await pm.claimVoidedOutcomeShares({
  marketId,
  outcomeId,
  wrapped
});

3. Portfolio

3.1 Fetch portfolio

The following method fetches the user’s holdings and claim status for each outcome.

const portfolio = await pm.getPortfolio({
	user
});

console.log(portfolio);
// Example response:
// {
//   ..,
//   20: {
//     liquidity: {
//       shares: 1000,
//       price: 0.89035,
//     },
//     outcomes: {
//       0: {
//         shares: 1591.87,
//         price: 0.6281,
//         voidedWinningsToClaim: false,
//         voidedWinningsClaimed: false,
//       },
//       1: {
//         shares: 0,
//         price: 0,
//         voidedWinningsToClaim: false,
//         voidedWinningsClaimed: false,
//       }
//     }
//     claimStatus: {
//       winningsToClaim: false,
//       winningsClaimed: false,
//       liquidityToClaim: false,
//       liquidityClaimed: false,
//       voidedWinningsToClaim: false,
//       voidedWinningsClaimed: false,
//     }
//   },
//   ...
// }

4. Market Prices

4.1 Fetch market prices

The following method fetches the user’s holdings and claim status for each outcome. Prices range from 0 to 1.

const prices = await pm.getMarketPrices({
	marketId
});

console.log(prices);
// Example response:
// {
//     "liquidity": 0.6181712323806557,
//     "outcomes": {
//         "0": 0.8930217320508439,
//         "1": 0.10697826794915608
//     }
// }

5. Prediction Market Querier

A predictionMarketQuerier contract can be used in order to avoid making N RPC calls (where N is the number of desired markets) to fetch info such as:

  • Market ERC20 decimals
  • User market positions
  • Market outcome prices

The querier contract receives an array of market IDs and aggregates all the info into one return. You can use it by adding querierContractAddress as an argument of the initialization of the PredictionMarketV3 instance (see code above).


ERC20 Contract

Create an ERC20 contract instance using polkamarkets.getERC20Contract(...). This snippet assumes you’ve already instantiated your polkamarkets application:

const erc20 = polkamarkets.getERC20Contract({
  contractAddress: '0xYOUR_ERC20_TOKEN_ADDRESS'
});

ERC20 Contract addresses:

All subsequent calls in this guide assume you have a valid erc20 reference.


1. Check Approval Status

Checks if the user has approved at least amount of tokens for spender:

await erc20.isApproved({
	address: polkamarkets.getAddress(),
  amount,
  spenderAddress
});

2. Approve

Grants the spender contract permission to move up to amount tokens on behalf of the user:

await erc20.approve({
	address,
	amount
});

Below there’s an example of a complete flow using abstract mainnet. We’ll:

  1. Initialize Polkamarkets with a web3Provider and web3PrivateKey.
  2. Instantiate a Prediction Market V3 contract (pm) and an ERC20 contract (erc20).
  3. Check approval, approve if needed, create a market, buy outcome shares, and finally claim winnings.

import * as polkamarketsjs from 'polkamarkets-js';

// 1) Initialize polkamarkets
const polkamarkets = new polkamarketsjs.Application({
  web3Provider: 'api.mainnet.abs.xyz',
  web3PrivateKey: '', // add your pk here
});

// 2) Get the Prediction Market V3 contract
const pm = polkamarkets.getPredictionMarketV3Contract({
  contractAddress: '0x4f4988A910f8aE9B3214149A8eA1F2E4e3Cd93CC',   // pmContractAddress
  querierContractAddress: '0x710f30abdadb86a33fae984d6678d4ed31517b18' // pmQuerierAddress (optional)
});

// 3) Get the ERC20 contract
const erc20 = polkamarkets.getERC20Contract({
  contractAddress: '0xf19609e96187cdaa34cffb96473fac567e547302' // erc20Address
});

// 4) (Optional) Log in (not strictly required if using private key, but included for completeness)
await polkamarkets.login();

// 5) Grab current user address
const userAddress = await polkamarkets.getAddress();
console.log('User address:', userAddress);

// 6) Check allowance for the pm contract
const neededAmount = '100000000'; 
const spender = '0x4f4988A910f8aE9B3214149A8eA1F2E4e3Cd93CC';

const approved = await erc20.isApproved({
  address: userAddress,
  spenderAddress: spender,
  amount: neededAmount
});

if (!approved) {
  console.log('Not enough allowance; approving now...');
  await erc20.approve({
    address: userAddress,
    amount: neededAmount,
    spenderAddress: spender
  });
  console.log('Approval successful!');
} else {
  console.log('Sufficient allowance already exists.');
}

// 7) Buy some outcome shares of a marketId
const marketId = 123; // the market id you want to purchase shares
const outcomeId = 0; // the market id you want to purchase shares
const value = 10; // the amount (in human format, it is converted to the correct decimals in the function)
const minOutcomeSharesToBuy = await pm.calcBuyAmount({
	marketId,
	outcomeId,
	value
});

await pm.buy({
  marketId,
  outcomeId,
  value,
  minOutcomeSharesToBuy
});
console.log('Bought outcome shares!');
const portfolio = await pm.getPortfolio({ user: userAddress });
console.log(portfolio);

// 9) (Later) Claim winnings (assumes market eventually resolves in your favor)
// ...
// await pm.claimWinnings(marketId);
// console.log('Winnings claimed!');

Flow

  1. Initialization: We pass a web3Provider (api.mainnet.abs.xyz) and a random web3PrivateKey for direct signing, plus isSocialLogin: false to skip the wallet UI.
  2. Contracts:
    • pm is our Prediction Market V3 instance.
    • erc20 is the token contract used for buying shares or adding liquidity.
  3. Login: If you prefer a standard wallet approach (Metamask, etc.), remove web3PrivateKey and set isSocialLogin: true; calling await polkamarkets.login() triggers the wallet flow.
  4. Approval: We check if the user has at least neededAmount allowance for the PM contract, then approve if needed.
  5. Buy: We purchase outcome 0 with '50000000' units of the token. Adjust to match your token’s decimals.
  6. Claim: Eventually, after resolution, you might call pm.claimWinnings(marketId) if you hold the winning outcome.