fix: fast exit
MODIFY
package-lock.json
package-lock.json
"requires": {
"mimic-fn": "^2.1.0"
}
- }
- }
},
"webpack-merge": {
- "version": "5.7.3",
- "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.7.3.tgz",
- "integrity": "sha512-6/JUQv0ELQ1igjGDzHkXbVDRxkfA57Zw7PfiupdLFJYrgFqY5ZP8xxbpp2lU3EPwYx89ht5Z/aDkD40hFCm5AA==",
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.8.0.tgz",
+ "integrity": "sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q==",
"dev": true,
"requires": {
"clone-deep": "^4.0.1",
"wildcard": "^2.0.0"
}
+ }
+ }
+ },
+ "webpack-merge": {
+ "version": "4.2.2",
+ "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-4.2.2.tgz",
+ "integrity": "sha512-TUE1UGoTX2Cd42j3krGYqObZbOD+xF7u28WB7tfUordytSjbWTIjK/8V0amkBfTYN4/pB/GIDlJZZ657BGG19g==",
+ "dev": true,
+ "requires": {
+ "lodash": "^4.17.15"
+ }
},
"webpack-sources": {
"version": "1.4.3",

MODIFY
package.json
package.json
"clean": "rimraf lib dist",
"build": "npm run build:dev",
"build:link": "npm run build && npm link",
- "build:webpack": "npm run lint && webpack",
+ "build:webpack": "npm run lint && webpack --config webpack/webpack.node.config.js",
"build:pack": "npm run build:dev && npm pack",
"build:dev": "cross-env NODE_ENV=development npm run build:webpack",
"build:prod": "cross-env NODE_ENV=production npm run build:webpack",
"typescript": "^3.8.3",
"web3": "^1.5.0",
"webpack": "^4.43.0",
- "webpack-cli": "^4.2.0"
+ "webpack-cli": "^4.2.0",
+ "webpack-merge": "^4.2.2"
},
"peerDependencies": {
"web3": "^1.5.0"

MODIFY
src/pos/exit_manager.ts
src/pos/exit_manager.ts
@@ -5,7 +5,7 @@ import assert from "assert";
import BN from "bn.js";
import ethUtils from "ethereumjs-util";
import { ITransactionOption, ITransactionReceipt } from "src/interfaces";
-import { NetworkService } from "../services";
+import { service } from "../services";
interface IChainBlockInfo {
lastChildBlock: string;
@@ -56,8 +56,9 @@ export class ExitManager {
default:
logIndex = receipt.logs.findIndex(log => log.topics[0].toLowerCase() === logEventSig.toLowerCase());
}
-
- assert.ok(logIndex > -1, 'Log not found in receipt');
+ if (logIndex < 0) {
+ throw new Error("Log not found in receipt");
+ }
return logIndex;
}
@@ -102,16 +103,16 @@ export class ExitManager {
}
private async getRootBlockInfoFromAPI(txBlockNumber: number) {
- const service = new NetworkService(
- this.rootChain['client'].metaNetwork.Matic.NetworkAPI
- );
try {
+ console.log("block info from API 1");
const headerBlock = await service.getBlockIncluded(txBlockNumber);
+ console.log("block info from API 2", headerBlock);
if (!headerBlock || !headerBlock.start || !headerBlock.end || !headerBlock.headerBlockNumber) {
throw Error('Network API Error');
}
return headerBlock;
} catch (err) {
+ console.log("block info from API", err);
return this.getRootBlockInfo(txBlockNumber);
}
}
@@ -126,9 +127,7 @@ export class ExitManager {
}
private async getBlockProofFromAPI(txBlockNumber: number, rootBlockInfo: { start, end }) {
- const service = new NetworkService(
- this.rootChain['client'].metaNetwork.Matic.NetworkAPI
- );
+
try {
const blockProof = await service.getProof(
rootBlockInfo.start, rootBlockInfo.end,
@@ -137,6 +136,7 @@ export class ExitManager {
if (!blockProof) {
throw Error('Network API Error');
}
+ console.log("block proof from API 1");
return blockProof;
} catch (err) {
return this.getBlockProof(txBlockNumber, rootBlockInfo);

MODIFY
src/pos/index.ts
src/pos/index.ts
@@ -5,6 +5,7 @@ import { IPOSClientConfig } from "../interfaces";
import { LOGGER } from "../constant";
import { ExitManager } from "./exit_manager";
import { RootChain } from "./root_chain";
+import { initService } from "../services";
export class POSClient {
@@ -20,6 +21,7 @@ export class POSClient {
const mainPOSContracts = this.client_.mainPOSContracts;
+ initService(this.client_.metaNetwork.Matic.NetworkAPI);
config = Object.assign(
{

MODIFY
src/services/index.ts
src/services/index.ts
import { HttpRequest } from "../utils";
import BN from "bn.js";
-export class NetworkService {
+class NetworkService {
httpRequest: HttpRequest;
constructor(baseUrl: string) {
@@ -9,7 +9,7 @@ export class NetworkService {
}
getBlockIncluded(blockNumber: number) {
- const url = `block-included/${blockNumber}`;
+ const url = `/block-included/${blockNumber}`;
return this.httpRequest.get<{
start: string;
end: string;
@@ -22,11 +22,17 @@ export class NetworkService {
}
getProof(start, end, blockNumber) {
- const url = `fast-merkle-proof?start=${start}&end=${end}&number=${blockNumber}`;
+ const url = `/fast-merkle-proof?start=${start}&end=${end}&number=${blockNumber}`;
return this.httpRequest.get<any>(url).then(result => {
return result.proof;
});
}
}
+export let service: NetworkService;
+
+export const initService = (url: string) => {
+ service = new NetworkService(url);
+};
+

MODIFY
src/utils/http_request.ts
src/utils/http_request.ts
+const fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response> =
+ (() => {
+ if (process.env.BUILD_ENV === "node") {
+ return require('node-fetch').default;
+ }
+ return window.fetch;
+ })();
+
+
export class HttpRequest {
baseUrl = "";
- private fetch_: (input: RequestInfo, init?: RequestInit) => Promise<Response> = window ? window.fetch : require('node-fetch');
constructor(option: { baseUrl: string } | string = {} as any) {
option = typeof option === "string" ? {
@@ -16,7 +24,7 @@ export class HttpRequest {
url = this.baseUrl + url + Object.keys(query).
map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`).join('&');
- return this.fetch_(url, {
+ return fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
@@ -30,7 +38,7 @@ export class HttpRequest {
post(url = "", body) {
url = this.baseUrl + url;
- return this.fetch_(url, {
+ return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',

MODIFY
test/debug.js
test/debug.js
@@ -65,11 +65,11 @@ const execute = async () => {
'0xbb7670ba7bf40f0f2909b544e78bbf9dca8b666e28f74ffdf9beda6726e164bd',
'0xa712bfe19bc53825da425f50276a84f72f85c9f660c28c88f3a4d7a2b03a3415',
]
- const exitHash = exitHashes[1];
+ const exitHash = exitHashes[2];
// const isCheckPointed = await maticPOS.isCheckPointed(exitHash);
// const isCheckPointed = await parentErc20.isCheckPointed(exitHash);
// return console.log("isCheckPointed", isCheckPointed);
- const exitResult = await parentErc20.withdrawExit(exitHash);
+ const exitResult = await parentErc20.withdrawExitFaster(exitHash);
// console.log("isExited", exitResult)
console.log('txHash', await exitResult.getTransactionHash());
console.log('receipt', await exitResult.getReceipt());

MODIFY
webpack.config.js
webpack.config.js
@@ -9,7 +9,7 @@ const isProd = mode === 'production'
console.log('build runing for mode', mode)
-const clientConfig = {
+const baseConfig = {
mode,
devtool: 'source-map',
entry: `${__dirname}/src/index.ts`,
@@ -56,10 +56,18 @@ const clientConfig = {
patterns: [{ from: path.resolve('build_helper', 'npm.export.js'), to: '' }],
}),
],
-}
+};
+
+const libraryTarget = [{
+ type: "umd",
+ name: `${libraryName}.umd${isProd ? '.min' : ''}.js`
+}, {
+ type: "commonjs2",
+ name: `${libraryName}.node${isProd ? '.min' : ''}.js`
+}];
const serverConfig = {
- ...clientConfig,
+ ...baseConfig,
target: 'node',
output: {
path: `${__dirname}/dist`,
@@ -70,13 +78,13 @@ const serverConfig = {
}
const standaloneConfig = {
- ...clientConfig,
+ ...baseConfig,
output: {
- ...clientConfig.output,
+ ...baseConfig.output,
library: 'Matic',
filename: `${libraryName}${isProd ? '.min' : ''}.js`,
},
externals: {},
}
-module.exports = [clientConfig, serverConfig, standaloneConfig]
+module.exports = [baseConfig, serverConfig, standaloneConfig]

ADD
webpack/webpack.base.config.js
+const path = require('path')
+const copyPlugin = require('copy-webpack-plugin')
+
+const libraryName = 'matic'
+exports.libraryName = libraryName;
+let mode = process.env.NODE_ENV
+const isProd = mode === 'production'
+exports.isProd = isProd;
+
+console.log('build runing for mode', mode);
+exports.default = {
+ mode,
+ devtool: 'source-map',
+ entry: `./src/index.ts`,
+ target: 'web',
+ output: {
+ path: path.join(__dirname, "./../dist"),
+ filename: `${libraryName}.umd${isProd ? '.min' : ''}.js`,
+ library: libraryName,
+ libraryTarget: 'umd',
+ libraryExport: 'default',
+ umdNamedDefine: true,
+ },
+ module: {
+ rules: [
+ {
+ test: /\.ts$/,
+ use: 'ts-loader',
+ exclude: /node_modules/,
+ },
+ ],
+ },
+ externals: {
+ web3: 'web3',
+ 'ethereumjs-util': 'ethereumjs-util',
+ 'query-string': 'query-string',
+ 'bn.js': 'bn.js',
+ axios: 'axios',
+ '@maticnetwork/meta/network': '@maticnetwork/meta/network',
+ 'ethereumjs-tx': 'ethereumjs-tx',
+ 'ethereumjs-util': 'ethereumjs-util',
+ 'merkle-patricia-tree': 'merkle-patricia-tree',
+ 'ethereumjs-block': 'ethereumjs-block',
+ 'eth-sig-util': 'eth-sig-util',
+ },
+ resolve: {
+ modules: [path.resolve(__dirname, 'src'), 'node_modules'],
+ extensions: ['.json', '.js', '.ts', 'tsx'],
+ alias: {
+ // "@": path.resolve(__dirname, "./src")
+ },
+ },
+ plugins: [
+ new copyPlugin({
+ patterns: [{ from: path.resolve('build_helper', 'npm.export.js'), to: '' }],
+ }),
+ ],
+}
\ No newline at end of file

ADD
webpack/webpack.node.config.js
+const webpackMerge = require("webpack-merge");
+const { default: webpackBaseConfig, libraryName, isProd } = require("./webpack.base.config");
+var webpack = require('webpack');
+
+exports.default = webpackMerge(webpackBaseConfig, {
+ target: 'node',
+ output: {
+ filename: `${libraryName}.node${isProd ? '.min' : ''}.js`,
+ // globalObject: 'this',
+ libraryTarget: 'commonjs2',
+ },
+ plugins: [
+ new webpack.DefinePlugin({
+ 'process.env.BUILD_ENV': JSON.stringify("node")
+ }),
+ ],
+})
\ No newline at end of file

fix: fast exit