增加多链的资产展示

This commit is contained in:
CounterFire2023 2023-06-30 17:50:21 +08:00
parent 3edab20653
commit b29fa53af3
7 changed files with 310 additions and 346 deletions

View File

@ -1,293 +1,293 @@
export const AllChains = [ export const AllChains = [
{ {
name: "Ethereum Mainnet RPC", name: 'Ethereum Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.ankr.com/eth", rpc: 'https://rpc.ankr.com/eth',
id: 1, id: 1,
symbol: "ETH", symbol: 'ETH',
explorerurl: "https://etherscan.io", explorerurl: 'https://etherscan.io',
}, },
{ {
name: "Ethereum Ropsten Testnet RPC", name: 'Ethereum Ropsten Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", rpc: 'https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161',
id: 3, id: 3,
symbol: "ETH", symbol: 'ETH',
explorerurl: "https://ropsten.etherscan.io", explorerurl: 'https://ropsten.etherscan.io',
}, },
{ {
name: "Ethereum Rinkeby Testnet RPC", name: 'Ethereum Rinkeby Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://rinkey.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", rpc: 'https://rinkey.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161',
id: 4, id: 4,
symbol: "ETH", symbol: 'ETH',
explorerurl: "https://rinkey.etherscan.io", explorerurl: 'https://rinkey.etherscan.io',
}, },
{ {
name: "Ethereum Goerli Testnet RPC", name: 'Ethereum Goerli Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", rpc: 'https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161',
id: 5, id: 5,
symbol: "ETH", symbol: 'ETH',
explorerurl: "https://goerli.etherscan.io", explorerurl: 'https://goerli.etherscan.io',
}, },
{ {
name: "Ethereum Kovan Testnet RPC", name: 'Ethereum Kovan Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://kovan.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", rpc: 'https://kovan.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161',
id: 6, id: 6,
symbol: "ETH", symbol: 'ETH',
explorerurl: "https://kovan.etherscan.io", explorerurl: 'https://kovan.etherscan.io',
}, },
{ {
name: "Ubiq Mainnet RPC", name: 'Ubiq Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.octano.dev/", rpc: 'https://rpc.octano.dev/',
id: 8, id: 8,
symbol: "UBQ", symbol: 'UBQ',
explorerurl: "https://ubiqscan.io/", explorerurl: 'https://ubiqscan.io/',
}, },
{ {
name: "Elastos ETH Mainnet RPC", name: 'Elastos ETH Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://api.elastos.io/eth", rpc: 'https://api.elastos.io/eth',
id: 20, id: 20,
symbol: "ELA", symbol: 'ELA',
explorerurl: "https://explorer.elaeth.io/", explorerurl: 'https://explorer.elaeth.io/',
}, },
{ {
name: "Cronos Mainnet RPC", name: 'Cronos Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://evm-cronos.crypto.org", rpc: 'https://evm-cronos.crypto.org',
id: 25, id: 25,
symbol: "CRO", symbol: 'CRO',
explorerurl: "https://cronos.crypto.org/explorer/", explorerurl: 'https://cronos.crypto.org/explorer/',
}, },
{ {
name: "Telos EVM Mainnet RPC", name: 'Telos EVM Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://mainnet.telos.net/evm", rpc: 'https://mainnet.telos.net/evm',
id: 40, id: 40,
symbol: "TLOS", symbol: 'TLOS',
explorerurl: "https://telos.net/", explorerurl: 'https://telos.net/',
}, },
{ {
name: "Binance Smart Chain", name: 'Binance Smart Chain',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.ankr.com/bsc", rpc: 'https://rpc.ankr.com/bsc',
id: 56, id: 56,
symbol: "BNB", symbol: 'BNB',
explorerurl: "https://bscscan.com", explorerurl: 'https://bscscan.com',
}, },
{ {
name: "OKExChain Mainnet RPC", name: 'OKExChain Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://exchainrpc.okex.org", rpc: 'https://exchainrpc.okex.org',
id: 66, id: 66,
symbol: "OKT", symbol: 'OKT',
explorerurl: "https://www.oklink.com/okexchain", explorerurl: 'https://www.oklink.com/okexchain',
}, },
{ {
name: "Hoo Mainnet RPC", name: 'Hoo Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://http-mainnet.hoosmartchain.com", rpc: 'https://http-mainnet.hoosmartchain.com',
id: 70, id: 70,
symbol: "HOO", symbol: 'HOO',
explorerurl: "https://hooscan.com", explorerurl: 'https://hooscan.com',
}, },
{ {
name: "Binance Testnet", name: 'Binance Testnet',
type: "Testnet", type: 'Testnet',
rpc: "https://data-seed-prebsc-1-s1.binance.org:8545/", rpc: 'https://data-seed-prebsc-1-s1.binance.org:8545/',
id: 97, id: 97,
symbol: "BNB", symbol: 'BNB',
explorerurl: "https://testnet.bscscan.com", explorerurl: 'https://testnet.bscscan.com',
}, },
{ {
name: "xDai Mainnet RPC", name: 'xDai Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.xdaichain.com/", rpc: 'https://rpc.xdaichain.com/',
id: 100, id: 100,
symbol: "XDAI", symbol: 'XDAI',
explorerurl: "https://blockscout.com/xdai/mainnet/", explorerurl: 'https://blockscout.com/xdai/mainnet/',
}, },
{ {
name: "Fuse Mainnet RPC", name: 'Fuse Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.fuse.io", rpc: 'https://rpc.fuse.io',
id: 122, id: 122,
symbol: "FUSE", symbol: 'FUSE',
explorerurl: "https://explorer.fuse.io/", explorerurl: 'https://explorer.fuse.io/',
}, },
{ {
name: "HECO Mainnet RPC", name: 'HECO Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://http-mainnet-node.huobichain.com/", rpc: 'https://http-mainnet-node.huobichain.com/',
id: 128, id: 128,
symbol: "HT", symbol: 'HT',
explorerurl: "https://hecoinfo.com/", explorerurl: 'https://hecoinfo.com/',
}, },
{ {
name: "Matic Mainnet RPC", name: 'Matic Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://polygon-rpc.com", rpc: 'https://polygon-rpc.com',
id: 137, id: 137,
symbol: "MATIC", symbol: 'MATIC',
explorerurl: "https://explorer.matic.network/", explorerurl: 'https://explorer.matic.network/',
}, },
{ {
name: "Fantom Opera Mainnet RPC", name: 'Fantom Opera Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.ftm.tools/", rpc: 'https://rpc.ftm.tools/',
id: 250, id: 250,
symbol: "FTM", symbol: 'FTM',
explorerurl: "https://ftmscan.com", explorerurl: 'https://ftmscan.com',
}, },
{ {
name: "HECO Testnet RPC", name: 'HECO Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://http-testnet.hecochain.com", rpc: 'https://http-testnet.hecochain.com',
id: 256, id: 256,
symbol: "HT", symbol: 'HT',
explorerurl: "https://testnet.hecoinfo.com/", explorerurl: 'https://testnet.hecoinfo.com/',
}, },
{ {
name: "KCC Mainnet", name: 'KCC Mainnet',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc-mainnet.kcc.network", rpc: 'https://rpc-mainnet.kcc.network',
id: 321, id: 321,
symbol: "KCS", symbol: 'KCS',
explorerurl: "https://scan.kcc.network", explorerurl: 'https://scan.kcc.network',
}, },
{ {
name: "KCC Testnet", name: 'KCC Testnet',
type: "Testnet", type: 'Testnet',
rpc: "https://rpc-testnet.kcc.network", rpc: 'https://rpc-testnet.kcc.network',
id: 322, id: 322,
symbol: "tKCS", symbol: 'tKCS',
explorerurl: "https://scan-testnet.kcc.network", explorerurl: 'https://scan-testnet.kcc.network',
}, },
{ {
name: "Moonriver Mainnet RPC", name: 'Moonriver Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.moonriver.moonbeam.network", rpc: 'https://rpc.moonriver.moonbeam.network',
id: 1285, id: 1285,
symbol: "MOVR", symbol: 'MOVR',
explorerurl: "https://blockscout.moonriver.moonbeam.network/", explorerurl: 'https://blockscout.moonriver.moonbeam.network/',
}, },
{ {
name: "Fantom Testnet RPC", name: 'Fantom Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://rpc.testnet.fantom.network/", rpc: 'https://rpc.testnet.fantom.network/',
id: 4002, id: 4002,
symbol: "FTM", symbol: 'FTM',
explorerurl: "https://testnet.ftmscan.com", explorerurl: 'https://testnet.ftmscan.com',
}, },
{ {
name: "IoTeX Mainnet RPC", name: 'IoTeX Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://babel-api.mainnet.iotex.io", rpc: 'https://babel-api.mainnet.iotex.io',
id: 4689, id: 4689,
symbol: "IOTEX", symbol: 'IOTEX',
explorerurl: "https://iotexscan.io/", explorerurl: 'https://iotexscan.io/',
}, },
{ {
name: "Nahmii Mainnet RPC", name: 'Nahmii Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://l2.nahmii.io/", rpc: 'https://l2.nahmii.io/',
id: 5551, id: 5551,
symbol: "ETH", symbol: 'ETH',
explorerurl: "https://explorer.nahmii.io/", explorerurl: 'https://explorer.nahmii.io/',
}, },
{ {
name: "Nahmii Testnet RPC", name: 'Nahmii Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://l2.testnet.nahmii.io/", rpc: 'https://l2.testnet.nahmii.io/',
id: 5553, id: 5553,
symbol: "ETH", symbol: 'ETH',
explorerurl: "https://explorer.testnet.nahmii.io/", explorerurl: 'https://explorer.testnet.nahmii.io/',
}, },
{ {
name: "Arbitrum One", name: 'Arbitrum One',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.ankr.com/arbitrum", rpc: 'https://arb1.arbitrum.io/rpc',
id: 42161, id: 42161,
network: "ARBITRUM", network: 'ARBITRUM',
symbol: "ETH", symbol: 'ETH',
explorerurl: "https://arbiscan.io/", explorerurl: 'https://arbiscan.io/',
}, },
{ {
name: "Arbitrum Goerli", name: 'Arbitrum Goerli',
type: "Testnet", type: 'Testnet',
rpc: "https://endpoints.omniatech.io/v1/arbitrum/goerli/public", rpc: 'https://endpoints.omniatech.io/v1/arbitrum/goerli/public',
id: 421613, id: 421613,
network: "AGOR", network: 'AGOR',
symbol: "AGOR", symbol: 'AGOR',
explorerurl: "https://testnet.arbiscan.io", explorerurl: 'https://testnet.arbiscan.io',
}, },
{ {
name: "Celo Mainnet RPC", name: 'Celo Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.ankr.com/celo", rpc: 'https://rpc.ankr.com/celo',
id: 42220, id: 42220,
symbol: "CELO", symbol: 'CELO',
explorerurl: "https://celoscan.com", explorerurl: 'https://celoscan.com',
}, },
{ {
name: "Avalanche C Chain Local RPC", name: 'Avalanche C Chain Local RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://localhost:9650/ext/bc/C/rpc", rpc: 'https://localhost:9650/ext/bc/C/rpc',
id: 43112, id: 43112,
symbol: "AVAX", symbol: 'AVAX',
explorerurl: "https://snowtrace.io", explorerurl: 'https://snowtrace.io',
}, },
{ {
name: "Avalanche FUJI Testnet RPC", name: 'Avalanche FUJI Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://api.avax-test.network/ext/bc/C/rpc", rpc: 'https://api.avax-test.network/ext/bc/C/rpc',
id: 43113, id: 43113,
symbol: "AVAX", symbol: 'AVAX',
explorerurl: "https://testnet.explorer.avax.network/", explorerurl: 'https://testnet.explorer.avax.network/',
}, },
{ {
name: "Avalanche C Chain Mainnet RPC", name: 'Avalanche C Chain Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://rpc.ankr.com/avalanche", rpc: 'https://rpc.ankr.com/avalanche',
id: 43114, id: 43114,
symbol: "AVAX", symbol: 'AVAX',
explorerurl: "https://snowtrace.io", explorerurl: 'https://snowtrace.io',
}, },
{ {
name: "Matic Testnet RPC", name: 'Matic Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://rpc-mumbai.maticvigil.com", rpc: 'https://rpc-mumbai.maticvigil.com',
id: 80001, id: 80001,
symbol: "MATIC", symbol: 'MATIC',
explorerurl: "https://mumbai.polygonscan.com/", explorerurl: 'https://mumbai.polygonscan.com/',
}, },
{ {
name: "Harmony Mainnet RPC", name: 'Harmony Mainnet RPC',
type: "Mainnet", type: 'Mainnet',
rpc: "https://api.harmony.one/", rpc: 'https://api.harmony.one/',
id: 1666600000, id: 1666600000,
symbol: "ONE", symbol: 'ONE',
explorerurl: "https://explorer.harmony.one", explorerurl: 'https://explorer.harmony.one',
}, },
{ {
name: "Harmony Testnet RPC", name: 'Harmony Testnet RPC',
type: "Testnet", type: 'Testnet',
rpc: "https://api.s0.b.hmny.io/", rpc: 'https://api.s0.b.hmny.io/',
id: 1666700000, id: 1666700000,
symbol: "ONE", symbol: 'ONE',
explorerurl: "https://explorer.harmony.one", explorerurl: 'https://explorer.harmony.one',
}, },
{ {
name: "Local Testnet", name: 'Local Testnet',
type: "Local", type: 'Local',
rpc: "https://login-test.kingsome.cn/rpc", rpc: 'https://login-test.kingsome.cn/rpc',
id: 1338, id: 1338,
symbol: "ETH", symbol: 'ETH',
explorerurl: "https://explorer.harmony.one", explorerurl: 'https://explorer.harmony.one',
}, },
]; ];

View File

@ -1,56 +1,34 @@
import { import { recoverTypedSignature, signTypedData, SignTypedDataVersion } from '@metamask/eth-sig-util';
recoverTypedSignature, import Web3 from 'web3';
signTypedData, import 'whatwg-fetch';
SignTypedDataVersion, import { createWalletEvents, WALLET_ACCOUNT_CHANGE, WALLET_CHAIN_CHANGE } from './common/WalletEvent';
} from "@metamask/eth-sig-util"; import { JazzIcon } from './comp/JazzIcon';
import Web3 from "web3"; import { ZWalletConnect } from './comp/ZWalletConnect';
import "whatwg-fetch"; import { AVAILABLE_CHAINS, NATIVE_PK_PREFIX, TX_CONFIRM_BLOCKS, WALLET_STORAGE_KEY_NAME } from './config/constants';
import { import { AllChains } from './data/allchain';
createWalletEvents, import { singleton } from './decorator/singleton.decorator';
WALLET_ACCOUNT_CHANGE, import { parseUrl } from './manage/SchemeManage';
WALLET_CHAIN_CHANGE, import { exportSecKey, loadInternalWallet, loginByEmail, verifyPassword, walletPreLogin } from './manage/WalletManage';
} from "./common/WalletEvent"; import { EmailVerifySvr } from './services/EmailVerifySvr';
import { JazzIcon } from "./comp/JazzIcon"; import { NativeSvr } from './services/NativeSvr';
import { ZWalletConnect } from "./comp/ZWalletConnect"; import { PaySvr } from './services/PaySvr';
import { import { TranHistorySvr } from './services/TranHistorySvr';
AVAILABLE_CHAINS, import { ChainCommon } from './standards/ChainCommon';
NATIVE_PK_PREFIX, import { ERC1155Standard } from './standards/ERC1155Standard';
TX_CONFIRM_BLOCKS, import { ERC20Standard } from './standards/ERC20Standard';
WALLET_STORAGE_KEY_NAME, import { ERC721Standard } from './standards/ERC721Standard';
} from "./config/constants"; import { JCStandard } from './standards/JCStandard';
import { AllChains } from "./data/allchain"; import { WalletType } from './types/data.enums';
import { singleton } from "./decorator/singleton.decorator"; import { IChainData } from './types/data.types';
import { parseUrl } from "./manage/SchemeManage"; import { universalChainCb } from './util/chain.util';
import { import { fromTokenMinimalUnit, renderFromTokenMinimalUnit, safeNumberToBN } from './util/number.util';
exportSecKey, import { buildLoginSignMsg, signLogin } from './util/sign.util';
loadInternalWallet, import { parse } from 'url';
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";
var global = var global =
(typeof globalThis !== "undefined" && globalThis) || (typeof globalThis !== 'undefined' && globalThis) ||
(typeof self !== "undefined" && self) || (typeof self !== 'undefined' && self) ||
(typeof global !== "undefined" && global) || (typeof global !== 'undefined' && global) ||
{}; {};
window.debug = true; window.debug = true;
@ -59,7 +37,7 @@ window.debug = true;
export default class JCWallet { export default class JCWallet {
web3: Web3 = null; web3: Web3 = null;
private wallet: any = null; private wallet: any = null;
private password: string = "111111"; private password: string = '111111';
private chainSet: Set<number> = new Set(); private chainSet: Set<number> = new Set();
private chainMap: Map<number, IChainData> = new Map(); private chainMap: Map<number, IChainData> = new Map();
private _currentChain: IChainData; private _currentChain: IChainData;
@ -73,12 +51,12 @@ export default class JCWallet {
public emailVerifySvr: EmailVerifySvr; public emailVerifySvr: EmailVerifySvr;
public paySvr: PaySvr; public paySvr: PaySvr;
public wConnect: ZWalletConnect; public wConnect: ZWalletConnect;
public mainHandlers = createWalletEvents();
private walletType: WalletType = WalletType.INTERNAL; private walletType: WalletType = WalletType.INTERNAL;
private rpcUrl: string = ""; private rpcUrl: string = '';
public rpc: any = {}; public rpc: any = {};
public nativeAccount = ""; public nativeAccount = '';
private env = "dev"; private env = 'dev';
private web3Map = new Map();
constructor({ type }: { type: number }) { constructor({ type }: { type: number }) {
this.nativeSvr = new NativeSvr(); this.nativeSvr = new NativeSvr();
@ -94,7 +72,7 @@ export default class JCWallet {
chain = chain || 80001; chain = chain || 80001;
let data = this.chainMap.get(chain); let data = this.chainMap.get(chain);
if (!data) { if (!data) {
throw new Error("no current chain data"); throw new Error('no current chain data');
} }
this._currentChain = data; this._currentChain = data;
this.rpcUrl = data.rpc; this.rpcUrl = data.rpc;
@ -121,42 +99,32 @@ export default class JCWallet {
return loginByEmail(email, password); return loginByEmail(email, password);
} }
public async initInternalWallet( public async initInternalWallet(chain: number, pass: string, env: string = 'dev') {
chain: number,
pass: string,
env: string = "dev"
) {
this.env = env; this.env = env;
this.walletType = WalletType.INTERNAL; this.walletType = WalletType.INTERNAL;
this.updateChain(chain); this.updateChain(chain);
let address: string = await loadInternalWallet(pass); let address: string = await loadInternalWallet(pass);
this.nativeAccount = address; this.nativeAccount = address;
console.log("native wallet address: " + address); console.log('native wallet address: ' + address);
var start = Date.now(); var start = Date.now();
this.web3 = new Web3(this.rpcUrl); this.web3 = this.generateWeb3(chain);
this.web3.eth.transactionConfirmationBlocks = TX_CONFIRM_BLOCKS;
console.log(`init web3 cost: ${(Date.now() - start) / 1000}s`); console.log(`init web3 cost: ${(Date.now() - start) / 1000}s`);
this.erc20Standard = new ERC20Standard(this.web3); this.erc20Standard = new ERC20Standard(this.web3);
console.log("init Erc20Standard"); console.log('init Erc20Standard');
this.erc721Standard = new ERC721Standard(this.web3); this.erc721Standard = new ERC721Standard(this.web3);
console.log("init Erc721Standard"); console.log('init Erc721Standard');
this.erc1155Standard = new ERC1155Standard(this.web3); this.erc1155Standard = new ERC1155Standard(this.web3);
console.log("init ERC1155Standard"); console.log('init ERC1155Standard');
this.jcStandard = new JCStandard(this.web3); this.jcStandard = new JCStandard(this.web3);
this.chainCommon = new ChainCommon(this.web3); this.chainCommon = new ChainCommon(this.web3);
console.log("init JCStandard"); console.log('init JCStandard');
this.injectAccount(); console.log('this.web3.eth.defaultAccount: ' + JSON.stringify(this.web3.eth.defaultAccount));
console.log(JSON.stringify(this.wallet[0]));
console.log(
"this.web3.eth.defaultAccount: " +
JSON.stringify(this.web3.eth.defaultAccount)
);
} }
/** /**
* init wallet connect * init wallet connect
* @returns * @returns
*/ */
public async initThirdPartyWallet(chain: number, env: string = "dev") { public async initThirdPartyWallet(chain: number, env: string = 'dev') {
this.env = env; this.env = env;
this.walletType = WalletType.THIRD_PATH; this.walletType = WalletType.THIRD_PATH;
this.updateChain(chain); this.updateChain(chain);
@ -184,19 +152,19 @@ export default class JCWallet {
}) })
.then((chainId: number) => { .then((chainId: number) => {
if (chainId === this._currentChain.id) { if (chainId === this._currentChain.id) {
resolve && resolve(""); resolve && resolve('');
} else { } else {
this.updateCurrentChain(this.currentChain.id) this.updateCurrentChain(this.currentChain.id)
.then(() => { .then(() => {
resolve && resolve(""); resolve && resolve('');
}) })
.catch((err) => { .catch((err) => {
reject && reject("error change network"); reject && reject('error change network');
}); });
} }
}) })
.catch((err: Error) => { .catch((err: Error) => {
console.log("initThirdPartyWallet error: " + err); console.log('initThirdPartyWallet error: ' + err);
reject && reject(err.message); reject && reject(err.message);
}); });
}); });
@ -232,15 +200,14 @@ export default class JCWallet {
if (this.walletType === WalletType.INTERNAL) { if (this.walletType === WalletType.INTERNAL) {
const chainData = this.chainMap.get(chainId); const chainData = this.chainMap.get(chainId);
if (!chainData) { if (!chainData) {
reject && reject("chain data not found"); reject && reject('chain data not found');
return; return;
} }
this._currentChain = chainData; this._currentChain = chainData;
this.web3.eth.setProvider(chainData.rpc); this.web3.eth.setProvider(chainData.rpc);
this.mainHandlers.emit(WALLET_CHAIN_CHANGE, chainData);
resolve && resolve(this.currentChain); resolve && resolve(this.currentChain);
} else { } else {
console.log("third party wallet change chain: " + chainId); console.log('third party wallet change chain: ' + chainId);
const chainData = this.chainMap.get(chainId); const chainData = this.chainMap.get(chainId);
this.wConnect this.wConnect
.addOrChangeChain(chainData) .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() { public get currentAccAddr() {
if (this.walletType === WalletType.INTERNAL) { if (this.walletType === WalletType.INTERNAL) {
return this.nativeAccount; return this.nativeAccount;
@ -278,17 +260,16 @@ export default class JCWallet {
} }
} }
public injectAccount() { public injectAccount(web3: any, isDefault: boolean = true) {
this.wallet = this.web3.eth.accounts.wallet; const nativePrivateKey = `${NATIVE_PK_PREFIX}${this.currentAccAddr.slice(2)}`;
const nativePrivateKey = `${NATIVE_PK_PREFIX}${this.currentAccAddr.slice( const acc = web3.eth.accounts.privateKeyToAccount(nativePrivateKey);
2 const account = web3.eth.accounts.wallet.add(acc);
)}`; web3.eth.defaultAccount = account.address;
const acc = this.web3.eth.accounts.privateKeyToAccount(nativePrivateKey); console.log('web3 account: ' + JSON.stringify(web3.eth.accounts.wallet[0]));
const account = this.wallet.add(acc); if (isDefault) {
this.web3.eth.defaultAccount = account.address; this.wallet = web3.eth.accounts.wallet;
console.log("web3 account: " + JSON.stringify(this.wallet[0])); web3.eth.accounts.wallet.save(this.password, WALLET_STORAGE_KEY_NAME);
this.wallet.save(this.password, WALLET_STORAGE_KEY_NAME); }
this.mainHandlers.emit(WALLET_ACCOUNT_CHANGE, account.address);
return account.address; return account.address;
} }
@ -296,11 +277,8 @@ export default class JCWallet {
let chainData = this.currentChain; let chainData = this.currentChain;
let price = await new PaySvr().getGasPrice(chainData.id); let price = await new PaySvr().getGasPrice(chainData.id);
let ehtBN = safeNumberToBN(price).mul(safeNumberToBN(gas)); let ehtBN = safeNumberToBN(price).mul(safeNumberToBN(gas));
let ethSymbol = chainData.type !== "Testnet" ? chainData.symbol : "ETH"; let ethSymbol = chainData.type !== 'Testnet' ? chainData.symbol : 'ETH';
let network = let network = chainData.type !== 'Testnet' ? chainData.network || chainData.symbol : 'ETH';
chainData.type !== "Testnet"
? chainData.network || chainData.symbol
: "ETH";
let fiatPrice = await new PaySvr().queryTokenPrice(network, ethSymbol); let fiatPrice = await new PaySvr().queryTokenPrice(network, ethSymbol);
let priceFloat = parseFloat(fiatPrice) * 100; let priceFloat = parseFloat(fiatPrice) * 100;
let fiatPriceBN = safeNumberToBN(priceFloat); let fiatPriceBN = safeNumberToBN(priceFloat);
@ -308,6 +286,13 @@ export default class JCWallet {
let eth = fromTokenMinimalUnit(ehtBN, 18); let eth = fromTokenMinimalUnit(ehtBN, 18);
return { gas, price, eth, usd }; 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的法币价格
* token * token
@ -317,10 +302,7 @@ export default class JCWallet {
*/ */
public async calcTokenPrice(tokenName: string, amount: string) { public async calcTokenPrice(tokenName: string, amount: string) {
let chainData = this.currentChain; let chainData = this.currentChain;
let network = let network = chainData.type !== 'Testnet' ? chainData.network || chainData.symbol : 'ETH';
chainData.type !== "Testnet"
? chainData.network || chainData.symbol
: "ETH";
let env = this.env; let env = this.env;
let fiatPrice = await new PaySvr().queryTokenPrice(network, tokenName, env); let fiatPrice = await new PaySvr().queryTokenPrice(network, tokenName, env);
let priceFloat = parseFloat(fiatPrice); let priceFloat = parseFloat(fiatPrice);
@ -329,11 +311,11 @@ export default class JCWallet {
public async sendEth(to: string, amount: number | string, estimate: number) { public async sendEth(to: string, amount: number | string, estimate: number) {
let from = this.currentAccAddr; 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({ let gas = await this.web3.eth.estimateGas({
from, from,
to, to,
value: "0", value: '0',
}); });
if (estimate) { if (estimate) {
return this.generateGasShow(gas); return this.generateGasShow(gas);
@ -346,14 +328,14 @@ export default class JCWallet {
}; };
const logData = { const logData = {
gas, gas,
title: "transfer", title: 'transfer',
details: [ details: [
{ {
address: "eth", address: 'eth',
from, from,
to, to,
value: amountToSend, value: amountToSend,
id: "0", id: '0',
}, },
], ],
}; };
@ -361,7 +343,7 @@ export default class JCWallet {
} }
public async getBalance(account?: string) { 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); let balance = await this.chainCommon.getBalance(account);
return balance; return balance;
} }
@ -370,7 +352,7 @@ export default class JCWallet {
const account = this.currentAccount(); const account = this.currentAccount();
return signTypedData({ return signTypedData({
data: signObj, data: signObj,
privateKey: Buffer.from(account.privateKey.replace("0x", ""), "hex"), privateKey: Buffer.from(account.privateKey.replace('0x', ''), 'hex'),
version: SignTypedDataVersion.V4, version: SignTypedDataVersion.V4,
}); });
} }
@ -430,12 +412,7 @@ export default class JCWallet {
return result; return result;
} }
public async sendErc20( public async sendErc20(address: string, to: string, amount: string, estimate: number) {
address: string,
to: string,
amount: string,
estimate: number
) {
let from = this.currentAccAddr; let from = this.currentAccAddr;
let result = await this.erc20Standard.transfer({ let result = await this.erc20Standard.transfer({
address, address,
@ -447,12 +424,7 @@ export default class JCWallet {
return result; return result;
} }
public async sendNFT( public async sendNFT(address: string, to: string, tokenId: string, estimate: number) {
address: string,
to: string,
tokenId: string,
estimate: number
) {
let from = this.currentAccAddr; let from = this.currentAccAddr;
return this.erc721Standard.transfer({ return this.erc721Standard.transfer({
address, address,
@ -463,16 +435,8 @@ export default class JCWallet {
}); });
} }
public async erc1155Balance( public async erc1155Balance(address: string, account: string, tokenId: string) {
address: string, let result = await this.erc1155Standard.getBalanceOf(address, account, tokenId);
account: string,
tokenId: string
) {
let result = await this.erc1155Standard.getBalanceOf(
address,
account,
tokenId
);
return result; return result;
} }
@ -484,13 +448,7 @@ export default class JCWallet {
} }
} }
public async sendErc1155( public async sendErc1155(address: string, to: string, tokenIds: string[], amounts: string[], estimate: number) {
address: string,
to: string,
tokenIds: string[],
amounts: string[],
estimate: number
) {
let from = this.currentAccAddr; let from = this.currentAccAddr;
return this.erc1155Standard.transferBatch({ return this.erc1155Standard.transferBatch({
address, address,
@ -503,9 +461,9 @@ export default class JCWallet {
} }
public async scanQr(title: string) { public async scanQr(title: string) {
let result = (await this.nativeSvr.scanQRCode(title)) + ""; let result = (await this.nativeSvr.scanQRCode(title)) + '';
console.log("scan qr code: " + result); console.log('scan qr code: ' + result);
if (result && result.indexOf("://") >= 0) { if (result && result.indexOf('://') >= 0) {
parseUrl(result); parseUrl(result);
} }
return result; return result;
@ -514,8 +472,8 @@ export default class JCWallet {
// window.jc = window.jc || {wallet: new JCWallet()}; // window.jc = window.jc || {wallet: new JCWallet()};
export * from "./common/WalletEvent"; export * from './common/WalletEvent';
export * from "./common/ZError"; export * from './common/ZError';
export * from "./lib/WalletConnect"; export * from './lib/WalletConnect';
export * from "./util/number.util"; export * from './util/number.util';
export * from "./util/wallet.util"; export * from './util/wallet.util';

View File

@ -1,5 +1,5 @@
import Web3 from "web3"; import Web3 from 'web3';
import { BN } from "ethereumjs-util"; import { BN } from 'ethereumjs-util';
export const SAMPLE_GAS = 1000000; export const SAMPLE_GAS = 1000000;
@ -13,9 +13,9 @@ export class ChainCommon {
public async checkEthEnough(gas: string, address?: string) { public async checkEthEnough(gas: string, address?: string) {
address = address || jc.wallet.currentAccAddr; address = address || jc.wallet.currentAccAddr;
let gasPrice = await this.web3.eth.getGasPrice(); 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); 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))); return new BN(balance).gte(new BN(gasPrice).mul(new BN(gas)));
} }

View File

@ -200,7 +200,7 @@ export class ERC1155Standard {
title: 'transfer', title: 'transfer',
details: detailArr, details: detailArr,
}; };
let gasPrice = await this.web3.eth.getGasPrice(); let gasPrice = await jc.wallet.fetchGasPrice();
return universalChainCb( return universalChainCb(
logData, logData,
contract.methods.safeBatchTransferFrom(from, to, tokenIds, amounts, []).send({ contract.methods.safeBatchTransferFrom(from, to, tokenIds, amounts, []).send({

View File

@ -176,7 +176,7 @@ export class ERC20Standard {
}, },
], ],
}; };
let gasPrice = await this.web3.eth.getGasPrice(); let gasPrice = await jc.wallet.fetchGasPrice();
return universalChainCb( return universalChainCb(
logData, logData,
contract.methods.transfer(to, amountBN).send({ contract.methods.transfer(to, amountBN).send({

View File

@ -68,8 +68,12 @@ export class ERC721Standard {
}); });
}; };
getBalance = async (address: string, selectedAddress: string): Promise<number> => { getBalance = async (address: string, selectedAddress: string, chainId?: string): Promise<number> => {
const contract = new this.web3.eth.Contract(abiERC721, address); 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<number>((resolve, reject) => { return new Promise<number>((resolve, reject) => {
contract.methods.balanceOf(selectedAddress).call((error: Error, result: number) => { contract.methods.balanceOf(selectedAddress).call((error: Error, result: number) => {
/* istanbul ignore if */ /* 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( return universalChainCb(
logData, logData,
contract.methods.safeTransferFrom(from, to, tokenId).send({ contract.methods.safeTransferFrom(from, to, tokenId).send({

View File

@ -69,7 +69,7 @@ export class JCStandard {
title: 'mint_nft', title: 'mint_nft',
details: details, details: details,
}; };
let gasPrice = await this.web3.eth.getGasPrice(); let gasPrice = await jc.wallet.fetchGasPrice();
return universalChainCb( return universalChainCb(
logData, logData,
contract.methods.mintNft(address, tokenIds, startTime, saltNonce, signature).send({ gas, gasPrice }) 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 approved = await tokenInstance.methods.getApproved(tokenId);
let gasApprove = 0; let gasApprove = 0;
let gasPrice = await this.web3.eth.getGasPrice(); let gasPrice = await jc.wallet.fetchGasPrice();
if (approved != addressMarket) { if (approved != addressMarket) {
gasApprove = await tokenInstance.methods.approve(addressMarket, tokenId).estimateGas(); gasApprove = await tokenInstance.methods.approve(addressMarket, tokenId).estimateGas();
gasApprove = (gasApprove * GAS_BOOST) | 1; gasApprove = (gasApprove * GAS_BOOST) | 1;
@ -187,7 +187,7 @@ export class JCStandard {
title: 'market_update_price', title: 'market_update_price',
details: details, 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 })); return universalChainCb(logData, contract.methods.updatePrice(orderId, price).send({ gas, gasPrice }));
} }
@ -225,7 +225,7 @@ export class JCStandard {
id: orderInfo.tokenId, id: orderInfo.tokenId,
}, },
]; ];
let gasPrice = await this.web3.eth.getGasPrice(); let gasPrice = await jc.wallet.fetchGasPrice();
const logData = { const logData = {
gas, gas,
title: 'market_cancel_order', title: 'market_cancel_order',
@ -254,7 +254,7 @@ export class JCStandard {
let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressMarket).call(); let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressMarket).call();
console.log('approved:: ', approved); console.log('approved:: ', approved);
let gasApprove = 0; let gasApprove = 0;
let gasPrice = await this.web3.eth.getGasPrice(); let gasPrice = await jc.wallet.fetchGasPrice();
if (approved < orderInfo.price) { if (approved < orderInfo.price) {
gasApprove = await tokenInstance.methods.approve(addressMarket, orderInfo.price).estimateGas(); gasApprove = await tokenInstance.methods.approve(addressMarket, orderInfo.price).estimateGas();
gasApprove = (gasApprove * GAS_BOOST) | 1; gasApprove = (gasApprove * GAS_BOOST) | 1;
@ -346,10 +346,11 @@ export class JCStandard {
let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressGameMall).call(); let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressGameMall).call();
console.log('approved:: ', approved); console.log('approved:: ', approved);
let gasApprove = 0; let gasApprove = 0;
let gasPrice = await this.web3.eth.getGasPrice(); let gasPrice = await jc.wallet.fetchGasPrice();
if (approved < price) { if (approved < price) {
gasApprove = await tokenInstance.methods.approve(addressGameMall, price).estimateGas(); gasApprove = await tokenInstance.methods.approve(addressGameMall, price).estimateGas();
gasApprove = (gasApprove * GAS_BOOST) | 1; gasApprove = (gasApprove * GAS_BOOST) | 1;
console.log('gasApprove:: ', gasApprove);
await tokenInstance.methods.approve(addressGameMall, price).send({ gas: gasApprove, gasPrice }); 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(); let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressGameMarket).call();
console.log('approved:: ', approved); console.log('approved:: ', approved);
let gasApprove = 0; let gasApprove = 0;
let gasPrice = await this.web3.eth.getGasPrice(); let gasPrice = await jc.wallet.fetchGasPrice();
if (approved < price) { if (approved < price) {
gasApprove = await tokenInstance.methods.approve(addressGameMarket, price).estimateGas(); gasApprove = await tokenInstance.methods.approve(addressGameMarket, price).estimateGas();
gasApprove = (gasApprove * GAS_BOOST) | 1; gasApprove = (gasApprove * GAS_BOOST) | 1;
@ -504,7 +505,8 @@ export class JCStandard {
}); });
let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressMall).call(); let approved = await tokenInstance.methods.allowance(jc.wallet.currentAccAddr, addressMall).call();
console.log('approved:: ', approved); 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; let gasApprove = 0;
if (approved < values[1]) { if (approved < values[1]) {
gasApprove = await tokenInstance.methods.approve(addressMall, values[1]).estimateGas(); gasApprove = await tokenInstance.methods.approve(addressMall, values[1]).estimateGas();