Giter Site home page Giter Site logo

maticnetwork / matic.js Goto Github PK

View Code? Open in Web Editor NEW
536.0 38.0 257.0 28.94 MB

Javascript developer library to interact with Matic Network

Home Page: https://wiki.polygon.technology/docs/tools/matic-js/get-started/

License: MIT License

JavaScript 11.96% TypeScript 87.92% HTML 0.12%
ethereum sidechain smart-contracts dapps web3 maticnetwork matic polygon

matic.js's Introduction

Matic SDK

GitHub version Build Status npm version GitHub TEST

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.

Docs

https://wiki.polygon.technology/docs/tools/matic-js/get-started

Support

Our Discord is the best way to reach us โœจ.

Contributors

You are very welcome to contribute, please see contributing guidelines - [Contribute].

Thank you to all the people who already contributed to matic.js!

Made with contributors-img.

Development

Setup

npm ci

How to debug

Write your code inside file test/debug.js and run below code

npm run debug

Above command will build the source code & install the built version into test folder, which will be used by debug.js.

Lint

# To check lint errors
npm run lint

# To fix most common lint errors
# Note that it might not fix all errors, some need manual intervention
npm run lint:fix

Build code

npm run build

Run test

npm run test

Generate distribution files

npm run deploy

NPM publish

Before running publish script, make sure you have updated version properly.

Note that prepublishOnly script will be automatically called while publishing. It will check lint, clean dist/lib folders and build fresh distribution files before it executes npm publish.

npm publish

License

MIT

matic.js's People

Contributors

ankitboghra avatar arthcp avatar atvanguard avatar clarkchen avatar dbstock avatar dependabot[bot] avatar enaqx avatar etienne-martin avatar fuzious avatar itsmnthn avatar itzmeanjan avatar jdkanani avatar meshugah avatar mt-polygon-technology avatar nitinmittal23 avatar omahs avatar ptsayli avatar py-zoid avatar rahuldamodar94 avatar sanchaymittal avatar saranonearth avatar shahbhavir avatar shivamklr avatar steversio avatar tomafrench avatar ujjwalgupta94 avatar ujjwalguptaofficial avatar vaibhavchellani avatar vers10ne avatar wolf76 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

matic.js's Issues

Add `getMappedTokenAddress` to get mapped token address

Add getMappedTokenAddress method to get token address mapped with mainchain token address.

this._tokenMappedCache = {}

async getMappedTokenAddress(address) {
    const _a = address.toLowerCase()
    if (!this._tokenMappedCache[_a]) {
        this._tokenMappedCache[_a] =  await this._rootChainContract.methods.tokens(_a).call()
    }
    return this._tokenMappedCache[_a]
}

RaidGuild Request: indexed.wtf doc edits and additions

Hello blessed devs,
@ptsayli @rahuldamodar94 @arthcp @shahbhavir @atvanguard @jdkanani @itzmeanjan @delroybosco @Meshugah @itsmnthn @vers10ne @everdreamsoft @ayushgupta0610 @0xAshish @sanchaymittal @vaibhavchellani

We here at Raid Guild have brought you indexed.wtf and are taking care to make sure the docs we display for each Layer 2 and side-chain project are accurate and filled with information the dev teams would like to highlight specifically. Having easily accessible information about all these solutions will bring more attention to your project.

Please find the markdown for the docs for your project below.

Kindly review, edit and provide any missing details and information at your taste and discretion as project leaders.

Moving forward we aim to keep indexed.wtf as current and beneficial to developers researching the ecosystem as possible. Please feel free at any time to submit an issue or PR to update the displayed information.

Thank you for your attention to this matter.

Best,
The Indexed Army
We stand for accurate data.

www.RaidGuild.org
@chair28980 @kittyslasher

###### tags: `Tag(Index.wtf)`
# Polygon (Previously Matic) Docs


## Name
Polygon (Previously [Matic Network](https://matic.network/))

## Description
Polygon is a protocol and a framework for building and connecting Ethereum-compatible blockchain networks

## Consensus Type
Dual-consensus architecture (Plasma + Proof-of-Stake)

## Tx Cost
<!--- Need to update ---->

## Average TPS
<!--- Need to update ---->

## Governance/validator Token
โ“‚๏ธ Matic โ“‚๏ธ

## Transactional Token
โ“‚๏ธ Matic + ETH + Any ERC Token  โ“‚๏ธ

## Resources
[Website](https://polygon.technology/)
[Github](https://github.com/maticnetwork/)
[Docs](https://polygon.technology/papers/)


## Social Media & Community
[Twitter](https://twitter.com/maticnetwork)
[Telegram](https://t.me/maticnetwork)
[Discodrd](https://discord.com/invite/XvpHAxZ)
[Reddit](https://www.reddit.com/r/maticnetwork/)
[Career Opportunities](https://polygon.technology/careers/)

maticPOSClient.exitERC20 returns error

When I run maticPOSClient.exitERC20 (with correct burnTxHash value) it always returns the following error:

TypeError: Cannot read property 'blockNumber' of null

Even after waiting a long time to make sure checkpoint have been validated.

Question: Withdraw NFT from Matic to Ethereum

Hello,

I'd like to understand the process of withdrawing ERC721 tokens that were minted on the Polygon Network.

Can an ERC721 token be minted on the Polygon network then withdrawn to L1? Or do withdrawals only work if the ERC721 token is first minted on L1, transferred to L2 and then withdrawn back to L1?

If the former is true, what needs to be deployed on L1 to make this work i.e. Another ERC721 contract that has some customizations?

I see you've got some sample code for this, but it is not clear on how one would mint on Polygon and then later withdraw.

References:
[1] - https://github.com/maticnetwork/matic.js/blob/80a482ea4931ebf9cf2906ca541cffb668c63e43/examples/node/initiate-withdraw-ERC721.js
[2] - https://github.com/maticnetwork/matic.js/blob/80a482ea4931ebf9cf2906ca541cffb668c63e43/examples/node/confirm-withdraw-ERC721.js

[Inquiry] Project status?

Hello,

A few questions:

  • Is this being actively developed?
  • Is there a roadmap?
  • If either of the previous answers is no, why not? Is this something that additional community involvement can help with?

Cheers,

Will

AssertionError: Burn transaction has not been checkpointed as yet

Im getting this error using mumbai network. Havent tried on mainnet yet.

const txHash = "0xdba139794982873b00827003be64db0ec0205886f7450fa773af747009bf91b1";
const isProcessed = await maticPOSClient.isERC20ExitProcessed(txHash);

What would be the best workaround to check for a txHash?

UnhandledPromiseRejectionWarning while trying to bridge ERC20 tokens to the Matic network

I followed the tutorial to bridge our ERC20 token into the Matic network. My code looks like this:

`const Matic = require('@maticnetwork/maticjs').default
const config = require('./config.json')

const from = config.FROM_ADDRESS // from address

// Create object of Matic
const matic = new Matic({
maticProvider: config.MATIC_PROVIDER,
parentProvider: config.PARENT_PROVIDER,
rootChain: config.ROOTCHAIN_ADDRESS,
withdrawManager: config.WITHDRAWMANAGER_ADDRESS,
depositManager: config.DEPOSITMANAGER_ADDRESS,
registry: config.REGISTRY,
})

// async function execute() {
// await matic.initialize()
// matic.setWallet(config.PRIVATE_KEY)
// }

const token = config.MAINNET_ERC20 // ERC20 token address
const amount = '20' // amount in wei

async function execute() {
await matic.initialize()
matic.setWallet(config.PRIVATE_KEY)
// Approve Deposit Manager contract to transfer tokens
await matic.approveERC20TokensForDeposit(token, amount, { from, gasPrice: '10000000000' });
console.log('Approval done...');
// Deposit tokens
return matic.depositERC20ForUser(token, from, amount, { from, gasPrice: '10000000000' })
}

console.log('starting...');
execute();`

{ "MATIC_PROVIDER": "https://rpc-mainnet.matic.network", "PARENT_PROVIDER": "https://mainnet.infura.io/v3/60df93ecf023472aaa84725af955fde2", "ROOTCHAIN_ADDRESS": "0x2890bA17EfE978480615e330ecB65333b880928e", "WITHDRAWMANAGER_ADDRESS": "0x2923C8dD6Cdf6b2507ef91de74F1d5E0F11Eac53", "DEPOSITMANAGER_ADDRESS": "0x7850ec290A2e2F40B82Ed962eaf30591bb5f5C96", "PRIVATE_KEY": "_MY_PRIVATE_KEY_HERE_, "FROM_ADDRESS": "0x3115b321904572e05b4C2E5DC3e55628110593EE", "GOERLI_ERC20": "0x655f2166b0709cd575202630952d71e2bb0d61af", "MATIC_ERC20": "0x2d7882beDcbfDDce29Ba99965dd3cdF7fcB10A1e", "REGISTRY": "0xeE11713Fe713b2BfF2942452517483654078154D", "MUMBAI_ERC721":"0xa38c6F7FEaB941160f32DA7Bbc8a4897b37876b5", "GOERLI_ERC721":"0x0217B02596Dfe39385946f82Aab6A92509b7F352", "MUMBAI_WETH":"0x4DfAe612aaCB5b448C12A591cD0879bFa2e51d62", "GOERLI_WETH":"0x60D4dB9b534EF9260a88b0BED6c486fe13E604Fc", "MAINNET_ERC20":"0xdacd69347de42babfaecd09dc88958378780fb62" }

However, when I run the app using node matic-example.js, I get the following error::

(node:58539) UnhandledPromiseRejectionWarning: Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
at ABICoder.decodeParametersWith (/Users/nikola/Projects/matic-js-test/node_modules/web3-eth-abi/lib/index.js:298:15)
at ABICoder.decodeParameters (/Users/nikola/Projects/matic-js-test/node_modules/web3-eth-abi/lib/index.js:285:17)
at Contract._decodeMethodReturn (/Users/nikola/Projects/matic-js-test/node_modules/web3-eth-contract/lib/index.js:470:22)
at Method.outputFormatter (/Users/nikola/Projects/matic-js-test/node_modules/web3-eth-contract/lib/index.js:760:42)
at Method.formatOutput (/Users/nikola/Projects/matic-js-test/node_modules/web3-core-method/lib/index.js:147:54)
at sendTxCallback (/Users/nikola/Projects/matic-js-test/node_modules/web3-core-method/lib/index.js:523:33)
at /Users/nikola/Projects/matic-js-test/node_modules/web3-core-requestmanager/lib/index.js:308:9
at XMLHttpRequest.request.onreadystatechange (/Users/nikola/Projects/matic-js-test/node_modules/web3-providers-http/lib/index.js:98:13)
at XMLHttpRequestEventTarget.dispatchEvent (/Users/nikola/Projects/matic-js-test/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
at XMLHttpRequest._setReadyState (/Users/nikola/Projects/matic-js-test/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
at XMLHttpRequest._onHttpResponseEnd (/Users/nikola/Projects/matic-js-test/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
at IncomingMessage. (/Users/nikola/Projects/matic-js-test/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
at IncomingMessage.emit (events.js:326:22)
at endReadableNT (_stream_readable.js:1244:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)

Problem with npm install !

npm install @maticnetwork/[email protected]
npm WARN deprecated [email protected]: New package name format for new versions: @ethereumjs/block. Please update.
npm WARN deprecated [email protected]: New package name format for new versions: @ethereumjs/tx. Please update.
npm WARN deprecated [email protected]: New package name format for new versions: @ethereumjs/common. Please update.
npm WARN deprecated [email protected]: This package is broken and no longer maintained. 'mkdirp' itself supports promises now, please switch to that.
npm WARN deprecated [email protected]: request has been deprecated, see request/request#3142
npm ERR! Unexpected end of JSON input while parsing near '..."mime-types":"~2.0.11'

npm ERR! A complete log of this run can be found in:
npm ERR! /home/robert/.npm/_logs/2021-05-06T16_46_44_187Z-debug.log

Examples. POS-Client / Ether fails with BUFFER OVERRUN error code

Error:

worker@lenovo ~/Documents/MyProjects/etherium/POS-client/Ether $ node exit.js 
Error: data out-of-bounds (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7)
    at Logger.makeError (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/logger/lib/index.js:180:21)
    at Logger.throwError (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/logger/lib/index.js:189:20)
    at Reader._peekBytes (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/abi/lib/coders/abstract-coder.js:149:24)
    at Reader.readBytes (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/abi/lib/coders/abstract-coder.js:161:26)
    at Reader.readValue (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/abi/lib/coders/abstract-coder.js:167:48)
    at NumberCoder.decode (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/abi/lib/coders/number.js:49:28)
    at /home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/abi/lib/coders/array.js:106:31
    at Array.forEach (<anonymous>)
    at Object.unpack (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/abi/lib/coders/array.js:85:12)
    at TupleCoder.decode (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/abi/lib/coders/tuple.js:39:49)
    at AbiCoder.decode (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@ethersproject/abi/lib/abi-coder.js:93:22)
    at ABICoder.decodeParametersWith (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/web3-eth-abi/lib/index.js:304:30)
    at ABICoder.decodeParameters (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/web3-eth-abi/lib/index.js:285:17)
    at Contract._decodeMethodReturn (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/web3-eth-contract/lib/index.js:470:22)
    at Method.outputFormatter (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/web3-eth-contract/lib/index.js:760:42)
    at Method.formatOutput (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/web3-core-method/lib/index.js:147:54)
    at sendTxCallback (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/web3-core-method/lib/index.js:523:33)
    at /home/worker/Documents/MyProjects/etherium/POS-client/node_modules/web3-core-requestmanager/lib/index.js:308:9
    at /home/worker/Documents/MyProjects/etherium/POS-client/node_modules/@trufflesuite/web3-provider-engine/index.js:240:9
    at /home/worker/Documents/MyProjects/etherium/POS-client/node_modules/async/internal/once.js:12:16
    at replenish (/home/worker/Documents/MyProjects/etherium/POS-client/node_modules/async/internal/eachOfLimit.js:61:25)
    at /home/worker/Documents/MyProjects/etherium/POS-client/node_modules/async/internal/eachOfLimit.js:71:9 {
  reason: 'data out-of-bounds',
  code: 'BUFFER_OVERRUN',
  length: 3,
  offset: 32
}

How to reproduce:

  1. Run deposit.js
worker@lenovo ~/Documents/MyProjects/etherium/POS-client/Ether $ node deposit.js 
0x7b5a6c05bef2ac8008b09f699250e6f16eec2d8f4d526592de1d08642d477c3d
  1. Run burn.js
worker@lenovo ~/Documents/MyProjects/etherium/POS-client/Ether $ node burn.js 
0xac77350551b6eaee6f09d77e3cf7ca03258dfeb7f86368ad85684dec4dd7a6aa
  1. Edit exit.js to insert 0xac77350551b6eaee6f09d77e3cf7ca03258dfeb7f86368ad85684dec4dd7a6aa from the previous step. Then run
worker@lenovo ~/Documents/MyProjects/etherium/POS-client/Ether $ node exit.js 

The above error follows.

Approval method never executes while trying to bridge tokens to the Matic network

I am trying to bridge our token into the Matic network. However, I'm experiencing some problems. When the approve method of the ERC20 token smart contract is being called I never get the results and everything is stuck.

Here's my code:
`const Network = require("@maticnetwork/meta/network");
const Matic = require('@maticnetwork/maticjs').default
const config = require('./config.json')

const network = new Network(config.network, config.version);
const from = config.FROM_ADDRESS; // from address
const MainNetwork = network.Main;
console.log('Network');
console.log(Network);

// Create object of Matic
const matic = new Matic({
maticProvider: config.MATIC_PROVIDER,
parentProvider: config.PARENT_PROVIDER,
rootChain: MainNetwork.Contracts.RootChain,
withdrawManager: MainNetwork.Contracts.WithdrawManagerProxy,
depositManager: MainNetwork.Contracts.DepositManagerProxy,
registry: MainNetwork.Contracts.Registry
});

// async function execute() {
// await matic.initialize()
// matic.setWallet(config.PRIVATE_KEY)
// }

const token = config.MAINNET_ERC20 // ERC20 token address
// const token = config.GOERLI_ERC20;
const amount = '20'; // amount in wei

async function execute() {
console.log('wallet initializing...');
await matic.initialize();
matic.setWallet(config.PRIVATE_KEY);
console.log('wallet initialized...');
// Approve Deposit Manager contract to transfer tokens
await matic.approveERC20TokensForDeposit(token, amount, { from, gasPrice: '10000000000' });
console.log('Approval done...');
// Deposit tokens
return matic.depositERC20ForUser(token, from, amount, { from, gasPrice: '10000000000' })
}

console.log('starting...');
execute();`

{ "MATIC_PROVIDER": "https://rpc-mumbai.matic.today", "PARENT_PROVIDER": "https://mainnet.infura.io/v3/60df93ecf023472aaa84725af955fde2", "ROOTCHAIN_ADDRESS": "0x2890bA17EfE978480615e330ecB65333b880928e", "WITHDRAWMANAGER_ADDRESS": "0x2923C8dD6Cdf6b2507ef91de74F1d5E0F11Eac53", "DEPOSITMANAGER_ADDRESS": "0x7850ec290A2e2F40B82Ed962eaf30591bb5f5C96", "PRIVATE_KEY": "_MY_PRIVATE_KEY_GOES_HERE_", "FROM_ADDRESS": "0x3115b321904572e05b4C2E5DC3e55628110593EE", "GOERLI_ERC20": "0x655f2166b0709cd575202630952d71e2bb0d61af", "MATIC_ERC20": "0x2d7882beDcbfDDce29Ba99965dd3cdF7fcB10A1e", "REGISTRY": "0xeE11713Fe713b2BfF2942452517483654078154D", "MUMBAI_ERC721":"0xa38c6F7FEaB941160f32DA7Bbc8a4897b37876b5", "GOERLI_ERC721":"0x0217B02596Dfe39385946f82Aab6A92509b7F352", "MUMBAI_WETH":"0x4DfAe612aaCB5b448C12A591cD0879bFa2e51d62", "GOERLI_WETH":"0x60D4dB9b534EF9260a88b0BED6c486fe13E604Fc", "MAINNET_ERC20":"0xdacd69347de42babfaecd09dc88958378780fb62", "network":"mainnet", "version": "v1" }

TypeError: param is undefined

Im trying to bridge tokens from ethereum to matic but Ive been having this issue and cannot get to find the answer, I believe this issue comes from ABICoder

FYI Im using nextjs with typescript

const posClientParent = (account: string) => {
    const maticPoSClient = new MaticPOSClient({
        network: "testnet",
        version: "mumbai",
        maticProvider:  new Web3(`https://rpc-mumbai.maticvigil.com/v1/${process.env.MATIC_API_KEY}`),
        parentProvider: window.ethereum,
        parentDefaultOptions: { from: account },
        maticDefaultOptions: { from: account },
        posRootChainManager: '0xBbD7cBFA79faee899Eaf900F13C9065bF03B1A74',
        posERC20Predicate: '0xdD6596F2029e6233DEFfaCa316e6A95217d4Dc34', 
    });
    return maticPoSClient;
  };

await posClientParent.approveERC20ForDeposit("0xBBA4d2917790B35822F37237f7963C261A8399a9", amount, { from });

Respone:

image

Matic initialization fail - TypeError: Matic is not a constructor

When I try to instantiate Matic, I have this error:

TypeError: Matic is not a constructor

Here is the code:

import Matic from '@maticnetwork/maticjs'

// for mumbai testnet
const matic = new Matic({
network: "testnet",
version: "mumbai",
parentProvider,
maticProvider
})

matic.initialize()

Do you know why I have this error?

For information, I use node v14.

TypeError: a.call is not a function

Error while calling the exit function for pos withdraw

TypeError: a.call is not a function
    at e.exports (/Users/rahulprabhu/Documents/GitHub/pos-matic-demo/node_modules/@maticnetwork/maticjs/dist/matic.node.js:15:1706957)
    at t.<anonymous> (/Users/rahulprabhu/Documents/GitHub/pos-matic-demo/node_modules/@maticnetwork/maticjs/dist/matic.node.js:8:26133)
    at /Users/rahulprabhu/Documents/GitHub/pos-matic-demo/node_modules/@maticnetwork/maticjs/dist/matic.node.js:8:23422
    at Object.next (/Users/rahulprabhu/Documents/GitHub/pos-matic-demo/node_modules/@maticnetwork/maticjs/dist/matic.node.js:8:23527)
    at r (/Users/rahulprabhu/Documents/GitHub/pos-matic-demo/node_modules/@maticnetwork/maticjs/dist/matic.node.js:8:22241)

Add receiveMessage method for tunnel contract

Tunnel contract helps developers to move arbitrary data from Ethereum to Matic and Matic to Ethereum.

While moving data from Matic to Ethereum, one event is generated event MessageSent(bytes message) - https://github.com/maticnetwork/pos-portal/blob/master/contracts/tunnel/BaseChildTunnel.sol#L13

There is one method on RootTunnel, receiveMessage, that needs to be called on the Ethereum chain to get the data. After the checkpoint, the user will send one tx (function receiveMessage at RootTunnel contract) on the Ethereum chain. That tx will validate the event/log and processes the received data based on the DApp developer's custom logic. DApp developer will write custom logic here: https://github.com/maticnetwork/pos-portal/blob/master/contracts/tunnel/BaseRootTunnel.sol#L217

To generate the payload for receiveMessage and to call that function, we need one more method on Matic.js. Here is the pseudocode for it:

const contractAddress = rootTunnelContractAddressOnEthereum
const txHash = txHashWhichHasMessageSentEventOnMatic
const logSignature = keccak256('MessageSent(bytes)')
export function processReceivedMessage(contractAddress, txHash) {
    const payload = await this.exitManager.buildPayloadForExitHermoine(txHash, logSignature)
    return rootTunnelContract.at(contractAddress).methods.receiveMessage(payload)
}

Sends Too Many Requests at Same Time

receipts = await Promise.all(receiptPromises)
sends more than 100 requests to RPC at same time while almost all the providers will discard your request, I have tried with Infura, maticvigil registed and ankr.
Improve: sends 10/other number of requests at same time, wait them finished and then next.

Update CDN version in README

I was stuck for over an hour using the CDN version 2.0.1 which is shown in the README trying to call the function depositEtherForUser(...)

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'network' of undefined TypeError: Cannot read property 'network' of undefined

Using the latest version worked like a charm:

<script src="https://cdn.jsdelivr.net/npm/@maticnetwork/maticjs@latest/dist/matic.js"></script>

Error: Cannot find module './mainnet/mumbai/index.json'

Hi, I'm getting the error Error: Cannot find module './mainnet/mumbai/index.json' when using network: 'mainnet' config with MaticPOSClient. It works however when using network: 'testnet'.

Set up:

import { MaticPOSClient } from '@maticnetwork/maticjs'

const maticPOSClient = new MaticPOSClient({
  network: 'mainnet',
  maticProvider: new Web3.providers.HttpProvider(
    'https://rpc-mainnet.maticvigil.com'
  ),
  parentProvider: new Web3.providers.HttpProvider(
    'https://mainnet.infura.io/...'
  ),
  posRootChainManager: '0xA0c68C638235ee32657e8f720a23ceC1bFc77C77',
  posERC20Predicate: '0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf'
})

Error:

{ Error: Cannot find module './mainnet/mumbai/index.json'
    at s (/home/mota/Sandbox/hop/monorepo/packages/hop-node/node_modules/@maticnetwork/maticjs/dist/matic.node.js:15:105460)
    at i (/home/mota/Sandbox/hop/monorepo/packages/hop-node/node_modules/@maticnetwork/maticjs/dist/matic.node.js:15:105409)
    at new i (/home/mota/Sandbox/hop/monorepo/packages/hop-node/node_modules/@maticnetwork/maticjs/dist/matic.node.js:15:104854)
    at Function.t.initializeNetwork (/home/mota/Sandbox/hop/monorepo/packages/hop-node/node_modules/@maticnetwork/maticjs/dist/matic.node.js:15:102223)
    at new t (/home/mota/Sandbox/hop/monorepo/packages/hop-node/node_modules/@maticnetwork/maticjs/dist/matic.node.js:15:87121)
    at polygonBridgeWatcher.getPayload (/home/mota/Sandbox/hop/monorepo/packages/hop-node/dist/src/watchers/polygonBridgeWatcher.js:108:32)
    at processTicksAndRejections (internal/process/task_queues.js:86:5) code: 'MODULE_NOT_FOUND' }

Version:

    "@maticnetwork/maticjs": "^2.0.40"

Any ideas on how to make it work with mainnet? Thanks in advance.

MaticJS example scripts not working, documentation outdated

The example scripts for MaticJS in the /examples directory is outdated. The scripts error out without any actionable message and the documentation for the same is also outdated.
For example: There is no balance-of-ERC20.js file in the examples directory, but it is mentioned in README. Other scripts also don't work even after following the README configuration steps.

3000 post requests to RPC for function call maticPOSClient.exitERC20??

Hey there,

when executing maticPOSClient.exitERC20(burnHash, {encodeAbi:true, legacyProof:true, from:user})
Chrome does 3000 post requests to the RPC within around 10 seconds. The function works fine otherwise, I'm just wondering if this is intended since it appears to be unnecessary load to the RPC.

maticPOSClient.depositSingleERC1155ForUser is timing out.

WIth a properly configured maticPOSClient i attempt to invoke depositSinglERC1155ForUser and it hangs until the default timeout of 750 seconds is reached.

I know the client is properly configured because i can use it to call the .balanceOfERC721 and .balanceOfERC20 functinos successfully.

Here's the code that fails:

const singleDepositTx = maticPOSClient.depositSingleERC1155ForUser(
        megaTokensContract.address,
        from,
        tokenId,
        amountToTransfer,
        [],
        {
            from,
            gasPrice: '200000000000'
        }
    );

Worth noting, my code below WORKS and successfully sends tokens across the PoS bridge:

let user = '0xd954F4513BdE1E00F3986630A7e73c4f9aA564fE'; 
    let rootToken = '0x4b048C00d746bd2559FcA9f9733D2A6a2a8ef3D9'; 
    let tokenIds = ['1']; 
    let amounts = [5]; 
    let data = [];
    let depositData = web3.eth.abi.encodeParameters(['uint256[]', 'uint256[]', 'bytes'], [tokenIds, amounts, data]);

    // (2) get contract
    let artifact = require("./pos-portal/artifacts/RootChainManager.json"); 
    const proxyForRootChainManagerAddress = '0xBbD7cBFA79faee899Eaf900F13C9065bF03B1A74'; 
    let root = new web3.eth.Contract(artifact.abi, proxyForRootChainManagerAddress);

    // (3) call depositFor
    let gasPrice = '20000000000';
    let tx = root.methods.depositFor(user, rootToken, depositData).send({from: accounts[0], gasPrice });

Getting TOKEN_NOT_SUPPORTED when trying to bridge tokens to the Matic network

I'm trying to bridge our ERC20 token to the Matic network. Here's my code:
`const Network = require("@maticnetwork/meta/network");
const Matic = require('@maticnetwork/maticjs').default
const config = require('./config.json')

const network = new Network(config.network, config.version);
const from = config.FROM_ADDRESS; // from address
const MainNetwork = network.Main;
console.log('Network');
console.log(Network);

// Create object of Matic
const matic = new Matic({
maticProvider: config.MATIC_PROVIDER,
parentProvider: config.PARENT_PROVIDER,
rootChain: MainNetwork.Contracts.RootChain,
withdrawManager: MainNetwork.Contracts.WithdrawManagerProxy,
depositManager: MainNetwork.Contracts.DepositManagerProxy,
registry: MainNetwork.Contracts.Registry
});

const token = config.MAINNET_ERC20 // ERC20 token address
// const token = config.GOERLI_ERC20;
const amount = '20'; // amount in wei

async function execute() {
console.log('wallet initializing...');
await matic.initialize();
matic.setWallet(config.PRIVATE_KEY);
console.log('wallet initialized...');

// Approve Deposit Manager contract to transfer tokens
await matic.approveERC20TokensForDeposit(token, amount, { 
	from: from, 
	gasPrice: '300000000000',
	// nonce: '0x00',
	// gasLimit: '9000000',
	onTransactionHash: txHash => {
		console.log("Tx hash: " + txHash);
	}
});
console.log('Approval done...');
// Deposit tokens
await matic.depositERC20ForUser(token, from, amount, { 
	from: from, 
	gasPrice: '300000000000',
	// nonce: '0x00',
	// gasLimit: '9000000',
	onTransactionHash: txHash => {
		console.log("Tx hash: " + txHash);
	}
})

}

console.log('starting...');
execute();

<config.json>
{
"MATIC_PROVIDER": "https://rpc-mumbai.matic.today",
"PARENT_PROVIDER": "https://mainnet.infura.io/v3/60df93ecf023472aaa84725af955fde2",
"ROOTCHAIN_ADDRESS": "0x2890bA17EfE978480615e330ecB65333b880928e",
"WITHDRAWMANAGER_ADDRESS": "0x2923C8dD6Cdf6b2507ef91de74F1d5E0F11Eac53",
"DEPOSITMANAGER_ADDRESS": "0x7850ec290A2e2F40B82Ed962eaf30591bb5f5C96",
"PRIVATE_KEY": "0x79d2a887f61676da7b9431b44d29b40a59030b16b622b1dfb067cf861d83a399",
"FROM_ADDRESS": "0x3115b321904572e05b4C2E5DC3e55628110593EE",
"GOERLI_ERC20": "0x655f2166b0709cd575202630952d71e2bb0d61af",
"MATIC_ERC20": "0x2d7882beDcbfDDce29Ba99965dd3cdF7fcB10A1e",
"REGISTRY": "0xeE11713Fe713b2BfF2942452517483654078154D",
"MUMBAI_ERC721":"0xa38c6F7FEaB941160f32DA7Bbc8a4897b37876b5",
"GOERLI_ERC721":"0x0217B02596Dfe39385946f82Aab6A92509b7F352",
"MUMBAI_WETH":"0x4DfAe612aaCB5b448C12A591cD0879bFa2e51d62",
"GOERLI_WETH":"0x60D4dB9b534EF9260a88b0BED6c486fe13E604Fc",
"MAINNET_ERC20":"0xdacd69347de42babfaecd09dc88958378780fb62",
"network":"mainnet",
"version": "v1"
}
`

The approve function gets executed just fine. However, when the depositERC20ForUser() method is called, I get the following error: Error: Returned error: execution reverted: TOKEN_NOT_SUPPORTED

isSingleERC1155ExitProcessed throws "TypeError: i is null" for old TXs

Hi !
Since last week, ERC1155 tokens that were waiting to be retrieved on L1 after being burned on L2 are throwing an error when checked for exit being processed:
maticPOSClient.isSingleERC1155ExitProcessed("0xbfc70c164f6951d9c9f3f87f2d1361ff216eb3d6fe9571430bd3f0711847a782");
This check throws the error "TypeError: i is null" in the file "matic.umd.js", and when I try to call exitSingleERC1155 on it I get the same error. Batch operations are also failing.

Note that everything was working fine beginning of last week, and it doesn't affect all withdrawals.

Can someone help me on this ?

Here is an example you can play with:

<html >
  <meta charset="UTF-8">
  <body>
    <script src="https://unpkg.com/@maticnetwork/maticjs@latest/dist/matic.js"></script>
    <script>
      const brokenTransactions = [
        '0xbfc70c164f6951d9c9f3f87f2d1361ff216eb3d6fe9571430bd3f0711847a782',
        '0x2550f010066187641f688df808ebe4abd730f6c8a2a28f1a5d01e10c6d99d8e7',
      ];

      const maticPOSClient = new Matic.MaticPOSClient({
        network: 'mainnet',
        version: 'v1',
        parentProvider: 'eth-mainnet-rpc',
        maticProvider: 'matic-rpc'
      });

      brokenTransactions.forEach((transactionHash) => {
        document.body.innerHTML += `<div id="${transactionHash}">TX ${transactionHash}, status: <span class="status">Pending</span></div>`
        maticPOSClient.isSingleERC1155ExitProcessed(transactionHash)
          .then(response => {
            console.log(`for ${transactionHash}`, response);
            document.getElementById(transactionHash).getElementsByClassName('status')[0].innerHTML = 'Success';
          })
          .catch(e => {
            console.error(`for ${transactionHash}`, e);
            document.getElementById(transactionHash).getElementsByClassName('status')[0].innerHTML = 'Error, check console';
          });
      })
    </script>
  </body>
</html>

Unable to use exitERC721 function

Hey! I have been trying to use exiterc721 function. Whenever I run it, it throws an exception. they nft was minted on matic chain. After that I burnt it and executed exiterc721 function.

runnig the maticPOSClient.exitERC20 errer?

mycode:
const burnHash = '0x37991a88ab2b4602e9ff942f99144501749c4d8c21e2323f18f5f1b4d3ec607f'
maticPOSClient.exitERC20(burnHash, options).then((res)=>{
console.log("res: ", res);
process.exit(0)
}).catch((err)=>{
console.log("err: ", err);
process.exit(0)
})

errers:
err: AssertionError [ERR_ASSERTION]: Burn transaction has not been checkpointed as yet
at t. (D:\Project\solidity\matic\eth\node_modules@maticnetwork\maticjs\dist\matic.node.js:8:26981)
at D:\Project\solidity\matic\eth\node_modules@maticnetwork\maticjs\dist\matic.node.js:8:23381
at Object.next (D:\Project\solidity\matic\eth\node_modules@maticnetwork\maticjs\dist\matic.node.js:8:23486)
at r (D:\Project\solidity\matic\eth\node_modules@maticnetwork\maticjs\dist\matic.node.js:8:22200)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
}

Add transferTokens/ethers for other network

We could pass parent flag in options to give a hint which network we want to use.

// This will transfer tokens on Mainchain
matic.transferTokens(token, user, amount, {
   ...,
   parent: true
})

Only two methods we have to implement -

  1. matic.transferTokens (already implemented). Add simple parent flag in options.
  2. matic.transferEthers(to, amount, options) (new method). It will also have parent flag. It will work like this -
  • For Matic: when matic.js is initialized (or when transferEthers is called first time), fetch WETH address on Matic and store it as maticWethAddress. Use that to do matic.transferEthers(to, amount, options) and internally it will call matic.transferTokens
transferEthers (to, amount, options = {}) {
    if (!options.parent) {
        // fetch `maticWethAddress`
        return matic.transferTokens(this.maticWethAddress, to, amount, options)
    }
        
    // send ethers on parent network
} 
  • For Parent: Do simple sendTransaction when matic.transferEthers(to, amount, options) is being called.

Withdrawal from Polygon to Ethereum Stuck

Hi,

I was testing bridging Ether to Polygon for use in DeFi and using the Matic Wallet bridge from Ethereum to Polygon was successful. However, on my test of withdrawing back to Ethereum the transaction was processed but the Ether never reached my Metamask wallet.

Transaction ID here: https://etherscan.io/tx/0x31b078face2ec2b5dbe2d3a419e0118dac4bb4e07bfc0ce83c5e1b88c65c4dfa

In the Polygon Discord, this seems to be a recurring problem. It has been said these can be
"manually pulled" by creating a new contract but I am not skilled in doing so. I am less concerned about the Ether lost and more concerned about this being a problem in general as I have other assets like Stablecoins and other Erc-20 tokens already on the Polygon network that I will need to withdraw in the near future. For reference, I have also submitted a Ticket to Polygon, ID # 6185. Thank you

Edit:

Here is a Doc with all the transaction ID's and screencaps showing my Ethereum balance decreasing on deposit but not increasing on withdrawal.

https://docs.google.com/document/d/12tkir1okq_WxpUH82ZGrf8Y85A_QIbku7AR5CxVr654/edit?usp=sharing

litely no enviremental envireables

matic = new Matic({
      maticProvider: process.env.MATIC_PROVIDER,
      parentProvider: process.env.PARENT_PROVIDER,
      rootChainAddress: process.env.ROOTCHAIN_ADDRESS,
      maticWethAddress: process.env.MATIC_WETH_ADDRESS,
      syncerUrl: process.env.SYNCER_URL,
      watcherUrl: process.env.WATCHER_URL,
      withdrawManagerAddress: process.env.WITHDRAWMANAGER_ADDRESS,	
    })
  • I would expect README info how to define them of define it in the code.

MetaMask - RPC Error: MetaMask Tx Signature: User denied transaction signature.

Our game works flawlessly on the rinkeby testnetwork. We have deployed our contracts to mumbai tesnet successfully. But when we make a transaction, we are stuck on this issue.

  1. MetaMask - RPC Error: MetaMask Tx Signature: User denied transaction signature.
  2. Uncaught (in promise) Error: Transaction has been reverted by the EVM:
    We are building dungeon crawler on the matic mumbai tesnet. It is an RPG game that has NFTs and a DAO in the game with our very own ERC-20 token $DGN

Error on React-Native project

Describe the bug
Getting the following error when installing and importing @maticnetwork/maticjs into a React-Native project.

Following is a screenshot of the error
Screenshot_20210627_135643

2.0.43 is the @maticnetwork/maticjs version that I'm using

Version 1.0.0-beta.1

For version v1.0.0-beta.1, following checklist should be required:

  • Deposit
  • Local withdraw
  • Withdraw with backend APIs
  • Tx/receipt/header proof and verify proof APIs
  • Webpack setup
  • Eslint fixes for future pull requests
  • Necessary testcases
  • Documentation

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.