diff --git a/src/data/allchain.ts b/src/data/allchain.ts index d309ec2..c419d1b 100644 --- a/src/data/allchain.ts +++ b/src/data/allchain.ts @@ -1,293 +1,293 @@ export const AllChains = [ { - name: "Ethereum Mainnet RPC", - type: "Mainnet", - rpc: "https://rpc.ankr.com/eth", + name: 'Ethereum Mainnet RPC', + type: 'Mainnet', + rpc: 'https://rpc.ankr.com/eth', id: 1, - symbol: "ETH", - explorerurl: "https://etherscan.io", + symbol: 'ETH', + explorerurl: 'https://etherscan.io', }, { - name: "Ethereum Ropsten Testnet RPC", - type: "Testnet", - rpc: "https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", + name: 'Ethereum Ropsten Testnet RPC', + type: 'Testnet', + rpc: 'https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161', id: 3, - symbol: "ETH", - explorerurl: "https://ropsten.etherscan.io", + symbol: 'ETH', + explorerurl: 'https://ropsten.etherscan.io', }, { - name: "Ethereum Rinkeby Testnet RPC", - type: "Testnet", - rpc: "https://rinkey.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", + name: 'Ethereum Rinkeby Testnet RPC', + type: 'Testnet', + rpc: 'https://rinkey.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161', id: 4, - symbol: "ETH", - explorerurl: "https://rinkey.etherscan.io", + symbol: 'ETH', + explorerurl: 'https://rinkey.etherscan.io', }, { - name: "Ethereum Goerli Testnet RPC", - type: "Testnet", - rpc: "https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", + name: 'Ethereum Goerli Testnet RPC', + type: 'Testnet', + rpc: 'https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161', id: 5, - symbol: "ETH", - explorerurl: "https://goerli.etherscan.io", + symbol: 'ETH', + explorerurl: 'https://goerli.etherscan.io', }, { - name: "Ethereum Kovan Testnet RPC", - type: "Testnet", - rpc: "https://kovan.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", + name: 'Ethereum Kovan Testnet RPC', + type: 'Testnet', + rpc: 'https://kovan.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161', id: 6, - symbol: "ETH", - explorerurl: "https://kovan.etherscan.io", + symbol: 'ETH', + explorerurl: 'https://kovan.etherscan.io', }, { - name: "Ubiq Mainnet RPC", - type: "Mainnet", - rpc: "https://rpc.octano.dev/", + name: 'Ubiq Mainnet RPC', + type: 'Mainnet', + rpc: 'https://rpc.octano.dev/', id: 8, - symbol: "UBQ", - explorerurl: "https://ubiqscan.io/", + symbol: 'UBQ', + explorerurl: 'https://ubiqscan.io/', }, { - name: "Elastos ETH Mainnet RPC", - type: "Mainnet", - rpc: "https://api.elastos.io/eth", + name: 'Elastos ETH Mainnet RPC', + type: 'Mainnet', + rpc: 'https://api.elastos.io/eth', id: 20, - symbol: "ELA", - explorerurl: "https://explorer.elaeth.io/", + symbol: 'ELA', + explorerurl: 'https://explorer.elaeth.io/', }, { - name: "Cronos Mainnet RPC", - type: "Mainnet", - rpc: "https://evm-cronos.crypto.org", + name: 'Cronos Mainnet RPC', + type: 'Mainnet', + rpc: 'https://evm-cronos.crypto.org', id: 25, - symbol: "CRO", - explorerurl: "https://cronos.crypto.org/explorer/", + symbol: 'CRO', + explorerurl: 'https://cronos.crypto.org/explorer/', }, { - name: "Telos EVM Mainnet RPC", - type: "Mainnet", - rpc: "https://mainnet.telos.net/evm", + name: 'Telos EVM Mainnet RPC', + type: 'Mainnet', + rpc: 'https://mainnet.telos.net/evm', id: 40, - symbol: "TLOS", - explorerurl: "https://telos.net/", + symbol: 'TLOS', + explorerurl: 'https://telos.net/', }, { - name: "Binance Smart Chain", - type: "Mainnet", - rpc: "https://rpc.ankr.com/bsc", + name: 'Binance Smart Chain', + type: 'Mainnet', + rpc: 'https://rpc.ankr.com/bsc', id: 56, - symbol: "BNB", - explorerurl: "https://bscscan.com", + symbol: 'BNB', + explorerurl: 'https://bscscan.com', }, { - name: "OKExChain Mainnet RPC", - type: "Mainnet", - rpc: "https://exchainrpc.okex.org", + name: 'OKExChain Mainnet RPC', + type: 'Mainnet', + rpc: 'https://exchainrpc.okex.org', id: 66, - symbol: "OKT", - explorerurl: "https://www.oklink.com/okexchain", + symbol: 'OKT', + explorerurl: 'https://www.oklink.com/okexchain', }, { - name: "Hoo Mainnet RPC", - type: "Mainnet", - rpc: "https://http-mainnet.hoosmartchain.com", + name: 'Hoo Mainnet RPC', + type: 'Mainnet', + rpc: 'https://http-mainnet.hoosmartchain.com', id: 70, - symbol: "HOO", - explorerurl: "https://hooscan.com", + symbol: 'HOO', + explorerurl: 'https://hooscan.com', }, { - name: "Binance Testnet", - type: "Testnet", - rpc: "https://data-seed-prebsc-1-s1.binance.org:8545/", + name: 'Binance Testnet', + type: 'Testnet', + rpc: 'https://data-seed-prebsc-1-s1.binance.org:8545/', id: 97, - symbol: "BNB", - explorerurl: "https://testnet.bscscan.com", + symbol: 'BNB', + explorerurl: 'https://testnet.bscscan.com', }, { - name: "xDai Mainnet RPC", - type: "Mainnet", - rpc: "https://rpc.xdaichain.com/", + name: 'xDai Mainnet RPC', + type: 'Mainnet', + rpc: 'https://rpc.xdaichain.com/', id: 100, - symbol: "XDAI", - explorerurl: "https://blockscout.com/xdai/mainnet/", + symbol: 'XDAI', + explorerurl: 'https://blockscout.com/xdai/mainnet/', }, { - name: "Fuse Mainnet RPC", - type: "Mainnet", - rpc: "https://rpc.fuse.io", + name: 'Fuse Mainnet RPC', + type: 'Mainnet', + rpc: 'https://rpc.fuse.io', id: 122, - symbol: "FUSE", - explorerurl: "https://explorer.fuse.io/", + symbol: 'FUSE', + explorerurl: 'https://explorer.fuse.io/', }, { - name: "HECO Mainnet RPC", - type: "Mainnet", - rpc: "https://http-mainnet-node.huobichain.com/", + name: 'HECO Mainnet RPC', + type: 'Mainnet', + rpc: 'https://http-mainnet-node.huobichain.com/', id: 128, - symbol: "HT", - explorerurl: "https://hecoinfo.com/", + symbol: 'HT', + explorerurl: 'https://hecoinfo.com/', }, { - name: "Matic Mainnet RPC", - type: "Mainnet", - rpc: "https://polygon-rpc.com", + name: 'Matic Mainnet RPC', + type: 'Mainnet', + rpc: 'https://polygon-rpc.com', id: 137, - symbol: "MATIC", - explorerurl: "https://explorer.matic.network/", + symbol: 'MATIC', + explorerurl: 'https://explorer.matic.network/', }, { - name: "Fantom Opera Mainnet RPC", - type: "Mainnet", - rpc: "https://rpc.ftm.tools/", + name: 'Fantom Opera Mainnet RPC', + type: 'Mainnet', + rpc: 'https://rpc.ftm.tools/', id: 250, - symbol: "FTM", - explorerurl: "https://ftmscan.com", + symbol: 'FTM', + explorerurl: 'https://ftmscan.com', }, { - name: "HECO Testnet RPC", - type: "Testnet", - rpc: "https://http-testnet.hecochain.com", + name: 'HECO Testnet RPC', + type: 'Testnet', + rpc: 'https://http-testnet.hecochain.com', id: 256, - symbol: "HT", - explorerurl: "https://testnet.hecoinfo.com/", + symbol: 'HT', + explorerurl: 'https://testnet.hecoinfo.com/', }, { - name: "KCC Mainnet", - type: "Mainnet", - rpc: "https://rpc-mainnet.kcc.network", + name: 'KCC Mainnet', + type: 'Mainnet', + rpc: 'https://rpc-mainnet.kcc.network', id: 321, - symbol: "KCS", - explorerurl: "https://scan.kcc.network", + symbol: 'KCS', + explorerurl: 'https://scan.kcc.network', }, { - name: "KCC Testnet", - type: "Testnet", - rpc: "https://rpc-testnet.kcc.network", + name: 'KCC Testnet', + type: 'Testnet', + rpc: 'https://rpc-testnet.kcc.network', id: 322, - symbol: "tKCS", - explorerurl: "https://scan-testnet.kcc.network", + symbol: 'tKCS', + explorerurl: 'https://scan-testnet.kcc.network', }, { - name: "Moonriver Mainnet RPC", - type: "Mainnet", - rpc: "https://rpc.moonriver.moonbeam.network", + name: 'Moonriver Mainnet RPC', + type: 'Mainnet', + rpc: 'https://rpc.moonriver.moonbeam.network', id: 1285, - symbol: "MOVR", - explorerurl: "https://blockscout.moonriver.moonbeam.network/", + symbol: 'MOVR', + explorerurl: 'https://blockscout.moonriver.moonbeam.network/', }, { - name: "Fantom Testnet RPC", - type: "Testnet", - rpc: "https://rpc.testnet.fantom.network/", + name: 'Fantom Testnet RPC', + type: 'Testnet', + rpc: 'https://rpc.testnet.fantom.network/', id: 4002, - symbol: "FTM", - explorerurl: "https://testnet.ftmscan.com", + symbol: 'FTM', + explorerurl: 'https://testnet.ftmscan.com', }, { - name: "IoTeX Mainnet RPC", - type: "Mainnet", - rpc: "https://babel-api.mainnet.iotex.io", + name: 'IoTeX Mainnet RPC', + type: 'Mainnet', + rpc: 'https://babel-api.mainnet.iotex.io', id: 4689, - symbol: "IOTEX", - explorerurl: "https://iotexscan.io/", + symbol: 'IOTEX', + explorerurl: 'https://iotexscan.io/', }, { - name: "Nahmii Mainnet RPC", - type: "Mainnet", - rpc: "https://l2.nahmii.io/", + name: 'Nahmii Mainnet RPC', + type: 'Mainnet', + rpc: 'https://l2.nahmii.io/', id: 5551, - symbol: "ETH", - explorerurl: "https://explorer.nahmii.io/", + symbol: 'ETH', + explorerurl: 'https://explorer.nahmii.io/', }, { - name: "Nahmii Testnet RPC", - type: "Testnet", - rpc: "https://l2.testnet.nahmii.io/", + name: 'Nahmii Testnet RPC', + type: 'Testnet', + rpc: 'https://l2.testnet.nahmii.io/', id: 5553, - symbol: "ETH", - explorerurl: "https://explorer.testnet.nahmii.io/", + symbol: 'ETH', + explorerurl: 'https://explorer.testnet.nahmii.io/', }, { - name: "Arbitrum One", - type: "Mainnet", - rpc: "https://rpc.ankr.com/arbitrum", + name: 'Arbitrum One', + type: 'Mainnet', + rpc: 'https://arb1.arbitrum.io/rpc', id: 42161, - network: "ARBITRUM", - symbol: "ETH", - explorerurl: "https://arbiscan.io/", + network: 'ARBITRUM', + symbol: 'ETH', + explorerurl: 'https://arbiscan.io/', }, { - name: "Arbitrum Goerli", - type: "Testnet", - rpc: "https://endpoints.omniatech.io/v1/arbitrum/goerli/public", + name: 'Arbitrum Goerli', + type: 'Testnet', + rpc: 'https://endpoints.omniatech.io/v1/arbitrum/goerli/public', id: 421613, - network: "AGOR", - symbol: "AGOR", - explorerurl: "https://testnet.arbiscan.io", + network: 'AGOR', + symbol: 'AGOR', + explorerurl: 'https://testnet.arbiscan.io', }, { - name: "Celo Mainnet RPC", - type: "Mainnet", - rpc: "https://rpc.ankr.com/celo", + name: 'Celo Mainnet RPC', + type: 'Mainnet', + rpc: 'https://rpc.ankr.com/celo', id: 42220, - symbol: "CELO", - explorerurl: "https://celoscan.com", + symbol: 'CELO', + explorerurl: 'https://celoscan.com', }, { - name: "Avalanche C Chain Local RPC", - type: "Testnet", - rpc: "https://localhost:9650/ext/bc/C/rpc", + name: 'Avalanche C Chain Local RPC', + type: 'Testnet', + rpc: 'https://localhost:9650/ext/bc/C/rpc', id: 43112, - symbol: "AVAX", - explorerurl: "https://snowtrace.io", + symbol: 'AVAX', + explorerurl: 'https://snowtrace.io', }, { - name: "Avalanche FUJI Testnet RPC", - type: "Testnet", - rpc: "https://api.avax-test.network/ext/bc/C/rpc", + name: 'Avalanche FUJI Testnet RPC', + type: 'Testnet', + rpc: 'https://api.avax-test.network/ext/bc/C/rpc', id: 43113, - symbol: "AVAX", - explorerurl: "https://testnet.explorer.avax.network/", + symbol: 'AVAX', + explorerurl: 'https://testnet.explorer.avax.network/', }, { - name: "Avalanche C Chain Mainnet RPC", - type: "Mainnet", - rpc: "https://rpc.ankr.com/avalanche", + name: 'Avalanche C Chain Mainnet RPC', + type: 'Mainnet', + rpc: 'https://rpc.ankr.com/avalanche', id: 43114, - symbol: "AVAX", - explorerurl: "https://snowtrace.io", + symbol: 'AVAX', + explorerurl: 'https://snowtrace.io', }, { - name: "Matic Testnet RPC", - type: "Testnet", - rpc: "https://rpc-mumbai.maticvigil.com", + name: 'Matic Testnet RPC', + type: 'Testnet', + rpc: 'https://rpc-mumbai.maticvigil.com', id: 80001, - symbol: "MATIC", - explorerurl: "https://mumbai.polygonscan.com/", + symbol: 'MATIC', + explorerurl: 'https://mumbai.polygonscan.com/', }, { - name: "Harmony Mainnet RPC", - type: "Mainnet", - rpc: "https://api.harmony.one/", + name: 'Harmony Mainnet RPC', + type: 'Mainnet', + rpc: 'https://api.harmony.one/', id: 1666600000, - symbol: "ONE", - explorerurl: "https://explorer.harmony.one", + symbol: 'ONE', + explorerurl: 'https://explorer.harmony.one', }, { - name: "Harmony Testnet RPC", - type: "Testnet", - rpc: "https://api.s0.b.hmny.io/", + name: 'Harmony Testnet RPC', + type: 'Testnet', + rpc: 'https://api.s0.b.hmny.io/', id: 1666700000, - symbol: "ONE", - explorerurl: "https://explorer.harmony.one", + symbol: 'ONE', + explorerurl: 'https://explorer.harmony.one', }, { - name: "Local Testnet", - type: "Local", - rpc: "https://login-test.kingsome.cn/rpc", + name: 'Local Testnet', + type: 'Local', + rpc: 'https://login-test.kingsome.cn/rpc', id: 1338, - symbol: "ETH", - explorerurl: "https://explorer.harmony.one", + symbol: 'ETH', + explorerurl: 'https://explorer.harmony.one', }, ]; diff --git a/src/index.ts b/src/index.ts index 5c5e1ca..a60381f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,56 +1,34 @@ -import { - recoverTypedSignature, - signTypedData, - SignTypedDataVersion, -} from "@metamask/eth-sig-util"; -import Web3 from "web3"; -import "whatwg-fetch"; -import { - createWalletEvents, - WALLET_ACCOUNT_CHANGE, - WALLET_CHAIN_CHANGE, -} from "./common/WalletEvent"; -import { JazzIcon } from "./comp/JazzIcon"; -import { ZWalletConnect } from "./comp/ZWalletConnect"; -import { - AVAILABLE_CHAINS, - NATIVE_PK_PREFIX, - TX_CONFIRM_BLOCKS, - WALLET_STORAGE_KEY_NAME, -} from "./config/constants"; -import { AllChains } from "./data/allchain"; -import { singleton } from "./decorator/singleton.decorator"; -import { parseUrl } from "./manage/SchemeManage"; -import { - exportSecKey, - loadInternalWallet, - loginByEmail, - verifyPassword, - walletPreLogin, -} from "./manage/WalletManage"; -import { EmailVerifySvr } from "./services/EmailVerifySvr"; -import { NativeSvr } from "./services/NativeSvr"; -import { PaySvr } from "./services/PaySvr"; -import { TranHistorySvr } from "./services/TranHistorySvr"; -import { ChainCommon } from "./standards/ChainCommon"; -import { ERC1155Standard } from "./standards/ERC1155Standard"; -import { ERC20Standard } from "./standards/ERC20Standard"; -import { ERC721Standard } from "./standards/ERC721Standard"; -import { JCStandard } from "./standards/JCStandard"; -import { WalletType } from "./types/data.enums"; -import { IChainData } from "./types/data.types"; -import { universalChainCb } from "./util/chain.util"; -import { - fromTokenMinimalUnit, - renderFromTokenMinimalUnit, - safeNumberToBN, -} from "./util/number.util"; -import { buildLoginSignMsg, signLogin } from "./util/sign.util"; +import { recoverTypedSignature, signTypedData, SignTypedDataVersion } from '@metamask/eth-sig-util'; +import Web3 from 'web3'; +import 'whatwg-fetch'; +import { createWalletEvents, WALLET_ACCOUNT_CHANGE, WALLET_CHAIN_CHANGE } from './common/WalletEvent'; +import { JazzIcon } from './comp/JazzIcon'; +import { ZWalletConnect } from './comp/ZWalletConnect'; +import { AVAILABLE_CHAINS, NATIVE_PK_PREFIX, TX_CONFIRM_BLOCKS, WALLET_STORAGE_KEY_NAME } from './config/constants'; +import { AllChains } from './data/allchain'; +import { singleton } from './decorator/singleton.decorator'; +import { parseUrl } from './manage/SchemeManage'; +import { exportSecKey, loadInternalWallet, loginByEmail, verifyPassword, walletPreLogin } from './manage/WalletManage'; +import { EmailVerifySvr } from './services/EmailVerifySvr'; +import { NativeSvr } from './services/NativeSvr'; +import { PaySvr } from './services/PaySvr'; +import { TranHistorySvr } from './services/TranHistorySvr'; +import { ChainCommon } from './standards/ChainCommon'; +import { ERC1155Standard } from './standards/ERC1155Standard'; +import { ERC20Standard } from './standards/ERC20Standard'; +import { ERC721Standard } from './standards/ERC721Standard'; +import { JCStandard } from './standards/JCStandard'; +import { WalletType } from './types/data.enums'; +import { IChainData } from './types/data.types'; +import { universalChainCb } from './util/chain.util'; +import { fromTokenMinimalUnit, renderFromTokenMinimalUnit, safeNumberToBN } from './util/number.util'; +import { buildLoginSignMsg, signLogin } from './util/sign.util'; +import { parse } from 'url'; var global = - (typeof globalThis !== "undefined" && globalThis) || - (typeof self !== "undefined" && self) || - (typeof global !== "undefined" && global) || + (typeof globalThis !== 'undefined' && globalThis) || + (typeof self !== 'undefined' && self) || + (typeof global !== 'undefined' && global) || {}; window.debug = true; @@ -59,7 +37,7 @@ window.debug = true; export default class JCWallet { web3: Web3 = null; private wallet: any = null; - private password: string = "111111"; + private password: string = '111111'; private chainSet: Set = new Set(); private chainMap: Map = new Map(); private _currentChain: IChainData; @@ -73,12 +51,12 @@ export default class JCWallet { public emailVerifySvr: EmailVerifySvr; public paySvr: PaySvr; public wConnect: ZWalletConnect; - public mainHandlers = createWalletEvents(); private walletType: WalletType = WalletType.INTERNAL; - private rpcUrl: string = ""; + private rpcUrl: string = ''; public rpc: any = {}; - public nativeAccount = ""; - private env = "dev"; + public nativeAccount = ''; + private env = 'dev'; + private web3Map = new Map(); constructor({ type }: { type: number }) { this.nativeSvr = new NativeSvr(); @@ -94,7 +72,7 @@ export default class JCWallet { chain = chain || 80001; let data = this.chainMap.get(chain); if (!data) { - throw new Error("no current chain data"); + throw new Error('no current chain data'); } this._currentChain = data; this.rpcUrl = data.rpc; @@ -121,42 +99,32 @@ export default class JCWallet { return loginByEmail(email, password); } - public async initInternalWallet( - chain: number, - pass: string, - env: string = "dev" - ) { + public async initInternalWallet(chain: number, pass: string, env: string = 'dev') { this.env = env; this.walletType = WalletType.INTERNAL; this.updateChain(chain); let address: string = await loadInternalWallet(pass); this.nativeAccount = address; - console.log("native wallet address: " + address); + console.log('native wallet address: ' + address); var start = Date.now(); - this.web3 = new Web3(this.rpcUrl); - this.web3.eth.transactionConfirmationBlocks = TX_CONFIRM_BLOCKS; + this.web3 = this.generateWeb3(chain); console.log(`init web3 cost: ${(Date.now() - start) / 1000}s`); this.erc20Standard = new ERC20Standard(this.web3); - console.log("init Erc20Standard"); + console.log('init Erc20Standard'); this.erc721Standard = new ERC721Standard(this.web3); - console.log("init Erc721Standard"); + console.log('init Erc721Standard'); this.erc1155Standard = new ERC1155Standard(this.web3); - console.log("init ERC1155Standard"); + console.log('init ERC1155Standard'); this.jcStandard = new JCStandard(this.web3); this.chainCommon = new ChainCommon(this.web3); - console.log("init JCStandard"); - this.injectAccount(); - console.log(JSON.stringify(this.wallet[0])); - console.log( - "this.web3.eth.defaultAccount: " + - JSON.stringify(this.web3.eth.defaultAccount) - ); + console.log('init JCStandard'); + console.log('this.web3.eth.defaultAccount: ' + JSON.stringify(this.web3.eth.defaultAccount)); } /** * init wallet connect * @returns */ - public async initThirdPartyWallet(chain: number, env: string = "dev") { + public async initThirdPartyWallet(chain: number, env: string = 'dev') { this.env = env; this.walletType = WalletType.THIRD_PATH; this.updateChain(chain); @@ -184,19 +152,19 @@ export default class JCWallet { }) .then((chainId: number) => { if (chainId === this._currentChain.id) { - resolve && resolve(""); + resolve && resolve(''); } else { this.updateCurrentChain(this.currentChain.id) .then(() => { - resolve && resolve(""); + resolve && resolve(''); }) .catch((err) => { - reject && reject("error change network"); + reject && reject('error change network'); }); } }) .catch((err: Error) => { - console.log("initThirdPartyWallet error: " + err); + console.log('initThirdPartyWallet error: ' + err); reject && reject(err.message); }); }); @@ -232,15 +200,14 @@ export default class JCWallet { if (this.walletType === WalletType.INTERNAL) { const chainData = this.chainMap.get(chainId); if (!chainData) { - reject && reject("chain data not found"); + reject && reject('chain data not found'); return; } this._currentChain = chainData; this.web3.eth.setProvider(chainData.rpc); - this.mainHandlers.emit(WALLET_CHAIN_CHANGE, chainData); resolve && resolve(this.currentChain); } else { - console.log("third party wallet change chain: " + chainId); + console.log('third party wallet change chain: ' + chainId); const chainData = this.chainMap.get(chainId); this.wConnect .addOrChangeChain(chainData) @@ -270,6 +237,21 @@ export default class JCWallet { } } + public generateWeb3(chainId: number, isDefault: boolean = true) { + if (this.web3Map.has(chainId)) { + return this.web3Map.get(chainId); + } + const chainData = this.chainMap.get(chainId); + if (!chainData) { + return null; + } + let web3 = new Web3(chainData.rpc); + web3.eth.transactionConfirmationBlocks = TX_CONFIRM_BLOCKS; + this.injectAccount(web3, isDefault); + this.web3Map.set(chainId, web3); + return web3; + } + public get currentAccAddr() { if (this.walletType === WalletType.INTERNAL) { return this.nativeAccount; @@ -278,17 +260,16 @@ export default class JCWallet { } } - public injectAccount() { - this.wallet = this.web3.eth.accounts.wallet; - const nativePrivateKey = `${NATIVE_PK_PREFIX}${this.currentAccAddr.slice( - 2 - )}`; - const acc = this.web3.eth.accounts.privateKeyToAccount(nativePrivateKey); - const account = this.wallet.add(acc); - this.web3.eth.defaultAccount = account.address; - console.log("web3 account: " + JSON.stringify(this.wallet[0])); - this.wallet.save(this.password, WALLET_STORAGE_KEY_NAME); - this.mainHandlers.emit(WALLET_ACCOUNT_CHANGE, account.address); + public injectAccount(web3: any, isDefault: boolean = true) { + const nativePrivateKey = `${NATIVE_PK_PREFIX}${this.currentAccAddr.slice(2)}`; + const acc = web3.eth.accounts.privateKeyToAccount(nativePrivateKey); + const account = web3.eth.accounts.wallet.add(acc); + web3.eth.defaultAccount = account.address; + console.log('web3 account: ' + JSON.stringify(web3.eth.accounts.wallet[0])); + if (isDefault) { + this.wallet = web3.eth.accounts.wallet; + web3.eth.accounts.wallet.save(this.password, WALLET_STORAGE_KEY_NAME); + } return account.address; } @@ -296,11 +277,8 @@ export default class JCWallet { let chainData = this.currentChain; let price = await new PaySvr().getGasPrice(chainData.id); let ehtBN = safeNumberToBN(price).mul(safeNumberToBN(gas)); - let ethSymbol = chainData.type !== "Testnet" ? chainData.symbol : "ETH"; - let network = - chainData.type !== "Testnet" - ? chainData.network || chainData.symbol - : "ETH"; + let ethSymbol = chainData.type !== 'Testnet' ? chainData.symbol : 'ETH'; + let network = chainData.type !== 'Testnet' ? chainData.network || chainData.symbol : 'ETH'; let fiatPrice = await new PaySvr().queryTokenPrice(network, ethSymbol); let priceFloat = parseFloat(fiatPrice) * 100; let fiatPriceBN = safeNumberToBN(priceFloat); @@ -308,6 +286,13 @@ export default class JCWallet { let eth = fromTokenMinimalUnit(ehtBN, 18); return { gas, price, eth, usd }; } + + public async fetchGasPrice() { + let gasPrice = await this.web3.eth.getGasPrice(); + console.log('fetchGasPrice::' + gasPrice); + let gasPriceNum = (parseInt(gasPrice) * 1.3) | 0; + return gasPriceNum + ''; + } /** * 查询token的法币价格 * token 必须已经在去中心化交易所上架 @@ -317,10 +302,7 @@ export default class JCWallet { */ public async calcTokenPrice(tokenName: string, amount: string) { let chainData = this.currentChain; - let network = - chainData.type !== "Testnet" - ? chainData.network || chainData.symbol - : "ETH"; + let network = chainData.type !== 'Testnet' ? chainData.network || chainData.symbol : 'ETH'; let env = this.env; let fiatPrice = await new PaySvr().queryTokenPrice(network, tokenName, env); let priceFloat = parseFloat(fiatPrice); @@ -329,11 +311,11 @@ export default class JCWallet { public async sendEth(to: string, amount: number | string, estimate: number) { let from = this.currentAccAddr; - const amountToSend = this.web3.utils.toWei(amount + "", "ether"); + const amountToSend = this.web3.utils.toWei(amount + '', 'ether'); let gas = await this.web3.eth.estimateGas({ from, to, - value: "0", + value: '0', }); if (estimate) { return this.generateGasShow(gas); @@ -346,14 +328,14 @@ export default class JCWallet { }; const logData = { gas, - title: "transfer", + title: 'transfer', details: [ { - address: "eth", + address: 'eth', from, to, value: amountToSend, - id: "0", + id: '0', }, ], }; @@ -361,7 +343,7 @@ export default class JCWallet { } public async getBalance(account?: string) { - console.log("get balance with address: ", account); + console.log('get balance with address: ', account); let balance = await this.chainCommon.getBalance(account); return balance; } @@ -370,7 +352,7 @@ export default class JCWallet { const account = this.currentAccount(); return signTypedData({ data: signObj, - privateKey: Buffer.from(account.privateKey.replace("0x", ""), "hex"), + privateKey: Buffer.from(account.privateKey.replace('0x', ''), 'hex'), version: SignTypedDataVersion.V4, }); } @@ -430,12 +412,7 @@ export default class JCWallet { return result; } - public async sendErc20( - address: string, - to: string, - amount: string, - estimate: number - ) { + public async sendErc20(address: string, to: string, amount: string, estimate: number) { let from = this.currentAccAddr; let result = await this.erc20Standard.transfer({ address, @@ -447,12 +424,7 @@ export default class JCWallet { return result; } - public async sendNFT( - address: string, - to: string, - tokenId: string, - estimate: number - ) { + public async sendNFT(address: string, to: string, tokenId: string, estimate: number) { let from = this.currentAccAddr; return this.erc721Standard.transfer({ address, @@ -463,16 +435,8 @@ export default class JCWallet { }); } - public async erc1155Balance( - address: string, - account: string, - tokenId: string - ) { - let result = await this.erc1155Standard.getBalanceOf( - address, - account, - tokenId - ); + public async erc1155Balance(address: string, account: string, tokenId: string) { + let result = await this.erc1155Standard.getBalanceOf(address, account, tokenId); return result; } @@ -484,13 +448,7 @@ export default class JCWallet { } } - public async sendErc1155( - address: string, - to: string, - tokenIds: string[], - amounts: string[], - estimate: number - ) { + public async sendErc1155(address: string, to: string, tokenIds: string[], amounts: string[], estimate: number) { let from = this.currentAccAddr; return this.erc1155Standard.transferBatch({ address, @@ -503,9 +461,9 @@ export default class JCWallet { } public async scanQr(title: string) { - let result = (await this.nativeSvr.scanQRCode(title)) + ""; - console.log("scan qr code: " + result); - if (result && result.indexOf("://") >= 0) { + let result = (await this.nativeSvr.scanQRCode(title)) + ''; + console.log('scan qr code: ' + result); + if (result && result.indexOf('://') >= 0) { parseUrl(result); } return result; @@ -514,8 +472,8 @@ export default class JCWallet { // window.jc = window.jc || {wallet: new JCWallet()}; -export * from "./common/WalletEvent"; -export * from "./common/ZError"; -export * from "./lib/WalletConnect"; -export * from "./util/number.util"; -export * from "./util/wallet.util"; +export * from './common/WalletEvent'; +export * from './common/ZError'; +export * from './lib/WalletConnect'; +export * from './util/number.util'; +export * from './util/wallet.util'; diff --git a/src/standards/ChainCommon.ts b/src/standards/ChainCommon.ts index 69a3610..775d906 100644 --- a/src/standards/ChainCommon.ts +++ b/src/standards/ChainCommon.ts @@ -1,5 +1,5 @@ -import Web3 from "web3"; -import { BN } from "ethereumjs-util"; +import Web3 from 'web3'; +import { BN } from 'ethereumjs-util'; export const SAMPLE_GAS = 1000000; @@ -13,9 +13,9 @@ export class ChainCommon { public async checkEthEnough(gas: string, address?: string) { address = address || jc.wallet.currentAccAddr; let gasPrice = await this.web3.eth.getGasPrice(); - console.log("gasPrice: " + new BN(gasPrice)); + console.log('gasPrice: ' + new BN(gasPrice)); let balance = await this.web3.eth.getBalance(address); - console.log("eth balance: " + new BN(balance)); + console.log('eth balance: ' + new BN(balance)); return new BN(balance).gte(new BN(gasPrice).mul(new BN(gas))); } diff --git a/src/standards/ERC1155Standard.ts b/src/standards/ERC1155Standard.ts index 4652d8f..820e9c9 100644 --- a/src/standards/ERC1155Standard.ts +++ b/src/standards/ERC1155Standard.ts @@ -200,7 +200,7 @@ export class ERC1155Standard { title: 'transfer', details: detailArr, }; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); return universalChainCb( logData, contract.methods.safeBatchTransferFrom(from, to, tokenIds, amounts, []).send({ diff --git a/src/standards/ERC20Standard.ts b/src/standards/ERC20Standard.ts index e1598b2..2a59315 100644 --- a/src/standards/ERC20Standard.ts +++ b/src/standards/ERC20Standard.ts @@ -176,7 +176,7 @@ export class ERC20Standard { }, ], }; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); return universalChainCb( logData, contract.methods.transfer(to, amountBN).send({ diff --git a/src/standards/ERC721Standard.ts b/src/standards/ERC721Standard.ts index 4167cbb..a1e2fe4 100644 --- a/src/standards/ERC721Standard.ts +++ b/src/standards/ERC721Standard.ts @@ -68,8 +68,12 @@ export class ERC721Standard { }); }; - getBalance = async (address: string, selectedAddress: string): Promise => { - const contract = new this.web3.eth.Contract(abiERC721, address); + getBalance = async (address: string, selectedAddress: string, chainId?: string): Promise => { + let web3 = this.web3; + if (chainId && parseInt(chainId) !== jc.wallet.currentChain.id) { + web3 = jc.wallet.generateWeb3(parseInt(chainId), false); + } + const contract = new web3.eth.Contract(abiERC721, address); return new Promise((resolve, reject) => { contract.methods.balanceOf(selectedAddress).call((error: Error, result: number) => { /* istanbul ignore if */ @@ -290,7 +294,7 @@ export class ERC721Standard { }, ], }; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); return universalChainCb( logData, contract.methods.safeTransferFrom(from, to, tokenId).send({ diff --git a/src/standards/JCStandard.ts b/src/standards/JCStandard.ts index 9e128d3..fbd3474 100644 --- a/src/standards/JCStandard.ts +++ b/src/standards/JCStandard.ts @@ -69,7 +69,7 @@ export class JCStandard { title: 'mint_nft', details: details, }; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); return universalChainCb( logData, contract.methods.mintNft(address, tokenIds, startTime, saltNonce, signature).send({ gas, gasPrice }) @@ -107,7 +107,7 @@ export class JCStandard { }); let approved = await tokenInstance.methods.getApproved(tokenId); let gasApprove = 0; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); if (approved != addressMarket) { gasApprove = await tokenInstance.methods.approve(addressMarket, tokenId).estimateGas(); gasApprove = (gasApprove * GAS_BOOST) | 1; @@ -187,7 +187,7 @@ export class JCStandard { title: 'market_update_price', details: details, }; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); return universalChainCb(logData, contract.methods.updatePrice(orderId, price).send({ gas, gasPrice })); } @@ -225,7 +225,7 @@ export class JCStandard { id: orderInfo.tokenId, }, ]; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); const logData = { gas, title: 'market_cancel_order', @@ -254,7 +254,7 @@ export class JCStandard { let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressMarket).call(); console.log('approved:: ', approved); let gasApprove = 0; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); if (approved < orderInfo.price) { gasApprove = await tokenInstance.methods.approve(addressMarket, orderInfo.price).estimateGas(); gasApprove = (gasApprove * GAS_BOOST) | 1; @@ -346,10 +346,11 @@ export class JCStandard { let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressGameMall).call(); console.log('approved:: ', approved); let gasApprove = 0; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); if (approved < price) { gasApprove = await tokenInstance.methods.approve(addressGameMall, price).estimateGas(); gasApprove = (gasApprove * GAS_BOOST) | 1; + console.log('gasApprove:: ', gasApprove); await tokenInstance.methods.approve(addressGameMall, price).send({ gas: gasApprove, gasPrice }); } @@ -424,7 +425,7 @@ export class JCStandard { let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressGameMarket).call(); console.log('approved:: ', approved); let gasApprove = 0; - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); if (approved < price) { gasApprove = await tokenInstance.methods.approve(addressGameMarket, price).estimateGas(); gasApprove = (gasApprove * GAS_BOOST) | 1; @@ -504,7 +505,8 @@ export class JCStandard { }); let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressMall).call(); console.log('approved:: ', approved); - let gasPrice = await this.web3.eth.getGasPrice(); + let gasPrice = await jc.wallet.fetchGasPrice(); + console.log('gas price: ' + gasPrice); let gasApprove = 0; if (approved < values[1]) { gasApprove = await tokenInstance.methods.approve(addressMall, values[1]).estimateGas();