
Security News
The Changelog Podcast: Practical Steps to Stay Safe on npm
Learn the essential steps every developer should take to stay secure on npm and reduce exposure to supply chain attacks.
This repository contains the maticjs client library. maticjs makes it easy for developers, who may not be deeply familiar with smart contract development, to interact with the various components of Matic Network.
This library will help developers to move assets from Ethereum chain to Matic chain, and withdraw from Matic to Ethereum using fraud proofs.
We will be improving this library to make all features available like Plasma Faster Exit, challenge exit, finalize exit and more.
$ npm install --save web3 maticjs # or yarn add web3 maticjs
Note: This library is dependent on web3.js library. Tested with web3@1.0.0-beta.34
<script> IncludeSimply download dist/matic.js and include with a script tag. Matic will be registered as a global variable.
<script src="https://cdn.jsdelivr.net/npm/maticjs/dist/matic.js"></script>
Matic is also available on unpkg
// Import Matic sdk
import Matic from 'maticjs'
// Create sdk instance
const matic = new Matic({
  // Set Matic provider - string or provider instance
  // Example: 'https://testnet.matic.network' OR new Web3.providers.HttpProvider('http://localhost:8545')
  maticProvider: <web3-provider>,
  // Set Mainchain provider - string or provider instance
  // Example: 'https://kovan.infura.io' OR new Web3.providers.HttpProvider('http://localhost:8545')
  parentProvider: <web3-provider>,
  // Set rootchain contract. See below for more information
  rootChainAddress: <root-contract-address>,
  // Set withdraw-manager Address. See below for more information
  withdrawManagerAddress: <withdraw-manager-address>,
  // Set deposit-manager Address. See below for more information
  depositManagerAddress: <deposit-manager-address>,
  // Set matic network's WETH address. See below for more information
  maticWethAddress: <matic-weth-address>,
  // Syncer API URL
  // Fetches tx/receipt proof data instead of fetching whole block on client side
  syncerUrl: 'https://matic-syncer2.api.matic.network/api/v1', // (optional)
  // Watcher API URL
  // Fetches headerBlock info from mainchain & finds appropriate headerBlock for given blockNumber
  watcherUrl: 'https://ropsten-watcher2.api.matic.network/api/v1', // (optional)
})
// Set wallet
// Warning: Not-safe
// matic.wallet = <private-key> // Use metamask provider or use WalletConnect provider instead.
// get token address mapped with mainchain token address
const tokenAddressOnMatic = await matic.getMappedTokenAddress(
  tokenAddress // token address on mainchain
)
// get ERC20 token balance
await matic.balanceOfERC20(
  user, //User address
  tokenAddress, // Token address
  options // transaction fields
)
// get ERC721 token balance
await matic.balanceOfERC721(
  user, // User address
  tokenAddress,  // Token address
  options // transaction fields
)
// get ERC721 token ID
await matic.tokenOfOwnerByIndexERC721(
  from, // User address
  tokenAddress,  // Token address
  index, // index of tokenId
  options // transaction fields
)
// Deposit Ether into Matic chain
await matic.depositEthers(
  options // transaction fields
)
// Approve ERC20 token for deposit
await matic.approveERC20TokensForDeposit(
  token,  // Token address,
  amount,  // Token amount for approval (in wei)
  options // transaction fields
)
// Deposit token into Matic chain. Remember to call `approveERC20TokensForDeposit` before
await matic.depositERC20Tokens(
  token,  // Token address
  user,   // User address (in most cases, this will be sender's address),
  amount,  // Token amount for deposit (in wei)
  options // transaction fields
)
// Deposit ERC721 token into Matic chain.(older ERC721 or some newer contracts will not support this.
// in that case, first call `approveERC721TokenForDeposit` and `depositERC721Tokens`)
await matic.safeDepositERC721Tokens(
  token,  // Token addres
  tokenId,  // Token Id for deposit
  options // transaction fields
)
// Approve ERC721 token for deposit
await matic.approveERC721TokenForDeposit(
  token,  // Token address,
  tokenId,  // Token Id
  options // transaction fields
)
// Deposit token into Matic chain. Remember to call `approveERC721TokenForDeposit` before
await matic.depositERC721Tokens(
  token,  // Token address
  user,   // User address (in most cases, this will be sender's address),
  tokenId,  // Token Id
  options // transaction fields
)
// Transfer token on Matic
await matic.transferTokens(
  token,  // Token address
  user,   // Recipient address
  amount,  // Token amount
  options // transaction fields
)
// Transfer ERC721 token on Matic
await matic.transferERC721Tokens(
  token,  // Token address
  user,   // Recipient address
  tokenId,  // Token Id
  options // transaction fields
)
// Transfer Ether
await matic.transferEthers(
  user,   // Recipient address
  amount,  // Token amount
  options // transaction fields
)
// Initiate withdrawal of ERC20 from Matic and retrieve the Transaction id
await matic.startWithdraw(
  token, // Token address
  amount, // Token amount for withdraw (in wei)
  options // transaction fields
)
// Initiate withdrawal of ERC721 from Matic and retrieve the Transaction id
await matic.startERC721Withdraw(
  token, // Token address
  tokenId, // tokenId
  options // transaction fields
)
// Withdraw funds from the Matic chain using the Transaction id generated from the 'startWithdraw' method
// after header has been submitted to mainchain
await matic.withdraw(
  txId, // Transaction id generated from the 'startWithdraw' method
  options // transaction fields
)
// Process exits after completion of challenge period
await matic.processExits(
  rootTokenAddress, // RootToken address
  options // transaction fields
)
The flow for asset transfers on the Matic Network is as follows:
Matic Testnet
Ropsten testnet addresses
Please write to info@matic.network to request TEST tokens for development purposes. We will soon have a faucet in place for automatic distribution of tokens for testing.
new Matic()matic.getMappedTokenAddress()matic.balanceOfERC20()matic.balanceOfERC721()matic.tokenOfOwnerByIndexERC721()matic.depositEther()matic.approveERC20TokensForDeposit()matic.depositERC20Tokens()matic.safeDepositERC721Tokens()matic.approveERC721TokenForDeposit()matic.depositERC721Tokens()matic.depositEthers()matic.transferTokens()matic.transferERC721Tokens()matic.transferEthers()matic.startWithdraw()matic.startERC721Withdraw()matic.getHeaderObject()matic.withdraw()matic.processExits()matic.getTx()matic.getReceipt()Creates Matic SDK instance with give options. It returns a MaticSDK object.
import Matic from "maticjs"
const matic = new Matic(options)
options is simple Javascript object which can have following fields:
maticProvider can be string or Web3.providers instance. This provider must connect to Matic chain. Value can be anyone of following:
'https://testnet2.matic.network'new Web3.providers.HttpProvider('http://localhost:8545')parentProvider can be string or Web3.providers instance. This provider must connect to Ethereum chain (testnet or mainchain). Value can be anyone of following:
'https://ropsten.infura.io'new Web3.providers.HttpProvider('http://localhost:8545')rootChainAddress must be valid Ethereum contract address.syncerUrl must be valid API host. MaticSDK uses this value to fetch receipt/tx proofs instead of getting whole block to client side.watcherUrl must be valid API host. MaticSDK uses this value to fetch headerBlock info from mainchain and to find appropriate headerBlock for given blockNumber.withdrawManagerAddress must be valid Ethereum contract address.depositManagerAddress must be valid Ethereum contract address.get matic token address mapped with mainchain tokenAddress.
tokenAddress must be valid token addressThis returns matic address.
Example:
matic
  .getMappedTokenAddress("0x670568761764f53E6C10cd63b71024c31551c9EC")
  .then(address => {
    console.log("matic address", address)
  })
get balance of ERC20 token for address.
token must be valid token addressaddress must be valid user addressoptions see more infomation here
parent must be boolean value. For balance on Main chain, use parent: trueThis returns balance.
Example:
matic
  .balanceOfERC20("0xABc578455...", "0x5E9c4ccB05...", {
    from: "0xABc578455..."
  })
  .then(balance => {
    console.log("balance", balance)
  })
get balance of ERC721 token for address.
token must be valid token addressaddress must be valid user addressoptions see more infomation here
parent must be boolean value. For balance on Main chain, use parent: trueThis returns balance.
Example:
matic
  .balanceOfERC721("0xABc578455...", "0x5E9c4ccB05...", {
    from: "0xABc578455..."
  })
  .then(balance => {
    console.log("balance", balance)
  })
get ERC721 tokenId at index for token and for address.
token must be valid token addressaddress must be valid user addressindex index of tokenIdThis returns matic tokenId.
Example:
matic
  .tokenOfOwnerByIndexERC721("0xfeb14b...", "21", 0, {
    from: "0xABc578455..."
  })
  .then(tokenID => {
    console.log("Token ID", tokenID)
  })
Approves given amount of token to rootChainContract.
token must be valid ERC20 token addressamount must be token amount in wei (string, not in Number)options (optional) must be valid javascript object containing from, gasPrice, gasLimit, nonce, value, onTransactionHash, onReceipt or onError
from must be valid account address(required)gasPrice same as Ethereum sendTransactiongasLimit same as Ethereum sendTransactionnonce same as Ethereum sendTransactionnonce same as Ethereum sendTransactionvalue contains ETH value. Same as Ethereum sendTransaction.encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueonTransactionHash must be function. This function will be called when transaction will be broadcasted.onReceipt must be function. This function will be called when transaction will be included in block (when transaction gets confirmed)onError must be function. This function will be called when sending transaction fails.This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
matic
  .approveERC20TokensForDeposit("0x718Ca123...", "1000000000000000000", {
    from: "0xABc578455..."
  })
  .on("onTransactionHash", txHash => {
    console.log("New transaction", txHash)
  })
Deposit given amount of token with user user.
token must be valid ERC20 token addressuser must be value account addressamount must be token amount in wei (string, not in Number)options see more infomation here
encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
const user = <your-address> or <any-account-address>
matic.depositToken('0x718Ca123...', user, '1000000000000000000', {
  from: '0xABc578455...'
})
Deposit given tokenId of token.
token must be valid ERC721 token addresstokenId must be tokenIdoptions see more infomation here
encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
matic.safeDepositERC721Tokens('0x718Ca123...', '21', {
  from: '0xABc578455...'
})
Approves given amount of token to rootChainContract.
token must be valid ERC721 token addresstokenId must be tokenId (string, not in Number)options (optional) must be valid javascript object containing from, gasPrice, gasLimit, nonce, value, onTransactionHash, onReceipt or onError
from must be valid account address(required)gasPrice same as Ethereum sendTransactiongasLimit same as Ethereum sendTransactionnonce same as Ethereum sendTransactionnonce same as Ethereum sendTransactionvalue contains ETH value. Same as Ethereum sendTransaction.encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueonTransactionHash must be function. This function will be called when transaction will be broadcasted.onReceipt must be function. This function will be called when transaction will be included in block (when transaction gets confirmed)onError must be function. This function will be called when sending transaction fails.This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
matic
  .approveERC721TokenForDeposit("0x718Ca123...", "21", {
    from: "0xABc578455..."
  })
  .on("onTransactionHash", txHash => {
    console.log("New transaction", txHash)
  })
Deposit given tokenId of token with user user.
token must be valid ERC721 token addressuser must be value account addresstokenId must be valid tokenIdoptions see more infomation here
encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
const user = <your-address> or <any-account-address>
matic.depositERC721Tokens('0x718Ca123...', user, tokenId, {
  from: '0xABc578455...'
})
Deposit options.value
options see more infomation here.
value amount of ethers.from must be valid account address(required)encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
matic.depositEthers({
  from: '0xABc578455...',
  value: '1000000000000000000'
})
Transfer given amount of token to user.
token must be valid ERC20 token addressuser must be value account addressamount must be token amount in wei (string, not in Number)options see more infomation here
parent must be boolean value. For token transfer on Main chain, use parent: trueencodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
const user = <your-address> or <any-account-address>
matic.transferERC20Tokens('0x718Ca123...', user, '1000000000000000000', {
  from: '0xABc578455...',
  // For token transfer on Main network
  // parent: true
})
Transfer ownership tokenId of token to user.
token must be valid ERC721 token addressuser must be value account addresstokenId tokenIdoptions see more infomation here
parent must be boolean value. For token transfer on Main chain, use parent: trueencodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
const user = <your-address> or <any-account-address>
matic.transferERC721Tokens('0x718Ca123...', user, tokenId, {
  from: '0xABc578455...',
  // For token transfer on Main network
  // parent: true
})
Transfer given amount of ethers to user.
user must be value account addressamount must be ethers amount in wei (string, not in Number)options see more infomation here
parent must be boolean value. For ether transfer on Main chain, use parent: trueisCustomEth must be boolean value. For custom ether transfer on Matic Chain, use isCustomEth: trueencodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
const user = <your-address> or <any-account-address>
matic.transferEthers(user, '1000000000000000000', {
  from: '0xABc578455...',
  // For token transfer on Main network
  // parent: true
})
Start withdraw process with given amount for token.
token must be valid ERC20 token addressamount must be token amount in wei (string, not in Number)options see more infomation here
encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
matic
  .startWithdraw("0x718Ca123...", "1000000000000000000", {
    from: "0xABc578455..."
  })
  .on("onTransactionHash", txHash => {
    console.log("Started withdraw process with txId", txHash)
  })
Start withdraw process with given tokenId for token.
token must be valid ERC721 token addresstokenId must be token tokenId in wei (string, not in Number)options see more infomation here
encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
matic
  .startERC721Withdraw("0x718Ca123...", "21", {
    from: "0xABc578455..."
  })
  .on("onTransactionHash", txHash => {
    console.log("Started withdraw process with txId", txHash)
  })
Fetch header/checkpoint corresponding to blockNumber
blockNumber must be valid Matic's sidechain block numberThis returns Promise object, which will be fulfilled when header/checkpoint is found corresponding to blockNumber.
Example:
matic.getHeaderObject(673874).then(header => {
  // header.start
  // header.end
  // header.proposer
  // header.number
})
Withdraw tokens on mainchain using txId from startWithdraw method after header has been submitted to mainchain.
txId must be valid tx hashoptions see more infomation here
encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
matic.withdraw("0xabcd...789", {
  from: "0xABc578455..."
})
Call processExits after completion of challenge period, after that withdrawn funds get transfered to your account on mainchain
rootTokenAddress RootToken addressoptions see more infomation here
encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: trueThis returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).
Example:
matic.processExits("0xabcd...789", {
  from: "0xABc578455..."
})
Get transaction object using txId from Matic chain.
txId must be valid tx idThis returns Promise object.
Example:
matic
  .getTx("0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b")
  .then(txObject => {
    console.log(txObject)
  })
Get receipt object using txId from Matic chain.
txId must be valid tx idThis returns Promise object.
Example:
matic
  .getReceipt(
    "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b"
  )
  .then(obj => {
    console.log(obj)
  })
Please write to info@matic.network for integration support. If you have any queries, feedback or feature requests, feel free to reach out to us on telegram: t.me/maticnetwork
MIT
FAQs
Javascript developer library for interacting with Matic Network
The npm package maticjs receives a total of 4 weekly downloads. As such, maticjs popularity was classified as not popular.
We found that maticjs demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 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
Learn the essential steps every developer should take to stay secure on npm and reduce exposure to supply chain attacks.

Security News
Experts push back on new claims about AI-driven ransomware, warning that hype and sponsored research are distorting how the threat is understood.

Security News
Ruby's creator Matz assumes control of RubyGems and Bundler repositories while former maintainers agree to step back and transfer all rights to end the dispute.