重构代码

This commit is contained in:
zhl 2023-03-23 14:08:06 +08:00
parent 47c1c81ccb
commit 1824e4230e
9 changed files with 52 additions and 80 deletions

12
src/api/PayApi.ts Normal file
View File

@ -0,0 +1,12 @@
import { WALLET_API_HOST } from "../config/constants";
import { POST_JSON } from "../lib/Http";
export function alchemyPrePay(data: any) {
const url = `${WALLET_API_HOST}/pay/alchemy/buy`;
return POST_JSON(url, data);
}
// update email info of logined user
export function updateEmailVerify(data: { email: string }) {
const url = `${WALLET_API_HOST}/email/verify`;
return POST_JSON(url, data);
}

View File

@ -50,3 +50,9 @@ export function uploadInfoForWebLogin(data) {
const url = `${WALLET_API_HOST}/bridge/upload`; const url = `${WALLET_API_HOST}/bridge/upload`;
return POST_JSON(url, data); return POST_JSON(url, data);
} }
// request /wallet/info/email to get if email is verified
export function isEmailVerified() {
const url = `${WALLET_API_HOST}/wallet/info/email`;
return GET_JSON(url);
}

View File

@ -1,5 +1,5 @@
import { IChainData } from "..";
import WalletConnectProvider from "../lib/WalletConnectProvider"; import WalletConnectProvider from "../lib/WalletConnectProvider";
import { IChainData } from "../types/data.types";
import { toHexChainId } from "../util/chain.util"; import { toHexChainId } from "../util/chain.util";
export class ZWalletConnect { export class ZWalletConnect {

View File

@ -35,6 +35,8 @@ import { ERC1155Standard } from "./standards/ERC1155Standard";
import { ERC20Standard } from "./standards/ERC20Standard"; import { ERC20Standard } from "./standards/ERC20Standard";
import { ERC721Standard } from "./standards/ERC721Standard"; import { ERC721Standard } from "./standards/ERC721Standard";
import { JCStandard } from "./standards/JCStandard"; import { JCStandard } from "./standards/JCStandard";
import { WalletType } from "./types/data.enums";
import { IChainData } from "./types/data.types";
import { import {
getJCErc721Info, getJCErc721Info,
getTypeByAddress, getTypeByAddress,
@ -53,20 +55,6 @@ var global =
window.debug = false; window.debug = false;
export interface IChainData {
name: string;
type: string;
rpc: string;
id: number;
symbol: string;
explorerurl: string;
decimals?: number;
}
export enum WalletType {
INTERNAL = 0,
THIRD_PATH = 1,
}
@singleton @singleton
export default class JCWallet { export default class JCWallet {
web3: Web3 = null; web3: Web3 = null;
@ -132,23 +120,11 @@ export default class JCWallet {
this.chainCommon = new ChainCommon(this.web3); this.chainCommon = new ChainCommon(this.web3);
console.log("init JCStandard"); console.log("init JCStandard");
this.createAccount(); this.createAccount();
// this.wallet = this.web3.eth.accounts.wallet.load(
// this.password,
// WALLET_STORAGE_KEY_NAME
// );
// console.log(`load wallet cost: ${(Date.now() - start) / 1000}`);
console.log(JSON.stringify(this.wallet[0])); console.log(JSON.stringify(this.wallet[0]));
console.log( console.log(
"this.web3.eth.defaultAccount: " + "this.web3.eth.defaultAccount: " +
JSON.stringify(this.web3.eth.defaultAccount) JSON.stringify(this.web3.eth.defaultAccount)
); );
// if (!this.wallet || this.wallet.length === 0) {
// // this.createAccount();
// this.newWallet(this.password);
// }
// start = Date.now();
// this.data = loadData();
// console.log(`init wallet ext data cost: ${(Date.now() - start) / 1000}`);
} }
/** /**
* init wallet connect * init wallet connect
@ -273,14 +249,6 @@ export default class JCWallet {
return [...this.chainMap.values()]; return [...this.chainMap.values()];
} }
public saveLocal() {}
public loadLocal() {}
public saveRemote() {}
public loadRemote() {}
public currentAccount() { public currentAccount() {
if (this.walletType === WalletType.INTERNAL) { if (this.walletType === WalletType.INTERNAL) {
return this.wallet[this.accountIndex]; return this.wallet[this.accountIndex];
@ -323,7 +291,6 @@ export default class JCWallet {
} }
public createAccount() { public createAccount() {
// let account = this.web3.eth.accounts.create()
this.wallet = this.web3.eth.accounts.wallet; this.wallet = this.web3.eth.accounts.wallet;
const index = this.getMaxIdexOfType(0); const index = this.getMaxIdexOfType(0);
const nativePrivateKey = `${NATIVE_PK_PREFIX}${this.currentAccAddr.slice( const nativePrivateKey = `${NATIVE_PK_PREFIX}${this.currentAccAddr.slice(

4
src/types/data.enums.ts Normal file
View File

@ -0,0 +1,4 @@
export enum WalletType {
INTERNAL = 0,
THIRD_PATH = 1,
}

9
src/types/data.types.ts Normal file
View File

@ -0,0 +1,9 @@
export interface IChainData {
name: string;
type: string;
rpc: string;
id: number;
symbol: string;
explorerurl: string;
decimals?: number;
}

View File

@ -1,41 +1,15 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// ID generater for runtime // ID generater for runtime
var NonUuidMark = '.'; var NonUuidMark = ".";
/* /*
* @param {string} [category] - You can specify a unique category to avoid id collision with other instance of IdGenerater * @param {string} [category] - You can specify a unique category to avoid id collision with other instance of IdGenerater
*/ */
function IdGenerater (category) { function IdGenerater(category) {
// init with a random id to emphasize that the returns id should not be stored in persistence data // init with a random id to emphasize that the returns id should not be stored in persistence data
this.id = 0 | (Math.random() * 998); this.id = 0 | (Math.random() * 998);
this.prefix = category ? (category + NonUuidMark) : ''; this.prefix = category ? category + NonUuidMark : "";
} }
/* /*
@ -43,13 +17,13 @@ function IdGenerater (category) {
* @return {string} * @return {string}
*/ */
IdGenerater.prototype.getNewId = function () { IdGenerater.prototype.getNewId = function () {
return this.prefix + (++this.id); return this.prefix + ++this.id;
}; };
/* /*
* The global id generater might have a conflict problem once every 365 days, * The global id generater might have a conflict problem once every 365 days,
* if the game runs at 60 FPS and each frame 4760273 counts of new id are requested. * if the game runs at 60 FPS and each frame 4760273 counts of new id are requested.
*/ */
IdGenerater.global = new IdGenerater('global'); IdGenerater.global = new IdGenerater("global");
module.exports = IdGenerater; module.exports = IdGenerater;

View File

@ -1,5 +1,5 @@
import Web3 from 'web3'; import Web3 from "web3";
import { BN } from 'ethereumjs-util'; import { BN } from "ethereumjs-util";
/** /**
* Converts some token minimal unit to render format string, showing 5 decimals * Converts some token minimal unit to render format string, showing 5 decimals
@ -65,14 +65,14 @@ export function fromTokenMinimalUnit(minimalInput, decimals) {
* @returns {String} - Number of token minimal unit, in render format * @returns {String} - Number of token minimal unit, in render format
* If value is less than 5 precision decimals will show '< 0.00001' * If value is less than 5 precision decimals will show '< 0.00001'
*/ */
export function renderFromWei(value, decimalsToShow = 5) { export function renderFromWei(value, decimalsToShow = 5) {
let renderWei = '0'; let renderWei = "0";
// avoid undefined // avoid undefined
if (value) { if (value) {
const wei = Web3.utils.fromWei(value); const wei = Web3.utils.fromWei(value);
const weiNumber = parseFloat(wei); const weiNumber = parseFloat(wei);
if (weiNumber < 0.00001 && weiNumber > 0) { if (weiNumber < 0.00001 && weiNumber > 0) {
renderWei = '< 0.00001'; renderWei = "< 0.00001";
} else { } else {
const base = Math.pow(10, decimalsToShow); const base = Math.pow(10, decimalsToShow);
renderWei = (Math.round(weiNumber * base) / base).toString(); renderWei = (Math.round(weiNumber * base) / base).toString();
@ -98,7 +98,7 @@ export function calcTokenValueToSend(value, decimals) {
* @param {string} value - String to check * @param {string} value - String to check
* @returns {boolean} - True if the string is a valid decimal * @returns {boolean} - True if the string is a valid decimal
*/ */
export function isDecimal(value) { export function isDecimal(value): boolean {
return ( return (
Number.isFinite(parseFloat(value)) && Number.isFinite(parseFloat(value)) &&
!Number.isNaN(parseFloat(value)) && !Number.isNaN(parseFloat(value)) &&
@ -112,7 +112,7 @@ export function isDecimal(value) {
* @param {string} value - Some numeric value represented as a string * @param {string} value - Some numeric value represented as a string
* @returns {Object} - BN instance * @returns {Object} - BN instance
*/ */
export function toBN(value) { export function toBN(value: string | number) {
return Web3.utils.toBN(value); return Web3.utils.toBN(value);
} }
@ -122,7 +122,7 @@ export function toBN(value) {
* @param {string} str - The string to prefix. * @param {string} str - The string to prefix.
* @returns {string} The prefixed string. * @returns {string} The prefixed string.
*/ */
export const addHexPrefix = (str: string) => { export function addHexPrefix(str: string): string {
if (typeof str !== "string" || str.match(/^-?0x/u)) { if (typeof str !== "string" || str.match(/^-?0x/u)) {
return str; return str;
} }
@ -136,7 +136,7 @@ export const addHexPrefix = (str: string) => {
} }
return `0x${str}`; return `0x${str}`;
}; }
/** /**
* Wraps 'numberToBN' method to avoid potential undefined and decimal values * Wraps 'numberToBN' method to avoid potential undefined and decimal values

View File

@ -11,7 +11,7 @@ export function retry<T = any>(
maxRetries: number = 3, maxRetries: number = 3,
errorWhiteList: any[] = [], errorWhiteList: any[] = [],
retries: number = 0 retries: number = 0
) { ): Promise<T> {
return new Promise<T>((resolve, reject) => { return new Promise<T>((resolve, reject) => {
fn() fn()
.then(resolve) .then(resolve)