Coder Social home page Coder Social logo

maticnetwork / contracts Goto Github PK

View Code? Open in Web Editor NEW
1.1K 72.0 498.0 12.88 MB

Smart contracts comprising the business logic of the Matic Network

Home Page: https://matic.network

License: GNU General Public License v3.0

JavaScript 51.56% Solidity 48.02% Shell 0.42%
ethereum blockchain decentralised-exchange payment cryptocurrencies dapps scalability

contracts's Introduction

Warning

This repository is no longer in use, and has been migrated to https://github.com/0xPolygon/pos-contracts

Matic contracts

Build Status

Ethereum smart contracts that power the Matic Network.

Install dependencies with

npm install

Setup

pre-commit install

Compile

npm run template:process -- --bor-chain-id 15001

bor-chain-id should be:
local: 15001
Mainnet = 137
TestnetV4 (Mumbai) = 80001

Main chain and side chain

  • Main chain

All tests are run against a fork of mainnet using Hardhat's forking functionality. No need to run any local chain!

  • Start Matic side chain. Requires docker.
npm run bor:simulate
  • Stop with
npm run bor:stop
  • If you want a clean chain, this also deletes your /data folder containing the chain state.
npm run bor:clean

Run tests

Run Hardhat test

npm test:hardhat

Run Foundry test

npm test:foundry

Coverage

Run coverage with

npm run coverage

contracts's People

Contributors

0xashish avatar 0xcvh avatar arthcp avatar atvanguard avatar ayushkaul avatar coinsandsteeldev avatar dhairyasethi avatar gretzke avatar imyourm8 avatar jdkanani avatar k06a avatar leovct avatar ptsayli avatar rahuldamodar94 avatar sanchaymittal avatar sandeepnailwal avatar shogochiai avatar simondos avatar ssandeep avatar vaibhavchellani avatar zorancuc 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  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

contracts's Issues

`isValidator` returns true even if startEpoch is in future

Currently, the validator is getting activated when even if activationEpoch > currentEpoch.

Current code -

stakers[user].amount > 0 &&
      stakers[user].activationEpoch > 0 &&
      (stakers[user].deactivationEpoch == 0 ||
      stakers[user].deactivationEpoch >= currentEpoch)

Expected behavior - validator must be activated when --

(stakers[user].activationEpoch <= currentEpoch && 
(stakers[user].deactivationEpoch == 0 || stakers[user].deactivationEpoch >= currentEpoch)

Add bond for exit and reward challenger

While starting an exit, an exitNFT's owner will put small bond and challenger will get that bond if challenge gets accepted.

Question - is there any way we can avoid exit bond?

Represent PoS slot as NFT

Current implementation: #26

Can we represent PoS validator slot as NFT?

As a validator node owner, one can sell slot on open market without through decentralized exchanges (@0xProject) or marketplace (like OpenSea). That way one doesn't have to wait for 2-4 dynasty for rewards or exit.

Upgrade parity config to work with latest stable release

poa-spec.json in /test-blockchain expects to work with parity v2.1.11 - but this version is far too old and reverts whenever a contract function returns a value.

The changes can be tested on dev-marketplace branch by invoking truffle test test/child/misc/Marketplace.test.js. It passes on ganache but not on parity v2.1.11.

panic: interface conversion: consensus.Engine is *ethash.Ethash, not *bor.Bor

After setting up bor, i am trying to run it but got an error - The error is

panic: interface conversion: consensus.Engine is *ethash.Ethash, not *bor.Bor

goroutine 1 [running]:
github.com/maticnetwork/bor/eth.(*EthAPIBackend).SubscribeStateEvent(0xc000336b40, 0xc0001d3da0, 0x13c0f20, 0xc00adda220)
        /root/Desktop/Programs/MaticNetworks/bor/eth/api_backend.go:161 +0x8c
github.com/maticnetwork/bor/eth/filters.NewEventSystem(0xc0001ea4e0, 0x13e3b00, 0xc000336b40, 0xc00027f400, 0xae4a9a)
        /root/Desktop/Programs/MaticNetworks/bor/eth/filters/filter_system.go:148 +0x2ff
github.com/maticnetwork/bor/eth/filters.NewPublicFilterAPI(0x13e3b00, 0xc000336b40, 0xc00adda100, 0x8)
        /root/Desktop/Programs/MaticNetworks/bor/eth/filters/api.go:71 +0xa6
github.com/maticnetwork/bor/eth.(*Ethereum).APIs(0xc0000fa0e0, 0xc00007cb40, 0xc00027f848, 0x1)
        /root/Desktop/Programs/MaticNetworks/bor/eth/backend.go:338 +0x266
github.com/maticnetwork/bor/node.(*Node).startRPC(0xc0000cc780, 0xc00007cb40, 0x0, 0x0)
        /root/Desktop/Programs/MaticNetworks/bor/node/node.go:284 +0x33f
github.com/maticnetwork/bor/node.(*Node).Start(0xc0000cc780, 0x0, 0x0)
        /root/Desktop/Programs/MaticNetworks/bor/node/node.go:239 +0xc6b
github.com/maticnetwork/bor/cmd/utils.StartNode(0xc0000cc780)
        /root/Desktop/Programs/MaticNetworks/bor/cmd/utils/cmd.go:67 +0x2f
main.startNode(0xc0002ae160, 0xc0000cc780)
        /root/Desktop/Programs/MaticNetworks/bor/cmd/bor/main.go:328 +0x70
main.geth(0xc0002ae160, 0x0, 0x0)
        /root/Desktop/Programs/MaticNetworks/bor/cmd/bor/main.go:316 +0x11c
gopkg.in/urfave/cli%2ev1.HandleAction(0xf841e0, 0x11f97c0, 0xc0002ae160, 0xc00007aa20, 0x0)
        /root/go/pkg/mod/gopkg.in/urfave/[email protected]/app.go:490 +0xc8
gopkg.in/urfave/cli%2ev1.(*App).Run(0xc0002a41a0, 0xc0001181b0, 0x1, 0x1, 0x0, 0x0)
        /root/go/pkg/mod/gopkg.in/urfave/[email protected]/app.go:264 +0x5dd
main.main()
        /root/Desktop/Programs/MaticNetworks/bor/cmd/bor/main.go:301 +0x55

I also tried to run it by "npm run bor:simulate" but got an error. The error is shared below -

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /root/Desktop/Programs/MaticNetworks/bor/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/root/Desktop/Programs/MaticNetworks/bor/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-06-03T10_25_53_143Z-debug.log

The contents of debug file -

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'bor:simulate' ]
2 info using [email protected]
3 info using [email protected]
4 verbose stack Error: ENOENT: no such file or directory, open '/root/Desktop/Programs/MaticNetworks/bor/package.json'
5 verbose cwd /root/Desktop/Programs/MaticNetworks/bor
6 verbose Linux 5.4.0-kali2-amd64
7 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "bor:simulate"
8 verbose node v10.20.1
9 verbose npm  v6.14.4
10 error code ENOENT
11 error syscall open
12 error path /root/Desktop/Programs/MaticNetworks/bor/package.json
13 error errno -2
14 error enoent ENOENT: no such file or directory, open '/root/Desktop/Programs/MaticNetworks/bor/package.json'
15 error enoent This is related to npm not being able to find a file.
16 verbose exit [ -2, true ]

Kindly take a look and guide me how to run this instance.

Contracts refactoring

@0xAshish reported that making changes in contracts exceeds the max permissible bytecode size of a contract. FYI the byte limit for contract size is 24576. See this.

Moreover, there are a lot of calls among the contracts; interfaces for which are not every clean - for instance rootchain.setWethToken calling withdrawManager.setWethToken AND depositManager.setWethToken - This is code duplication which is one the reasons for large contract sizes. Also, the contracts are abundant with calls of the nature setContract (setExitNFTContract, setDepositManager etc)

To combat the same, some sort of contracts refactoring is required.

Add priority queue and marketplace for faster exits

  • Add priority queue for each token
  • Create an exit object when the user asks for the exit. Need to check if tx is included and balance is valid.
  • Create challengeExit or equivalent method to challenge invalid/double spent transaction
  • Add finalizeExit or equivalent method to process exits
  • Add test-case for whole exit process

Add conditions for leave/join events for stakeholders

Following are conditions to leave/join PoS system -

  • Add epoch for 100 header blocks
  • Add minimum and maximum stake amount
  • Add minimum lock-in period (in terms of the number of the epoch)
  • Leave request
  • Minimum time period (in terms of the number of the epoch) between leave request and actual leave event (+ refund stake amount)

Non-compliance mandatory tokenFallback

receiver.tokenFallback(msg.sender, _value, _data);

With this modification the StardardToken forces the contracts receiving tokens to implement the tokenFallback method; this causes the StandardToken.sol not to follow the ERC20 standard.

I believe this method is meant to replicate the mandatory fallback on the Ethereum network, if that is the case, may be a good idea to move this to MaticWETH.sol

Another possible solution is making a nonThrow call to tokenFallback and ignore a potential failure, that will not replicate the functionality of the mandatory fallback, but it will be ERC20 compliance.

Remove tokenFallback

tokenFallback hash to be public and that will cause security concerns for RootChain contract.

potentially unbounded validation effort for users

as discussed here: #22

So on the matic sidechain, there can only be one certified ERC20 implementation where none of the token holders can be contracts?
Why allow any other transactions than in these certified ERC20 contracts? wouldn't it just open a window for the operator to flood users with garbage transactions, until users can not keep up to validate everything, then the operator sneaks in invalid state transitions, based on which he can then steal funds from the users?

I think the user can have simple latest state of (if users need it in any form example - Merkle sum as you mentioned) which they need and use it to get data instead of storing the whole chain. You can do same in UTXO (where you keep only unspent TXs).

I understand that you suggest to run a light client by users.

I don't think that is possible, because everyone needs to check all transactions, hence an invalid transfer by some other user can mean that at the end i'll end up in the exit queue while the contract has been emptied already.

Add sol-coverage to the Matic contracts repo

This bounty is to improve test coverage on the Matic contracts repo. The repo contains the following contracts:

For an overview of Matic, see https://blog.matic.network/what-is-matic-network/ and refer https://docs.matic.today/docs/resources/architecture for a basic overview of the 3 major components of Matic - Ethereum contracts, Heimdall and Bor.

Some points to consider:

  • Contracts are deployed on 2 different chains - Ethereum and Matic and there are a few interactions as well.
  • Coverage can be generated separately but we need to run 2 chains(one Ganache and one Bor inside sol-coverage). See https://github.com/maticnetwork/bor for more info.
  • For test purposes, Ganache represents an Ethereum testnet and Bor is the Bor devnet.
  • Ganache part is working fine, but need to figure out the child chain aka Bor contracts part.

Readme is wrong

For "Start Matic side chain" steps

bash start.sh produces the error:

mkdir: /bordata: No such file or directory
Fatal: Failed to read genesis file: open /bordata/genesis.json: no such file or directory
cp: directory /bordata/data does not exist
start.sh: line 18: /bordata/data/node.log: No such file or directory
tail: /bordata/data/node.log: No such file or directory

Split storage and methods

Split storage and methods into the different contracts. That will make contract upgradable, easy to manage and secure.

`npm install` fails

In file included from ../../nan/nan.h:192:
../../nan/nan_maybe_43_inl.h:112:15: error: no member named 'ForceSet' in 'v8::Object'
  return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs);

This is a known issue with older version of nan package (<= 2.7) with newer versions of node (>= 10).

Add rewards and slash amounts

Stakeholders must get rewards for submitting the header blocks periodically.

Following things need to be added

  • Reward amount
  • Slash amount (80%)
  • Challenger rewards (20%)

Slashing the operator if invalid receipt is committed in a checkpoint

If invalid state transitions are committed in a checkpoint, in addition to providing MoreVP constructs to users to mass exit, it should also be possible to slash the operator. The slashed amount can go to the Matic SAFU fund.

This will involve code reuse from the predicates and will involve some work to alter predicate interfaces from slashing.

Refactor test suite

There are some things in test suite that could cause us to overlook some test failures (false positives - positive in this context meaning, a test passes).

  1. Don't use accounts[0] and accounts[1] to run tests.

    • Since these accounts contain ether on genesis, some assertions on their account balances become infeasible.
    • Since these accounts are used by default to deploy contracts, using them within the tests might give them extra privileges. e.g. a method ACLed on onlyOwner will succeed even if that wasn't the intention.
  2. Use HDwalletProvider to instantiate web3 instead of assuming unlocked accounts on ganache / bor.

    • This will enable us to run the test suite against any network. e.g. for testing devnets
  3. Deprecate utils.startExitForErc20PredicateLegacy, utils.startExitNew and any other duplicated flavours of calling exit functions from the tests.

  4. Delete /test-v1. Make sure to migrate any tests before deleting it though.

Optimize testcases

Currently, test cases take too much time as it deploys contracts on each test-case. Make changes such a way that it can be deployed once, and can used as many as times you want.

Add a way to add multiple UTXOs to an exit

Let’s say I have w tokens (of a particular type); and have x, y and z tokens locked in Dapp X, Y and Z respectively on plasma chain. Then when starting an exit, I’ll reference my balance of w tokens and use the X, Y, Z predicates to add inputs to my exit to eventually attempt to exit with w + x + y + z tokens.

Make deposits pause-able

  1. A master switch to pause deposits.
    This is to prevent new users from depositing funds in the plasma contract if something is not right on the side chain.

  2. If a checkpoint has not been submitted for a specified duration, it should be possible to mark the side chain as halted on the root chain. After that no more checkpoints can be submitted and the deposits will be paused as well.

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.